Debian Codegraph @

Xpjproject/pjmedia/src/pjmedia-audiodev/oboe_dev.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19
20 /* This file is the implementation of Android Oboe audio device. */
21
22 #include <pjmedia-audiodev/audiodev_imp.h>
23 #include <pj/assert.h>
24 #include <pj/atomic_queue.h>
25 #include <pj/lock.h>
26 #include <pj/log.h>
27 #include <pj/os.h>
28 #include <pjmedia/circbuf.h>
29 #include <pjmedia/errno.h>
30 #include <pjmedia/event.h>
31
32 #if defined(PJMEDIA_AUDIO_DEV_HAS_OBOE) && PJMEDIA_AUDIO_DEV_HAS_OBOE != 0
33
34 #define THIS_FILE "oboe_dev.cpp"
35 #define DRIVER_NAME "Oboe"
36
37 #include <jni.h>
38 #include <semaphore.h>
39 #include <android/log.h>
40 #include <oboe/Oboe.h>
41
42 /* Setting of maximum number of consecutive stream restart attempts. */
43 #define MAX_RESTART 3
44
45 /* Device info */
46 typedef struct aud_dev_info
47 {
48 pjmedia_aud_dev_info info; /**< Base info */
49 int id; /**< Original dev ID */
50 } aud_dev_info;
51
52
53 /* Oboe factory */
54 struct oboe_aud_factory
55 {
56 pjmedia_aud_dev_factory base;
57 pj_pool_factory *pf;
58 pj_pool_t *pool;
59
60 pj_pool_t *dev_pool; /**< Device list pool */
61 unsigned dev_count; /**< Device count */
62 aud_dev_info *dev_info; /**< Device info list */
63 };
64
65 class MyOboeEngine;
66
67
68 /*
69 * Sound stream descriptor.
70 * This struct may be used for both unidirectional or bidirectional sound
71 * streams.
72 */
73 struct oboe_aud_stream
74 {
75 pjmedia_aud_stream base;
76 pj_pool_t *pool;
77 pj_str_t name;
78 pjmedia_dir dir;
79 pjmedia_aud_param param;
80 struct oboe_aud_factory *f;
81
82 int bytes_per_sample;
83 pj_uint32_t samples_per_sec;
84 unsigned samples_per_frame;
85 int channel_count;
86 void *user_data;
87 pj_bool_t running;
88
89 /* Capture/record */
90 MyOboeEngine *rec_engine;
91 pjmedia_aud_rec_cb rec_cb;
92
93 /* Playback */
94 MyOboeEngine *play_engine;
95 pjmedia_aud_play_cb play_cb;
96 };
97
98 /* Factory prototypes */
99 static pj_status_t oboe_init(pjmedia_aud_dev_factory *f);
100 static pj_status_t oboe_destroy(pjmedia_aud_dev_factory *f);
101 static pj_status_t oboe_refresh(pjmedia_aud_dev_factory *f);
102 static unsigned oboe_get_dev_count(pjmedia_aud_dev_factory *f);
103 static pj_status_t oboe_get_dev_info(pjmedia_aud_dev_factory *f,
104 unsigned index,
105 pjmedia_aud_dev_info *info);
106 static pj_status_t oboe_default_param(pjmedia_aud_dev_factory *f,
107 unsigned index,
108 pjmedia_aud_param *param);
109 static pj_status_t oboe_create_stream(pjmedia_aud_dev_factory *f,
110 const pjmedia_aud_param *param,
111 pjmedia_aud_rec_cb rec_cb,
112 pjmedia_aud_play_cb play_cb,
113 void *user_data,
114 pjmedia_aud_stream **p_aud_strm);
115
116 /* Stream prototypes */
117 static pj_status_t strm_get_param(pjmedia_aud_stream *strm,
118 pjmedia_aud_param *param);
119 static pj_status_t strm_get_cap(pjmedia_aud_stream *strm,
120 pjmedia_aud_dev_cap cap,
121 void *value);
122 static pj_status_t strm_set_cap(pjmedia_aud_stream *strm,
123 pjmedia_aud_dev_cap cap,
124 const void *value);
125 static pj_status_t strm_start(pjmedia_aud_stream *strm);
126 static pj_status_t strm_stop(pjmedia_aud_stream *strm);
127 static pj_status_t strm_destroy(pjmedia_aud_stream *strm);
128
129 static pjmedia_aud_dev_factory_op oboe_op =
130 {
131 &oboe_init,
132 &oboe_destroy,
133 &oboe_get_dev_count,
134 &oboe_get_dev_info,
135 &oboe_default_param,
136 &oboe_create_stream,
137 &oboe_refresh
138 };
139
140 static pjmedia_aud_stream_op oboe_strm_op =
141 {
142 &strm_get_param,
143 &strm_get_cap,
144 &strm_set_cap,
145 &strm_start,
146 &strm_stop,
147 &strm_destroy
148 };
149
150
151 /*
152 * Init Android Oboe audio driver.
153 */
154 #ifdef __cplusplus
155 extern "C"{
156 #endif
157 pjmedia_aud_dev_factory* pjmedia_android_oboe_factory(pj_pool_factory *pf)
158 {
159 struct oboe_aud_factory *f;
160 pj_pool_t *pool;
161
162 pool = pj_pool_create(pf, "oboe", 256, 256, NULL);
163 f = PJ_POOL_ZALLOC_T(pool, struct oboe_aud_factory);
164 f->pf = pf;
165 f->pool = pool;
166 f->base.op = &oboe_op;
167 f->dev_pool = pj_pool_create(pf, "oboe_dev", 256, 256, NULL);
168
169 return &f->base;
170 }
171 #ifdef __cplusplus
172 }
173 #endif
174
175
176 /* JNI stuff for enumerating audio devices. This will invoke Java code
177 * in pjmedia/src/pjmedia-audiodev/android/PjAudioDevInfo.java.
178 */
179 #define PJ_AUDDEV_INFO_CLASS_PATH "org/pjsip/PjAudioDevInfo"
180
181 static struct jni_objs_t
182 {
183 struct {
184 jclass cls;
185 jmethodID m_get_cnt;
186 jmethodID m_get_info;
187 jmethodID m_refresh;
188 jfieldID f_id;
189 jfieldID f_name;
190 jfieldID f_direction;
191 jfieldID f_sup_clockrates;
192 jfieldID f_sup_channels;
193 } dev_info;
194
195 struct {
196 jclass cls;
197 jmethodID m_current;
198 jmethodID m_get_app;
199 } activity_thread;
200
201 } jobjs;
202
203
204 #define GET_CLASS(class_path, class_name, cls) \
205 cls = jni_env->FindClass(class_path); \
206 if (cls == NULL || jni_env->ExceptionCheck()) { \
207 jni_env->ExceptionClear(); \
208 PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find class '" \
209 class_name "'")); \
210 status = PJMEDIA_EAUD_SYSERR; \
211 goto on_return; \
212 } else { \
213 jclass tmp = cls; \
214 cls = (jclass)jni_env->NewGlobalRef(tmp); \
215 jni_env->DeleteLocalRef(tmp); \
216 if (cls == NULL) { \
217 PJ_LOG(3, (THIS_FILE, "[JNI] Unable to get global ref for " \
218 "class '" class_name "'")); \
219 status = PJMEDIA_EAUD_SYSERR; \
220 goto on_return; \
221 } \
222 }
223 #define GET_METHOD_ID(cls, class_name, method_name, signature, id) \
224 id = jni_env->GetMethodID(cls, method_name, signature); \
225 if (id == 0) { \
226 PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find method '" method_name \
227 "' in class '" class_name "'")); \
228 status = PJMEDIA_EAUD_SYSERR; \
229 goto on_return; \
230 }
231 #define GET_SMETHOD_ID(cls, class_name, method_name, signature, id) \
232 id = jni_env->GetStaticMethodID(cls, method_name, signature); \
233 if (id == 0) { \
234 PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find static method '" \
235 method_name "' in class '" class_name "'")); \
236 status = PJMEDIA_EAUD_SYSERR; \
237 goto on_return; \
238 }
239 #define GET_FIELD_ID(cls, class_name, field_name, signature, id) \
240 id = jni_env->GetFieldID(cls, field_name, signature); \
241 if (id == 0) { \
242 PJ_LOG(3, (THIS_FILE, "[JNI] Unable to find field '" field_name \
243 "' in class '" class_name "'")); \
244 status = PJMEDIA_EAUD_SYSERR; \
245 goto on_return; \
246 }
247
248 /* Get Java object IDs (via FindClass, GetMethodID, GetFieldID, etc).
249 * Note that this function should be called from library-loader thread,
250 * otherwise FindClass, etc, may fail, see:
251 * http://developer.android.com/training/articles/perf-jni.html#faq_FindClass
252 */
253 static pj_status_t jni_init_ids()
254 {
255 JNIEnv *jni_env;
256 pj_status_t status = PJ_SUCCESS;
257 pj_bool_t with_attach = pj_jni_attach_jvm((void **)&jni_env);
258
259 /* PjAudioDevInfo class info */
260 GET_CLASS(PJ_AUDDEV_INFO_CLASS_PATH, "PjAudioDevInfo", jobjs.dev_info.cls);
261 GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "GetCount", "()I",
262 jobjs.dev_info.m_get_cnt);
263 GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "GetInfo",
264 "(I)L" PJ_AUDDEV_INFO_CLASS_PATH ";",
265 jobjs.dev_info.m_get_info);
266 GET_SMETHOD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "RefreshDevices",
267 "(Landroid/content/Context;)V",
268 jobjs.dev_info.m_refresh);
269 GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "id", "I",
270 jobjs.dev_info.f_id);
271 GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "name", "Ljava/lang/String;",
272 jobjs.dev_info.f_name);
273 GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "direction", "I",
274 jobjs.dev_info.f_direction);
275 GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "supportedClockRates", "[I",
276 jobjs.dev_info.f_sup_clockrates);
277 GET_FIELD_ID(jobjs.dev_info.cls, "PjAudioDevInfo", "supportedChannelCounts", "[I",
278 jobjs.dev_info.f_sup_channels);
279
280 /* ActivityThread class info */
281 GET_CLASS("android/app/ActivityThread", "ActivityThread",
282 jobjs.activity_thread.cls);
283 GET_SMETHOD_ID(jobjs.activity_thread.cls, "ActivityThread",
284 "currentActivityThread", "()Landroid/app/ActivityThread;",
285 jobjs.activity_thread.m_current);
286 GET_METHOD_ID(jobjs.activity_thread.cls, "ActivityThread",
287 "getApplication", "()Landroid/app/Application;",
288 jobjs.activity_thread.m_get_app);
289
290 on_return:
291 pj_jni_detach_jvm(with_attach);
292 return status;
293 }
294
295 #undef GET_CLASS_ID
296 #undef GET_METHOD_ID
297 #undef GET_SMETHOD_ID
298 #undef GET_FIELD_ID
299
300 static void jni_deinit_ids()
301 {
302 JNIEnv *jni_env;
303 pj_bool_t with_attach = pj_jni_attach_jvm((void **)&jni_env);
304
305 if (jobjs.dev_info.cls) {
306 jni_env->DeleteGlobalRef(jobjs.dev_info.cls);
307 jobjs.dev_info.cls = NULL;
308 }
309
310 if (jobjs.activity_thread.cls) {
311 jni_env->DeleteGlobalRef(jobjs.activity_thread.cls);
312 jobjs.activity_thread.cls = NULL;
313 }
314
315 pj_jni_detach_jvm(with_attach);
316 }
317
318 static jobject get_global_context(JNIEnv *jni_env)
319 {
320 jobject context = NULL;
321 jobject cur_at = jni_env->CallStaticObjectMethod(
322 jobjs.activity_thread.cls,
323 jobjs.activity_thread.m_current);
324 if (cur_at==NULL)
325 return NULL;
326
327 context = jni_env->CallObjectMethod(cur_at,
328 jobjs.activity_thread.m_get_app);
329 return context;
330 }
331
332
333 /* API: Init factory */
334 static pj_status_t oboe_init(pjmedia_aud_dev_factory *f)
335 {
336 pj_status_t status;
337
338 status = jni_init_ids();
339 if (status != PJ_SUCCESS)
340 return status;
341
342 status = oboe_refresh(f);
343 if (status != PJ_SUCCESS)
344 return status;
345
346 return PJ_SUCCESS;
347 }
348
349
350 /* API: refresh the list of devices */
351 static pj_status_t oboe_refresh(pjmedia_aud_dev_factory *ff)
352 {
353 struct oboe_aud_factory *f = (struct oboe_aud_factory*)ff;
354 JNIEnv *jni_env;
355 pj_bool_t with_attach;
356 int i, dev_count = 0;
357 pj_status_t status = PJ_SUCCESS;
358
359 /* Clean up device info and pool */
360 f->dev_count = 0;
361 pj_pool_reset(f->dev_pool);
362
363 with_attach = pj_jni_attach_jvm((void **)&jni_env);
364
365 jobject context = get_global_context(jni_env);
366 if (context == NULL) {
367 PJ_LOG(3, (THIS_FILE, "Failed to get context"));
368 status = PJMEDIA_EAUD_SYSERR;
369 goto on_return;
370 }
371
372 /* PjAudioDevInfo::RefreshDevices(Context) */
373 jni_env->CallStaticVoidMethod(jobjs.dev_info.cls,
374 jobjs.dev_info.m_refresh, context);
375
376 /* dev_count = PjAudioDevInfo::GetCount() */
377 dev_count = jni_env->CallStaticIntMethod(jobjs.dev_info.cls,
378 jobjs.dev_info.m_get_cnt);
379 if (dev_count < 0) {
380 PJ_LOG(3, (THIS_FILE, "Failed to get camera count"));
381 status = PJMEDIA_EAUD_SYSERR;
382 goto on_return;
383 }
384
385 /* Start querying device info */
386 f->dev_info = (aud_dev_info*)
387 pj_pool_calloc(f->dev_pool, dev_count,
388 sizeof(aud_dev_info));
389
390 for (i = 0; i < dev_count; i++) {
391 aud_dev_info *adi = &f->dev_info[f->dev_count];
392 pjmedia_aud_dev_info *base_adi = &adi->info;
393 jobject jdev_info;
394 jint jinttmp;
395
396 /* jdev_info = PjAudioDevInfo::GetInfo(i) */
397 jdev_info = jni_env->CallStaticObjectMethod(
398 jobjs.dev_info.cls,
399 jobjs.dev_info.m_get_info,
400 i);
401 if (jdev_info == NULL)
402 continue;
403
404 /* Get device ID, direction, etc */
405 adi->id = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_id);
406 jinttmp = jni_env->GetIntField(jdev_info, jobjs.dev_info.f_direction);
407 base_adi->input_count = (jinttmp & PJMEDIA_DIR_CAPTURE);
408 base_adi->output_count = (jinttmp & PJMEDIA_DIR_PLAYBACK);
409 base_adi->caps = 0;
410
411 /* Get name info */
412 jstring jstrtmp = (jstring)
413 jni_env->GetObjectField(jdev_info,
414 jobjs.dev_info.f_name);
415 const char *strtmp = jni_env->GetStringUTFChars(jstrtmp, NULL);
416 pj_ansi_strxcpy(base_adi->name, strtmp, sizeof(base_adi->name));
417 pj_ansi_strxcpy(base_adi->driver, DRIVER_NAME,
418 sizeof(base_adi->driver));
419
420 f->dev_count++;
421
422 jni_env->DeleteLocalRef(jdev_info);
423 }
424
425 PJ_LOG(4, (THIS_FILE,
426 "Oboe audio device initialized with %d device(s):",
427 f->dev_count));
428
429 for (i = 0; i < f->dev_count; i++) {
430 aud_dev_info *adi = &f->dev_info[i];
431 PJ_LOG(4, (THIS_FILE, "%2d (native id=%d): %s (%s%s%s)",
432 i, adi->id, adi->info.name,
433 adi->info.input_count?"in":"",
434 adi->info.input_count && adi->info.output_count?"+":"",
435 adi->info.output_count?"out":""
436 ));
437 }
438
439 on_return:
440 if (context)
441 jni_env->DeleteLocalRef(context);
442
443 pj_jni_detach_jvm(with_attach);
444 return status;
445 }
446
447
448 /* API: Destroy factory */
449 static pj_status_t oboe_destroy(pjmedia_aud_dev_factory *f)
450 {
451 struct oboe_aud_factory *pa = (struct oboe_aud_factory*)f;
452 pj_pool_t *pool;
453
454 PJ_LOG(4, (THIS_FILE, "Oboe sound library shutting down.."));
455
456 jni_deinit_ids();
457
458 pool = pa->pool;
459 pa->pool = NULL;
460 pj_pool_release(pool);
461
462 return PJ_SUCCESS;
463 }
464
465 /* API: Get device count. */
466 static unsigned oboe_get_dev_count(pjmedia_aud_dev_factory *ff)
467 {
468 struct oboe_aud_factory *f = (struct oboe_aud_factory*)ff;
469 return f->dev_count;
470 }
471
472 /* API: Get device info. */
473 static pj_status_t oboe_get_dev_info(pjmedia_aud_dev_factory *ff,
474 unsigned index,
475 pjmedia_aud_dev_info *info)
476 {
477 struct oboe_aud_factory *f = (struct oboe_aud_factory*)ff;
478
479 PJ_ASSERT_RETURN(index < f->dev_count, PJMEDIA_EAUD_INVDEV);
480
481 pj_memcpy(info, &f->dev_info[index].info, sizeof(*info));
482
483 return PJ_SUCCESS;
484 }
485
486 /* API: fill in with default parameter. */
487 static pj_status_t oboe_default_param(pjmedia_aud_dev_factory *ff,
488 unsigned index,
489 pjmedia_aud_param *param)
490 {
491 struct oboe_aud_factory *f = (struct oboe_aud_factory*)ff;
492 pjmedia_aud_dev_info adi;
493 pj_status_t status;
494
495 PJ_ASSERT_RETURN(index < f->dev_count, PJMEDIA_EAUD_INVDEV);
496
497 status = oboe_get_dev_info(ff, index, &adi);
498 if (status != PJ_SUCCESS)
499 return status;
500
501 pj_bzero(param, sizeof(*param));
502 if (adi.input_count && adi.output_count) {
503 param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK;
504 param->rec_id = index;
505 param->play_id = index;
506 } else if (adi.input_count) {
507 param->dir = PJMEDIA_DIR_CAPTURE;
508 param->rec_id = index;
509 param->play_id = PJMEDIA_AUD_INVALID_DEV;
510 } else if (adi.output_count) {
511 param->dir = PJMEDIA_DIR_PLAYBACK;
512 param->play_id = index;
513 param->rec_id = PJMEDIA_AUD_INVALID_DEV;
514 } else {
515 return PJMEDIA_EAUD_INVDEV;
516 }
517
518 param->clock_rate = adi.default_samples_per_sec;
519 param->channel_count = 1;
520 param->samples_per_frame = adi.default_samples_per_sec * 20 / 1000;
521 param->bits_per_sample = 16;
522 param->input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY;
523 param->output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY;
524
525 return PJ_SUCCESS;
526 }
527
528 /* Interface to Oboe */
529 class MyOboeEngine : oboe::AudioStreamDataCallback,
530 oboe::AudioStreamErrorCallback
531 {
532 public:
533 MyOboeEngine(struct oboe_aud_stream *stream_, pjmedia_dir dir_)
534 : stream(stream_), dir(dir_), oboe_stream(NULL), dir_st(NULL),
535 thread(NULL), thread_quit(PJ_TRUE), nrestart(0), queue(NULL),
536 err_thread_registered(false), mutex(NULL)
537 {
538 pj_assert(dir == PJMEDIA_DIR_CAPTURE || dir == PJMEDIA_DIR_PLAYBACK);
539 dir_st = (dir == PJMEDIA_DIR_CAPTURE? "capture":"playback");
540 pj_set_timestamp32(&ts, 0, 0);
541 }
542
543 pj_status_t Start() {
544 pj_status_t status;
545
546 if (!mutex) {
547 status = pj_mutex_create_recursive(stream->pool, "oboe", &mutex);
548 if (status != PJ_SUCCESS) {
549 PJ_PERROR(3,(THIS_FILE, status,
550 "Oboe stream %s failed creating mutex", dir_st));
551 return status;
552 }
553 }
554
555 int dev_id = 0;
556 oboe::PerformanceMode performance_mode;
557 oboe::AudioStreamBuilder sb;
558
559 pj_mutex_lock(mutex);
560
561 if (oboe_stream) {
562 pj_mutex_unlock(mutex);
563 return PJ_SUCCESS;
564 }
565
566 if (dir == PJMEDIA_DIR_CAPTURE) {
567 sb.setDirection(oboe::Direction::Input);
568 if (stream->param.rec_id >= 0 &&
569 stream->param.rec_id < stream->f->dev_count)
570 {
571 dev_id = stream->f->dev_info[stream->param.rec_id].id;
572 }
573 } else {
574 sb.setDirection(oboe::Direction::Output);
575 if (stream->param.play_id >= 0 &&
576 stream->param.play_id < stream->f->dev_count)
577 {
578 dev_id = stream->f->dev_info[stream->param.play_id].id;
579 }
580 }
581
582 if (PJMEDIA_OBOE_USE_LOWLATENCY) {
583 performance_mode= oboe::PerformanceMode::LowLatency;
584 } else {
585 performance_mode = oboe::PerformanceMode::None;
586 }
587
588 sb.setDeviceId(dev_id);
589 sb.setSampleRate(stream->param.clock_rate);
590 sb.setChannelCount(stream->param.channel_count);
591 sb.setPerformanceMode(performance_mode);
592 sb.setFormat(oboe::AudioFormat::I16);
593 sb.setUsage(oboe::Usage::VoiceCommunication);
594 sb.setInputPreset(oboe::InputPreset::VoiceCommunication);
595 sb.setContentType(oboe::ContentType::Speech);
596 sb.setDataCallback(this);
597 sb.setErrorCallback(this);
598 sb.setFramesPerDataCallback(stream->param.samples_per_frame /
599 stream->param.channel_count);
600
601 /* Somehow mic does not work on Samsung S10 (get no error and
602 * low latency, but callback is never invoked) if sample rate
603 * conversion is specified. If it is not specified (default is None),
604 * mic does not get low latency on, but it works.
605 */
606 if (dir == PJMEDIA_DIR_PLAYBACK) {
607 sb.setSampleRateConversionQuality(
608 oboe::SampleRateConversionQuality::High);
609
610 /* Also if mic is Exclusive, it won't reopen after
611 * plug/unplug headset (on Samsung S10).
612 */
613 sb.setSharingMode(oboe::SharingMode::Exclusive);
614 }
615
616 /* Create queue */
617 unsigned latency = (dir == PJMEDIA_DIR_CAPTURE?
618 stream->param.input_latency_ms :
619 stream->param.output_latency_ms);
620 unsigned queue_size = latency * stream->param.clock_rate *
621 stream->param.channel_count / 1000 /
622 stream->param.samples_per_frame;
623
624 /* Normalize queue size to be in range of 3-10 frames */
625 if (queue_size < 3) queue_size = 3;
626 if (queue_size > 10) queue_size = 10;
627
628 PJ_LOG(3,(THIS_FILE,
629 "Oboe stream %s queue size=%d frames (latency=%d ms)",
630 dir_st, queue_size, latency));
631
632 pj_atomic_queue_create(stream->pool, queue_size,
633 stream->param.samples_per_frame*2, dir_st,
634 &queue);
635
636 /* Create semaphore */
637 if (sem_init(&sem, 0, 0) != 0) {
638 pj_mutex_unlock(mutex);
639 return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
640 }
641
642 /* Create thread */
643 thread_quit = PJ_FALSE;
644 status = pj_thread_create(stream->pool, "android_oboe",
645 &AudioThread, this, 0, 0, &thread);
646 if (status != PJ_SUCCESS) {
647 pj_mutex_unlock(mutex);
648 return status;
649 }
650
651 /* Open & start oboe stream */
652 oboe::Result result = sb.openStream(&oboe_stream);
653 if (result != oboe::Result::OK) {
654 PJ_LOG(3,(THIS_FILE,
655 "Oboe stream %s open failed (err=%d/%s)",
656 dir_st, result, oboe::convertToText(result)));
657 pj_mutex_unlock(mutex);
658 return PJMEDIA_EAUD_SYSERR;
659 }
660
661 result = oboe_stream->requestStart();
662 if (result != oboe::Result::OK) {
663 PJ_LOG(3,(THIS_FILE,
664 "Oboe stream %s start failed (err=%d/%s)",
665 dir_st, result, oboe::convertToText(result)));
666 pj_mutex_unlock(mutex);
667 return PJMEDIA_EAUD_SYSERR;
668 }
669
670 PJ_LOG(4, (THIS_FILE,
671 "Oboe stream %s started, "
672 "id=%d, clock_rate=%d, channel_count=%d, "
673 "samples_per_frame=%d (%dms), "
674 "API=%d/%s, exclusive=%s, low latency=%s, "
675 "size per callback=%d, buffer capacity=%d, burst size=%d",
676 dir_st,
677 stream->param.play_id,
678 stream->param.clock_rate,
679 stream->param.channel_count,
680 stream->param.samples_per_frame,
681 stream->param.samples_per_frame * 1000 /
682 stream->param.clock_rate,
683 oboe_stream->getAudioApi(),
684 (oboe_stream->usesAAudio()? "AAudio":"other"),
685 (oboe_stream->getSharingMode()==
686 oboe::SharingMode::Exclusive? "yes":"no"),
687 (oboe_stream->getPerformanceMode()==
688 oboe::PerformanceMode::LowLatency? "yes":"no"),
689 oboe_stream->getFramesPerDataCallback()*
690 stream->param.channel_count,
691 oboe_stream->getBufferCapacityInFrames(),
692 oboe_stream->getFramesPerBurst()
693 ));
694
695 pj_mutex_unlock(mutex);
696 return PJ_SUCCESS;
697 }
698
699 void Stop() {
700 /* Just return if it has not been started */
701 if (!mutex || thread_quit) {
702 PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop request when "
703 "already stopped.", dir_st));
704 return;
705 }
706
707 PJ_LOG(5, (THIS_FILE, "Oboe stream %s stop requested.", dir_st));
708
709 pj_mutex_lock(mutex);
710
711 if (thread) {
712 PJ_LOG(5,(THIS_FILE, "Oboe %s stopping thread", dir_st));
713 thread_quit = PJ_TRUE;
714 sem_post(&sem);
715 pj_thread_join(thread);
716 pj_thread_destroy(thread);
717 thread = NULL;
718 }
719
720 if (oboe_stream) {
721 PJ_LOG(5,(THIS_FILE, "Oboe %s closing stream", dir_st));
722 oboe_stream->close();
723 delete oboe_stream;
724 oboe_stream = NULL;
725 }
726
727 if (queue) {
728 PJ_LOG(5,(THIS_FILE, "Oboe %s deleting queue", dir_st));
729 pj_atomic_queue_destroy(queue);
730 queue = NULL;
731 }
732
733 sem_destroy(&sem);
734
735 pj_mutex_unlock(mutex);
736
737 PJ_LOG(4, (THIS_FILE, "Oboe stream %s stopped.", dir_st));
738 }
739
740 /* Oboe callback, here let's just use Android native mutex & semaphore
741 * so we don't need to register the thread to PJLIB.
742 */
743 oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboeStream,
744 void *audioData,
745 int32_t numFrames)
746 {
747 if (dir == PJMEDIA_DIR_CAPTURE) {
748 /* Put the audio frame to queue */
749 pj_atomic_queue_put(this->queue, audioData);
750 } else {
751 /* Get audio frame from queue */
752 if (pj_atomic_queue_get(this->queue, audioData) != PJ_SUCCESS) {
753 pj_bzero(audioData, stream->param.samples_per_frame*2);
754 __android_log_write(ANDROID_LOG_WARN, THIS_FILE,
755 "Oboe playback got an empty queue");
756 }
757 }
758
759 this->nrestart = 0;
760 sem_post(&sem);
761
762 return (thread_quit? oboe::DataCallbackResult::Stop :
763 oboe::DataCallbackResult::Continue);
764 }
765
766 void onErrorAfterClose(oboe::AudioStream *oboeStream, oboe::Result result)
767 {
768 __android_log_print(ANDROID_LOG_INFO, THIS_FILE,
769 "Oboe %s got onErrorAfterClose(%d)",
770 dir_st, result);
771
772 /* Register callback thread */
773 if (!err_thread_registered || !pj_thread_is_registered())
774 {
775 pj_thread_t* tmp_thread;
776 pj_bzero(err_thread_desc, sizeof(pj_thread_desc));
777 pj_thread_register("oboe_err_thread", err_thread_desc,
778 &tmp_thread);
779 err_thread_registered = true;
780 }
781
782 /* Just try to restart */
783 pj_mutex_lock(mutex);
784
785 /* Make sure stop request has not been made */
786 if (!thread_quit) {
787 pj_status_t status;
788
789 PJ_LOG(3,(THIS_FILE,
790 "Oboe stream %s error (%d/%s)",
791 dir_st, result, oboe::convertToText(result)));
792
793 Stop();
794
795 if (nrestart < MAX_RESTART) {
796 ++nrestart;
797 PJ_LOG(3, (THIS_FILE, "Trying to restart Oboe %s stream #%d",
798 dir_st, nrestart));
799 status = Start();
800 } else {
801 status = PJMEDIA_EAUD_SYSERR;
802 }
803
804 if (status != PJ_SUCCESS) {
805 pjmedia_event e;
806
807 PJ_PERROR(3,(THIS_FILE, status, "Oboe stream restart failed"));
808
809 /* Broadcast Oboe error */
810 pjmedia_event_init(&e, PJMEDIA_EVENT_AUD_DEV_ERROR, &ts,
811 &stream->base);
812 e.data.aud_dev_err.dir = dir;
813 e.data.aud_dev_err.status = status;
814 e.data.aud_dev_err.id = (dir == PJMEDIA_DIR_PLAYBACK)?
815 stream->param.play_id :
816 stream->param.rec_id;
817
818 pjmedia_event_publish(NULL, &stream->base, &e,
819 PJMEDIA_EVENT_PUBLISH_DEFAULT);
820 }
821 }
822
823 pj_mutex_unlock(mutex);
824 }
825
826 ~MyOboeEngine() {
827 /* Oboe should have been stopped before destroying the engine.
828 * As stopping it here (below) may cause undefined behaviour when
829 * there is race condition against restart in onErrorAfterClose().
830 */
831 pj_assert(thread_quit == PJ_TRUE);
832
833 /* Forcefully stopping Oboe anyway */
834 Stop();
835
836 /* Try to trigger context switch in case onErrorAfterClose() is
837 * waiting for mutex.
838 */
839 pj_thread_sleep(1);
840
841 if (mutex)
842 pj_mutex_destroy(mutex);
843 }
844
845 private:
846
847 static int AudioThread(void *arg) {
848 MyOboeEngine *this_ = (MyOboeEngine*)arg;
849 struct oboe_aud_stream *stream = this_->stream;
850 pj_int16_t *tmp_buf;
851 unsigned ts_inc;
852 pj_status_t status;
853
854 /* Try to bump up the thread priority */
855 enum {
856 THREAD_PRIORITY_AUDIO = -16,
857 THREAD_PRIORITY_URGENT_AUDIO = -19
858 };
859 status = pj_thread_set_prio(NULL, THREAD_PRIORITY_URGENT_AUDIO);
860 if (status != PJ_SUCCESS) {
861 PJ_PERROR(3,(THIS_FILE, status,
862 "Warning: Oboe %s failed increasing thread priority",
863 this_->dir_st));
864 }
865
866 tmp_buf = new pj_int16_t[this_->stream->param.samples_per_frame]();
867 ts_inc = stream->param.samples_per_frame/stream->param.channel_count;
868
869 /* Queue a silent frame to playback buffer */
870 if (this_->dir == PJMEDIA_DIR_PLAYBACK) {
871 pj_atomic_queue_put(this_->queue, tmp_buf);
872 }
873
874 while (1) {
875 sem_wait(&this_->sem);
876 if (this_->thread_quit)
877 break;
878
879 if (this_->dir == PJMEDIA_DIR_CAPTURE) {
880 unsigned cnt = 0;
881 bool stop_stream = false;
882
883 /* Read audio frames from Oboe */
884 while (pj_atomic_queue_get(this_->queue, tmp_buf) == PJ_SUCCESS)
885 {
886 /* Send audio frame to app via callback rec_cb() */
887 pjmedia_frame frame;
888 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
889 frame.size = stream->param.samples_per_frame * 2;
890 frame.bit_info = 0;
891 frame.buf = (void *)tmp_buf;
892 frame.timestamp = this_->ts;
893 status = (*stream->rec_cb)(stream->user_data, &frame);
894 if (status != PJ_SUCCESS) {
895 /* App wants to stop audio dev stream */
896 stop_stream = true;
897 break;
898 }
899
900 /* Increment timestamp */
901 pj_add_timestamp32(&this_->ts, ts_inc);
902 ++cnt;
903 }
904
905 if (stop_stream)
906 break;
907
908 /* Print log for debugging purpose */
909 if (cnt == 0) {
910 PJ_LOG(5,(THIS_FILE, "Oboe %s got an empty queue",
911 this_->dir_st));
912 } else if (cnt > 1) {
913 PJ_LOG(5,(THIS_FILE, "Oboe %s got a burst of %d frames",
914 this_->dir_st, cnt));
915 }
916 } else {
917 /* Get audio frame from app via callback play_cb() */
918 pjmedia_frame frame;
919 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
920 frame.size = stream->param.samples_per_frame * 2;
921 frame.bit_info = 0;
922 frame.buf = (void *)tmp_buf;
923 frame.timestamp = this_->ts;
924 status = (*stream->play_cb)(stream->user_data, &frame);
925
926 /* Send audio frame to Oboe */
927 if (status == PJ_SUCCESS) {
928 pj_atomic_queue_put(this_->queue, tmp_buf);
929 } else {
930 /* App wants to stop audio dev stream */
931 break;
932 }
933
934 /* Increment timestamp */
935 pj_add_timestamp32(&this_->ts, ts_inc);
936 }
937 }
938
939 delete [] tmp_buf;
940
941 PJ_LOG(5,(THIS_FILE, "Oboe %s thread stopped", this_->dir_st));
942 return 0;
943 }
944
945 private:
946 struct oboe_aud_stream *stream;
947 pjmedia_dir dir;
948 oboe::AudioStream *oboe_stream;
949 const char *dir_st;
950 pj_thread_t *thread;
951 volatile pj_bool_t thread_quit;
952 unsigned nrestart;
953 sem_t sem;
954 pj_atomic_queue_t *queue;
955 pj_timestamp ts;
956 bool err_thread_registered;
957 pj_thread_desc err_thread_desc;
958 pj_mutex_t *mutex;
959
960 };
961
962
963 /* API: create stream */
964 static pj_status_t oboe_create_stream(pjmedia_aud_dev_factory *f,
965 const pjmedia_aud_param *param,
966 pjmedia_aud_rec_cb rec_cb,
967 pjmedia_aud_play_cb play_cb,
968 void *user_data,
969 pjmedia_aud_stream **p_aud_strm)
970 {
971 struct oboe_aud_factory *pa = (struct oboe_aud_factory*)f;
972 pj_pool_t *pool;
973 struct oboe_aud_stream *stream;
974 pj_status_t status = PJ_SUCCESS;
975
976 PJ_ASSERT_RETURN(param->channel_count >= 1 && param->channel_count <= 2,
977 PJ_EINVAL);
978 PJ_ASSERT_RETURN(param->bits_per_sample==8 || param->bits_per_sample==16,
979 PJ_EINVAL);
980 PJ_ASSERT_RETURN(play_cb && rec_cb && p_aud_strm, PJ_EINVAL);
981
982 pool = pj_pool_create(pa->pf, "oboestrm", 1024, 1024, NULL);
983 if (!pool)
984 return PJ_ENOMEM;
985
986 PJ_LOG(4, (THIS_FILE, "Creating Oboe stream"));
987
988 stream = PJ_POOL_ZALLOC_T(pool, struct oboe_aud_stream);
989 stream->pool = pool;
990 stream->f = pa;
991 pj_strdup2_with_null(pool, &stream->name, "Oboe stream");
992 stream->dir = param->dir;
993 pj_memcpy(&stream->param, param, sizeof(*param));
994 stream->user_data = user_data;
995 stream->rec_cb = rec_cb;
996 stream->play_cb = play_cb;
997
998 if (param->dir & PJMEDIA_DIR_CAPTURE) {
999 stream->rec_engine = new MyOboeEngine(stream, PJMEDIA_DIR_CAPTURE);
1000 if (!stream->rec_engine) {
1001 status = PJ_ENOMEM;
1002 goto on_error;
1003 }
1004 }
1005
1006 if (stream->dir & PJMEDIA_DIR_PLAYBACK) {
1007 stream->play_engine = new MyOboeEngine(stream, PJMEDIA_DIR_PLAYBACK);
1008 if (!stream->play_engine) {
1009 status = PJ_ENOMEM;
1010 goto on_error;
1011 }
1012 }
1013
1014 /* Done */
1015 stream->base.op = &oboe_strm_op;
1016 *p_aud_strm = &stream->base;
1017
1018 return PJ_SUCCESS;
1019
1020 on_error:
1021 strm_destroy(&stream->base);
1022 return status;
1023 }
1024
1025 /* API: Get stream parameters */
1026 static pj_status_t strm_get_param(pjmedia_aud_stream *s,
1027 pjmedia_aud_param *pi)
1028 {
1029 struct oboe_aud_stream *strm = (struct oboe_aud_stream*)s;
1030 PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL);
1031 pj_memcpy(pi, &strm->param, sizeof(*pi));
1032
1033 return PJ_SUCCESS;
1034 }
1035
1036 /* API: get capability */
1037 static pj_status_t strm_get_cap(pjmedia_aud_stream *s,
1038 pjmedia_aud_dev_cap cap,
1039 void *pval)
1040 {
1041 struct oboe_aud_stream *strm = (struct oboe_aud_stream*)s;
1042 pj_status_t status = PJMEDIA_EAUD_INVCAP;
1043
1044 PJ_UNUSED_ARG(strm);
1045
1046 PJ_ASSERT_RETURN(s && pval, PJ_EINVAL);
1047
1048 return status;
1049 }
1050
1051 /* API: set capability */
1052 static pj_status_t strm_set_cap(pjmedia_aud_stream *s,
1053 pjmedia_aud_dev_cap cap,
1054 const void *value)
1055 {
1056 struct oboe_aud_stream *strm = (struct oboe_aud_stream*)s;
1057
1058 PJ_UNUSED_ARG(strm);
1059
1060 PJ_ASSERT_RETURN(s && value, PJ_EINVAL);
1061
1062 return PJMEDIA_EAUD_INVCAP;
1063 }
1064
1065 /* API: start stream. */
1066 static pj_status_t strm_start(pjmedia_aud_stream *s)
1067 {
1068 struct oboe_aud_stream *stream = (struct oboe_aud_stream*)s;
1069 pj_status_t status;
1070
1071 if (stream->running)
1072 return PJ_SUCCESS;
1073
1074 if (stream->rec_engine) {
1075 status = stream->rec_engine->Start();
1076 if (status != PJ_SUCCESS)
1077 goto on_error;
1078 }
1079 if (stream->play_engine) {
1080 status = stream->play_engine->Start();
1081 if (status != PJ_SUCCESS)
1082 goto on_error;
1083 }
1084
1085 stream->running = PJ_TRUE;
1086 PJ_LOG(4, (THIS_FILE, "Oboe stream started"));
1087
1088 return PJ_SUCCESS;
1089
1090 on_error:
1091 if (stream->rec_engine)
1092 stream->rec_engine->Stop();
1093 if (stream->play_engine)
1094 stream->play_engine->Stop();
1095
1096 PJ_LOG(4, (THIS_FILE, "Failed starting Oboe stream"));
1097
1098 return status;
1099 }
1100
1101 /* API: stop stream. */
1102 static pj_status_t strm_stop(pjmedia_aud_stream *s)
1103 {
1104 struct oboe_aud_stream *stream = (struct oboe_aud_stream*)s;
1105
1106 if (!stream->running)
1107 return PJ_SUCCESS;
1108
1109 stream->running = PJ_FALSE;
1110
1111 if (stream->rec_engine)
1112 stream->rec_engine->Stop();
1113 if (stream->play_engine)
1114 stream->play_engine->Stop();
1115
1116 PJ_LOG(4,(THIS_FILE, "Oboe stream stopped"));
1117
1118 return PJ_SUCCESS;
1119 }
1120
1121 /* API: destroy stream. */
1122 static pj_status_t strm_destroy(pjmedia_aud_stream *s)
1123 {
1124 struct oboe_aud_stream *stream = (struct oboe_aud_stream*)s;
1125
1126 PJ_LOG(4,(THIS_FILE, "Destroying Oboe stream..."));
1127
1128 /* Stop the stream */
1129 strm_stop(s);
1130
1131 if (stream->rec_engine) {
1132 delete stream->rec_engine;
1133 stream->rec_engine = NULL;
1134 }
1135 if (stream->play_engine) {
1136 delete stream->play_engine;
1137 stream->play_engine = NULL;
1138 }
1139
1140 pj_pool_release(stream->pool);
1141 PJ_LOG(4, (THIS_FILE, "Oboe stream destroyed"));
1142
1143 return PJ_SUCCESS;
1144 }
1145
1146 #endif /* PJMEDIA_AUDIO_DEV_HAS_OBOE */