1 // Copyright 2013 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.
5 #include "chrome/renderer/media/cast_session_delegate.h"
7 #include "base/callback_helpers.h"
8 #include "base/lazy_instance.h"
9 #include "base/logging.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "chrome/renderer/media/cast_threads.h"
14 #include "chrome/renderer/media/cast_transport_sender_ipc.h"
15 #include "components/version_info/version_info.h"
16 #include "content/public/renderer/render_thread.h"
17 #include "media/cast/cast_config.h"
18 #include "media/cast/cast_environment.h"
19 #include "media/cast/cast_sender.h"
20 #include "media/cast/logging/log_serializer.h"
21 #include "media/cast/logging/logging_defines.h"
22 #include "media/cast/logging/proto/raw_events.pb.h"
23 #include "media/cast/logging/raw_event_subscriber_bundle.h"
24 #include "media/cast/net/cast_transport_config.h"
25 #include "media/cast/net/cast_transport_sender.h"
27 using media::cast::AudioSenderConfig
;
28 using media::cast::CastEnvironment
;
29 using media::cast::CastSender
;
30 using media::cast::VideoSenderConfig
;
32 static base::LazyInstance
<CastThreads
> g_cast_threads
=
33 LAZY_INSTANCE_INITIALIZER
;
35 CastSessionDelegateBase::CastSessionDelegateBase()
37 content::RenderThread::Get()->GetIOMessageLoopProxy()),
39 DCHECK(io_task_runner_
.get());
41 // Note that this also increases the accuracy of PostDelayTask,
42 // which is is very helpful to cast.
43 if (!base::Time::ActivateHighResolutionTimer(true)) {
44 LOG(WARNING
) << "Failed to activate high resolution timers for cast.";
49 CastSessionDelegateBase::~CastSessionDelegateBase() {
50 DCHECK(io_task_runner_
->BelongsToCurrentThread());
52 base::Time::ActivateHighResolutionTimer(false);
56 void CastSessionDelegateBase::StartUDP(
57 const net::IPEndPoint
& local_endpoint
,
58 const net::IPEndPoint
& remote_endpoint
,
59 scoped_ptr
<base::DictionaryValue
> options
,
60 const ErrorCallback
& error_callback
) {
61 DCHECK(io_task_runner_
->BelongsToCurrentThread());
63 // CastSender uses the renderer's IO thread as the main thread. This reduces
64 // thread hopping for incoming video frames and outgoing network packets.
65 // TODO(hubbe): Create cast environment in ctor instead.
66 cast_environment_
= new CastEnvironment(
67 scoped_ptr
<base::TickClock
>(new base::DefaultTickClock()).Pass(),
68 base::ThreadTaskRunnerHandle::Get(),
69 g_cast_threads
.Get().GetAudioEncodeMessageLoopProxy(),
70 g_cast_threads
.Get().GetVideoEncodeMessageLoopProxy());
72 // Rationale for using unretained: The callback cannot be called after the
73 // destruction of CastTransportSenderIPC, and they both share the same thread.
74 cast_transport_
.reset(new CastTransportSenderIPC(
78 base::Bind(&CastSessionDelegateBase::ReceivePacket
,
79 base::Unretained(this)),
80 base::Bind(&CastSessionDelegateBase::StatusNotificationCB
,
81 base::Unretained(this), error_callback
),
82 base::Bind(&CastSessionDelegateBase::LogRawEvents
,
83 base::Unretained(this))));
86 void CastSessionDelegateBase::StatusNotificationCB(
87 const ErrorCallback
& error_callback
,
88 media::cast::CastTransportStatus status
) {
89 DCHECK(io_task_runner_
->BelongsToCurrentThread());
90 std::string error_message
;
93 case media::cast::TRANSPORT_AUDIO_UNINITIALIZED
:
94 case media::cast::TRANSPORT_VIDEO_UNINITIALIZED
:
95 case media::cast::TRANSPORT_AUDIO_INITIALIZED
:
96 case media::cast::TRANSPORT_VIDEO_INITIALIZED
:
97 return; // Not errors, do nothing.
98 case media::cast::TRANSPORT_INVALID_CRYPTO_CONFIG
:
99 error_callback
.Run("Invalid encrypt/decrypt configuration.");
101 case media::cast::TRANSPORT_SOCKET_ERROR
:
102 error_callback
.Run("Socket error.");
107 CastSessionDelegate::CastSessionDelegate()
108 : weak_factory_(this) {
109 DCHECK(io_task_runner_
.get());
112 CastSessionDelegate::~CastSessionDelegate() {
113 DCHECK(io_task_runner_
->BelongsToCurrentThread());
116 void CastSessionDelegate::StartAudio(
117 const AudioSenderConfig
& config
,
118 const AudioFrameInputAvailableCallback
& callback
,
119 const ErrorCallback
& error_callback
) {
120 DCHECK(io_task_runner_
->BelongsToCurrentThread());
122 if (!cast_transport_
|| !cast_sender_
) {
123 error_callback
.Run("Destination not set.");
127 audio_frame_input_available_callback_
= callback
;
128 cast_sender_
->InitializeAudio(
130 base::Bind(&CastSessionDelegate::OnOperationalStatusChange
,
131 weak_factory_
.GetWeakPtr(), true, error_callback
));
134 void CastSessionDelegate::StartVideo(
135 const VideoSenderConfig
& config
,
136 const VideoFrameInputAvailableCallback
& callback
,
137 const ErrorCallback
& error_callback
,
138 const media::cast::CreateVideoEncodeAcceleratorCallback
& create_vea_cb
,
139 const media::cast::CreateVideoEncodeMemoryCallback
&
140 create_video_encode_mem_cb
) {
141 DCHECK(io_task_runner_
->BelongsToCurrentThread());
143 if (!cast_transport_
|| !cast_sender_
) {
144 error_callback
.Run("Destination not set.");
148 video_frame_input_available_callback_
= callback
;
150 cast_sender_
->InitializeVideo(
152 base::Bind(&CastSessionDelegate::OnOperationalStatusChange
,
153 weak_factory_
.GetWeakPtr(), false, error_callback
),
155 create_video_encode_mem_cb
);
159 void CastSessionDelegate::StartUDP(
160 const net::IPEndPoint
& local_endpoint
,
161 const net::IPEndPoint
& remote_endpoint
,
162 scoped_ptr
<base::DictionaryValue
> options
,
163 const ErrorCallback
& error_callback
) {
164 DCHECK(io_task_runner_
->BelongsToCurrentThread());
165 CastSessionDelegateBase::StartUDP(local_endpoint
,
169 event_subscribers_
.reset(
170 new media::cast::RawEventSubscriberBundle(cast_environment_
));
172 cast_sender_
= CastSender::Create(cast_environment_
, cast_transport_
.get());
175 void CastSessionDelegate::ToggleLogging(bool is_audio
, bool enable
) {
176 DCHECK(io_task_runner_
->BelongsToCurrentThread());
177 if (!event_subscribers_
.get())
181 event_subscribers_
->AddEventSubscribers(is_audio
);
183 event_subscribers_
->RemoveEventSubscribers(is_audio
);
186 void CastSessionDelegate::GetEventLogsAndReset(
188 const std::string
& extra_data
,
189 const EventLogsCallback
& callback
) {
190 DCHECK(io_task_runner_
->BelongsToCurrentThread());
192 if (!event_subscribers_
.get()) {
193 callback
.Run(make_scoped_ptr(new base::BinaryValue
).Pass());
197 media::cast::EncodingEventSubscriber
* subscriber
=
198 event_subscribers_
->GetEncodingEventSubscriber(is_audio
);
200 callback
.Run(make_scoped_ptr(new base::BinaryValue
).Pass());
204 media::cast::proto::LogMetadata metadata
;
205 media::cast::FrameEventList frame_events
;
206 media::cast::PacketEventList packet_events
;
208 subscriber
->GetEventsAndReset(&metadata
, &frame_events
, &packet_events
);
210 if (!extra_data
.empty())
211 metadata
.set_extra_data(extra_data
);
212 media::cast::proto::GeneralDescription
* gen_desc
=
213 metadata
.mutable_general_description();
214 gen_desc
->set_product(version_info::GetProductName());
215 gen_desc
->set_product_version(version_info::GetVersionNumber());
216 gen_desc
->set_os(version_info::GetOSType());
218 scoped_ptr
<char[]> serialized_log(new char[media::cast::kMaxSerializedBytes
]);
220 bool success
= media::cast::SerializeEvents(metadata
,
224 media::cast::kMaxSerializedBytes
,
225 serialized_log
.get(),
229 DVLOG(2) << "Failed to serialize event log.";
230 callback
.Run(make_scoped_ptr(new base::BinaryValue
).Pass());
234 DVLOG(2) << "Serialized log length: " << output_bytes
;
236 scoped_ptr
<base::BinaryValue
> blob(
237 new base::BinaryValue(serialized_log
.Pass(), output_bytes
));
238 callback
.Run(blob
.Pass());
241 void CastSessionDelegate::GetStatsAndReset(bool is_audio
,
242 const StatsCallback
& callback
) {
243 DCHECK(io_task_runner_
->BelongsToCurrentThread());
245 if (!event_subscribers_
.get()) {
246 callback
.Run(make_scoped_ptr(new base::DictionaryValue
).Pass());
250 media::cast::StatsEventSubscriber
* subscriber
=
251 event_subscribers_
->GetStatsEventSubscriber(is_audio
);
253 callback
.Run(make_scoped_ptr(new base::DictionaryValue
).Pass());
257 scoped_ptr
<base::DictionaryValue
> stats
= subscriber
->GetStats();
260 callback
.Run(stats
.Pass());
263 void CastSessionDelegate::OnOperationalStatusChange(
265 const ErrorCallback
& error_callback
,
266 media::cast::OperationalStatus status
) {
267 DCHECK(cast_sender_
);
270 case media::cast::STATUS_UNINITIALIZED
:
271 case media::cast::STATUS_CODEC_REINIT_PENDING
:
273 // TODO(miu): As an optimization, signal the client to pause sending more
274 // frames until the state becomes STATUS_INITIALIZED again.
276 case media::cast::STATUS_INITIALIZED
:
277 // Once initialized, run the "frame input available" callback to allow the
278 // client to begin sending frames. If STATUS_INITIALIZED is encountered
279 // again, do nothing since this is only an indication that the codec has
280 // successfully re-initialized.
282 if (!audio_frame_input_available_callback_
.is_null()) {
283 base::ResetAndReturn(&audio_frame_input_available_callback_
).Run(
284 cast_sender_
->audio_frame_input());
287 if (!video_frame_input_available_callback_
.is_null()) {
288 base::ResetAndReturn(&video_frame_input_available_callback_
).Run(
289 cast_sender_
->video_frame_input());
293 case media::cast::STATUS_INVALID_CONFIGURATION
:
294 error_callback
.Run(base::StringPrintf("Invalid %s configuration.",
295 is_for_audio
? "audio" : "video"));
297 case media::cast::STATUS_UNSUPPORTED_CODEC
:
298 error_callback
.Run(base::StringPrintf("%s codec not supported.",
299 is_for_audio
? "Audio" : "Video"));
301 case media::cast::STATUS_CODEC_INIT_FAILED
:
302 error_callback
.Run(base::StringPrintf("%s codec initialization failed.",
303 is_for_audio
? "Audio" : "Video"));
305 case media::cast::STATUS_CODEC_RUNTIME_ERROR
:
306 error_callback
.Run(base::StringPrintf("%s codec runtime error.",
307 is_for_audio
? "Audio" : "Video"));
312 void CastSessionDelegate::ReceivePacket(
313 scoped_ptr
<media::cast::Packet
> packet
) {
314 // Do nothing (frees packet)
317 void CastSessionDelegate::LogRawEvents(
318 const std::vector
<media::cast::PacketEvent
>& packet_events
,
319 const std::vector
<media::cast::FrameEvent
>& frame_events
) {
320 DCHECK(io_task_runner_
->BelongsToCurrentThread());
322 for (std::vector
<media::cast::PacketEvent
>::const_iterator it
=
323 packet_events
.begin();
324 it
!= packet_events
.end();
326 cast_environment_
->Logging()->InsertPacketEvent(it
->timestamp
,
335 for (std::vector
<media::cast::FrameEvent
>::const_iterator it
=
336 frame_events
.begin();
337 it
!= frame_events
.end();
339 if (it
->type
== media::cast::FRAME_PLAYOUT
) {
340 cast_environment_
->Logging()->InsertFrameEventWithDelay(
348 cast_environment_
->Logging()->InsertFrameEvent(