summaryrefslogtreecommitdiff
path: root/pjmedia/src/pjmedia/pasound.c
blob: 8b2aa5ab04db2bcb2ddc11cfe5fc566fea260c7d (plain)
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
379
380
381
382
383
384
385
386
387
/* $Header: /pjproject/pjmedia/src/pjmedia/pasound.c 3     6/24/05 11:13p Bennylp $ */
#include <pjmedia/sound.h>
#include <pj/string.h>
#include <pj/os.h>
#include <pj/log.h>
#include <portaudio.h>

#define THIS_FILE	"pasound.c"

static struct snd_mgr
{
    pj_pool_factory *factory;
} snd_mgr;

struct pj_snd_stream
{
    pj_pool_t	    *pool;
    PaStream	    *stream;
    int		     dev_index;
    int		     bytes_per_sample;
    pj_uint32_t	     samples_per_sec;
    pj_uint32_t	     timestamp;
    pj_uint32_t	     underflow;
    pj_uint32_t	     overflow;
    void	    *user_data;
    pj_snd_rec_cb    rec_cb;
    pj_snd_play_cb   play_cb;
    pj_bool_t	     quit_flag;
    pj_bool_t	     thread_has_exited;
    pj_bool_t	     thread_initialized;
    pj_thread_desc   thread_desc;
    pj_thread_t	    *thread;
};


static int PaRecorderCallback(const void *input, 
			      void *output,
			      unsigned long frameCount,
			      const PaStreamCallbackTimeInfo* timeInfo,
			      PaStreamCallbackFlags statusFlags,
			      void *userData )
{
    pj_snd_stream *stream = userData;
    pj_status_t status;

    PJ_UNUSED_ARG(output)
    PJ_UNUSED_ARG(timeInfo)

    if (stream->quit_flag)
	goto on_break;

    if (stream->thread_initialized == 0) {
	stream->thread = pj_thread_register("pa_rec", stream->thread_desc);
	stream->thread_initialized = 1;
    }

    if (statusFlags & paInputUnderflow)
	++stream->underflow;
    if (statusFlags & paInputOverflow)
	++stream->overflow;

    stream->timestamp += frameCount;

    status = (*stream->rec_cb)(stream->user_data, stream->timestamp, 
			       input, frameCount * stream->bytes_per_sample);
    
    if (status==0) 
	return paContinue;

on_break:
    stream->thread_has_exited = 1;
    return paAbort;
}

static int PaPlayerCallback( const void *input, 
			     void *output,
			     unsigned long frameCount,
			     const PaStreamCallbackTimeInfo* timeInfo,
			     PaStreamCallbackFlags statusFlags,
			     void *userData )
{
    pj_snd_stream *stream = userData;
    pj_status_t status;
    unsigned size = frameCount * stream->bytes_per_sample;

    PJ_UNUSED_ARG(input)
    PJ_UNUSED_ARG(timeInfo)

    if (stream->quit_flag)
	goto on_break;

    if (stream->thread_initialized == 0) {
	stream->thread = pj_thread_register("pa_rec", stream->thread_desc);
	stream->thread_initialized = 1;
    }

    if (statusFlags & paInputUnderflow)
	++stream->underflow;
    if (statusFlags & paInputOverflow)
	++stream->overflow;

    stream->timestamp += frameCount;

    status = (*stream->play_cb)(stream->user_data, stream->timestamp, 
			        output, size);
    
    if (status==0) 
	return paContinue;

on_break:
    stream->thread_has_exited = 1;
    return paAbort;
}


/*
 * Init sound library.
 */
PJ_DEF(pj_status_t) pj_snd_init(pj_pool_factory *factory)
{
    int err;

    snd_mgr.factory = factory;
    err = Pa_Initialize();

    PJ_LOG(4,(THIS_FILE, "PortAudio sound library initialized, status=%d", err));

    return err;
}


/*
 * Get device count.
 */
PJ_DEF(int) pj_snd_get_dev_count(void)
{
    return Pa_GetDeviceCount();
}


/*
 * Get device info.
 */
PJ_DEF(const pj_snd_dev_info*) pj_snd_get_dev_info(unsigned index)
{
    static pj_snd_dev_info info;
    const PaDeviceInfo *pa_info;

    pa_info = Pa_GetDeviceInfo(index);
    if (!pa_info)
	return NULL;

    pj_memset(&info, 0, sizeof(info));
    strncpy(info.name, pa_info->name, sizeof(info.name));
    info.name[sizeof(info.name)-1] = '\0';
    info.input_count = pa_info->maxInputChannels;
    info.output_count = pa_info->maxOutputChannels;
    info.default_samples_per_sec = (unsigned)pa_info->defaultSampleRate;

    return &info;
}


/*
 * Open stream.
 */
PJ_DEF(pj_snd_stream*) pj_snd_open_recorder( int index,
					     const pj_snd_stream_info *param,
					     pj_snd_rec_cb rec_cb,
					     void *user_data)
{
    pj_pool_t *pool;
    pj_snd_stream *stream;
    PaStreamParameters inputParam;
    int sampleFormat;
    const PaDeviceInfo *paDevInfo = NULL;
    PaError err;

    if (index == -1) {
	int count = Pa_GetDeviceCount();
	for (index=0; index<count; ++index) {
	    paDevInfo = Pa_GetDeviceInfo(index);
	    if (paDevInfo->maxInputChannels > 0)
		break;
	}
	if (index == count) {
	    PJ_LOG(2,(THIS_FILE, "Error: unable to find recorder device"));
	    return NULL;
	}
    } else {
	paDevInfo = Pa_GetDeviceInfo(index);
	if (!paDevInfo)
	    return NULL;
    }

    if (param->bits_per_sample == 8)
	sampleFormat = paUInt8;
    else if (param->bits_per_sample == 16)
	sampleFormat = paInt16;
    else if (param->bits_per_sample == 32)
	sampleFormat = paInt32;
    else
	return NULL;
    
    pool = pj_pool_create( snd_mgr.factory, "sndstream", 1024, 1024, NULL);
    if (!pool)
	return NULL;

    stream = pj_pool_calloc(pool, 1, sizeof(*stream));
    stream->pool = pool;
    stream->user_data = user_data;
    stream->dev_index = index;
    stream->samples_per_sec = param->samples_per_frame;
    stream->bytes_per_sample = param->bits_per_sample / 8;
    stream->rec_cb = rec_cb;

    pj_memset(&inputParam, 0, sizeof(inputParam));
    inputParam.device = index;
    inputParam.channelCount = 1;
    inputParam.hostApiSpecificStreamInfo = NULL;
    inputParam.sampleFormat = sampleFormat;
    inputParam.suggestedLatency = paDevInfo->defaultLowInputLatency;

    err = Pa_OpenStream( &stream->stream, &inputParam, NULL,
			 param->samples_per_sec, 
			 param->samples_per_frame * param->frames_per_packet, 
			 0,
			 &PaRecorderCallback, stream );
    if (err != paNoError) {
	pj_pool_release(pool);
	PJ_LOG(2,(THIS_FILE, "Error opening player: %s", Pa_GetErrorText(err)));
	return NULL;
    }

    PJ_LOG(4,(THIS_FILE, "%s opening device %s for recording, sample rate=%d, "
			 "%d bits per sample, %d samples per buffer",
			 (err==0 ? "Success" : "Error"),
			 paDevInfo->name, param->samples_per_sec, 
			 param->bits_per_sample,
			 param->samples_per_frame * param->frames_per_packet));

    return stream;
}


PJ_DEF(pj_snd_stream*) pj_snd_open_player(int index,
					   const pj_snd_stream_info *param,
					   pj_snd_play_cb play_cb,
					   void *user_data)
{
    pj_pool_t *pool;
    pj_snd_stream *stream;
    PaStreamParameters outputParam;
    int sampleFormat;
    const PaDeviceInfo *paDevInfo = NULL;
    PaError err;

    if (index == -1) {
	int count = Pa_GetDeviceCount();
	for (index=0; index<count; ++index) {
	    paDevInfo = Pa_GetDeviceInfo(index);
	    if (paDevInfo->maxOutputChannels > 0)
		break;
	}
	if (index == count) {
	    PJ_LOG(2,(THIS_FILE, "Error: unable to find player device"));
	    return NULL;
	}
    } else {
	paDevInfo = Pa_GetDeviceInfo(index);
	if (!paDevInfo)
	    return NULL;
    }

    if (param->bits_per_sample == 8)
	sampleFormat = paUInt8;
    else if (param->bits_per_sample == 16)
	sampleFormat = paInt16;
    else if (param->bits_per_sample == 32)
	sampleFormat = paInt32;
    else
	return NULL;
    
    pool = pj_pool_create( snd_mgr.factory, "sndstream", 1024, 1024, NULL);
    if (!pool)
	return NULL;

    stream = pj_pool_calloc(pool, 1, sizeof(*stream));
    stream->pool = pool;
    stream->user_data = user_data;
    stream->samples_per_sec = param->samples_per_frame;
    stream->bytes_per_sample = param->bits_per_sample / 8;
    stream->dev_index = index;
    stream->play_cb = play_cb;

    pj_memset(&outputParam, 0, sizeof(outputParam));
    outputParam.device = index;
    outputParam.channelCount = 1;
    outputParam.hostApiSpecificStreamInfo = NULL;
    outputParam.sampleFormat = sampleFormat;
    outputParam.suggestedLatency = paDevInfo->defaultLowInputLatency;

    err = Pa_OpenStream( &stream->stream, NULL, &outputParam,
			 param->samples_per_sec, 
			 param->samples_per_frame * param->frames_per_packet, 
			 0,
			 &PaPlayerCallback, stream );
    if (err != paNoError) {
	pj_pool_release(pool);
	PJ_LOG(2,(THIS_FILE, "Error opening player: %s", Pa_GetErrorText(err)));
	return NULL;
    }

    PJ_LOG(4,(THIS_FILE, "%s opening device %s for playing, sample rate=%d, "
			 "%d bits per sample, %d samples per buffer",
			 (err==0 ? "Success" : "Error"),
			 paDevInfo->name, param->samples_per_sec, 
		 	 param->bits_per_sample,
			 param->samples_per_frame * param->frames_per_packet));

    return stream;
}


/*
 * Start stream.
 */
PJ_DEF(pj_status_t) pj_snd_stream_start(pj_snd_stream *stream)
{
    PJ_LOG(4,(THIS_FILE, "Starting stream.."));
    return Pa_StartStream(stream->stream);
}

/*
 * Stop stream.
 */
PJ_DEF(pj_status_t) pj_snd_stream_stop(pj_snd_stream *stream)
{
    int i, err;

    stream->quit_flag = 1;
    for (i=0; !stream->thread_has_exited && i<100; ++i)
	pj_thread_sleep(10);

    pj_thread_sleep(1);

    PJ_LOG(4,(THIS_FILE, "Stopping stream.."));

    err = Pa_StopStream(stream->stream);
    return err;
}

/*
 * Destroy stream.
 */
PJ_DEF(pj_status_t) pj_snd_stream_close(pj_snd_stream *stream)
{
    int i, err;
    const PaDeviceInfo *paDevInfo;

    stream->quit_flag = 1;
    for (i=0; !stream->thread_has_exited && i<100; ++i)
	pj_thread_sleep(10);

    pj_thread_sleep(1);

    paDevInfo = Pa_GetDeviceInfo(stream->dev_index);

    PJ_LOG(4,(THIS_FILE, "Closing %s: %lu underflow, %lu overflow",
			 paDevInfo->name,
			 stream->underflow, stream->overflow));

    err = Pa_CloseStream(stream->stream);
    pj_pool_release(stream->pool);
    return err;
}

/*
 * Deinitialize sound library.
 */
PJ_DEF(pj_status_t) pj_snd_deinit(void)
{
    PJ_LOG(4,(THIS_FILE, "PortAudio sound library shutting down.."));

    return Pa_Terminate();
}