androidsound_opensles.cpp 32.8 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(MSSndCardManager *m);
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
};

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) {
251 252
	SoundDeviceDescription* d = NULL;
	MSDevicesInfo *devices = NULL;
253 254
	if (initOpenSLES() == 0) { // Try to dlopen libOpenSLES
		ms_message("libOpenSLES correctly loaded, creating OpenSLES MS soundcard");
255 256 257 258 259 260
		devices = ms_factory_get_devices_info(m->factory);
		d = ms_devices_info_get_sound_device_description(devices);
		if (d->flags & DEVICE_HAS_CRAPPY_OPENSLES)
            return;
        MSSndCard *card = android_snd_card_new(m);
        ms_snd_card_manager_add_card(m, card);
261
	} else {
262
		ms_warning("Failed to dlopen libOpenSLES, OpenSLES MS soundcard unavailable");
263 264 265 266 267 268
	}
}

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

269 270
	result = slwCreateEngine(&(ctx->engineObject), 0, NULL, 0, NULL, NULL);
	if (result != SL_RESULT_SUCCESS) {
271
		ms_error("OpenSLES Error %u while creating SL engine", result);
272
		return result;
273 274
	}

275 276
	result = (*ctx->engineObject)->Realize(ctx->engineObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
277
		ms_error("OpenSLES Error %u while realizing SL engine", result);
278
		return result;
279 280
	}

281
	result = (*ctx->engineObject)->GetInterface(ctx->engineObject, SLW_IID_ENGINE, &(ctx->engineEngine));
282 283 284

	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while getting SL engine interface", result);
285
		return result;
286 287
	}

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

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);
314
	SLuint32 channels = (SLuint32) ictx->opensles_context->nchannels;
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

	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,
335
		channels,
336 337 338 339 340 341 342 343 344 345 346 347 348
		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[] = {
349 350
		SLW_IID_ANDROIDSIMPLEBUFFERQUEUE,
		SLW_IID_ANDROIDCONFIGURATION
351 352 353 354 355 356 357 358 359 360 361 362 363
	};

	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;
	}

364
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_ANDROIDCONFIGURATION, &ictx->recorderConfig);
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	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;
	}

382
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_RECORD, &ictx->recorderRecord);
383 384 385 386 387
	if (SL_RESULT_SUCCESS != result) {
		ms_error("OpenSLES Error %u while getting the audio recorder's interface", result);
		return result;
	}

388
	result = (*ictx->recorderObject)->GetInterface(ictx->recorderObject, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, &ictx->recorderBufferQueue);
389 390 391 392 393 394 395 396 397 398 399 400 401
	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;
402
	ictx->mAvSkew = ms_ticker_synchronizer_set_external_time(ictx->mTickerSynchronizer, &ts);
403 404
}

405 406 407 408 409 410 411

/*
 * 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.
**/
412 413 414 415 416 417
static void opensles_recorder_callback(SLAndroidSimpleBufferQueueItf bq, void *context) {
	SLresult result;
	OpenSLESInputContext *ictx = (OpenSLESInputContext *)context;

	if (ictx->mTickerSynchronizer == NULL) {
		MSFilter *obj = ictx->mFilter;
418 419 420 421 422 423 424
		/*
		 * 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
425 426
		int loglevel=ortp_get_log_level_mask(ORTP_LOG_DOMAIN);
		ortp_set_log_level_mask(ORTP_LOG_DOMAIN, ORTP_ERROR|ORTP_FATAL);
427
		ictx->mTickerSynchronizer = ms_ticker_synchronizer_new();
428
		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
429
		ortp_set_log_level_mask(ORTP_LOG_DOMAIN, loglevel);
430 431 432 433 434 435 436 437 438 439 440 441 442 443
	}
	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) {
444
		/*ms_error("OpenSLES Error %u while enqueueing record buffer", result);*/
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
	}
	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;
504 505 506 507 508 509 510 511 512 513

	if (SL_RESULT_SUCCESS != opensles_recorder_init(ictx)) {
	    ms_error("Problem when initialization of opensles recorder");
	    return;
	}
	if (SL_RESULT_SUCCESS != opensles_recorder_callback_init(ictx)) {
	    ms_error("Problem when initialization of opensles recorder callback");
	    return;
	}

514 515 516 517 518 519 520 521 522 523 524 525 526 527
	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);
528 529 530
	if (obj->ticker->time % 5000 == 0)
			ms_message("sound/wall clock skew is average=%g ms", ictx->mAvSkew);
	
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
}

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;
	}

549 550 551 552 553 554
    if (ictx->recorderRecord != 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);
        }
    }
555

556 557 558 559 560 561
    if (ictx->recorderBufferQueue != NULL) {
        result = (*ictx->recorderBufferQueue)->Clear(ictx->recorderBufferQueue);
        if (SL_RESULT_SUCCESS != result) {
            ms_error("OpenSLES Error %u while clearing the audio recorder buffer queue", result);
        }
    }
562

563 564 565 566 567
	if (ictx->recorderObject != NULL) {
		(*ictx->recorderObject)->Destroy(ictx->recorderObject);
		ictx->recorderObject = NULL;
		ictx->recorderRecord = NULL;
		ictx->recorderBufferQueue = NULL;
568
	}
569 570 571 572 573 574 575 576
}

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) {
577
#if 0
578 579
	int *n = (int*)data;
	OpenSLESInputContext *ictx = (OpenSLESInputContext*)obj->data;
580 581 582 583
	if (ictx->opensles_context->forced_sample_rate > 0) {
		ms_warning("Sample rate is forced by mediastreamer2 device table, skipping...");
		return -1;
	}
584 585
	ictx->opensles_context->samplerate = *n;
	return 0;
586 587
#endif
	return -1; /*don't accept custom sample rates, use recommended rate always*/
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
}

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;
}

615
static MSFilterMethod android_snd_read_methods[] = {
616 617 618 619 620 621 622 623
	{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}
};

624
MSFilterDesc android_snd_opensles_read_desc = {
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
	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
};

640 641
static MSFilter* ms_android_snd_read_new(MSFactory *factory) {
	MSFilter *f = ms_factory_create_filter_from_desc(factory, &android_snd_opensles_read_desc);
642 643 644 645
	return f;
}

static MSFilter *android_snd_card_create_reader(MSSndCard *card) {
646
	MSFilter *f = ms_android_snd_read_new(ms_snd_card_get_factory(card));
647 648 649 650 651 652 653
	OpenSLESInputContext *ictx = static_cast<OpenSLESInputContext*>(f->data);
	ictx->setContext((OpenSLESContext*)card->data);
	return f;
}

static SLresult opensles_mixer_init(OpenSLESOutputContext *octx) {
	SLresult result;
654 655 656 657 658
	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) {
659 660 661
		ms_error("OpenSLES Error %u while creating output mixer", result);
		return result;
	}
662

663 664 665
	result = (*octx->outputMixObject)->Realize(octx->outputMixObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
		ms_error("OpenSLES Error %u while realizing output mixer", result);
666
		return result;
667
	}
668

669
	return result;
670 671 672 673
}

static SLresult opensles_sink_init(OpenSLESOutputContext *octx) {
	SLresult result;
674
	SLuint32 sample_rate = convertSamplerate(octx->opensles_context->samplerate);
675
	SLuint32 channels = (SLuint32) octx->opensles_context->nchannels;
676 677
	SLDataFormat_PCM format_pcm;

678
	format_pcm.formatType = SL_DATAFORMAT_PCM;
679 680 681 682 683
	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;
684
	if (channels == 1) {
685
		format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
686
	} else if (channels == 2) {
687
		format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
688
	} else {
689
		ms_error("OpenSLES Error trying to use %i channels", channels);
690
	}
691

692 693 694 695
	SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
		SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 
		2
	};
696

697 698 699 700
	SLDataSource audio_src = {
		&loc_bufq,
		&format_pcm
	};
701

702 703 704 705
	SLDataLocator_OutputMix loc_outmix = {
		SL_DATALOCATOR_OUTPUTMIX,
		octx->outputMixObject
	};
706

707 708 709 710
	SLDataSink audio_sink = {
		&loc_outmix,
		NULL
	};
711

712 713 714
	const SLuint32 nbInterface = 3;
	const SLInterfaceID ids[] = { SLW_IID_VOLUME, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, SLW_IID_ANDROIDCONFIGURATION};
	const SLboolean req[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
715
	result = (*octx->opensles_context->engineEngine)->CreateAudioPlayer(octx->opensles_context->engineEngine, &(octx->playerObject), &audio_src, &audio_sink, nbInterface, ids, req);
716
	if (result != SL_RESULT_SUCCESS) {
717 718
		ms_error("OpenSLES Error %u while creating ouput audio player", result);
		return result;
719
	}
720

721
	result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_ANDROIDCONFIGURATION, &octx->playerConfig);
722
	if (result != SL_RESULT_SUCCESS) {
723
		ms_error("OpenSLES Error %u while getting android configuration interface", result);
724
		return result;
725
	}
726

727
	result = (*octx->playerConfig)->SetConfiguration(octx->playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &octx->streamType, sizeof(SLint32));
728
	if (result != SL_RESULT_SUCCESS) {
729
		ms_error("OpenSLES Error %u while setting stream type configuration", result);
730
		return result;
731
	}
732

733 734
	result = (*octx->playerObject)->Realize(octx->playerObject, SL_BOOLEAN_FALSE);
	if (result != SL_RESULT_SUCCESS) {
735
		ms_error("OpenSLES Error %u while realizing output sink", result);
736
		return result;
737 738
	}

739 740
	result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_PLAY, &(octx->playerPlay));
	if (result != SL_RESULT_SUCCESS) {
741
		ms_error("OpenSLES Error %u while getting output sink interface play", result);
742
		return result;
743 744
	}

745 746
	result = (*octx->playerObject)->GetInterface(octx->playerObject, SLW_IID_ANDROIDSIMPLEBUFFERQUEUE, &(octx->playerBufferQueue));
	if (result != SL_RESULT_SUCCESS) {
747
		ms_error("OpenSLES Error %u while getting output sink interface buffer queue", result);
748
		return result;
749 750
	}

751
	return result;
752 753
}

754 755 756 757 758 759 760
/*
 * 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.
**/

761 762 763 764 765 766 767 768 769 770
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))) {
771
		/*ms_warning("OpenSLES skipping %i bytes", avail - (ask * 2) );*/
772 773 774 775
		ms_bufferizer_skip_bytes(&octx->buffer, avail - (ask * 2));
	}

	if (avail != 0) {
Ghislain MARY's avatar
Ghislain MARY committed
776
		if (octx->minBufferFilling == -1) {
777 778 779 780 781 782 783 784 785 786 787
			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;
788 789 790
		/*provide soundcard with a silence buffer*/
		bytes = ask;
		memset(octx->playBuffer[octx->currentBuffer], 0, bytes);
791 792 793 794 795 796
	}
	ms_mutex_unlock(&octx->mutex);
	octx->nbufs++;

 	result = (*octx->playerBufferQueue)->Enqueue(octx->playerBufferQueue, octx->playBuffer[octx->currentBuffer], bytes);
	if (result != SL_RESULT_SUCCESS) {
797
		/*ms_error("OpenSLES Error %u while adding buffer to output queue", result);*/
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
	}
	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;
	}

817 818
	result = (*octx->playerBufferQueue)->RegisterCallback(octx->playerBufferQueue, opensles_player_callback, octx);
	if (result != SL_RESULT_SUCCESS) {
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
		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) {
848
	MSFilter *f = ms_android_snd_write_new(ms_snd_card_get_factory(card));
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	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) {
865
#if 0
866 867
	int *n = (int*)data;
	OpenSLESOutputContext *octx = (OpenSLESOutputContext*)obj->data;
868 869 870 871
	if (octx->opensles_context->forced_sample_rate > 0) {
		ms_warning("Sample rate is forced by mediastreamer2 device table, skipping...");
		return -1;
	}
872 873
	octx->opensles_context->samplerate = *n;
	return 0;
874 875
#endif
	return -1; /*don't accept custom sample rates, use recommended rate always*/
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
}

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;
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
	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;
	}
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

	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;
936
		//ms_message("OpenSLES Time to flow control: minBufferFilling=%i, threshold=%i", octx->minBufferFilling, threshold);
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
		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);
	}

963
	if (octx->playerObject != NULL) {
964 965 966 967 968
		(*octx->playerObject)->Destroy(octx->playerObject);
		octx->playerObject = NULL;
		octx->playerPlay = NULL;
		octx->playerBufferQueue = NULL;
	}
969

970 971 972
	if (octx->outputMixObject != NULL) {
		(*octx->outputMixObject)->Destroy(octx->outputMixObject);
		octx->outputMixObject = NULL;
973
	}
974 975 976 977 978 979 980 981 982 983
}

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}
};

984
MSFilterDesc android_snd_opensles_write_desc = {
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
	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
};

1000 1001
static MSFilter* ms_android_snd_write_new(MSFactory* factory) {
	MSFilter *f = ms_factory_create_filter_from_desc(factory, &android_snd_opensles_write_desc);
1002 1003 1004
	return f;
}

1005
MSSndCardDesc android_native_snd_opensles_card_desc = {
1006
	"openSLES",
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
	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
};

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
static MSSndCard* android_snd_card_new(MSSndCardManager *m) {
	MSSndCard* card = NULL;
	SoundDeviceDescription *d = NULL;
	MSDevicesInfo *devices = NULL;
	
	card = ms_snd_card_new(&android_native_snd_opensles_card_desc);
	card->name = ms_strdup("android sound card");
	
	devices = ms_factory_get_devices_info(m->factory);
	d = ms_devices_info_get_sound_device_description(devices);
1029 1030
	
	OpenSLESContext *context = opensles_context_init();
1031
	if (d->flags & DEVICE_HAS_BUILTIN_OPENSLES_AEC) {
1032
		card->capabilities |= MS_SND_CARD_CAP_BUILTIN_ECHO_CANCELLER;
1033
		context->builtin_aec = true;
1034 1035
	} 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");
1036
		card->capabilities = MS_SND_CARD_CAP_PLAYBACK;
1037
	}
1038 1039
	card->latency = d->delay;
	card->data = context;
1040 1041 1042
	if (d->recommended_rate){
		context->samplerate = d->recommended_rate;
	}
1043
	return card;
1044
}
1045

1046