1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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 515 516 517 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 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 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 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 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 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 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 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
#ifndef SL_ANDROID_DATAFORMAT_PCM_EX
#define SL_ANDROID_DATAFORMAT_PCM_EX ((SLuint32) 0x00000004)
#endif
#ifndef SL_ANDROID_PCM_REPRESENTATION_FLOAT
#define SL_ANDROID_PCM_REPRESENTATION_FLOAT ((SLuint32) 0x00000003)
#endif
#ifndef SL_ANDROID_RECORDING_PRESET_UNPROCESSED
#define SL_ANDROID_RECORDING_PRESET_UNPROCESSED ((SLuint32) 0x00000005)
#endif
//==============================================================================
struct PCMDataFormatEx : SLDataFormat_PCM
{
SLuint32 representation;
};
//==============================================================================
template <typename T> struct IntfIID;
template <> struct IntfIID<SLObjectItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLEngineItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLOutputMixItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLPlayItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLRecordItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLAndroidSimpleBufferQueueItf_> { static SLInterfaceID_ iid; };
template <> struct IntfIID<SLAndroidConfigurationItf_> { static SLInterfaceID_ iid; };
SLInterfaceID_ IntfIID<SLObjectItf_>::iid = { 0x79216360, 0xddd7, 0x11db, 0xac16, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLEngineItf_>::iid = { 0x8d97c260, 0xddd4, 0x11db, 0x958f, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLOutputMixItf_>::iid = { 0x97750f60, 0xddd7, 0x11db, 0x92b1, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLPlayItf_>::iid = { 0xef0bd9c0, 0xddd7, 0x11db, 0xbf49, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLRecordItf_>::iid = { 0xc5657aa0, 0xdddb, 0x11db, 0x82f7, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLAndroidSimpleBufferQueueItf_>::iid = { 0x198e4940, 0xc5d7, 0x11df, 0xa2a6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
SLInterfaceID_ IntfIID<SLAndroidConfigurationItf_>::iid = { 0x89f6a7e0, 0xbeac, 0x11df, 0x8b5c, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
//==============================================================================
// Some life-time and type management of OpenSL objects
class SlObjectRef
{
public:
//==============================================================================
SlObjectRef() noexcept {}
SlObjectRef (const SlObjectRef& obj) noexcept : cb (obj.cb) {}
SlObjectRef (SlObjectRef&& obj) noexcept : cb (static_cast<ReferenceCountedObjectPtr<ControlBlock>&&> (obj.cb)) { obj.cb = nullptr; }
explicit SlObjectRef (SLObjectItf o) : cb (new ControlBlock (o)) {}
//==============================================================================
SlObjectRef& operator=(const SlObjectRef& r) noexcept { cb = r.cb; return *this; }
SlObjectRef& operator=(SlObjectRef&& r) noexcept { cb = static_cast<ReferenceCountedObjectPtr<ControlBlock>&&> (r.cb); r.cb = nullptr; return *this; }
SlObjectRef& operator=(std::nullptr_t) noexcept { cb = nullptr; return *this; }
//==============================================================================
const SLObjectItf_* const operator*() noexcept { return *cb->ptr.get(); }
SLObjectItf operator->() noexcept { return (cb == nullptr ? nullptr : cb->ptr.get()); }
operator SLObjectItf() noexcept { return (cb == nullptr ? nullptr : cb->ptr.get()); }
//==============================================================================
bool operator== (nullptr_t) const noexcept { return (cb == nullptr || cb->ptr == nullptr); }
bool operator!= (nullptr_t) const noexcept { return (cb != nullptr && cb->ptr != nullptr); }
private:
//==============================================================================
struct ControlBlock : ReferenceCountedObject { ScopedPointer<const SLObjectItf_* const> ptr; ControlBlock() {} ControlBlock (SLObjectItf o) : ptr (o) {} };
ReferenceCountedObjectPtr<ControlBlock> cb;
};
template <typename T>
class SlRef : public SlObjectRef
{
public:
//==============================================================================
SlRef() noexcept : type (nullptr) {}
SlRef (SlRef& r) noexcept : SlObjectRef (r), type (r.type) {}
SlRef (SlRef&& r) noexcept : SlObjectRef (static_cast<SlRef&&> (r)), type (r.type) { r.type = nullptr; }
//==============================================================================
SlRef& operator= (const SlRef& r) noexcept { SlObjectRef::operator= (r); type = r.type; return *this; }
SlRef& operator= (SlRef&& r) noexcept { SlObjectRef::operator= (static_cast<SlObjectRef&&> (r)); type = r.type; r.type = nullptr; return *this; }
SlRef& operator= (std::nullptr_t) noexcept { SlObjectRef::operator= (nullptr); type = nullptr; return *this; }
//==============================================================================
T* const operator*() noexcept { return *type; }
T* const * operator->() noexcept { return type; }
operator T* const *() noexcept { return type; }
//==============================================================================
static SlRef cast (SlObjectRef& base) { return SlRef (base); }
static SlRef cast (SlObjectRef&& base) { return SlRef (static_cast<SlObjectRef&&> (base)); }
private:
//==============================================================================
SlRef (SlObjectRef& base) : SlObjectRef (base)
{
SLObjectItf obj = SlObjectRef::operator->();
SLresult err = (*obj)->GetInterface (obj, &IntfIID<T>::iid, &type);
if (type == nullptr || err != SL_RESULT_SUCCESS)
*this = nullptr;
}
SlRef (SlObjectRef&& base) : SlObjectRef (static_cast<SlObjectRef&&> (base))
{
SLObjectItf obj = SlObjectRef::operator->();
SLresult err = (*obj)->GetInterface (obj, &IntfIID<T>::iid, &type);
base = nullptr;
if (type == nullptr || err != SL_RESULT_SUCCESS)
*this = nullptr;
}
T* const * type;
};
template <>
struct ContainerDeletePolicy<const SLObjectItf_* const>
{
static void destroy (SLObjectItf object)
{
if (object != nullptr)
(*object)->Destroy (object);
}
};
//==============================================================================
template <typename T> struct BufferHelpers {};
template <>
struct BufferHelpers<int16>
{
enum { isFloatingPoint = 0 };
static void initPCMDataFormat (PCMDataFormatEx& dataFormat, int numChannels, double sampleRate)
{
dataFormat.formatType = SL_DATAFORMAT_PCM;
dataFormat.numChannels = (SLuint32) numChannels;
dataFormat.samplesPerSec = (SLuint32) (sampleRate * 1000);
dataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
dataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
dataFormat.channelMask = (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER :
(SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;
dataFormat.representation = 0;
}
static void prepareCallbackBuffer (AudioSampleBuffer&, int16*) {}
static void convertFromOpenSL (const int16* srcInterleaved, AudioSampleBuffer& audioBuffer)
{
for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
{
typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DstSampleType;
typedef AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const> SrcSampleType;
DstSampleType dstData (audioBuffer.getWritePointer (i));
SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
dstData.convertSamples (srcData, audioBuffer.getNumSamples());
}
}
static void convertToOpenSL (const AudioSampleBuffer& audioBuffer, int16* dstInterleaved)
{
for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
{
typedef AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> DstSampleType;
typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SrcSampleType;
DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
SrcSampleType srcData (audioBuffer.getReadPointer (i));
dstData.convertSamples (srcData, audioBuffer.getNumSamples());
}
}
};
template <>
struct BufferHelpers<float>
{
enum { isFloatingPoint = 1 };
static void initPCMDataFormat (PCMDataFormatEx& dataFormat, int numChannels, double sampleRate)
{
dataFormat.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
dataFormat.numChannels = (SLuint32) numChannels;
dataFormat.samplesPerSec = (SLuint32) (sampleRate * 1000);
dataFormat.bitsPerSample = 32;
dataFormat.containerSize = 32;
dataFormat.channelMask = (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER :
(SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;
dataFormat.representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
}
static void prepareCallbackBuffer (AudioSampleBuffer& audioBuffer, float* native)
{
if (audioBuffer.getNumChannels() == 1)
audioBuffer.setDataToReferTo (&native, 1, audioBuffer.getNumSamples());
}
static void convertFromOpenSL (const float* srcInterleaved, AudioSampleBuffer& audioBuffer)
{
if (audioBuffer.getNumChannels() == 1)
{
jassert (srcInterleaved == audioBuffer.getWritePointer (0));
return;
}
for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
{
typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DstSampleType;
typedef AudioData::Pointer<AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const> SrcSampleType;
DstSampleType dstData (audioBuffer.getWritePointer (i));
SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
dstData.convertSamples (srcData, audioBuffer.getNumSamples());
}
}
static void convertToOpenSL (const AudioSampleBuffer& audioBuffer, float* dstInterleaved)
{
if (audioBuffer.getNumChannels() == 1)
{
jassert (dstInterleaved == audioBuffer.getReadPointer (0));
return;
}
for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
{
typedef AudioData::Pointer<AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> DstSampleType;
typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SrcSampleType;
DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
SrcSampleType srcData (audioBuffer.getReadPointer (i));
dstData.convertSamples (srcData, audioBuffer.getNumSamples());
}
}
};
class SLRealtimeThread;
//==============================================================================
class OpenSLAudioIODevice : public AudioIODevice
{
public:
//==============================================================================
template <typename T>
class OpenSLSessionT;
//==============================================================================
// CRTP
template <typename T, class Child, typename RunnerObjectType>
struct OpenSLQueueRunner
{
OpenSLQueueRunner (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
: owner (sessionToUse),
numChannels (numChannelsToUse),
nativeBuffer (static_cast<size_t> (numChannels * owner.bufferSize * owner.numBuffers)),
scratchBuffer (numChannelsToUse, owner.bufferSize),
sampleBuffer (scratchBuffer.getArrayOfWritePointers(), numChannelsToUse, owner.bufferSize),
nextBlock (0), numBlocksOut (0)
{}
~OpenSLQueueRunner()
{
if (config != nullptr && javaProxy != nullptr)
{
javaProxy.clear();
(*config)->ReleaseJavaProxy (config, /*SL_ANDROID_JAVA_PROXY_ROUTING*/1);
}
}
bool init()
{
runner = crtp().createPlayerOrRecorder();
if (runner == nullptr)
return false;
const bool supportsJavaProxy = (getEnv()->GetStaticIntField (AndroidBuildVersion, AndroidBuildVersion.SDK_INT) >= 24);
if (supportsJavaProxy)
{
// may return nullptr on some platforms - that's ok
config = SlRef<SLAndroidConfigurationItf_>::cast (runner);
if (config != nullptr)
{
jobject audioRoutingJni;
auto status = (*config)->AcquireJavaProxy (config, /*SL_ANDROID_JAVA_PROXY_ROUTING*/1,
&audioRoutingJni);
if (status == SL_RESULT_SUCCESS && audioRoutingJni != 0)
javaProxy = GlobalRef (audioRoutingJni);
}
}
queue = SlRef<SLAndroidSimpleBufferQueueItf_>::cast (runner);
if (queue == nullptr)
return false;
return ((*queue)->RegisterCallback (queue, staticFinished, this) == SL_RESULT_SUCCESS);
}
void clear()
{
nextBlock.set (0);
numBlocksOut.set (0);
zeromem (nativeBuffer.get(), static_cast<size_t> (owner.bufferSize * numChannels * owner.numBuffers) * sizeof (T));
scratchBuffer.clear();
(*queue)->Clear (queue);
}
void enqueueBuffer()
{
(*queue)->Enqueue (queue, getCurrentBuffer(), static_cast<SLuint32> (getBufferSizeInSamples() * sizeof (T)));
++numBlocksOut;
}
bool isBufferAvailable() const { return (numBlocksOut.get() < owner.numBuffers); }
T* getNextBuffer() { nextBlock.set((nextBlock.get() + 1) % owner.numBuffers); return getCurrentBuffer(); }
T* getCurrentBuffer() { return nativeBuffer.get() + (static_cast<size_t> (nextBlock.get()) * getBufferSizeInSamples()); }
size_t getBufferSizeInSamples() const { return static_cast<size_t> (owner.bufferSize * numChannels); }
void finished (SLAndroidSimpleBufferQueueItf)
{
attachAndroidJNI();
--numBlocksOut;
owner.doSomeWorkOnAudioThread();
}
static void staticFinished (SLAndroidSimpleBufferQueueItf caller, void *pContext)
{
reinterpret_cast<OpenSLQueueRunner*> (pContext)->finished (caller);
}
// get the "this" pointer for CRTP
Child& crtp() { return * ((Child*) this); }
const Child& crtp() const { return * ((Child*) this); }
OpenSLSessionT<T>& owner;
SlRef<RunnerObjectType> runner;
SlRef<SLAndroidSimpleBufferQueueItf_> queue;
SlRef<SLAndroidConfigurationItf_> config;
GlobalRef javaProxy;
int numChannels;
HeapBlock<T> nativeBuffer;
AudioSampleBuffer scratchBuffer, sampleBuffer;
Atomic<int> nextBlock, numBlocksOut;
};
//==============================================================================
template <typename T>
struct OpenSLQueueRunnerPlayer : OpenSLQueueRunner<T, OpenSLQueueRunnerPlayer<T>, SLPlayItf_>
{
typedef OpenSLQueueRunner<T, OpenSLQueueRunnerPlayer<T>, SLPlayItf_> Base;
enum { isPlayer = 1 };
OpenSLQueueRunnerPlayer (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
: Base (sessionToUse, numChannelsToUse)
{}
SlRef<SLPlayItf_> createPlayerOrRecorder()
{
SLDataLocator_AndroidSimpleBufferQueue queueLocator = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (Base::owner.numBuffers)};
SLDataLocator_OutputMix outputMix = {SL_DATALOCATOR_OUTPUTMIX, Base::owner.outputMix};
PCMDataFormatEx dataFormat;
BufferHelpers<T>::initPCMDataFormat (dataFormat, Base::numChannels, Base::owner.sampleRate);
SLDataSource source = {&queueLocator, &dataFormat};
SLDataSink sink = {&outputMix, nullptr};
SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid, &IntfIID<SLAndroidConfigurationItf_>::iid };
SLboolean interfaceRequired[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE};
SLObjectItf obj = nullptr;
SLresult status = (*Base::owner.engine)->CreateAudioPlayer (Base::owner.engine, &obj, &source, &sink, 2, queueInterfaces, interfaceRequired);
if (status != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
if (obj != nullptr)
(*obj)->Destroy (obj);
return SlRef<SLPlayItf_>();
}
return SlRef<SLPlayItf_>::cast (SlObjectRef (obj));
}
void setState (bool running) { (*Base::runner)->SetPlayState (Base::runner, running ? SL_PLAYSTATE_PLAYING : SL_PLAYSTATE_STOPPED); }
};
template <typename T>
struct OpenSLQueueRunnerRecorder : OpenSLQueueRunner<T, OpenSLQueueRunnerRecorder<T>, SLRecordItf_>
{
typedef OpenSLQueueRunner<T, OpenSLQueueRunnerRecorder<T>, SLRecordItf_> Base;
enum { isPlayer = 0 };
OpenSLQueueRunnerRecorder (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
: Base (sessionToUse, numChannelsToUse)
{}
SlRef<SLRecordItf_> createPlayerOrRecorder()
{
SLDataLocator_IODevice ioDeviceLocator = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, nullptr};
SLDataLocator_AndroidSimpleBufferQueue queueLocator = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (Base::owner.numBuffers)};
PCMDataFormatEx dataFormat;
BufferHelpers<T>::initPCMDataFormat (dataFormat, Base::numChannels, Base::owner.sampleRate);
SLDataSource source = {&ioDeviceLocator, nullptr};
SLDataSink sink = {&queueLocator, &dataFormat};
SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid, &IntfIID<SLAndroidConfigurationItf_>::iid };
SLboolean interfaceRequired[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE};
SLObjectItf obj = nullptr;
SLresult status = (*Base::owner.engine)->CreateAudioRecorder (Base::owner.engine, &obj, &source, &sink, 2, queueInterfaces, interfaceRequired);
if (status != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
if (obj != nullptr)
(*obj)->Destroy (obj);
return SlRef<SLRecordItf_>();
}
SlRef<SLRecordItf_> recorder = SlRef<SLRecordItf_>::cast (SlObjectRef (obj));
return recorder;
}
bool setAudioPreprocessingEnabled (bool shouldEnable)
{
if (Base::config != nullptr)
{
const bool supportsUnprocessed = (getEnv()->GetStaticIntField (AndroidBuildVersion, AndroidBuildVersion.SDK_INT) >= 25);
const SLuint32 recordingPresetValue
= (shouldEnable ? SL_ANDROID_RECORDING_PRESET_GENERIC
: (supportsUnprocessed ? SL_ANDROID_RECORDING_PRESET_UNPROCESSED
: SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION));
SLresult status = (*Base::config)->SetConfiguration (Base::config, SL_ANDROID_KEY_RECORDING_PRESET,
&recordingPresetValue, sizeof (recordingPresetValue));
return (status == SL_RESULT_SUCCESS);
}
return false;
}
void setState (bool running) { (*Base::runner)->SetRecordState (Base::runner, running ? SL_RECORDSTATE_RECORDING : SL_RECORDSTATE_STOPPED); }
};
//==============================================================================
class OpenSLSession
{
public:
OpenSLSession (DynamicLibrary& slLibraryToUse,
int numInputChannels, int numOutputChannels,
double samleRateToUse, int bufferSizeToUse,
int numBuffersToUse)
: inputChannels (numInputChannels), outputChannels (numOutputChannels),
sampleRate (samleRateToUse), bufferSize (bufferSizeToUse), numBuffers (numBuffersToUse),
running (false), audioProcessingEnabled (true), callback (nullptr)
{
jassert (numInputChannels > 0 || numOutputChannels > 0);
if (CreateEngineFunc createEngine = (CreateEngineFunc) slLibraryToUse.getFunction ("slCreateEngine"))
{
SLObjectItf obj = nullptr;
SLresult err = createEngine (&obj, 0, nullptr, 0, nullptr, nullptr);
if (err != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
if (obj != nullptr)
(*obj)->Destroy (obj);
return;
}
engine = SlRef<SLEngineItf_>::cast (SlObjectRef (obj));
}
if (outputChannels > 0)
{
SLObjectItf obj = nullptr;
SLresult err = (*engine)->CreateOutputMix (engine, &obj, 0, nullptr, nullptr);
if (err != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
if (obj != nullptr)
(*obj)->Destroy (obj);
return;
}
outputMix = SlRef<SLOutputMixItf_>::cast (SlObjectRef (obj));
}
}
virtual ~OpenSLSession() {}
virtual bool openedOK() const { return (engine != nullptr && (outputChannels == 0 || (outputMix != nullptr))); }
virtual void start() { stop(); jassert (callback.get() != nullptr); running = true; }
virtual void stop() { running = false; }
virtual bool setAudioPreprocessingEnabled (bool shouldEnable) = 0;
virtual bool supportsFloatingPoint() const noexcept = 0;
virtual int getXRunCount() const noexcept = 0;
void setCallback (AudioIODeviceCallback* callbackToUse)
{
if (! running)
{
callback.set (callbackToUse);
return;
}
// don't set callback to null! stop the playback instead!
jassert (callbackToUse != nullptr);
// spin-lock until we can set the callback
while (true)
{
AudioIODeviceCallback* old = callback.get();
if (old == callbackToUse)
break;
if (callback.compareAndSetBool (callbackToUse, old))
break;
Thread::sleep (1);
}
}
void process (const float** inputChannelData, float** outputChannelData)
{
if (AudioIODeviceCallback* cb = callback.exchange(nullptr))
{
cb->audioDeviceIOCallback (inputChannelData, inputChannels, outputChannelData, outputChannels, bufferSize);
callback.set (cb);
}
else
{
for (int i = 0; i < outputChannels; ++i)
zeromem (outputChannelData[i], sizeof(float) * static_cast<size_t> (bufferSize));
}
}
static OpenSLSession* create (DynamicLibrary& slLibrary,
int numInputChannels, int numOutputChannels,
double samleRateToUse, int bufferSizeToUse,
int numBuffersToUse);
//==============================================================================
typedef SLresult (*CreateEngineFunc)(SLObjectItf*,SLuint32,const SLEngineOption*,SLuint32,const SLInterfaceID*,const SLboolean*);
//==============================================================================
int inputChannels, outputChannels;
double sampleRate;
int bufferSize, numBuffers;
bool running, audioProcessingEnabled;
SlRef<SLEngineItf_> engine;
SlRef<SLOutputMixItf_> outputMix;
Atomic<AudioIODeviceCallback*> callback;
};
template <typename T>
class OpenSLSessionT : public OpenSLSession
{
public:
OpenSLSessionT (DynamicLibrary& slLibraryToUse,
int numInputChannels, int numOutputChannels,
double samleRateToUse, int bufferSizeToUse,
int numBuffersToUse)
: OpenSLSession (slLibraryToUse, numInputChannels, numOutputChannels, samleRateToUse, bufferSizeToUse, numBuffersToUse)
{
jassert (numInputChannels > 0 || numOutputChannels > 0);
if (OpenSLSession::openedOK())
{
if (inputChannels > 0)
{
recorder = new OpenSLQueueRunnerRecorder<T>(*this, inputChannels);
if (! recorder->init())
{
recorder = nullptr;
return;
}
}
if (outputChannels > 0)
{
player = new OpenSLQueueRunnerPlayer<T>(*this, outputChannels);
if (! player->init())
{
player = nullptr;
return;
}
const bool supportsUnderrunCount = (getEnv()->GetStaticIntField (AndroidBuildVersion, AndroidBuildVersion.SDK_INT) >= 24);
getUnderrunCount = supportsUnderrunCount ? getEnv()->GetMethodID (AudioTrack, "getUnderrunCount", "()I") : 0;
}
}
}
bool openedOK() const override
{
return (OpenSLSession::openedOK() && (inputChannels == 0 || recorder != nullptr)
&& (outputChannels == 0 || player != nullptr));
}
void start() override
{
OpenSLSession::start();
guard.set (0);
if (inputChannels > 0)
recorder->clear();
if (outputChannels > 0)
player->clear();
// first enqueue all buffers
for (int i = 0; i < numBuffers; ++i)
doSomeWorkOnAudioThread();
if (inputChannels > 0)
recorder->setState (true);
if (outputChannels > 0)
player->setState (true);
}
void stop() override
{
OpenSLSession::stop();
while (! guard.compareAndSetBool (1, 0))
Thread::sleep (1);
if (inputChannels > 0)
recorder->setState (false);
if (outputChannels > 0)
player->setState (false);
guard.set (0);
}
bool setAudioPreprocessingEnabled (bool shouldEnable) override
{
if (shouldEnable != audioProcessingEnabled)
{
audioProcessingEnabled = shouldEnable;
if (recorder != nullptr)
return recorder->setAudioPreprocessingEnabled (audioProcessingEnabled);
}
return true;
}
int getXRunCount() const noexcept override
{
if (player != nullptr && player->javaProxy != nullptr && getUnderrunCount != 0)
return getEnv()->CallIntMethod (player->javaProxy, getUnderrunCount);
return -1;
}
bool supportsFloatingPoint() const noexcept override { return (BufferHelpers<T>::isFloatingPoint != 0); }
void doSomeWorkOnAudioThread()
{
// only the player or the recorder should enter this section at any time
if (guard.compareAndSetBool (1, 0))
{
// are there enough buffers avaialable to process some audio
if ((inputChannels == 0 || recorder->isBufferAvailable()) && (outputChannels == 0 || player->isBufferAvailable()))
{
T* recorderBuffer = (inputChannels > 0 ? recorder->getNextBuffer() : nullptr);
T* playerBuffer = (outputChannels > 0 ? player->getNextBuffer() : nullptr);
const float** inputChannelData = nullptr;
float** outputChannelData = nullptr;
if (recorderBuffer != nullptr)
{
BufferHelpers<T>::prepareCallbackBuffer (recorder->sampleBuffer, recorderBuffer);
BufferHelpers<T>::convertFromOpenSL (recorderBuffer, recorder->sampleBuffer);
inputChannelData = recorder->sampleBuffer.getArrayOfReadPointers();
}
if (playerBuffer != nullptr)
{
BufferHelpers<T>::prepareCallbackBuffer (player->sampleBuffer, playerBuffer);
outputChannelData = player->sampleBuffer.getArrayOfWritePointers();
}
process (inputChannelData, outputChannelData);
if (recorderBuffer != nullptr)
recorder->enqueueBuffer();
if (playerBuffer != nullptr)
{
BufferHelpers<T>::convertToOpenSL (player->sampleBuffer, playerBuffer);
player->enqueueBuffer();
}
}
guard.set (0);
}
}
//==============================================================================
ScopedPointer<OpenSLQueueRunnerPlayer<T>> player;
ScopedPointer<OpenSLQueueRunnerRecorder<T>> recorder;
Atomic<int> guard;
jmethodID getUnderrunCount = 0;
};
//==============================================================================
OpenSLAudioIODevice (const String& deviceName)
: AudioIODevice (deviceName, openSLTypeName),
actualBufferSize (0), sampleRate (0),
audioProcessingEnabled (true),
callback (nullptr)
{
// OpenSL has piss-poor support for determining latency, so the only way I can find to
// get a number for this is by asking the AudioTrack/AudioRecord classes..
AndroidAudioIODevice javaDevice (deviceName);
// this is a total guess about how to calculate the latency, but seems to vaguely agree
// with the devices I've tested.. YMMV
inputLatency = (javaDevice.minBufferSizeIn * 2) / 3;
outputLatency = (javaDevice.minBufferSizeOut * 2) / 3;
const int64 longestLatency = jmax (inputLatency, outputLatency);
const int64 totalLatency = inputLatency + outputLatency;
inputLatency = (int) ((longestLatency * inputLatency) / totalLatency) & ~15;
outputLatency = (int) ((longestLatency * outputLatency) / totalLatency) & ~15;
bool success = slLibrary.open ("libOpenSLES.so");
// You can only create this class if you are sure that your hardware supports OpenSL
jassert (success);
ignoreUnused (success);
}
~OpenSLAudioIODevice()
{
close();
}
bool openedOk() const { return session != nullptr; }
StringArray getOutputChannelNames() override
{
StringArray s;
s.add ("Left");
s.add ("Right");
return s;
}
StringArray getInputChannelNames() override
{
StringArray s;
s.add ("Audio Input");
return s;
}
Array<double> getAvailableSampleRates() override
{
//see https://developer.android.com/ndk/guides/audio/opensl-for-android.html
static const double rates[] = { 8000.0, 11025.0, 12000.0, 16000.0,
22050.0, 24000.0, 32000.0, 44100.0, 48000.0 };
Array<double> retval (rates, numElementsInArray (rates));
// make sure the native sample rate is pafrt of the list
double native = getNativeSampleRate();
if (native != 0.0 && ! retval.contains (native))
retval.add (native);
return retval;
}
Array<int> getAvailableBufferSizes() override
{
// we need to offer the lowest possible buffer size which
// is the native buffer size
const int defaultNumMultiples = 8;
const int nativeBufferSize = getNativeBufferSize();
Array<int> retval;
for (int i = 1; i < defaultNumMultiples; ++i)
retval.add (i * nativeBufferSize);
return retval;
}
String open (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double requestedSampleRate,
int bufferSize) override
{
close();
lastError.clear();
sampleRate = (int) requestedSampleRate;
int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
activeOutputChans = outputChannels;
activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
int numOutputChannels = activeOutputChans.countNumberOfSetBits();
activeInputChans = inputChannels;
activeInputChans.setRange (1, activeInputChans.getHighestBit(), false);
int numInputChannels = activeInputChans.countNumberOfSetBits();
actualBufferSize = preferredBufferSize;
const int audioBuffersToEnqueue = hasLowLatencyAudioPath() ? buffersToEnqueueForLowLatency
: buffersToEnqueueSlowAudio;
if (numInputChannels > 0 && (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)))
{
// If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
// before trying to open an audio input device. This is not going to work!
jassertfalse;
lastError = "Error opening OpenSL input device: the app was not granted android.permission.RECORD_AUDIO";
}
session = OpenSLSession::create (slLibrary, numInputChannels, numOutputChannels,
sampleRate, actualBufferSize, audioBuffersToEnqueue);
if (session != nullptr)
session->setAudioPreprocessingEnabled (audioProcessingEnabled);
else
{
if (numInputChannels > 0 && numOutputChannels > 0 && RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
{
// New versions of the Android emulator do not seem to support audio input anymore on OS X
activeInputChans = BigInteger(0);
numInputChannels = 0;
session = OpenSLSession::create(slLibrary, numInputChannels, numOutputChannels,
sampleRate, actualBufferSize, audioBuffersToEnqueue);
}
}
DBG ("OpenSL: numInputChannels = " << numInputChannels
<< ", numOutputChannels = " << numOutputChannels
<< ", nativeBufferSize = " << getNativeBufferSize()
<< ", nativeSampleRate = " << getNativeSampleRate()
<< ", actualBufferSize = " << actualBufferSize
<< ", audioBuffersToEnqueue = " << audioBuffersToEnqueue
<< ", sampleRate = " << sampleRate
<< ", supportsFloatingPoint = " << (session != nullptr && session->supportsFloatingPoint() ? "true" : "false"));
if (session == nullptr)
lastError = "Unknown error initializing opensl session";
deviceOpen = (session != nullptr);
return lastError;
}
void close() override
{
stop();
session = nullptr;
callback = nullptr;
}
int getOutputLatencyInSamples() override { return outputLatency; }
int getInputLatencyInSamples() override { return inputLatency; }
bool isOpen() override { return deviceOpen; }
int getCurrentBufferSizeSamples() override { return actualBufferSize; }
int getCurrentBitDepth() override { return (session != nullptr && session->supportsFloatingPoint() ? 32 : 16); }
BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
BigInteger getActiveInputChannels() const override { return activeInputChans; }
String getLastError() override { return lastError; }
bool isPlaying() override { return callback != nullptr; }
int getXRunCount() const noexcept override { return (session != nullptr ? session->getXRunCount() : -1); }
int getDefaultBufferSize() override
{
// Only on a Pro-Audio device will we set the lowest possible buffer size
// by default. We need to be more conservative on other devices
// as they may be low-latency, but still have a crappy CPU.
return (isProAudioDevice() ? 1 : 6)
* defaultBufferSizeIsMultipleOfNative * getNativeBufferSize();
}
double getCurrentSampleRate() override
{
return (sampleRate == 0.0 ? getNativeSampleRate() : sampleRate);
}
void start (AudioIODeviceCallback* newCallback) override
{
if (session != nullptr && callback != newCallback)
{
AudioIODeviceCallback* oldCallback = callback;
if (newCallback != nullptr)
newCallback->audioDeviceAboutToStart (this);
if (oldCallback != nullptr)
{
// already running
if (newCallback == nullptr)
stop();
else
session->setCallback (newCallback);
oldCallback->audioDeviceStopped();
}
else
{
jassert (newCallback != nullptr);
// session hasn't started yet
session->setCallback (newCallback);
session->start();
}
callback = newCallback;
}
}
void stop() override
{
if (session != nullptr && callback != nullptr)
{
callback = nullptr;
session->stop();
session->setCallback (nullptr);
}
}
bool setAudioPreprocessingEnabled (bool shouldAudioProcessingBeEnabled) override
{
audioProcessingEnabled = shouldAudioProcessingBeEnabled;
if (session != nullptr)
session->setAudioPreprocessingEnabled (audioProcessingEnabled);
return true;
}
static const char* const openSLTypeName;
private:
//==============================================================================
friend class SLRealtimeThread;
//==============================================================================
DynamicLibrary slLibrary;
int actualBufferSize, sampleRate;
int inputLatency, outputLatency;
bool deviceOpen, audioProcessingEnabled;
String lastError;
BigInteger activeOutputChans, activeInputChans;
AudioIODeviceCallback* callback;
ScopedPointer<OpenSLSession> session;
enum
{
// The number of buffers to enqueue needs to be at least two for the audio to use the low-latency
// audio path (see "Performance" section in ndk/docs/Additional_library_docs/opensles/index.html)
buffersToEnqueueForLowLatency = 4,
buffersToEnqueueSlowAudio = 8,
defaultBufferSizeIsMultipleOfNative = 1
};
//==============================================================================
static String audioManagerGetProperty (const String& property)
{
const LocalRef<jstring> jProperty (javaString (property));
const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (JuceAppActivity.audioManagerGetProperty,
jProperty.get()));
if (text.get() != 0)
return juceString (text);
return {};
}
static bool androidHasSystemFeature (const String& property)
{
const LocalRef<jstring> jProperty (javaString (property));
return android.activity.callBooleanMethod (JuceAppActivity.hasSystemFeature, jProperty.get());
}
static double getNativeSampleRate()
{
return audioManagerGetProperty ("android.media.property.OUTPUT_SAMPLE_RATE").getDoubleValue();
}
static int getNativeBufferSize()
{
const int val = audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER").getIntValue();
return val > 0 ? val : 512;
}
static bool isProAudioDevice()
{
return androidHasSystemFeature ("android.hardware.audio.pro");
}
static bool hasLowLatencyAudioPath()
{
return androidHasSystemFeature ("android.hardware.audio.low_latency");
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioIODevice)
};
OpenSLAudioIODevice::OpenSLSession* OpenSLAudioIODevice::OpenSLSession::create (DynamicLibrary& slLibrary,
int numInputChannels, int numOutputChannels,
double samleRateToUse, int bufferSizeToUse,
int numBuffersToUse)
{
ScopedPointer<OpenSLSession> retval;
auto sdkVersion = getEnv()->GetStaticIntField (AndroidBuildVersion, AndroidBuildVersion.SDK_INT);
// SDK versions 21 and higher should natively support floating point...
if (sdkVersion >= 21)
{
retval = new OpenSLSessionT<float> (slLibrary, numInputChannels, numOutputChannels, samleRateToUse,
bufferSizeToUse, numBuffersToUse);
// ...however, some devices lie so re-try without floating point
if (retval != nullptr && (! retval->openedOK()))
retval = nullptr;
}
if (retval == nullptr)
{
retval = new OpenSLSessionT<int16> (slLibrary, numInputChannels, numOutputChannels, samleRateToUse,
bufferSizeToUse, numBuffersToUse);
if (retval != nullptr && (! retval->openedOK()))
retval = nullptr;
}
return retval.release();
}
//==============================================================================
class OpenSLAudioDeviceType : public AudioIODeviceType
{
public:
OpenSLAudioDeviceType() : AudioIODeviceType (OpenSLAudioIODevice::openSLTypeName) {}
//==============================================================================
void scanForDevices() override {}
StringArray getDeviceNames (bool) const override { return StringArray (OpenSLAudioIODevice::openSLTypeName); }
int getDefaultDeviceIndex (bool) const override { return 0; }
int getIndexOfDevice (AudioIODevice* device, bool) const override { return device != nullptr ? 0 : -1; }
bool hasSeparateInputsAndOutputs() const override { return false; }
AudioIODevice* createDevice (const String& outputDeviceName,
const String& inputDeviceName) override
{
ScopedPointer<OpenSLAudioIODevice> dev;
if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
dev = new OpenSLAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
: inputDeviceName);
return dev.release();
}
static bool isOpenSLAvailable()
{
DynamicLibrary library;
return library.open ("libOpenSLES.so");
}
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioDeviceType)
};
const char* const OpenSLAudioIODevice::openSLTypeName = "Android OpenSL";
//==============================================================================
bool isOpenSLAvailable() { return OpenSLAudioDeviceType::isOpenSLAvailable(); }
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES()
{
return isOpenSLAvailable() ? new OpenSLAudioDeviceType() : nullptr;
}
//==============================================================================
class SLRealtimeThread
{
public:
static constexpr int numBuffers = 4;
SLRealtimeThread()
{
if (auto createEngine = (OpenSLAudioIODevice::OpenSLSession::CreateEngineFunc) slLibrary.getFunction ("slCreateEngine"))
{
SLObjectItf obj = nullptr;
auto err = createEngine (&obj, 0, nullptr, 0, nullptr, nullptr);
if (err != SL_RESULT_SUCCESS || obj == nullptr)
return;
if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
(*obj)->Destroy (obj);
return;
}
engine = SlRef<SLEngineItf_>::cast (SlObjectRef (obj));
if (engine == nullptr)
{
(*obj)->Destroy (obj);
return;
}
obj = nullptr;
err = (*engine)->CreateOutputMix (engine, &obj, 0, nullptr, nullptr);
if (err != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
(*obj)->Destroy (obj);
return;
}
outputMix = SlRef<SLOutputMixItf_>::cast (SlObjectRef (obj));
if (outputMix == nullptr)
{
(*obj)->Destroy (obj);
return;
}
SLDataLocator_AndroidSimpleBufferQueue queueLocator = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (numBuffers)};
SLDataLocator_OutputMix outputMixLocator = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
PCMDataFormatEx dataFormat;
BufferHelpers<int16>::initPCMDataFormat (dataFormat, 1, OpenSLAudioIODevice::getNativeSampleRate());
SLDataSource source = { &queueLocator, &dataFormat };
SLDataSink sink = { &outputMixLocator, nullptr };
SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid };
SLboolean trueFlag = SL_BOOLEAN_TRUE;
obj = nullptr;
err = (*engine)->CreateAudioPlayer (engine, &obj, &source, &sink, 1, queueInterfaces, &trueFlag);
if (err != SL_RESULT_SUCCESS || obj == nullptr)
return;
if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
{
(*obj)->Destroy (obj);
return;
}
player = SlRef<SLPlayItf_>::cast (SlObjectRef (obj));
if (player == nullptr)
{
(*obj)->Destroy (obj);
return;
}
queue = SlRef<SLAndroidSimpleBufferQueueItf_>::cast (player);
if (queue == nullptr)
return;
if ((*queue)->RegisterCallback (queue, staticFinished, this) != SL_RESULT_SUCCESS)
{
queue = nullptr;
return;
}
pthread_cond_init (&threadReady, nullptr);
pthread_mutex_init (&threadReadyMutex, nullptr);
}
}
bool isOK() const { return queue != nullptr; }
pthread_t startThread (void* (*entry) (void*), void* userPtr)
{
memset (buffer.get(), 0, static_cast<size_t> (sizeof (int16) * static_cast<size_t> (bufferSize * numBuffers)));
for (int i = 0; i < numBuffers; ++i)
{
int16* dst = buffer.get() + (bufferSize * i);
(*queue)->Enqueue (queue, dst, static_cast<SLuint32> (static_cast<size_t> (bufferSize) * sizeof (int16)));
}
pthread_mutex_lock (&threadReadyMutex);
threadEntryProc = entry;
threadUserPtr = userPtr;
(*player)->SetPlayState (player, SL_PLAYSTATE_PLAYING);
pthread_cond_wait (&threadReady, &threadReadyMutex);
pthread_mutex_unlock (&threadReadyMutex);
return threadID;
}
void finished()
{
if (threadEntryProc != nullptr)
{
pthread_mutex_lock (&threadReadyMutex);
threadID = pthread_self();
pthread_cond_signal (&threadReady);
pthread_mutex_unlock (&threadReadyMutex);
threadEntryProc (threadUserPtr);
threadEntryProc = nullptr;
(*player)->SetPlayState (player, SL_PLAYSTATE_STOPPED);
MessageManager::callAsync ([this] () { delete this; });
}
}
private:
//=============================================================================
static void staticFinished (SLAndroidSimpleBufferQueueItf, void* context)
{
static_cast<SLRealtimeThread*> (context)->finished();
}
//=============================================================================
DynamicLibrary slLibrary { "libOpenSLES.so" };
SlRef<SLEngineItf_> engine;
SlRef<SLOutputMixItf_> outputMix;
SlRef<SLPlayItf_> player;
SlRef<SLAndroidSimpleBufferQueueItf_> queue;
int bufferSize = OpenSLAudioIODevice::getNativeBufferSize();
HeapBlock<int16> buffer { HeapBlock<int16> (static_cast<size_t> (1 * bufferSize * numBuffers)) };
void* (*threadEntryProc) (void*) = nullptr;
void* threadUserPtr = nullptr;
pthread_cond_t threadReady;
pthread_mutex_t threadReadyMutex;
pthread_t threadID;
};
pthread_t juce_createRealtimeAudioThread (void* (*entry) (void*), void* userPtr)
{
ScopedPointer<SLRealtimeThread> thread (new SLRealtimeThread);
if (! thread->isOK())
return 0;
pthread_t threadID = thread->startThread (entry, userPtr);
// the thread will de-allocate itself
thread.release();
return threadID;
}
} // namespace juce
|