/
AudioSignalAnalyzer.m
299 lines (245 loc) · 6.92 KB
/
AudioSignalAnalyzer.m
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
//
// AudioSignalAnalyzer.m
// iNfrared
//
// Created by George Dean on 11/28/08.
// Copyright 2008 Perceptive Development. All rights reserved.
//
#import "AudioSignalAnalyzer.h"
#define SAMPLE_RATE 44100
#define SAMPLE SInt16
#define NUM_CHANNELS 1
#define BYTES_PER_FRAME (NUM_CHANNELS * sizeof(SAMPLE))
#define SAMPLES_TO_NS(__samples__) (((UInt64)(__samples__) * 1000000000) / SAMPLE_RATE)
#define NS_TO_SAMPLES(__nanosec__) (unsigned)(((UInt64)(__nanosec__) * SAMPLE_RATE) / 1000000000)
#define US_TO_SAMPLES(__microsec__) (unsigned)(((UInt64)(__microsec__) * SAMPLE_RATE) / 1000000)
#define MS_TO_SAMPLES(__millisec__) (unsigned)(((UInt64)(__millisec__) * SAMPLE_RATE) / 1000)
#define EDGE_DIFF_THRESHOLD 16384
#define EDGE_SLOPE_THRESHOLD 256
#define EDGE_MAX_WIDTH 8
#define IDLE_CHECK_PERIOD MS_TO_SAMPLES(10)
static int analyze( SAMPLE *inputBuffer,
unsigned long framesPerBuffer,
AudioSignalAnalyzer* analyzer)
{
analyzerData *data = analyzer.pulseData;
SAMPLE *pSample = inputBuffer;
int lastFrame = data->lastFrame;
unsigned idleInterval = data->plateauWidth + data->lastEdgeWidth + data->edgeWidth;
for (long i=0; i < framesPerBuffer; i++, pSample++)
{
int thisFrame = *pSample;
int diff = thisFrame - lastFrame;
int sign = 0;
if (diff > EDGE_SLOPE_THRESHOLD)
{
// Signal is rising
sign = 1;
}
else if(-diff > EDGE_SLOPE_THRESHOLD)
{
// Signal is falling
sign = -1;
}
// If the signal has changed direction or the edge detector has gone on for too long,
// then close out the current edge detection phase
if(data->edgeSign != sign || (data->edgeSign && data->edgeWidth + 1 > EDGE_MAX_WIDTH))
{
if(abs(data->edgeDiff) > EDGE_DIFF_THRESHOLD && data->lastEdgeSign != data->edgeSign)
{
// The edge is significant
[analyzer edge:data->edgeDiff
width:data->edgeWidth
interval:data->plateauWidth + data->edgeWidth];
// Save the edge
data->lastEdgeSign = data->edgeSign;
data->lastEdgeWidth = data->edgeWidth;
// Reset the plateau
data->plateauWidth = 0;
idleInterval = data->edgeWidth;
#ifdef DETAILED_ANALYSIS
data->plateauSum = 0;
data->plateauMin = data->plateauMax = thisFrame;
#endif
}
else
{
// The edge is rejected; add the edge data to the plateau
data->plateauWidth += data->edgeWidth;
#ifdef DETAILED_ANALYSIS
data->plateauSum += data->edgeSum;
if(data->plateauMax < data->edgeMax)
data->plateauMax = data->edgeMax;
if(data->plateauMin > data->edgeMin)
data->plateauMin = data->edgeMin;
#endif
}
data->edgeSign = sign;
data->edgeWidth = 0;
data->edgeDiff = 0;
#ifdef DETAILED_ANALYSIS
data->edgeSum = 0;
data->edgeMin = data->edgeMax = lastFrame;
#endif
}
if(data->edgeSign)
{
// Sample may be part of an edge
data->edgeWidth++;
data->edgeDiff += diff;
#ifdef DETAILED_ANALYSIS
data->edgeSum += thisFrame;
if(data->edgeMax < thisFrame)
data->edgeMax = thisFrame;
if(data->edgeMin > thisFrame)
data->edgeMin = thisFrame;
#endif
}
else
{
// Sample is part of a plateau
data->plateauWidth++;
#ifdef DETAILED_ANALYSIS
data->plateauSum += thisFrame;
if(data->plateauMax < thisFrame)
data->plateauMax = thisFrame;
if(data->plateauMin > thisFrame)
data->plateauMin = thisFrame;
#endif
}
idleInterval++;
data->lastFrame = lastFrame = thisFrame;
if ( (idleInterval % IDLE_CHECK_PERIOD) == 0 )
[analyzer idle:idleInterval];
}
return 0;
}
static void recordingCallback (
void *inUserData,
AudioQueueRef inAudioQueue,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime,
UInt32 inNumPackets,
const AudioStreamPacketDescription *inPacketDesc
) {
// This is not a Cocoa thread, it needs a manually allocated pool
// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// This callback, being outside the implementation block, needs a reference to the AudioRecorder object
AudioSignalAnalyzer *analyzer = (AudioSignalAnalyzer *) inUserData;
// if there is audio data, analyze it
if (inNumPackets > 0) {
analyze((SAMPLE*)inBuffer->mAudioData, inBuffer->mAudioDataByteSize / BYTES_PER_FRAME, analyzer);
}
// if not stopping, re-enqueue the buffer so that it can be filled again
if ([analyzer isRunning]) {
AudioQueueEnqueueBuffer (
inAudioQueue,
inBuffer,
0,
NULL
);
}
// [pool release];
}
@implementation AudioSignalAnalyzer
@synthesize stopping;
- (analyzerData*) pulseData
{
return &pulseData;
}
- (id) init
{
self = [super init];
if (self != nil)
{
recognizers = [[NSMutableArray alloc] init];
// these statements define the audio stream basic description
// for the file to record into.
audioFormat.mSampleRate = SAMPLE_RATE;
audioFormat.mFormatID = kAudioFormatLinearPCM;
audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
audioFormat.mFramesPerPacket = 1;
audioFormat.mChannelsPerFrame = 1;
audioFormat.mBitsPerChannel = 16;
audioFormat.mBytesPerPacket = 2;
audioFormat.mBytesPerFrame = 2;
AudioQueueNewInput (
&audioFormat,
recordingCallback,
self, // userData
NULL, // run loop
NULL, // run loop mode
0, // flags
&queueObject
);
}
return self;
}
- (void) addRecognizer: (id<PatternRecognizer>)recognizer
{
[recognizers addObject:recognizer];
}
- (void) record
{
[self setupRecording];
[self reset];
AudioQueueStart (
queueObject,
NULL // start time. NULL means ASAP.
);
}
- (void) stop
{
AudioQueueStop (
queueObject,
TRUE
);
[self reset];
}
- (void) setupRecording
{
// allocate and enqueue buffers
int bufferByteSize = 4096; // this is the maximum buffer size used by the player class
int bufferIndex;
for (bufferIndex = 0; bufferIndex < 20; ++bufferIndex) {
AudioQueueBufferRef bufferRef;
AudioQueueAllocateBuffer (
queueObject,
bufferByteSize, &bufferRef
);
AudioQueueEnqueueBuffer (
queueObject,
bufferRef,
0,
NULL
);
}
}
- (void) idle: (unsigned)samples
{
// Convert to microseconds
UInt64 nsInterval = SAMPLES_TO_NS(samples);
for (id<PatternRecognizer> rec in recognizers)
[rec idle:nsInterval];
}
- (void) edge: (int)height width:(unsigned)width interval:(unsigned)interval
{
// Convert to microseconds
UInt64 nsInterval = SAMPLES_TO_NS(interval);
UInt64 nsWidth = SAMPLES_TO_NS(width);
for (id<PatternRecognizer> rec in recognizers)
[rec edge:height width:nsWidth interval:nsInterval];
}
- (void) reset
{
[recognizers makeObjectsPerformSelector:@selector(reset)];
memset(&pulseData, 0, sizeof(pulseData));
}
- (void) dealloc
{
AudioQueueDispose (queueObject,
TRUE);
[recognizers release];
[super dealloc];
}
@end