webrtc_audio_sink_adapter.cc 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/protocol/webrtc_audio_sink_adapter.h"
  5. #include "base/bind.h"
  6. #include "base/callback.h"
  7. #include "base/callback_helpers.h"
  8. #include "base/logging.h"
  9. #include "remoting/proto/audio.pb.h"
  10. #include "remoting/protocol/audio_stub.h"
  11. namespace remoting {
  12. namespace protocol {
  13. WebrtcAudioSinkAdapter::WebrtcAudioSinkAdapter(
  14. rtc::scoped_refptr<webrtc::MediaStreamInterface> stream,
  15. base::WeakPtr<AudioStub> audio_stub)
  16. : task_runner_(base::ThreadTaskRunnerHandle::Get()),
  17. audio_stub_(audio_stub),
  18. media_stream_(std::move(stream)) {
  19. webrtc::AudioTrackVector audio_tracks = media_stream_->GetAudioTracks();
  20. // Caller must verify that the media stream contains audio tracks.
  21. DCHECK(!audio_tracks.empty());
  22. if (audio_tracks.size() > 1U) {
  23. LOG(WARNING) << "Received media stream with multiple audio tracks.";
  24. }
  25. audio_track_ = audio_tracks[0];
  26. audio_track_->GetSource()->AddSink(this);
  27. }
  28. WebrtcAudioSinkAdapter::~WebrtcAudioSinkAdapter() {
  29. audio_track_->GetSource()->RemoveSink(this);
  30. }
  31. void WebrtcAudioSinkAdapter::OnData(const void* audio_data,
  32. int bits_per_sample,
  33. int sample_rate,
  34. size_t number_of_channels,
  35. size_t number_of_frames) {
  36. std::unique_ptr<AudioPacket> audio_packet(new AudioPacket());
  37. audio_packet->set_encoding(AudioPacket::ENCODING_RAW);
  38. switch (sample_rate) {
  39. case 44100:
  40. audio_packet->set_sampling_rate(AudioPacket::SAMPLING_RATE_44100);
  41. break;
  42. case 48000:
  43. audio_packet->set_sampling_rate(AudioPacket::SAMPLING_RATE_48000);
  44. break;
  45. default:
  46. LOG(WARNING) << "Unsupported sampling rate: " << sample_rate;
  47. return;
  48. }
  49. if (bits_per_sample != 16) {
  50. LOG(WARNING) << "Unsupported bits/sample: " << bits_per_sample;
  51. return;
  52. }
  53. audio_packet->set_bytes_per_sample(AudioPacket::BYTES_PER_SAMPLE_2);
  54. if (number_of_channels != 2) {
  55. LOG(WARNING) << "Unsupported number of channels: " << number_of_channels;
  56. return;
  57. }
  58. audio_packet->set_channels(AudioPacket::CHANNELS_STEREO);
  59. size_t data_size =
  60. number_of_frames * number_of_channels * (bits_per_sample / 8);
  61. audio_packet->add_data(reinterpret_cast<const char*>(audio_data), data_size);
  62. task_runner_->PostTask(
  63. FROM_HERE, base::BindOnce(&AudioStub::ProcessAudioPacket, audio_stub_,
  64. std::move(audio_packet), base::OnceClosure()));
  65. }
  66. } // namespace protocol
  67. } // namespace remoting