| 6 |
| 7 | #include "AudioInputAudioUnit.h" |
| 8 | #include "../../logging.h" |
| 9 | #include "AudioUnitIO.h" |
| 10 | #include <cassert> |
| 11 | #include <cstdio> |
| 12 | #include <cstdlib> |
| 13 |
| 14 | #define BUFFER_SIZE 960 |
| 15 |
| 16 | using namespace tgvoip; |
| 17 | using namespace tgvoip::audio; |
| 18 |
| 19 | AudioInputAudioUnit::AudioInputAudioUnit(std::string deviceID, AudioUnitIO* io) |
| 20 | { |
| 21 | remainingDataSize = 0; |
| 22 | isRecording = false; |
| 23 | this->io = io; |
| 24 | #if TARGET_OS_OSX |
| 25 | io->SetCurrentDevice(true, deviceID); |
| 26 | #endif |
| 27 | } |
| 28 |
| 29 | AudioInputAudioUnit::~AudioInputAudioUnit() |
| 30 | { |
| 31 | } |
| 32 |
| 33 | void AudioInputAudioUnit::Start() |
| 34 | { |
| 35 | isRecording = true; |
| 36 | io->EnableInput(true); |
| 37 | } |
| 38 |
| 39 | void AudioInputAudioUnit::Stop() |
| 40 | { |
| 41 | isRecording = false; |
| 42 | io->EnableInput(false); |
| 43 | } |
| 44 |
| 45 | void AudioInputAudioUnit::HandleBufferCallback(AudioBufferList* ioData) |
| 46 | { |
| 47 | int i; |
| 48 | for (i = 0; i < ioData->mNumberBuffers; i++) |
| 49 | { |
| 50 | AudioBuffer buf = ioData->mBuffers[i]; |
| 51 | #if TARGET_OS_OSX |
| 52 | assert(remainingDataSize + buf.mDataByteSize / 2 < 10240); |
| 53 | float* src = reinterpret_cast<float*>(buf.mData); |
| 54 | std::int16_t* dst = reinterpret_cast<std::int16_t*>(remainingData + remainingDataSize); |
| 55 | for (int j = 0; j < buf.mDataByteSize / 4; j++) |
| 56 | { |
| 57 | dst[j] = (std::int16_t)(src[j] * INT16_MAX); |
| 58 | } |
| 59 | remainingDataSize += buf.mDataByteSize / 2; |
| 60 | #else |
| 61 | assert(remainingDataSize + buf.mDataByteSize < 10240); |
| 62 | std::memcpy(remainingData + remainingDataSize, buf.mData, buf.mDataByteSize); |
| 63 | remainingDataSize += buf.mDataByteSize; |
| 64 | #endif |
| 65 | while (remainingDataSize >= BUFFER_SIZE * 2) |
| 66 | { |
| 67 | InvokeCallback(remainingData, BUFFER_SIZE * 2); |
| 68 | remainingDataSize -= BUFFER_SIZE * 2; |
| 69 | if (remainingDataSize > 0) |
| 70 | { |
| 71 | memmove(remainingData, remainingData + (BUFFER_SIZE * 2), remainingDataSize); |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 |
| 77 | #if TARGET_OS_OSX |
| 78 | void AudioInputAudioUnit::SetCurrentDevice(std::string deviceID) |
| 79 | { |
| 80 | io->SetCurrentDevice(true, deviceID); |
| 81 | } |
| 82 | #endif |
| 83 |