LibWebRTCAudioModule.cpp [plain text]
#include "config.h"
#include "LibWebRTCAudioModule.h"
#if USE(LIBWEBRTC)
#include <wtf/CurrentTime.h>
namespace WebCore {
LibWebRTCAudioModule::LibWebRTCAudioModule()
: m_audioTaskRunner(rtc::Thread::Create())
{
m_audioTaskRunner->SetName("WebKitWebRTCAudioModule", nullptr);
m_audioTaskRunner->Start();
}
int32_t LibWebRTCAudioModule::RegisterAudioCallback(webrtc::AudioTransport* audioTransport)
{
m_audioTransport = audioTransport;
return 0;
}
void LibWebRTCAudioModule::OnMessage(rtc::Message* message)
{
ASSERT_UNUSED(message, message->message_id == 1);
StartPlayoutOnAudioThread();
}
int32_t LibWebRTCAudioModule::StartPlayout()
{
if (!m_isPlaying && m_audioTaskRunner) {
m_audioTaskRunner->Post(RTC_FROM_HERE, this, 1);
m_isPlaying = true;
}
return 0;
}
int32_t LibWebRTCAudioModule::StopPlayout()
{
if (m_isPlaying)
m_isPlaying = false;
return 0;
}
const unsigned samplingRate = 48000;
const unsigned frameLengthMs = 10;
const unsigned samplesPerFrame = samplingRate * frameLengthMs / 1000;
const unsigned pollSamples = 5;
const unsigned pollInterval = 5 * frameLengthMs;
const unsigned channels = 2;
const unsigned bytesPerSample = 2;
void LibWebRTCAudioModule::StartPlayoutOnAudioThread()
{
double startTime = WTF::monotonicallyIncreasingTimeMS();
while (true) {
PollFromSource();
double now = WTF::monotonicallyIncreasingTimeMS();
double sleepFor = pollInterval - remainder(now - startTime, pollInterval);
m_audioTaskRunner->SleepMs(sleepFor);
if (!m_isPlaying)
return;
}
}
void LibWebRTCAudioModule::PollFromSource()
{
if (!m_audioTransport)
return;
for (unsigned i = 0; i < pollSamples; i++) {
int64_t elapsedTime = -1;
int64_t ntpTime = -1;
char data[(bytesPerSample * channels * samplesPerFrame)];
m_audioTransport->PullRenderData(bytesPerSample * 8, samplingRate, channels, samplesPerFrame, data, &elapsedTime, &ntpTime);
}
}
}
#endif // USE(LIBWEBRTC)