summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/media/cast_session_delegate.cc
blob: ed70c1e5d3c1d2430953c830c26971a27da119b1 (plain)
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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/media/cast_session_delegate.h"

#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_loop/message_loop_proxy.h"
#include "chrome/renderer/media/cast_threads.h"
#include "chrome/renderer/media/cast_transport_sender_ipc.h"
#include "content/public/renderer/render_thread.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/encoding_event_subscriber.h"
#include "media/cast/logging/log_serializer.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/transport/cast_transport_config.h"
#include "media/cast/transport/cast_transport_sender.h"

using media::cast::AudioSenderConfig;
using media::cast::CastEnvironment;
using media::cast::CastSender;
using media::cast::VideoSenderConfig;

static base::LazyInstance<CastThreads> g_cast_threads =
    LAZY_INSTANCE_INITIALIZER;

namespace {

// Allow 9MB for serialized video / audio event logs.
const int kMaxSerializedBytes = 9000000;

// Assume serialized log data for each frame will take up to 150 bytes.
const int kMaxVideoEventEntries = kMaxSerializedBytes / 150;

// Assume serialized log data for each frame will take up to 75 bytes.
const int kMaxAudioEventEntries = kMaxSerializedBytes / 75;

}  // namespace

CastSessionDelegate::CastSessionDelegate()
    : io_message_loop_proxy_(
          content::RenderThread::Get()->GetIOMessageLoopProxy()),
      weak_factory_(this) {
  DCHECK(io_message_loop_proxy_);
}

CastSessionDelegate::~CastSessionDelegate() {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  if (audio_event_subscriber_.get()) {
    cast_environment_->Logging()->RemoveRawEventSubscriber(
        audio_event_subscriber_.get());
  }
  if (video_event_subscriber_.get()) {
    cast_environment_->Logging()->RemoveRawEventSubscriber(
        video_event_subscriber_.get());
  }
}

void CastSessionDelegate::StartAudio(
    const AudioSenderConfig& config,
    const AudioFrameInputAvailableCallback& callback,
    const ErrorCallback& error_callback) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  if (!cast_transport_ || !cast_sender_) {
    error_callback.Run("Destination not set.");
    return;
  }

  audio_frame_input_available_callback_ = callback;
  media::cast::transport::CastTransportAudioConfig transport_config;
  transport_config.base.ssrc = config.sender_ssrc;
  transport_config.codec = config.codec;
  transport_config.base.rtp_config = config.rtp_config;
  transport_config.frequency = config.frequency;
  transport_config.channels = config.channels;
  cast_transport_->InitializeAudio(transport_config);
  cast_sender_->InitializeAudio(
      config,
      base::Bind(&CastSessionDelegate::InitializationResultCB,
                 weak_factory_.GetWeakPtr()));
}

void CastSessionDelegate::StartVideo(
    const VideoSenderConfig& config,
    const VideoFrameInputAvailableCallback& callback,
    const ErrorCallback& error_callback) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  if (!cast_transport_ || !cast_sender_) {
    error_callback.Run("Destination not set.");
    return;
  }

  video_frame_input_available_callback_ = callback;

  media::cast::transport::CastTransportVideoConfig transport_config;
  transport_config.base.ssrc = config.sender_ssrc;
  transport_config.codec = config.codec;
  transport_config.base.rtp_config = config.rtp_config;
  cast_transport_->InitializeVideo(transport_config);
  // TODO(mikhal): Pass in a valid GpuVideoAcceleratorFactories to support
  // hardware video encoding.
  cast_sender_->InitializeVideo(
      config,
      base::Bind(&CastSessionDelegate::InitializationResultCB,
                 weak_factory_.GetWeakPtr()),
      NULL /* GPU*/);
}

void CastSessionDelegate::StartUDP(const net::IPEndPoint& remote_endpoint) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  // Logging: enable raw events and stats collection.
  media::cast::CastLoggingConfig logging_config =
      media::cast::GetLoggingConfigWithRawEventsAndStatsEnabled();

  // CastSender uses the renderer's IO thread as the main thread. This reduces
  // thread hopping for incoming video frames and outgoing network packets.
  cast_environment_ = new CastEnvironment(
      scoped_ptr<base::TickClock>(new base::DefaultTickClock()).Pass(),
      base::MessageLoopProxy::current(),
      g_cast_threads.Get().GetAudioEncodeMessageLoopProxy(),
      g_cast_threads.Get().GetVideoEncodeMessageLoopProxy(),
      logging_config);

  // Rationale for using unretained: The callback cannot be called after the
  // destruction of CastTransportSenderIPC, and they both share the same thread.
  cast_transport_.reset(new CastTransportSenderIPC(
      remote_endpoint,
      base::Bind(&CastSessionDelegate::StatusNotificationCB,
                 base::Unretained(this)),
      logging_config,
      base::Bind(&CastSessionDelegate::LogRawEvents, base::Unretained(this))));

  cast_sender_ = CastSender::Create(cast_environment_, cast_transport_.get());
  cast_transport_->SetPacketReceiver(cast_sender_->packet_receiver());
}

void CastSessionDelegate::ToggleLogging(bool is_audio, bool enable) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());
  if (enable) {
    if (is_audio) {
      if (audio_event_subscriber_.get())
        return;
      audio_event_subscriber_.reset(new media::cast::EncodingEventSubscriber(
          media::cast::AUDIO_EVENT, kMaxAudioEventEntries));
      cast_environment_->Logging()->AddRawEventSubscriber(
          audio_event_subscriber_.get());
    } else {
      if (video_event_subscriber_.get())
        return;
      video_event_subscriber_.reset(new media::cast::EncodingEventSubscriber(
          media::cast::VIDEO_EVENT, kMaxVideoEventEntries));
      cast_environment_->Logging()->AddRawEventSubscriber(
          video_event_subscriber_.get());
    }
  } else {
    if (is_audio) {
      if (!audio_event_subscriber_.get())
        return;
      cast_environment_->Logging()->RemoveRawEventSubscriber(
          audio_event_subscriber_.get());
      audio_event_subscriber_.reset();
    } else {
      if (!video_event_subscriber_.get())
        return;
      cast_environment_->Logging()->RemoveRawEventSubscriber(
          video_event_subscriber_.get());
      video_event_subscriber_.reset();
    }
  }
}

void CastSessionDelegate::GetEventLogsAndReset(
    bool is_audio,
    const EventLogsCallback& callback) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  media::cast::EncodingEventSubscriber* subscriber =
      is_audio ? audio_event_subscriber_.get() : video_event_subscriber_.get();
  if (!subscriber) {
    callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
    return;
  }

  media::cast::proto::LogMetadata metadata;
  media::cast::FrameEventMap frame_events;
  media::cast::PacketEventMap packet_events;

  subscriber->GetEventsAndReset(&metadata, &frame_events, &packet_events);

  scoped_ptr<char[]> serialized_log(new char[kMaxSerializedBytes]);
  int output_bytes;
  bool success = media::cast::SerializeEvents(metadata,
                                              frame_events,
                                              packet_events,
                                              true,
                                              kMaxSerializedBytes,
                                              serialized_log.get(),
                                              &output_bytes);

  if (!success) {
    VLOG(2) << "Failed to serialize event log.";
    callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
    return;
  }

  DVLOG(2) << "Serialized log length: " << output_bytes;

  scoped_ptr<base::BinaryValue> blob(
      new base::BinaryValue(serialized_log.Pass(), output_bytes));
  callback.Run(blob.Pass());
}

void CastSessionDelegate::GetStatsAndReset(bool is_audio,
                                           const StatsCallback& callback) {
  media::cast::FrameStatsMap frame_stats =
      cast_environment_->Logging()->GetFrameStatsData(
          is_audio ? media::cast::AUDIO_EVENT : media::cast::VIDEO_EVENT);
  media::cast::PacketStatsMap packet_stats =
      cast_environment_->Logging()->GetPacketStatsData(
          is_audio ? media::cast::AUDIO_EVENT : media::cast::VIDEO_EVENT);

  scoped_ptr<base::DictionaryValue> stats = media::cast::ConvertStats(
      frame_stats, packet_stats);

  callback.Run(stats.Pass());
}

void CastSessionDelegate::StatusNotificationCB(
    media::cast::transport::CastTransportStatus unused_status) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());
  // TODO(hubbe): Call javascript UDPTransport error function.
}

void CastSessionDelegate::InitializationResultCB(
    media::cast::CastInitializationStatus result) const {
  DCHECK(cast_sender_);

  // TODO(pwestin): handle the error codes.
  if (result == media::cast::STATUS_AUDIO_INITIALIZED) {
    audio_frame_input_available_callback_.Run(
        cast_sender_->audio_frame_input());
  } else if (result == media::cast::STATUS_VIDEO_INITIALIZED) {
    video_frame_input_available_callback_.Run(
        cast_sender_->video_frame_input());
  }
}

void CastSessionDelegate::LogRawEvents(
    const std::vector<media::cast::PacketEvent>& packet_events) {
  DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());

  for (std::vector<media::cast::PacketEvent>::const_iterator it =
           packet_events.begin();
       it != packet_events.end();
       ++it) {
    cast_environment_->Logging()->InsertPacketEvent(it->timestamp,
                                                    it->type,
                                                    it->rtp_timestamp,
                                                    it->frame_id,
                                                    it->packet_id,
                                                    it->max_packet_id,
                                                    it->size);
  }
}