Linux Sandbox: make sure Credentials test pass on TSAN
[chromium-blink-merge.git] / media / blink / encrypted_media_player_support.cc
blob7b7669d5642dadfeb328ce3447c55ebd66d5721b
1 // Copyright 2014 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 "media/blink/encrypted_media_player_support.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
11 #include "base/metrics/histogram.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "media/base/bind_to_current_loop.h"
17 #include "media/base/key_systems.h"
18 #include "media/blink/webcontentdecryptionmodule_impl.h"
19 #include "third_party/WebKit/public/platform/WebContentDecryptionModule.h"
20 #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h"
21 #include "third_party/WebKit/public/web/WebDocument.h"
22 #include "third_party/WebKit/public/web/WebLocalFrame.h"
24 using blink::WebMediaPlayer;
25 using blink::WebMediaPlayerClient;
26 using blink::WebString;
28 namespace media {
30 #define BIND_TO_RENDER_LOOP(function) \
31 (BindToCurrentLoop(base::Bind(function, AsWeakPtr())))
33 #define BIND_TO_RENDER_LOOP1(function, arg1) \
34 (BindToCurrentLoop(base::Bind(function, AsWeakPtr(), arg1)))
36 // Prefix for histograms related to Encrypted Media Extensions.
37 static const char* kMediaEme = "Media.EME.";
39 // Convert a WebString to ASCII, falling back on an empty string in the case
40 // of a non-ASCII string.
41 static std::string ToASCIIOrEmpty(const WebString& string) {
42 return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
43 : std::string();
46 // Helper functions to report media EME related stats to UMA. They follow the
47 // convention of more commonly used macros UMA_HISTOGRAM_ENUMERATION and
48 // UMA_HISTOGRAM_COUNTS. The reason that we cannot use those macros directly is
49 // that UMA_* macros require the names to be constant throughout the process'
50 // lifetime.
51 static void EmeUMAHistogramEnumeration(const std::string& key_system,
52 const std::string& method,
53 int sample,
54 int boundary_value) {
55 base::LinearHistogram::FactoryGet(
56 kMediaEme + GetKeySystemNameForUMA(key_system) + "." + method,
57 1, boundary_value, boundary_value + 1,
58 base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
61 static void EmeUMAHistogramCounts(const std::string& key_system,
62 const std::string& method,
63 int sample) {
64 // Use the same parameters as UMA_HISTOGRAM_COUNTS.
65 base::Histogram::FactoryGet(
66 kMediaEme + GetKeySystemNameForUMA(key_system) + "." + method,
67 1, 1000000, 50, base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
70 // Helper enum for reporting generateKeyRequest/addKey histograms.
71 enum MediaKeyException {
72 kUnknownResultId,
73 kSuccess,
74 kKeySystemNotSupported,
75 kInvalidPlayerState,
76 kMaxMediaKeyException
79 static MediaKeyException MediaKeyExceptionForUMA(
80 WebMediaPlayer::MediaKeyException e) {
81 switch (e) {
82 case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
83 return kKeySystemNotSupported;
84 case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
85 return kInvalidPlayerState;
86 case WebMediaPlayer::MediaKeyExceptionNoError:
87 return kSuccess;
88 default:
89 return kUnknownResultId;
93 // Helper for converting |key_system| name and exception |e| to a pair of enum
94 // values from above, for reporting to UMA.
95 static void ReportMediaKeyExceptionToUMA(const std::string& method,
96 const std::string& key_system,
97 WebMediaPlayer::MediaKeyException e) {
98 MediaKeyException result_id = MediaKeyExceptionForUMA(e);
99 DCHECK_NE(result_id, kUnknownResultId) << e;
100 EmeUMAHistogramEnumeration(
101 key_system, method, result_id, kMaxMediaKeyException);
104 // Guess the type of |init_data|. This is only used to handle some corner cases
105 // so we keep it as simple as possible without breaking major use cases.
106 static std::string GuessInitDataType(const unsigned char* init_data,
107 unsigned init_data_length) {
108 // Most WebM files use KeyId of 16 bytes. CENC init data is always >16 bytes.
109 if (init_data_length == 16)
110 return "webm";
112 return "cenc";
115 EncryptedMediaPlayerSupport::EncryptedMediaPlayerSupport(
116 scoped_ptr<CdmFactory> cdm_factory,
117 blink::WebMediaPlayerClient* client,
118 MediaPermission* media_permission,
119 const SetCdmContextCB& set_cdm_context_cb)
120 : cdm_factory_(cdm_factory.Pass()),
121 client_(client),
122 media_permission_(media_permission),
123 set_cdm_context_cb_(set_cdm_context_cb) {
126 EncryptedMediaPlayerSupport::~EncryptedMediaPlayerSupport() {
129 WebMediaPlayer::MediaKeyException
130 EncryptedMediaPlayerSupport::GenerateKeyRequest(
131 blink::WebLocalFrame* frame,
132 const WebString& key_system,
133 const unsigned char* init_data,
134 unsigned init_data_length) {
135 DVLOG(1) << "generateKeyRequest: " << base::string16(key_system) << ": "
136 << std::string(reinterpret_cast<const char*>(init_data),
137 static_cast<size_t>(init_data_length));
139 std::string ascii_key_system =
140 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
142 WebMediaPlayer::MediaKeyException e = GenerateKeyRequestInternal(
143 frame, ascii_key_system, init_data, init_data_length);
144 ReportMediaKeyExceptionToUMA("generateKeyRequest", ascii_key_system, e);
145 return e;
148 WebMediaPlayer::MediaKeyException
149 EncryptedMediaPlayerSupport::GenerateKeyRequestInternal(
150 blink::WebLocalFrame* frame,
151 const std::string& key_system,
152 const unsigned char* init_data,
153 unsigned init_data_length) {
154 if (!PrefixedIsSupportedConcreteKeySystem(key_system))
155 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
157 // We do not support run-time switching between key systems for now.
158 if (current_key_system_.empty()) {
159 if (!proxy_decryptor_) {
160 proxy_decryptor_.reset(new ProxyDecryptor(
161 media_permission_,
162 BIND_TO_RENDER_LOOP(&EncryptedMediaPlayerSupport::OnKeyAdded),
163 BIND_TO_RENDER_LOOP(&EncryptedMediaPlayerSupport::OnKeyError),
164 BIND_TO_RENDER_LOOP(&EncryptedMediaPlayerSupport::OnKeyMessage)));
167 GURL security_origin(frame->document().securityOrigin().toString());
169 if (!proxy_decryptor_->InitializeCDM(cdm_factory_.get(), key_system,
170 security_origin)) {
171 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
174 if (proxy_decryptor_ && !set_cdm_context_cb_.is_null()) {
175 base::ResetAndReturn(&set_cdm_context_cb_)
176 .Run(proxy_decryptor_->GetCdmContext(),
177 base::Bind(&IgnoreCdmAttached));
180 current_key_system_ = key_system;
181 } else if (key_system != current_key_system_) {
182 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
185 std::string init_data_type = init_data_type_;
186 if (init_data_type.empty())
187 init_data_type = GuessInitDataType(init_data, init_data_length);
189 if (!proxy_decryptor_->GenerateKeyRequest(init_data_type, init_data,
190 init_data_length)) {
191 current_key_system_.clear();
192 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
195 return WebMediaPlayer::MediaKeyExceptionNoError;
198 WebMediaPlayer::MediaKeyException EncryptedMediaPlayerSupport::AddKey(
199 const WebString& key_system,
200 const unsigned char* key,
201 unsigned key_length,
202 const unsigned char* init_data,
203 unsigned init_data_length,
204 const WebString& session_id) {
205 DVLOG(1) << "addKey: " << base::string16(key_system) << ": "
206 << std::string(reinterpret_cast<const char*>(key),
207 static_cast<size_t>(key_length)) << ", "
208 << std::string(reinterpret_cast<const char*>(init_data),
209 static_cast<size_t>(init_data_length)) << " ["
210 << base::string16(session_id) << "]";
212 std::string ascii_key_system =
213 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
214 std::string ascii_session_id = ToASCIIOrEmpty(session_id);
216 WebMediaPlayer::MediaKeyException e = AddKeyInternal(ascii_key_system,
217 key,
218 key_length,
219 init_data,
220 init_data_length,
221 ascii_session_id);
222 ReportMediaKeyExceptionToUMA("addKey", ascii_key_system, e);
223 return e;
226 WebMediaPlayer::MediaKeyException
227 EncryptedMediaPlayerSupport::AddKeyInternal(
228 const std::string& key_system,
229 const unsigned char* key,
230 unsigned key_length,
231 const unsigned char* init_data,
232 unsigned init_data_length,
233 const std::string& session_id) {
234 DCHECK(key);
235 DCHECK_GT(key_length, 0u);
237 if (!PrefixedIsSupportedConcreteKeySystem(key_system))
238 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
240 if (current_key_system_.empty() || key_system != current_key_system_)
241 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
243 proxy_decryptor_->AddKey(
244 key, key_length, init_data, init_data_length, session_id);
245 return WebMediaPlayer::MediaKeyExceptionNoError;
248 WebMediaPlayer::MediaKeyException
249 EncryptedMediaPlayerSupport::CancelKeyRequest(
250 const WebString& key_system,
251 const WebString& session_id) {
252 DVLOG(1) << "cancelKeyRequest: " << base::string16(key_system) << ": "
253 << " [" << base::string16(session_id) << "]";
255 std::string ascii_key_system =
256 GetUnprefixedKeySystemName(ToASCIIOrEmpty(key_system));
257 std::string ascii_session_id = ToASCIIOrEmpty(session_id);
259 WebMediaPlayer::MediaKeyException e =
260 CancelKeyRequestInternal(ascii_key_system, ascii_session_id);
261 ReportMediaKeyExceptionToUMA("cancelKeyRequest", ascii_key_system, e);
262 return e;
265 WebMediaPlayer::MediaKeyException
266 EncryptedMediaPlayerSupport::CancelKeyRequestInternal(
267 const std::string& key_system,
268 const std::string& session_id) {
269 if (!PrefixedIsSupportedConcreteKeySystem(key_system))
270 return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
272 if (current_key_system_.empty() || key_system != current_key_system_)
273 return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;
275 proxy_decryptor_->CancelKeyRequest(session_id);
276 return WebMediaPlayer::MediaKeyExceptionNoError;
279 void EncryptedMediaPlayerSupport::SetInitDataType(
280 const std::string& init_data_type) {
281 DCHECK(!init_data_type.empty());
282 DLOG_IF(WARNING,
283 !init_data_type_.empty() && init_data_type != init_data_type_)
284 << "Mixed init data type not supported. The new type is ignored.";
285 if (init_data_type_.empty())
286 init_data_type_ = init_data_type;
289 void EncryptedMediaPlayerSupport::OnPipelineDecryptError() {
290 EmeUMAHistogramCounts(current_key_system_, "DecryptError", 1);
293 void EncryptedMediaPlayerSupport::OnKeyAdded(const std::string& session_id) {
294 EmeUMAHistogramCounts(current_key_system_, "KeyAdded", 1);
295 client_->keyAdded(
296 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
297 WebString::fromUTF8(session_id));
300 void EncryptedMediaPlayerSupport::OnKeyError(const std::string& session_id,
301 MediaKeys::KeyError error_code,
302 uint32 system_code) {
303 EmeUMAHistogramEnumeration(current_key_system_, "KeyError",
304 error_code, MediaKeys::kMaxKeyError);
306 uint16 short_system_code = 0;
307 if (system_code > std::numeric_limits<uint16>::max()) {
308 LOG(WARNING) << "system_code exceeds unsigned short limit.";
309 short_system_code = std::numeric_limits<uint16>::max();
310 } else {
311 short_system_code = static_cast<uint16>(system_code);
314 client_->keyError(
315 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
316 WebString::fromUTF8(session_id),
317 static_cast<WebMediaPlayerClient::MediaKeyErrorCode>(error_code),
318 short_system_code);
321 void EncryptedMediaPlayerSupport::OnKeyMessage(
322 const std::string& session_id,
323 const std::vector<uint8>& message,
324 const GURL& destination_url) {
325 DCHECK(destination_url.is_empty() || destination_url.is_valid());
327 client_->keyMessage(
328 WebString::fromUTF8(GetPrefixedKeySystemName(current_key_system_)),
329 WebString::fromUTF8(session_id),
330 message.empty() ? NULL : &message[0],
331 base::saturated_cast<unsigned int>(message.size()),
332 destination_url);
335 } // namespace media