androidsound_opensles.cpp 32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * androidsound_opensles.cpp -Android Media plugin for Linphone, based on OpenSLES APIs.
 *
 * Copyright (C) 2014  Belledonne Communications, Grenoble, France
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <mediastreamer2/msfilter.h>
22
#include <mediastreamer2/msjava.h>
23 24
#include <mediastreamer2/msticker.h>
#include <mediastreamer2/mssndcard.h>
25
#include <mediastreamer2/devices.h>
26 27 28 29 30 31 32

#include <sys/types.h>
#include <string.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_AndroidConfiguration.h>
#include <jni.h>
33
#include <dlfcn.h>
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
namespace fake_opensles {
	SLInterfaceID SLW_IID_ENGINE = NULL;
	SLInterfaceID SLW_IID_ANDROIDSIMPLEBUFFERQUEUE = NULL;
	SLInterfaceID SLW_IID_ANDROIDCONFIGURATION = NULL;
	SLInterfaceID SLW_IID_RECORD = NULL;
	SLInterfaceID SLW_IID_VOLUME = NULL;
	SLInterfaceID SLW_IID_PLAY = NULL;

	typedef SLresult (*OpenSLESConstructor)(
		SLObjectItf*,
		SLuint32,
		const SLEngineOption*,
		SLuint32,
		const SLInterfaceID*,
		const SLboolean*
	);

	OpenSLESConstructor slwCreateEngine = NULL;

	int findSymbol(void *handle, SLInterfaceID &dest, const char *name) {
		SLInterfaceID *sym = (SLInterfaceID *) dlsym(handle, name);
		const char *error = dlerror();
		if (sym == NULL || error) {
			ms_error("Couldn't find %s symbol : %s", name, error);
			return 1;
		}
		dest = *sym;
		return 0;
	}

	int initOpenSLES() {
		int result = 0;
		void *handle;

		if ((handle = dlopen("libOpenSLES.so", RTLD_NOW)) == NULL){
			ms_warning("Fail to load libOpenSLES : %s", dlerror());
			result = -1;
		} else {
			dlerror(); // Clear previous message if present

			result += findSymbol(handle, SLW_IID_ENGINE, "SL_IID_ENGINE");
			result += findSymbol(handle, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE");
			result += findSymbol(handle, SLW_IID_ANDROIDCONFIGURATION, "SL_IID_ANDROIDCONFIGURATION");
			result += findSymbol(handle, SLW_IID_RECORD, "SL_IID_RECORD");
			result += findSymbol(handle, SLW_IID_VOLUME, "SL_IID_VOLUME");
			result += findSymbol(handle, SLW_IID_PLAY, "SL_IID_PLAY");

			slwCreateEngine = (OpenSLESConstructor) dlsym(handle, "slCreateEngine");
			if (slwCreateEngine == NULL) {
				result += 1;
				ms_error("Couldn't find slCreateEngine symbol");
			}
		}
		return result;
	}
}

92 93 94 95
static const int flowControlIntervalMs = 1000;
static const int flowControlThresholdMs = 40;

static int DeviceFavoriteSampleRate = 44100;
96
static int DeviceFavoriteBufferSize = 256;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_org_linphone_mediastream_MediastreamerAndroidContext_setDeviceFavoriteSampleRate(JNIEnv* env, jclass thiz, jint samplerate) {
	DeviceFavoriteSampleRate = (int)samplerate;
}

JNIEXPORT void JNICALL Java_org_linphone_mediastream_MediastreamerAndroidContext_setDeviceFavoriteBufferSize(JNIEnv* env, jclass thiz, jint buffersize) {
	DeviceFavoriteBufferSize = (int)buffersize;
}
#ifdef __cplusplus
}
#endif 

112 113
using namespace fake_opensles;

114
static MSSndCard *android_snd_card_new(void);
115 116
static MSFilter *ms_android_snd_read_new(MSFactory *factory);
static MSFilter *ms_android_snd_write_new(MSFactory* factory);
117 118 119 120 121 122 123 124 125 126 127 128

struct OpenSLESContext {
	OpenSLESContext() {
		samplerate = DeviceFavoriteSampleRate;
		nchannels = 1;
		builtin_aec = false;
	}

	int samplerate;
	int nchannels;
	bool builtin_aec;

129 130
	SLObjectItf engineObject;
	SLEngineItf engineEngine;
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
};

struct OpenSLESOutputContext {
	OpenSLESOutputContext() {
		streamType = SL_ANDROID_STREAM_VOICE;
		nbufs = 0;
		outBufSize = DeviceFavoriteBufferSize;
		ms_bufferizer_init(&buffer);
		ms_mutex_init(&mutex,NULL);

		currentBuffer = 0;
		playBuffer[0] = (uint8_t *) calloc(outBufSize, sizeof(uint8_t));
		playBuffer[1] = (uint8_t *) calloc(outBufSize, sizeof(uint8_t));
	}

	~OpenSLESOutputContext() {
		free(playBuffer[0]);
		free(playBuffer[1]);
		ms_bufferizer_uninit(&buffer);
		ms_mutex_destroy(&mutex);
	}

	void setContext(OpenSLESContext *context) {
		opensles_context = context;
	}

	OpenSLESContext *opensles_context;

	SLObjectItf outputMixObject;
	SLObjectItf playerObject;
	SLPlayItf playerPlay;
	SLAndroidSimpleBufferQueueItf playerBufferQueue;
	SLAndroidConfigurationItf playerConfig;
	SLint32 streamType;

	MSBufferizer buffer;
	int nbufs;
	ms_mutex_t mutex;
	uint64_t flowControlStart;
	int minBufferFilling;

	uint8_t *playBuffer[2];
	int outBufSize;
	int currentBuffer;
};

struct OpenSLESInputContext {
	OpenSLESInputContext() {
179
		streamType = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION;
180 181 182 183 184
		inBufSize = DeviceFavoriteBufferSize;
		qinit(&q);
		ms_mutex_init(&mutex,NULL);
		mTickerSynchronizer = NULL;
		aec = NULL;
185
		mAvSkew = 0;
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
		
		currentBuffer = 0;
		recBuffer[0] = (uint8_t *) calloc(inBufSize, sizeof(uint8_t));
		recBuffer[1] = (uint8_t *) calloc(inBufSize, sizeof(uint8_t));
	}

	~OpenSLESInputContext() {
		free(recBuffer[0]);
		free(recBuffer[1]);
		flushq(&q,0);
		ms_mutex_destroy(&mutex);
	}

	void setContext(OpenSLESContext *context) {
		opensles_context = context;
	}

	OpenSLESContext *opensles_context;

	SLObjectItf recorderObject;
	SLRecordItf recorderRecord;
	SLAndroidSimpleBufferQueueItf recorderBufferQueue;
	SLAndroidConfigurationItf recorderConfig;
	SLint32 streamType;

	queue_t q;
	ms_mutex_t mutex;
	MSTickerSynchronizer *mTickerSynchronizer;
	MSFilter *mFilter;
	int64_t read_samples;
	jobject aec;

	uint8_t *recBuffer[2];
	int inBufSize;
	int currentBuffer;
221
	double mAvSkew;
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
};

static SLuint32 convertSamplerate(int samplerate)
{
    switch(samplerate) {
    case 8000:
        return SL_SAMPLINGRATE_8;
        break;
    case 16000:
        return SL_SAMPLINGRATE_16;
        break;
    case 22050:
        return SL_SAMPLINGRATE_22_05;
        break;
    case 32000:
        return SL_SAMPLINGRATE_32;
        break;
    case 44100:
        return SL_SAMPLINGRATE_44_1;
        break;
    case 48000:
        return SL_SAMPLINGRATE_48;
        break;
    default:
        return -1;
    }
}

static void android_snd_card_detect(MSSndCardManager *m) {
	
252 253 254 255
	if (initOpenSLES() == 0) { // Try to dlopen libOpenSLES
		ms_message("libOpenSLES correctly loaded, creating OpenSLES MS soundcard");
		MSSndCard *card = android_snd_card_new();
		ms_snd_card_manager_add_card(m, card);
256
	} else {
257
		ms_warning("Failed to dlopen libOpenSLES, OpenSLES MS soundcard unavailable");
258 259 260 261 262 263
	}
}

static SLresult opensles_engine_init(OpenSLESContext *ctx) {
	SLresult result;

264 265
	result = slwCreateEngine(&(ctx->engineObject), 0, NULL, 0, NULL, NULL);
	if (result != SL_RESULT_SUCCESS) {
266
		ms_error("OpenSLES Error %u while creating SL engine", result);
267
		return result;
268 269
	}

270 271
	result = (*ctx->engineObject)->Realize(ctx->engineObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
272
		ms_error("OpenSLES Error %u while realizing SL engine", result);
273
		return result;
274 275
	}

276
	result = (*ctx->engineObject)->GetInterface(ctx->engineObject, SLW_IID_ENGINE, &(ctx->engineEngine));
277 278 279

	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while getting SL engine interface", result);
280
		return result;
281 282
	}

283
	return result;
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
}

static OpenSLESContext* opensles_context_init() {
	OpenSLESContext* ctx = new OpenSLESContext();
	opensles_engine_init(ctx);
	return ctx;
} 

static void android_native_snd_card_init(MSSndCard *card) {

}

static void android_native_snd_card_uninit(MSSndCard *card) {
	OpenSLESContext *ctx = (OpenSLESContext*)card->data;
	ms_warning("Deletion of OpenSLES context [%p]", ctx);
	if (ctx->engineObject != NULL) {
                (*ctx->engineObject)->Destroy(ctx->engineObject);
                ctx->engineObject = NULL;
                ctx->engineEngine = NULL;
        }
}

static SLresult opensles_recorder_init(OpenSLESInputContext *ictx) {
	SLresult result;
	SLuint32 sample_rate = convertSamplerate(ictx->opensles_context->samplerate);
309
	SLuint32 channels = (SLuint32) ictx->opensles_context->nchannels;
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

	SLDataLocator_IODevice loc_dev = {
		SL_DATALOCATOR_IODEVICE,
		SL_IODEVICE_AUDIOINPUT,
		SL_DEFAULTDEVICEID_AUDIOINPUT,
		NULL
	};

	SLDataSource audio_src = {
		&loc_dev,
		NULL
	};

	SLDataLocator_AndroidSimpleBufferQueue loc_bq = {
		SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
		2
	};

	SLDataFormat_PCM format_pcm = {
		SL_DATAFORMAT_PCM,
330
		channels,
331 332 333 334 335 336 337 338 339 340 341 342 343
		sample_rate,
		SL_PCMSAMPLEFORMAT_FIXED_16,
		SL_PCMSAMPLEFORMAT_FIXED_16,
		SL_SPEAKER_FRONT_CENTER,
		SL_BYTEORDER_LITTLEENDIAN
	};

	SLDataSink audio_sink = {
		&loc_bq,
		&format_pcm
	};

	const SLInterfaceID ids[] = {
344 345
		SLW_IID_ANDROIDSIMPLEBUFFERQUEUE,
		SLW_IID_ANDROIDCONFIGURATION
346 347 348 349 350 351 352 353 354 355 356 357 358
	};

	const SLboolean req[] = {
		SL_BOOLEAN_TRUE,
		SL_BOOLEAN_TRUE
	};

	result = (*ictx->opensles_context->engineEngine)->CreateAudioRecorder(ictx->opensles_context->engineEngine, &ictx->recorderObject, &audio_src, &audio_sink, 2, ids, req);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while creating the audio recorder", result);
		return result;
	}

359
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_ANDROIDCONFIGURATION, &ictx->recorderConfig);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while getting the recorder's android config interface", result);
		return result;
	}

	result = (*ictx->recorderConfig)->SetConfiguration(ictx->recorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &ictx->streamType, sizeof(SLint32));
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while setting the audio recorder configuration", result);
		return result;
	}

	result = (*ictx->recorderObject)->Realize(ictx->recorderObject, SL_BOOLEAN_FALSE);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while realizing the audio recorder", result);
		return result;
	}

377
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_RECORD, &ictx->recorderRecord);
378 379 380 381 382
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while getting the audio recorder's interface", result);
		return result;
	}

383
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, &ictx->recorderBufferQueue);
384 385 386 387 388 389 390 391 392 393 394 395 396
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while getting the audio recorder's buffer interface", result);
		return result;
	}

	return result;
}

static void compute_timespec(OpenSLESInputContext *ictx) {
	uint64_t ns = ((1000 * ictx->read_samples) / (uint64_t) ictx->opensles_context->samplerate) * 1000000;
	MSTimeSpec ts;
	ts.tv_nsec = ns % 1000000000;
	ts.tv_sec = ns / 1000000000;
397
	ictx->mAvSkew = ms_ticker_synchronizer_set_external_time(ictx->mTickerSynchronizer, &ts);
398 399
}

400 401 402 403 404 405 406

/*
 * This is a callback function called by AudioRecord's thread. This thread is not created by ortp/ms2 and is not able to attach to a JVM without crashing
 * at the end, despite it is detached (since android 4.4).
 * We must not output a single log within this callback in the event that the application is using LinphoneCoreFactory.setLogHandler(), in which case
 * the log would be upcalled to java, which will attach the thread to the jvm.
**/
407 408 409 410 411 412
static void opensles_recorder_callback(SLAndroidSimpleBufferQueueItf bq, void *context) {
	SLresult result;
	OpenSLESInputContext *ictx = (OpenSLESInputContext *)context;

	if (ictx->mTickerSynchronizer == NULL) {
		MSFilter *obj = ictx->mFilter;
413 414 415 416 417 418 419
		/*
		 * ABSOLUTE HORRIBLE HACK. We temporarily disable logs to prevent ms_ticker_set_time_func() to output a debug log.
		 * This is horrible because this also suspends logs for all concurrent threads during these two lines of code.
		 * Possible way to do better:
		 *  1) understand why AudioRecord thread doesn't detach.
		 *  2) disable logs just for this thread (using a TLS)
		 */
Simon Morlat's avatar
Simon Morlat committed
420 421
		int loglevel=ortp_get_log_level_mask(ORTP_LOG_DOMAIN);
		ortp_set_log_level_mask(ORTP_LOG_DOMAIN, ORTP_ERROR|ORTP_FATAL);
422
		ictx->mTickerSynchronizer = ms_ticker_synchronizer_new();
423
		ms_ticker_set_time_func(obj->ticker,(uint64_t (*)(void*))ms_ticker_synchronizer_get_corrected_time, ictx->mTickerSynchronizer);
Simon Morlat's avatar
Simon Morlat committed
424
		ortp_set_log_level_mask(ORTP_LOG_DOMAIN, loglevel);
425 426 427 428 429 430 431 432 433 434 435 436 437 438
	}
	ictx->read_samples += ictx->inBufSize / sizeof(int16_t);

	mblk_t *m = allocb(ictx->inBufSize, 0);
	memcpy(m->b_wptr, ictx->recBuffer[ictx->currentBuffer], ictx->inBufSize);
	m->b_wptr += ictx->inBufSize;

	ms_mutex_lock(&ictx->mutex);
	compute_timespec(ictx);
	putq(&ictx->q, m);
	ms_mutex_unlock(&ictx->mutex);

 	result = (*ictx->recorderBufferQueue)->Enqueue(ictx->recorderBufferQueue, ictx->recBuffer[ictx->currentBuffer], ictx->inBufSize);
	if (result != SL_RESULT_SUCCESS) {
439
		/*ms_error("OpenSLES Error %u while enqueueing record buffer", result);*/
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	}
	ictx->currentBuffer = ictx->currentBuffer == 1 ? 0 : 1;
}

static SLresult opensles_recorder_callback_init(OpenSLESInputContext *ictx) {
	SLresult result;

	result = (*ictx->recorderBufferQueue)->RegisterCallback(ictx->recorderBufferQueue, opensles_recorder_callback, ictx);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while realizing the audio recorder", result);
		return result;
	}

	// in case already recording, stop recording and clear buffer queue
	result = (*ictx->recorderRecord)->SetRecordState(ictx->recorderRecord, SL_RECORDSTATE_STOPPED);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while stopping the audio recorder", result);
		return result;
	}

	result = (*ictx->recorderBufferQueue)->Clear(ictx->recorderBufferQueue);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while clearing the audio recorder buffer queue", result);
		return result;
	}

	result = (*ictx->recorderRecord)->SetRecordState(ictx->recorderRecord, SL_RECORDSTATE_RECORDING);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while starting the audio recorder", result);
		return result;
	}

	result = (*ictx->recorderBufferQueue)->Enqueue(ictx->recorderBufferQueue, ictx->recBuffer[0], ictx->inBufSize);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while enqueueing record buffer", result);
	}

	result = (*ictx->recorderBufferQueue)->Enqueue(ictx->recorderBufferQueue, ictx->recBuffer[1], ictx->inBufSize);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while enqueueing record buffer", result);
	}

	return result;
}

static OpenSLESInputContext* opensles_input_context_init() {
	OpenSLESInputContext* ictx = new OpenSLESInputContext();
	return ictx;
}

static void android_snd_read_init(MSFilter *obj) {
	OpenSLESInputContext *ictx = opensles_input_context_init();
	obj->data = ictx;
}

static void android_snd_read_preprocess(MSFilter *obj) {
	OpenSLESInputContext *ictx = (OpenSLESInputContext*) obj->data;
	ictx->mFilter = obj;
	ictx->read_samples = 0;
	opensles_recorder_init(ictx);
	opensles_recorder_callback_init(ictx);
	if (ictx->opensles_context->builtin_aec) { 
		//android_snd_read_activate_hardware_aec(obj);
	}
}

static void android_snd_read_process(MSFilter *obj) {
	OpenSLESInputContext *ictx = (OpenSLESInputContext*) obj->data;
	mblk_t *m;

	ms_mutex_lock(&ictx->mutex);
	while ((m = getq(&ictx->q)) != NULL) {
		ms_queue_put(obj->outputs[0], m);
	}
	ms_mutex_unlock(&ictx->mutex);
515 516 517
	if (obj->ticker->time % 5000 == 0)
			ms_message("sound/wall clock skew is average=%g ms", ictx->mAvSkew);
	
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
}

static void android_snd_read_postprocess(MSFilter *obj) {
	SLresult result;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;

	ms_ticker_set_time_func(obj->ticker, NULL, NULL);
	ms_mutex_lock(&ictx->mutex);
	ms_ticker_synchronizer_destroy(ictx->mTickerSynchronizer);
	ictx->mTickerSynchronizer = NULL;
	ms_mutex_unlock(&ictx->mutex);

	if (ictx->aec) {
		JNIEnv *env = ms_get_jni_env();
		env->DeleteGlobalRef(ictx->aec);
		ictx->aec = NULL;
	}

	result = (*ictx->recorderRecord)->SetRecordState(ictx->recorderRecord, SL_RECORDSTATE_STOPPED);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while stopping the audio recorder", result);
	}

	result = (*ictx->recorderBufferQueue)->Clear(ictx->recorderBufferQueue);
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while clearing the audio recorder buffer queue", result);
	}

	if (ictx->recorderObject != NULL)
547 548 549 550 551 552
	{
			(*ictx->recorderObject)->Destroy(ictx->recorderObject);
			ictx->recorderObject = NULL;
			ictx->recorderRecord = NULL;
			ictx->recorderBufferQueue = NULL;
	}
553 554 555 556 557 558 559 560
}

static void android_snd_read_uninit(MSFilter *obj) {
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
	delete ictx;
}

static int android_snd_read_set_sample_rate(MSFilter *obj, void *data) {
561
#if 0
562 563
	int *n = (int*)data;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
564 565 566 567
	if (ictx->opensles_context->forced_sample_rate > 0) {
		ms_warning("Sample rate is forced by mediastreamer2 device table, skipping...");
		return -1;
	}
568 569
	ictx->opensles_context->samplerate = *n;
	return 0;
570 571
#endif
	return -1; /*don't accept custom sample rates, use recommended rate always*/
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
}

static int android_snd_read_get_sample_rate(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
	*n = ictx->opensles_context->samplerate;
	return 0;
}

static int android_snd_read_set_nchannels(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
	ictx->opensles_context->nchannels = *n;
	return 0;
}

static int android_snd_read_get_nchannels(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
	*n = ictx->opensles_context->nchannels;
	return 0;
}

static int android_snd_read_hack_speaker_state(MSFilter *f, void *arg) {
	return 0;
}

599
static MSFilterMethod android_snd_read_methods[] = {
600 601 602 603 604 605 606 607
	{MS_FILTER_SET_SAMPLE_RATE, android_snd_read_set_sample_rate},
	{MS_FILTER_GET_SAMPLE_RATE, android_snd_read_get_sample_rate},
	{MS_FILTER_SET_NCHANNELS, android_snd_read_set_nchannels},
	{MS_FILTER_GET_NCHANNELS, android_snd_read_get_nchannels},
	{MS_AUDIO_CAPTURE_FORCE_SPEAKER_STATE, android_snd_read_hack_speaker_state},
	{0,NULL}
};

608
MSFilterDesc android_snd_opensles_read_desc = {
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
	MS_FILTER_PLUGIN_ID,
	"MSOpenSLESRecorder",
	"android sound source",
	MS_FILTER_OTHER,
	NULL,
	0,
	1,
	android_snd_read_init,
	android_snd_read_preprocess,
	android_snd_read_process,
	android_snd_read_postprocess,
	android_snd_read_uninit,
	android_snd_read_methods
};

624 625
static MSFilter* ms_android_snd_read_new(MSFactory *factory) {
	MSFilter *f = ms_factory_create_filter_from_desc(factory, &android_snd_opensles_read_desc);
626 627 628 629
	return f;
}

static MSFilter *android_snd_card_create_reader(MSSndCard *card) {
630
	MSFilter *f = ms_android_snd_read_new(ms_snd_card_get_factory(card));
631 632 633 634 635 636 637
	OpenSLESInputContext *ictx = static_cast<OpenSLESInputContext*>(f->data);
	ictx->setContext((OpenSLESContext*)card->data);
	return f;
}

static SLresult opensles_mixer_init(OpenSLESOutputContext *octx) {
	SLresult result;
638 639 640 641 642
	const SLuint32 nbInterface = 0;
	const SLInterfaceID ids[] = {};
	const SLboolean req[] = {};
	result = (*octx->opensles_context->engineEngine)->CreateOutputMix(octx->opensles_context->engineEngine, &(octx->outputMixObject), nbInterface, ids, req);
	if (result != SL_RESULT_SUCCESS) {
643 644 645
		ms_error("OpenSLES Error %u while creating output mixer", result);
		return result;
	}
646

647 648 649
	result = (*octx->outputMixObject)->Realize(octx->outputMixObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while realizing output mixer", result);
650
		return result;
651
	}
652

653
	return result;
654 655 656 657
}

static SLresult opensles_sink_init(OpenSLESOutputContext *octx) {
	SLresult result;
658
	SLuint32 sample_rate = convertSamplerate(octx->opensles_context->samplerate);
659
	SLuint32 channels = (SLuint32) octx->opensles_context->nchannels;
660 661
	SLDataFormat_PCM format_pcm;

662
	format_pcm.formatType = SL_DATAFORMAT_PCM;
663 664 665 666 667
	format_pcm.numChannels = channels;
	format_pcm.samplesPerSec = sample_rate;
	format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
	format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
	format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
668
	if (channels == 1) {
669
		format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
670
	} else if (channels == 2) {
671
		format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
672
	} else {
673
		ms_error("OpenSLES Error trying to use %i channels", channels);
674
	}
675

676 677 678 679
	SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
		SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 
		2
	};
680

681 682 683 684
	SLDataSource audio_src = {
		&loc_bufq,
		&format_pcm
	};
685

686 687 688 689
	SLDataLocator_OutputMix loc_outmix = {
		SL_DATALOCATOR_OUTPUTMIX,
		octx->outputMixObject
	};
690

691 692 693 694
	SLDataSink audio_sink = {
		&loc_outmix,
		NULL
	};
695

696 697 698 699
	const SLuint32 nbInterface = 2;
	const SLInterfaceID ids[] = { SLW_IID_VOLUME, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE };
	const SLboolean req[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
	result = (*octx->opensles_context->engineEngine)->CreateAudioPlayer(octx->opensles_context->engineEngine, &(octx->playerObject), &audio_src, &audio_sink, nbInterface, ids, req);
700
	if (result != SL_RESULT_SUCCESS) {
701 702
		ms_error("OpenSLES Error %u while creating ouput audio player", result);
		return result;
703
	}
704

705
	/*result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_ANDROIDCONFIGURATION, &octx->playerConfig);
706
	if (result != SL_RESULT_SUCCESS) {
707
		ms_error("OpenSLES Error %u while getting android configuration interface", result);
708
		return result;
709
	}*/
710

711
	/*result = (*octx->playerConfig)->SetConfiguration(octx->playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &octx->streamType, sizeof(SLint32));
712
	if (result != SL_RESULT_SUCCESS) {
713
		ms_error("OpenSLES Error %u while setting stream type configuration", result);
714
		return result;
715
	}*/
716

717 718
	result = (*octx->playerObject)->Realize(octx->playerObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
719
		ms_error("OpenSLES Error %u while realizing output sink", result);
720
		return result;
721 722
	}

723 724
	result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_PLAY, &(octx->playerPlay));
	if (result != SL_RESULT_SUCCESS) {
725
		ms_error("OpenSLES Error %u while getting output sink interface play", result);
726
		return result;
727 728
	}

729 730
	result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, &(octx->playerBufferQueue));
	if (result != SL_RESULT_SUCCESS) {
731
		ms_error("OpenSLES Error %u while getting output sink interface buffer queue", result);
732
		return result;
733 734
	}

735
	return result;
736 737
}

738 739 740 741 742 743 744
/*
 * This is a callback function called by AudioTrack's thread. This thread is not created by ortp/ms2 and is not able to attach to a JVM without crashing
 * at the end, despite it is detached (since android 4.4).
 * We must not output a single log within this callback in the event that the application is using LinphoneCoreFactory.setLogHandler(), in which case
 * the log would be upcalled to java, which will attach the thread to the jvm.
**/

745 746 747 748 749 750 751 752 753 754
static void opensles_player_callback(SLAndroidSimpleBufferQueueItf bq, void* context) {
	SLresult result;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)context;

	ms_mutex_lock(&octx->mutex);
	int ask = octx->outBufSize;
	int avail = ms_bufferizer_get_avail(&octx->buffer);
	int bytes = MIN(ask, avail);

	if ((octx->nbufs == 0) && (avail > (ask * 2))) {
755
		/*ms_warning("OpenSLES skipping %i bytes", avail - (ask * 2) );*/
756 757 758 759
		ms_bufferizer_skip_bytes(&octx->buffer, avail - (ask * 2));
	}

	if (avail != 0) {
Ghislain MARY's avatar
Ghislain MARY committed
760
		if (octx->minBufferFilling == -1) {
761 762 763 764 765 766 767 768 769 770 771
			octx->minBufferFilling = avail;
		} else if (avail < octx->minBufferFilling) {
			octx->minBufferFilling = avail;
		}
	}

	if (bytes > 0) {
		bytes = ms_bufferizer_read(&octx->buffer, octx->playBuffer[octx->currentBuffer], bytes);
	} else {
		/* we have an underrun (no more samples to deliver to the callback). We need to reset minBufferFilling*/
		octx->minBufferFilling = -1;
772 773 774
		/*provide soundcard with a silence buffer*/
		bytes = ask;
		memset(octx->playBuffer[octx->currentBuffer], 0, bytes);
775 776 777 778 779 780
	}
	ms_mutex_unlock(&octx->mutex);
	octx->nbufs++;

 	result = (*octx->playerBufferQueue)->Enqueue(octx->playerBufferQueue, octx->playBuffer[octx->currentBuffer], bytes);
	if (result != SL_RESULT_SUCCESS) {
781
		/*ms_error("OpenSLES Error %u while adding buffer to output queue", result);*/
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
	}
	octx->currentBuffer = octx->currentBuffer == 1 ? 0 : 1;
}

static SLresult opensles_player_callback_init(OpenSLESOutputContext *octx) {
	SLresult result;

	result = (*octx->playerPlay)->SetPlayState(octx->playerPlay, SL_PLAYSTATE_STOPPED);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while stopping player", result);
		return result;
	}

	result = (*octx->playerBufferQueue)->Clear(octx->playerBufferQueue);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while clearing player buffer queue", result);
		return result;
	}

801 802
	result = (*octx->playerBufferQueue)->RegisterCallback(octx->playerBufferQueue, opensles_player_callback, octx);
	if (result != SL_RESULT_SUCCESS) {
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
		ms_error("OpenSLES Error %u while registering player callback", result);
		return result;
	}

	result = (*octx->playerBufferQueue)->Enqueue(octx->playerBufferQueue, octx->playBuffer[0], octx->outBufSize);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while adding buffer to output queue", result);
	}

	result = (*octx->playerBufferQueue)->Enqueue(octx->playerBufferQueue, octx->playBuffer[1], octx->outBufSize);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while adding buffer to output queue", result);
	}

        result = (*octx->playerPlay)->SetPlayState(octx->playerPlay, SL_PLAYSTATE_PLAYING);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while starting player", result);
		return result;
	}

        return result;
}

static OpenSLESOutputContext* opensles_output_context_init() {
	OpenSLESOutputContext* octx = new OpenSLESOutputContext();
	return octx;
}

static MSFilter *android_snd_card_create_writer(MSSndCard *card) {
832
	MSFilter *f = ms_android_snd_write_new(ms_snd_card_get_factory(card));
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
	OpenSLESOutputContext *octx = static_cast<OpenSLESOutputContext*>(f->data);
	octx->setContext((OpenSLESContext*)card->data);
	return f;
}

static void android_snd_write_init(MSFilter *obj){
	OpenSLESOutputContext *octx = opensles_output_context_init();
	obj->data = octx;
}

static void android_snd_write_uninit(MSFilter *obj){
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
	delete octx;
}

static int android_snd_write_set_sample_rate(MSFilter *obj, void *data) {
849
#if 0
850 851
	int *n = (int*)data;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
852 853 854 855
	if (octx->opensles_context->forced_sample_rate > 0) {
		ms_warning("Sample rate is forced by mediastreamer2 device table, skipping...");
		return -1;
	}
856 857
	octx->opensles_context->samplerate = *n;
	return 0;
858 859
#endif
	return -1; /*don't accept custom sample rates, use recommended rate always*/
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
}

static int android_snd_write_get_sample_rate(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
	*n = octx->opensles_context->samplerate;
	return 0;
}

static int android_snd_write_set_nchannels(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
	octx->opensles_context->nchannels = *n;
	return 0;
}

static int android_snd_write_get_nchannels(MSFilter *obj, void *data) {
	int *n = (int*)data;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
	*n = octx->opensles_context->nchannels;
	return 0;
}

static void android_snd_write_preprocess(MSFilter *obj) {
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
	SLresult result;
	
	result = opensles_mixer_init(octx);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("Couldn't init OpenSLES mixer");
		return;
	}
	result = opensles_sink_init(octx);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("Couldn't init OpenSLES sink");
		return;
	}
	result = opensles_player_callback_init(octx);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("Couldn't init OpenSLES player");
		return;
	}
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

	octx->flowControlStart = obj->ticker->time;
	octx->minBufferFilling = -1;
	octx->nbufs = 0;
}

static int bytes_to_ms(OpenSLESOutputContext *octx, int bytes){
	return bytes * 1000 / (2 * octx->opensles_context->nchannels * octx->opensles_context->samplerate);
}

static void android_snd_write_process(MSFilter *obj) {
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;

	ms_mutex_lock(&octx->mutex);
	ms_bufferizer_put_from_queue(&octx->buffer, obj->inputs[0]);

	if (((uint32_t)(obj->ticker->time - octx->flowControlStart)) >= flowControlIntervalMs) {
		int threshold = (flowControlThresholdMs * octx->opensles_context->nchannels * 2 * octx->opensles_context->samplerate) / 1000;
920
		//ms_message("OpenSLES Time to flow control: minBufferFilling=%i, threshold=%i", octx->minBufferFilling, threshold);
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
		if (octx->minBufferFilling > threshold) {
			int drop = octx->minBufferFilling - (threshold/4); //keep a bit in order not to risk an underrun in the next period.
			ms_warning("OpenSLES Too many samples waiting in sound writer (minBufferFilling=%i ms, threshold=%i ms), dropping %i ms", 
					   bytes_to_ms(octx, octx->minBufferFilling), bytes_to_ms(octx, threshold), bytes_to_ms(octx, drop));
			ms_bufferizer_skip_bytes(&octx->buffer, drop);
		}
		octx->flowControlStart = obj->ticker->time;
		octx->minBufferFilling = -1;
	}
	ms_mutex_unlock(&octx->mutex);
}

static void android_snd_write_postprocess(MSFilter *obj) {
	SLresult result;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
	
	result = (*octx->playerPlay)->SetPlayState(octx->playerPlay, SL_PLAYSTATE_STOPPED);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while stopping player", result);
	}

	result = (*octx->playerBufferQueue)->Clear(octx->playerBufferQueue);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while clearing player buffer queue", result);
	}

947
	if (octx->playerObject != NULL) {
948 949 950 951 952
		(*octx->playerObject)->Destroy(octx->playerObject);
		octx->playerObject = NULL;
		octx->playerPlay = NULL;
		octx->playerBufferQueue = NULL;
	}
953

954 955 956
	if (octx->outputMixObject != NULL) {
		(*octx->outputMixObject)->Destroy(octx->outputMixObject);
		octx->outputMixObject = NULL;
957
	}
958 959 960 961 962 963 964 965 966 967
}

static MSFilterMethod android_snd_write_methods[] = {
	{MS_FILTER_SET_SAMPLE_RATE, android_snd_write_set_sample_rate},
	{MS_FILTER_GET_SAMPLE_RATE, android_snd_write_get_sample_rate},
	{MS_FILTER_SET_NCHANNELS, android_snd_write_set_nchannels},
	{MS_FILTER_GET_NCHANNELS, android_snd_write_get_nchannels},
	{0,NULL}
};

968
MSFilterDesc android_snd_opensles_write_desc = {
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	MS_FILTER_PLUGIN_ID,
	"MSOpenSLESPlayer",
	"android sound output",
	MS_FILTER_OTHER,
	NULL,
	1,
	0,
	android_snd_write_init,
	android_snd_write_preprocess,
	android_snd_write_process,
	android_snd_write_postprocess,
	android_snd_write_uninit,
	android_snd_write_methods
};

984 985
static MSFilter* ms_android_snd_write_new(MSFactory* factory) {
	MSFilter *f = ms_factory_create_filter_from_desc(factory, &android_snd_opensles_write_desc);
986 987 988
	return f;
}

989
MSSndCardDesc android_native_snd_opensles_card_desc = {
990
	"openSLES",
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
	android_snd_card_detect,
	android_native_snd_card_init,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	android_snd_card_create_reader,
	android_snd_card_create_writer,
	android_native_snd_card_uninit
};

static MSSndCard* android_snd_card_new(void) {
	MSSndCard* obj;
	SoundDeviceDescription *d;
	
1007
	obj = ms_snd_card_new(&android_native_snd_opensles_card_desc);
1008
	obj->name = ms_strdup("android sound card");
1009 1010
	d = sound_device_description_get();
	OpenSLESContext *context = opensles_context_init();
1011
	if (d->flags & DEVICE_HAS_BUILTIN_OPENSLES_AEC) {
1012 1013
		obj->capabilities |= MS_SND_CARD_CAP_BUILTIN_ECHO_CANCELLER;
		context->builtin_aec = true;
1014 1015 1016
	} else if (d->flags & DEVICE_HAS_BUILTIN_AEC) {
		ms_warning("Removing MS_SND_CARD_CAP_CAPTURE flag from soundcard to use HAEC Java capture soundcard");
		obj->capabilities = MS_SND_CARD_CAP_PLAYBACK;
1017
	}
1018
	obj->latency = d->delay;
1019
	obj->data = context;
1020 1021 1022
	if (d->recommended_rate){
		context->samplerate = d->recommended_rate;
	}
1023 1024
	return obj;
}
1025

1026