Pygpu 'missing BLAS library' and other test errors - theano

I am attempting to run Theano under Windows 10 with AMD OpenCL installed. Python, Theano, Pygpu, and the other dependencies were installed using Anaconda, including MKL as the BLAS installation, as per the developers' instructions. MKL seems to be where it's expected to be by numpy:
>>> import numpy as np
>>> np.__config__.show()
lapack_opt_info:
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
include_dirs = ['C:/ProgramData/Anaconda3\\Library\\include']
library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
blas_opt_info:
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
include_dirs = ['C:/ProgramData/Anaconda3\\Library\\include']
library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
lapack_mkl_info:
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
include_dirs = ['C:/ProgramData/Anaconda3\\Library\\include']
library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
blas_mkl_info:
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
include_dirs = ['C:/ProgramData/Anaconda3\\Library\\include']
library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
However, when I run pygpu.test() I get a lot of errors (1166, plus 2 failures). Approximately half of the errors are due to not being able to find the BLAS library:
======================================================================
ERROR: pygpu.tests.test_blas.test_dot(1, 'float32', True, True, True, False)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\nose\case.py", line 198, in runTest
self.test(*self.arg)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\tests\support.py", line 44, in f
func(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\tests\test_blas.py", line 44, in dot
gr = gblas.dot(gX, gY, gZ, overwrite_z=overwrite)
File "pygpu\blas.pyx", line 79, in pygpu.blas.dot
File "pygpu\blas.pyx", line 29, in pygpu.blas.pygpu_blas_rdot
pygpu.gpuarray.GpuArrayException: (b'Missing Blas library', 5)
...where the exact details of the test differ each time but the traceback is identical.
And the first two reported errors are Clang front-end compilation failures. I confess I don't understand how/why they're arising, but they sound serious:
======================================================================
ERROR: pygpu.tests.test_basic.test_tril
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\nose\case.py", line 198, in runTest
self.test(*self.arg)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\tests\test_basic.py", line 15, in test_tril
result = tril(ag, inplace=inplace)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\basic.py", line 62, in tril
k = _generate_kernel(A.context, cols, upper)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\basic.py", line 25, in _generate_kernel
k = GpuKernel(src, "extract_tri", spec, context=ctx)
File "pygpu\gpuarray.pyx", line 2428, in pygpu.gpuarray.GpuKernel.__cinit__
File "pygpu\gpuarray.pyx", line 446, in pygpu.gpuarray.kernel_init
pygpu.gpuarray.GpuArrayException: Program build failure ::
C:\Users\megha\AppData\Local\Temp\\OCL11404T5.cl:43:38: error: casting '__global float *' to type 'char *' changes address space of pointer
a = (GLOBAL_MEM ga_float *)(((char *)a) + a_off);
^ ~
1 error generated.
error: Clang front-end compilation failed!
Frontend phase failed compilation.
Error: Compiling CL to IR
1 #define local_barrier() barrier(CLK_LOCAL_MEM_FENCE)
2 #define WITHIN_KERNEL /* empty */
3 #define KERNEL __kernel
4 #define GLOBAL_MEM __global
5 #define LOCAL_MEM __local
6 #define LOCAL_MEM_ARG __local
7 #ifndef NULL
8 #define NULL ((void*)0)
9 #endif
10 #define LID_0 get_local_id(0)
11 #define LID_1 get_local_id(1)
12 #define LID_2 get_local_id(2)
13 #define LDIM_0 get_local_size(0)
14 #define LDIM_1 get_local_size(1)
15 #define LDIM_2 get_local_size(2)
16 #define GID_0 get_group_id(0)
17 #define GID_1 get_group_id(1)
18 #define GID_2 get_group_id(2)
19 #define GDIM_0 get_num_groups(0)
20 #define GDIM_1 get_num_groups(1)
21 #define GDIM_2 get_num_groups(2)
22 #define ga_bool uchar
23 #define ga_byte char
24 #define ga_ubyte uchar
25 #define ga_short short
26 #define ga_ushort ushort
27 #define ga_int int
28 #define ga_uint uint
29 #define ga_long long
30 #define ga_ulong ulong
31 #define ga_float float
32 #define ga_double double
33 #define ga_half half
34 #define ga_size ulong
35 #define ga_ssize long
36 #define load_half(p) vload_half(0, p)
37 #define store_half(p, v) vstore_half_rtn(v, 0, p)
38 #define GA_DECL_SHARED_PARAM(type, name) , __local type *name
39 #define GA_DECL_SHARED_BODY(type, name)
40 #define GA_WARP_SIZE 64
41
42 KERNEL void extract_tri(GLOBAL_MEM ga_float *a, ga_size a_off, ga_uint N) {
43 a = (GLOBAL_MEM ga_float *)(((char *)a) + a_off);
44 unsigned int idx = GID_1 * LDIM_0 * GDIM_0 +
45 GID_0 * LDIM_0 + LID_0;
46 unsigned int ix = idx/5;
47 unsigned int iy = idx%5;
48 if (idx < N) {
49 if (ix < iy)
50 a[idx] = 0.0;
51 }
52 }
53
======================================================================
ERROR: pygpu.tests.test_basic.test_triu
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\nose\case.py", line 198, in runTest
self.test(*self.arg)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\tests\test_basic.py", line 29, in test_triu
result = triu(ag, inplace=inplace)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\basic.py", line 43, in triu
k = _generate_kernel(A.context, cols, upper)
File "C:\ProgramData\Anaconda3\lib\site-packages\pygpu\basic.py", line 25, in _generate_kernel
k = GpuKernel(src, "extract_tri", spec, context=ctx)
File "pygpu\gpuarray.pyx", line 2428, in pygpu.gpuarray.GpuKernel.__cinit__
File "pygpu\gpuarray.pyx", line 446, in pygpu.gpuarray.kernel_init
pygpu.gpuarray.GpuArrayException: Program build failure ::
C:\Users\megha\AppData\Local\Temp\\OCL11404T7.cl:43:38: error: casting '__global float *' to type 'char *' changes address space of pointer
a = (GLOBAL_MEM ga_float *)(((char *)a) + a_off);
^ ~
1 error generated.
error: Clang front-end compilation failed!
Frontend phase failed compilation.
Error: Compiling CL to IR
1 #define local_barrier() barrier(CLK_LOCAL_MEM_FENCE)
2 #define WITHIN_KERNEL /* empty */
3 #define KERNEL __kernel
4 #define GLOBAL_MEM __global
5 #define LOCAL_MEM __local
6 #define LOCAL_MEM_ARG __local
7 #ifndef NULL
8 #define NULL ((void*)0)
9 #endif
10 #define LID_0 get_local_id(0)
11 #define LID_1 get_local_id(1)
12 #define LID_2 get_local_id(2)
13 #define LDIM_0 get_local_size(0)
14 #define LDIM_1 get_local_size(1)
15 #define LDIM_2 get_local_size(2)
16 #define GID_0 get_group_id(0)
17 #define GID_1 get_group_id(1)
18 #define GID_2 get_group_id(2)
19 #define GDIM_0 get_num_groups(0)
20 #define GDIM_1 get_num_groups(1)
21 #define GDIM_2 get_num_groups(2)
22 #define ga_bool uchar
23 #define ga_byte char
24 #define ga_ubyte uchar
25 #define ga_short short
26 #define ga_ushort ushort
27 #define ga_int int
28 #define ga_uint uint
29 #define ga_long long
30 #define ga_ulong ulong
31 #define ga_float float
32 #define ga_double double
33 #define ga_half half
34 #define ga_size ulong
35 #define ga_ssize long
36 #define load_half(p) vload_half(0, p)
37 #define store_half(p, v) vstore_half_rtn(v, 0, p)
38 #define GA_DECL_SHARED_PARAM(type, name) , __local type *name
39 #define GA_DECL_SHARED_BODY(type, name)
40 #define GA_WARP_SIZE 64
41
42 KERNEL void extract_tri(GLOBAL_MEM ga_float *a, ga_size a_off, ga_uint N) {
43 a = (GLOBAL_MEM ga_float *)(((char *)a) + a_off);
44 unsigned int idx = GID_1 * LDIM_0 * GDIM_0 +
45 GID_0 * LDIM_0 + LID_0;
46 unsigned int ix = idx/5;
47 unsigned int iy = idx%5;
48 if (idx < N) {
49 if (ix > iy)
50 a[idx] = 0.0;
51 }
52 }
53
Can anyone advise me on how I might resolve these errors? Thank you in advance.
(The rest of the errors that I've not pasted here state 'TypeError: This is for CUDA arrays', so I assume are irrelevant; and the two fails are to do with float16 support, which I've read is experimental and isn't needed here anyway.)

Related

Python ctypes dll - pass pointer to C structure

I am trying to extract data from a Hamamatsu C15713 MEMS-FPI spectrometer with the dll, through python ctypes.
The dll function I am trying to call is :
HRESULT hpkfpi_getdevcount(HPKFPI_INITPARAM* initparam);
Where the parameter initparam should be a pointer towards a structure:
#define HPKFPI_INITARY_NUMBER 127
#define HPKFPI_INITARY_STRLEN 32
typedef struct {
int32_t sizeof_parameter;
int32_t devicecount;
char buf_VID[HPKFPI_INITARY_NUMBER][HPKFPI_INITARY_STRLEN];
char buf_PID[HPKFPI_INITARY_NUMBER][HPKFPI_INITARY_STRLEN];
char buf_SERIAL[HPKFPI_INITARY_NUMBER][HPKFPI_INITARY_STRLEN];
} HPKFPI_INITPARAM;
My current code:
from ctypes import *
class HPKFPI_INITPARAM(Structure):
# Define the structure object
_fields_ = [("sizeof_parameter", c_uint32),("devicecount", c_uint32),
('buf_VID', (c_char*127)*32), ('buf_PID', (c_char*127)*32), ('buf_SERIAL', (c_char*127)*32)]
class Hamamatsu_C15713:
def __init__(self, dll_path):
dll_filename = os.path.join(dll_path, 'HPKFPI_x64.dll')
self._dll = windll.LoadLibrary(dll_filename)
logging.debug(f'dll loaded')
# Initialize the dll
self._dll.hpkfpi_init()
# Try to get the device count
deviceCount = HPKFPI_INITPARAM()
self._dll.hpkfpi_getdevcount(byref(deviceCount))
This code does not produce errors, however the fields of deviceCount all remain 0.
Numeric values are 0 and the char arrays are bitstrings value 0.
What have I tried to solve this:
POINTER(deviceCount) instead of byref(deviceCount) returns an error (TypeError: Not Hashable).
Whatever object I make as deviceCount, it is not changed by the function.
Can anyone give me advise?
With the help of a colleague, we managed advance on this problem.
Important point: There is an error in documentation of the Hamamatsu C15713 MEMS-FPI spectrometer dll: The dimensions of the initparam are wrong.
127 should be 255
HPKFPI_INITARY_NUMBER = 255
HPKFPI_INITARY_STRLEN = 32
class HPKFPI_INITPARAM(Structure):
_fields_ = [
("sizeof_parameter", c_int32),
("devicecount", c_int32),
('buf_VID', (c_char * HPKFPI_INITARY_STRLEN) * HPKFPI_INITARY_NUMBER),
('buf_PID', (c_char * HPKFPI_INITARY_STRLEN) * HPKFPI_INITARY_NUMBER),
('buf_SERIAL', (c_char * HPKFPI_INITARY_STRLEN) * HPKFPI_INITARY_NUMBER)
]
class HPKFPI_OPENPARAM(Structure):
_fields_ = [
("sizeof_parameter", c_int32),
("id", c_int32),
("hfpi", HANDLE)
]
class Hamamatsu_C15713:
"""
This class is intended to a a wrapper around the Hamamatsu C15713 dll
"""
def __init__(self, dll_path):
logging.debug("Loading dll %s", dll_path)
# add dll dir to os path env var so dependent dll can be found
os.environ['PATH'] = str(DLL_DIR) + ';' + os.environ['PATH']
self._dll = windll.LoadLibrary(str(dll_path))
logging.debug('dll loaded')
# Initialize the dll
ret = self._dll.hpkfpi_init()
logging.debug("init ret: %s", ret)
if ret < 0:
raise SystemError(f"hpkfpi_init failed, ret code: {ret}")
# Try to get the device count
init_param = HPKFPI_INITPARAM()
init_param.sizeof_parameter = sizeof(init_param)
logging.debug("devcount sizeof: %s",init_param.sizeof_parameter)
ret = self._dll.hpkfpi_getdevcount(byref(init_param))
logging.debug("hpkfpi_getdevcount ret: %s", ret)
if ret < 0:
raise SystemError(f"hpkfpi_getdevcount failed, ret code: {ret}")
logging.debug(
"Extracted devicecount : %d, VID %s, PID %s, SERIAL %s", init_param.devicecount,
bytes(init_param.buf_VID[0]).decode(),
bytes(init_param.buf_PID[0]).decode(),
bytes(init_param.buf_SERIAL[0]).decode())
open_param = HPKFPI_OPENPARAM()
open_param.id = 0 # device 0
open_param.sizeof_parameter = sizeof(open_param)
ret = self._dll.hpkfpi_open(byref(open_param))
logging.debug("hpkfpi_open ret: %s", ret)
if ret < 0:
raise SystemError(f"hpkfpi_open failed, ret code: {ret}")
self.dev_handle = open_param.hfpi
logging.debug("Open handle: %d", self.dev_handle)

pure-python callback function was called with parameter b'', lossing the actual data in cython function

I try to call a callback function in cython cdef block, I can printf the actual data during cython function call, but when my callback function was called or I call a print(buffer) in cython cdef block, I got the (paramter/result) with b'',I try other demo, It's all works fine.
windows 10, python3.7, cython
cython block
cdef ikcp_output(self, char *buffer, int size):
print("size: {}".format(size)) this can work
for i in range(size):
print(buffer[i]) # this can also works
cdef char* o
o = <char*> malloc(sizeof(char) * size)
memcpy(o, buffer, size)
for i in range(size):
print(o[i]) # this can also works
print(o) # this output b''
self.output(o) # the callback function get a parameter b''
free(o)
start iter buffer
0
0
0
1
81
0
0
32
28
-50
-113
-50
0
0
0
0
0
0
0
0
49
50
49
51
50
49
51
49
51
49
50
10
start iter o
0
0
0
1
81
0
0
32
28
-50
-113
-50
0
0
0
0
0
0
0
0
49
50
49
51
50
49
51
49
51
49
50
10
32
b'' # this is what i got in callback function
client output
output data b'' to addr: ('127.0.0.1', 8888)
Calling either print(o) or self.func(o) involves converting o to a Python object, in this case a bytes object. This conversion assumes that the char* is a c string (i.e. is null terminated) since Cython has no other way to determine the length. However your buffer starts with 0, and so is read a 0-length string.
The correct solution is to do the conversion manually using PyBytes_FromStringAndSize. You pass this a char* and the length of the string (hence it doesn't assume that the first 0 is the end of the string). You can cimport it from cpython.bytes.

Pointer from Python (ctypes) to C to save function output

I'm new to C integration in Python. I'm currently wrapping a .dll library into my Python code using ctypes and I'm having issues passing a pointer to save the output of a particular function.
My C function has the following structure:
function (int* w, int* h, unsigned short* data_output)
Where h and w are inputs and data_output is an array of size (w x h, 1).
I was able to successfully integrate and retrieve results from the function in Matlab by creating a zeros(w x h,1) array and passing it as a pointer using libpointer('uint16Ptr', zeros(w x h, 1)).
How can I do that in Python?
For other functions, where the output was of int* type I was able to successfully retrieve the values using create_string_buffer. But I haven't managed to make it work for this one.
Thank you.
According to [SO]: How to create a Minimal, Complete, and Verifiable example (mcve), your question doesn't contain basic info (e.g. your attempts). Make sure to correct that in the next ones.
Also, [Python.Docs]: ctypes - A foreign function library for Python.
Here's a dummy example that illustrates the concept.
dll00.c:
#if defined(_WIN32)
# define DLL_EXPORT __declspec(dllexport)
#else
# define DLL_EXPORT
#endif
DLL_EXPORT int function(int w, int h, unsigned short *pData) {
int k = 1;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++, k++)
pData[i * w + j] = k;
return w * h;
}
code00.py:
#!/usr/bin/env python3
import sys
import ctypes as ct
DLL = "./dll00.so"
def print_array(data, h, w):
for i in range(h):
for j in range(w):
print("{:2d}".format(data[i * w + j]), end=" ")
print()
def main(*argv):
dll_dll = ct.CDLL(DLL)
function = dll_dll.function
function.argtypes = [ct.c_int, ct.c_int, ct.POINTER(ct.c_ushort)]
function.restype = ct.c_int
h = 3
w = 5
ArrayType = ct.c_ushort * (h * w) # Dynamically declare the array type: `unsigned short[15]` in our case
array = ArrayType() # The array type instance
print_array(array, h, w)
res = function(w, h, ct.cast(array, ct.POINTER(ct.c_ushort)))
print("{:} returned: {:d}".format(function.__name__, res))
print_array(array, h, w)
if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)
Output:
[cfati#cfati-5510-0:/cygdrive/e/Work/Dev/StackOverflow/q054753828]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###
[064bit prompt]> ls
code00.py dll00.c
[064bit prompt]> gcc -fPIC -shared -o dll00.so dll00.c
[064bit prompt]> ls
code00.py dll00.c dll00.so
[064bit prompt]> python3 code00.py
Python 3.6.4 (default, Jan 7 2018, 15:53:53) [GCC 6.4.0] 064bit on cygwin
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
function returned: 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Done.

Wrong PWM pin output?

I am fairly new to programming, and as I have a fascination for music I thought to start with building a simple sequencer using codes from the web.
Now I found a perfect code but somehow it does not behave as it needs to and I hope to get some advice here in order to learn more and eventually build my own synthesizer!
/* analog inputs:
* A0 pitch step 1 (syncPhaseInc)
* A1 pitch step 2
* A2 pitch step 3
* A3 pitch step 4
* A4 tempo
* A5 effect (grainPhaseInc)
* plus volume potentiometer
*
* audio out via 220 ohm resistor to 3.5mm jack
* audio out via 10K/10K voltage divider and 10K volume pot and 10uF cap to internal mono amp with speaker
* power switch on amp
* built with Arduino Nano on perf board powered by USB cable
*/
#include <avr/io.h>
#include <avr/interrupt.h>
uint16_t syncPhaseAcc;
uint16_t syncPhaseInc;
uint16_t grainPhaseAcc;
uint16_t grainPhaseInc;
uint16_t grainAmp;
uint8_t grainDecay;
uint16_t grain2PhaseAcc;
uint16_t grain2PhaseInc;
uint16_t grain2Amp;
uint8_t grain2Decay;
// Changing these will also requires rewriting audioOn()
#if defined(__AVR_ATmega8__)
//
// On old ATmega8 boards.
// Output is on pin 11
//
#define LED_PIN 13
#define LED_PORT PORTB
#define LED_BIT 5
#define PWM_PIN 11
#define PWM_VALUE OCR2
#define PWM_INTERRUPT TIMER2_OVF_vect
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//
// On the Arduino Mega
// Output is on pin 3
//
#define LED_PIN 13
#define LED_PORT PORTB
#define LED_BIT 7
#define PWM_PIN 3
#define PWM_VALUE OCR3C
#define PWM_INTERRUPT TIMER3_OVF_vect
#else
//
// For modern ATmega168 and ATmega328 boards
// Output is on pin 3
//
#define PWM_PIN 3
#define PWM_VALUE OCR2B
#define LED_PIN 13
#define LED_PORT PORTB
#define LED_BIT 5
#define PWM_INTERRUPT TIMER2_OVF_vect
#endif
// Smooth logarithmic mapping
//
uint16_t antilogTable[] = {
64830, 64132, 63441, 62757, 62081, 61413, 60751, 60097, 59449, 58809, 58176, 57549, 56929, 56316, 55709, 55109,
54515, 53928, 53347, 52773, 52204, 51642, 51085, 50535, 49991, 49452, 48920, 48393, 47871, 47356, 46846, 46341,
45842, 45348, 44859, 44376, 43898, 43425, 42958, 42495, 42037, 41584, 41136, 40693, 40255, 39821, 39392, 38968,
38548, 38133, 37722, 37316, 36914, 36516, 36123, 35734, 35349, 34968, 34591, 34219, 33850, 33486, 33125, 32768
};
uint16_t mapPhaseInc(uint16_t input) {
return (antilogTable[input & 0x3f]) >> (input >> 6);
}
// Stepped chromatic mapping
//
uint16_t midiTable[] = {
17, 18, 19, 20, 22, 23, 24, 26, 27, 29, 31, 32, 34, 36, 38, 41, 43, 46, 48, 51, 54, 58, 61, 65, 69, 73,
77, 82, 86, 92, 97, 103, 109, 115, 122, 129, 137, 145, 154, 163, 173, 183, 194, 206, 218, 231,
244, 259, 274, 291, 308, 326, 346, 366, 388, 411, 435, 461, 489, 518, 549, 581, 616, 652, 691,
732, 776, 822, 871, 923, 978, 1036, 1097, 1163, 1232, 1305, 1383, 1465, 1552, 1644, 1742,
1845, 1955, 2071, 2195, 2325, 2463, 2610, 2765, 2930, 3104, 3288, 3484, 3691, 3910, 4143,
4389, 4650, 4927, 5220, 5530, 5859, 6207, 6577, 6968, 7382, 7821, 8286, 8779, 9301, 9854,
10440, 11060, 11718, 12415, 13153, 13935, 14764, 15642, 16572, 17557, 18601, 19708, 20879,
22121, 23436, 24830, 26306
};
uint16_t mapMidi(uint16_t input) {
return (midiTable[(1023 - input) >> 3]);
}
// Stepped Pentatonic mapping
//
uint16_t pentatonicTable[54] = {
0, 19, 22, 26, 29, 32, 38, 43, 51, 58, 65, 77, 86, 103, 115, 129, 154, 173, 206, 231, 259, 308, 346,
411, 461, 518, 616, 691, 822, 923, 1036, 1232, 1383, 1644, 1845, 2071, 2463, 2765, 3288,
3691, 4143, 4927, 5530, 6577, 7382, 8286, 9854, 11060, 13153, 14764, 16572, 19708, 22121, 26306
};
uint16_t mapPentatonic(uint16_t input) {
uint8_t value = (1023 - input) / (1024 / 53);
return (pentatonicTable[value]);
}
void audioOn() {
#if defined(__AVR_ATmega8__)
// ATmega8 has different registers
TCCR2 = _BV(WGM20) | _BV(COM21) | _BV(CS20);
TIMSK = _BV(TOIE2);
#elif defined(__AVR_ATmega1280__)
TCCR3A = _BV(COM3C1) | _BV(WGM30);
TCCR3B = _BV(CS30);
TIMSK3 = _BV(TOIE3);
#else
// Set up PWM to 31.25kHz, phase accurate
TCCR2A = _BV(COM2B1) | _BV(WGM20);
TCCR2B = _BV(CS20);
TIMSK2 = _BV(TOIE2);
#endif
}
long counter = 0;
long tempo;
int pattern = 0;
const byte pat0 = 4;
const byte pat1 = 5;
const byte pat2 = 6;
const byte pat3 = 7;
void setup() {
pinMode(PWM_PIN, OUTPUT);
audioOn();
pinMode(LED_PIN, OUTPUT);
pinMode(pat0, OUTPUT);
pinMode(pat1, OUTPUT);
pinMode(pat2, OUTPUT);
pinMode(pat3, OUTPUT);
digitalWrite(pat0, LOW);
digitalWrite(pat1, LOW);
digitalWrite(pat2, LOW);
digitalWrite(pat3, LOW);
// presets for 3 less important pots
grainDecay = 200 / 8;
grain2PhaseInc = mapPhaseInc(200) / 2;
grain2Decay = 200 / 4;
}
void loop() {
tempo = map(analogRead(A4), 0, 1023, 100, 4000);
counter++;
if (counter > tempo) {
counter = 0;
if (pattern == 4) {
pattern = 0;
}
switch (pattern) {
case 0:
syncPhaseInc = mapPentatonic(analogRead(A0));
digitalWrite(pat3, LOW);
digitalWrite(pat0, HIGH);
break;
case 1:
syncPhaseInc = mapPentatonic(analogRead(A1));
digitalWrite(pat0, LOW);
digitalWrite(pat1, HIGH);
break;
case 2:
syncPhaseInc = mapPentatonic(analogRead(A2));
digitalWrite(pat1, LOW);
digitalWrite(pat2, HIGH);
break;
case 3:
syncPhaseInc = mapPentatonic(analogRead(A3));
digitalWrite(pat2, LOW);
digitalWrite(pat3, HIGH);
break;
}
grainPhaseInc = mapPhaseInc(analogRead(A5)) / 2;
pattern++;
}
}
SIGNAL(PWM_INTERRUPT)
{
uint8_t value;
uint16_t output;
syncPhaseAcc += syncPhaseInc;
if (syncPhaseAcc < syncPhaseInc) {
// Time to start the next grain
grainPhaseAcc = 0;
grainAmp = 0x7fff;
grain2PhaseAcc = 0;
grain2Amp = 0x7fff;
LED_PORT ^= 1 << LED_BIT; // Faster than using digitalWrite } // Increment the phase of the grain oscillators grainPhaseAcc += grainPhaseInc; grain2PhaseAcc += grain2PhaseInc; // Convert phase into a triangle wave value = (grainPhaseAcc >> 7) & 0xff;
if (grainPhaseAcc & 0x8000) value = ~value;
// Multiply by current grain amplitude to get sample
output = value * (grainAmp >> 8);
// Repeat for second grain
value = (grain2PhaseAcc >> 7) & 0xff;
if (grain2PhaseAcc & 0x8000) value = ~value;
output += value * (grain2Amp >> 8);
// Make the grain amplitudes decay by a factor every sample (exponential decay)
grainAmp -= (grainAmp >> 8) * grainDecay;
grain2Amp -= (grain2Amp >> 8) * grain2Decay;
// Scale output to the available range, clipping if necessary
output >>= 9;
if (output > 255) output = 255;
// Output to PWM (this is faster than using analogWrite)
PWM_VALUE = output;
}
one thing I cannot explain is that the sound output pin is different from the one in the code. The code states that the output pin is PWM 3 for an ATmega328 which I use, but the sound from this pin is SUPER soft and noisy when I amplify the sound with an amplifier chip.
PWM 13 produces clean and loud sound, but putting filters and effects over the sound does not seem to work.
Does somebody know why this is the case? I would really like to use effects over the sounds. Because what is a synthesizer without awesome effects?!
Thanks in advance !!

AVPlayer plays HLS but crashes with MP4 video

AVPlayers plays HLS but crashes with MP4 video. I am using the following URLs; I am also using IMA SDK for iOS to play ads, which works perfectly with the 1st URL, but the app crashes with the 2nd one without playing the ad.
using iOS version: 10.1
//NSString *const kTestAppContentUrl_MP4 = #"http://50.7.149.90:1935/pitvlive/ptvsportsnew3.stream/playlist.m3u8";
NSString *const kTestAppContentUrl_MP4 = #"http://50.7.149.74/vods/trailers/OK Jaanu-Official Trailer.mp4";
> *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid number value (NaN) in JSON write'
*** First throw call stack:
(
0 CoreFoundation 0x00000001076b634b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010aba621e objc_exception_throw + 48
2 CoreFoundation 0x000000010771f265 +[NSException raise:format:] + 197
3 Foundation 0x000000010a6efbfe _writeJSONNumber + 302
4 Foundation 0x000000010a69a138 _writeJSONValue + 480
5 Foundation 0x000000010a6efa12 ___writeJSONObject_block_invoke + 226
6 CoreFoundation 0x0000000107646e55 __65-[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 85
7 CoreFoundation 0x0000000107646d6a -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] + 250
8 Foundation 0x000000010a6ef806 _writeJSONObject + 430
9 Foundation 0x000000010a69a0dd _writeJSONValue + 389
10 Foundation 0x000000010a6efa12 ___writeJSONObject_block_invoke + 226
11 CoreFoundation 0x000000010763d9d6 __65-[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 102
12 CoreFoundation 0x000000010763d8da -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 202
13 Foundation 0x000000010a6ef806 _writeJSONObject + 430
14 Foundation 0x000000010a69a0dd _writeJSONValue + 389
15 Foundation 0x000000010a699f04 -[_NSJSONWriter dataWithRootObject:options:error:] + 124
16 Foundation 0x000000010a699de4 +[NSJSONSerialization dataWithJSONObject:options:error:] + 333
17 AVPlayer 0x0000000106c552e4 -[IMAJavascriptDispatcher sendMessage:] + 313
18 AVPlayer 0x0000000106c55c5e -[IMAJavascriptSession sendMessage:] + 135
19 AVPlayer 0x0000000106c5f40d -[IMABaseManager sendMessage:data:] + 161
20 AVPlayer 0x0000000106c5dd1c -[IMABaseManager initializeWithAdsRenderingSettings:] + 1295
21 AVPlayer 0x0000000106c5d7f7 -[IMABaseManager initializeWithContentPlayhead:adsRenderingSettings:] + 100
22 AVPlayer 0x0000000106c5b336 -[IMAAdsManager initializeWithAdsRenderingSettings:] + 108
23 AVPlayer 0x0000000106c5173b -[ViewController adsLoader:adsLoadedWithData:] + 331
24 AVPlayer 0x0000000106c59e3f __39-[IMAAdsLoader handleMessageAdsLoaded:]_block_invoke + 94
25 libdispatch.dylib 0x000000010d3a9980 _dispatch_call_block_and_release + 12
26 libdispatch.dylib 0x000000010d3d30cd _dispatch_client_callout + 8
27 libdispatch.dylib 0x000000010d3b38d6 _dispatch_main_queue_callback_4CF + 406
28 CoreFoundation 0x000000010767a4f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
29 CoreFoundation 0x000000010763ff8d __CFRunLoopRun + 2205
30 CoreFoundation 0x000000010763f494 CFRunLoopRunSpecific + 420
31 GraphicsServices 0x000000010ce2ca6f GSEventRunModal + 161
32 UIKit 0x0000000108778964 UIApplicationMain + 159
33 AVPlayer 0x0000000106c5215f main + 111
34 libdyld.dylib 0x000000010d41f68d start + 1
35 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
There was a space in the URL, so i used the following method from someone to encode the URL.
- (NSString *) URLEncodedString_ch:(NSString*) str {
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[str UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}

Resources