Import Cobalt 13.108984
Change-Id: Ic087ddd013d13dfaf3cb3a7dd34c5ddb72c85d7c
diff --git a/src/cobalt/accessibility/screen_reader_tests.cc b/src/cobalt/accessibility/screen_reader_tests.cc
index 714f243..611d7ed 100644
--- a/src/cobalt/accessibility/screen_reader_tests.cc
+++ b/src/cobalt/accessibility/screen_reader_tests.cc
@@ -173,9 +173,9 @@
base::Bind(&LiveRegionMutationTest::OnError, base::Unretained(this)),
base::Bind(&LiveRegionMutationTest::OnClose, base::Unretained(this)),
base::Closure(), /* window_minimize_callback */
- NULL /* media_module */, &network_module, kDefaultViewportSize,
- kDefaultVideoPixelRatio, &resource_provider, kRefreshRate,
- web_module_options);
+ NULL /* can_play_type_handler */, NULL /* web_media_player_factory */,
+ &network_module, kDefaultViewportSize, kDefaultVideoPixelRatio,
+ &resource_provider, kRefreshRate, web_module_options);
// Wait for the test to quit.
quit_event_.Wait();
diff --git a/src/cobalt/base/c_val.cc b/src/cobalt/base/c_val.cc
index f0c9a84..d44f9fa 100644
--- a/src/cobalt/base/c_val.cc
+++ b/src/cobalt/base/c_val.cc
@@ -48,7 +48,9 @@
delete registered_vars_;
}
-void CValManager::RegisterCVal(const CValDetail::CValBase* cval) {
+void CValManager::RegisterCVal(
+ const CValDetail::CValBase* cval,
+ scoped_refptr<base::RefCountedThreadSafeLock>* value_lock) {
base::AutoLock auto_lock(cvals_lock_);
// CVals cannot share name. If this assert is triggered, we are trying to
@@ -57,6 +59,7 @@
DCHECK(registered_vars_->find(cval->GetName()) == registered_vars_->end());
(*registered_vars_)[cval->GetName()] = cval;
+ *value_lock = value_lock_refptr_;
}
void CValManager::UnregisterCVal(const CValDetail::CValBase* cval) {
diff --git a/src/cobalt/base/c_val.h b/src/cobalt/base/c_val.h
index a589822..b399965 100644
--- a/src/cobalt/base/c_val.h
+++ b/src/cobalt/base/c_val.h
@@ -437,8 +437,10 @@
~CValManager();
// Called in CVal constructors to register/deregister themselves with the
- // system.
- void RegisterCVal(const CValDetail::CValBase* cval);
+ // system. Registering a CVal will also provide that CVal with a value lock
+ // to lock when it modifies its value.
+ void RegisterCVal(const CValDetail::CValBase* cval,
+ scoped_refptr<base::RefCountedThreadSafeLock>* value_lock);
void UnregisterCVal(const CValDetail::CValBase* cval);
#if defined(ENABLE_DEBUG_C_VAL)
@@ -523,7 +525,6 @@
CommonConstructor();
}
virtual ~CValImpl() {
- base::AutoLock auto_lock(value_lock_refptr_->GetLock());
if (registered_) {
CValManager::GetInstance()->UnregisterCVal(this);
}
@@ -610,8 +611,7 @@
void RegisterWithManager() {
if (!registered_) {
CValManager* manager = CValManager::GetInstance();
- manager->RegisterCVal(this);
- value_lock_refptr_ = manager->value_lock_refptr_;
+ manager->RegisterCVal(this, &value_lock_refptr_);
registered_ = true;
}
}
diff --git a/src/cobalt/base/c_val_test.cc b/src/cobalt/base/c_val_test.cc
index 1087ad2..9729480 100644
--- a/src/cobalt/base/c_val_test.cc
+++ b/src/cobalt/base/c_val_test.cc
@@ -13,7 +13,10 @@
// limitations under the License.
#include <limits>
+#include <utility>
+#include "base/synchronization/waitable_event.h"
+#include "base/threading/simple_thread.h"
#include "base/time.h"
#include "cobalt/base/c_val.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -584,4 +587,113 @@
EXPECT_EQ(test_hook.value_changed_count_, 1);
}
+namespace {
+// Helper class for the RemoveAndRead test defined below.
+class ReadCValThread : public base::SimpleThread {
+ public:
+ ReadCValThread(const char* test_cval_name, int num_read_cycles,
+ std::pair<std::string, std::string> valid_values,
+ base::WaitableEvent* thread_ready_event,
+ base::WaitableEvent* start_processing_event)
+ : base::SimpleThread("ReadCValThread"),
+ test_cval_name_(test_cval_name),
+ num_read_cycles_(num_read_cycles),
+ valid_values_(valid_values),
+ thread_ready_event_(thread_ready_event),
+ start_processing_event_(start_processing_event) {}
+
+ void Run() OVERRIDE {
+ thread_ready_event_->Signal();
+ start_processing_event_->Wait();
+
+ base::CValManager* cvm = base::CValManager::GetInstance();
+ for (int i = 0; i < num_read_cycles_; ++i) {
+ base::optional<std::string> result =
+ cvm->GetValueAsString(test_cval_name_);
+ if (result) {
+ EXPECT_TRUE(*result == valid_values_.first ||
+ *result == valid_values_.second);
+ }
+ }
+ }
+
+ private:
+ const char* test_cval_name_;
+ int num_read_cycles_;
+ std::pair<std::string, std::string> valid_values_;
+ base::WaitableEvent* thread_ready_event_;
+ base::WaitableEvent* start_processing_event_;
+};
+
+// Helper class for the RemoveAndRead test defined below.
+class CreateDestroyCValThread : public base::SimpleThread {
+ public:
+ CreateDestroyCValThread(const char* test_cval_name,
+ int num_create_destroy_cycles,
+ std::pair<std::string, std::string> valid_values,
+ base::WaitableEvent* thread_ready_event,
+ base::WaitableEvent* start_processing_event)
+ : base::SimpleThread("CreateDestroyCValThread"),
+ test_cval_name_(test_cval_name),
+ num_create_destroy_cycles_(num_create_destroy_cycles),
+ valid_values_(valid_values),
+ thread_ready_event_(thread_ready_event),
+ start_processing_event_(start_processing_event) {}
+
+ void Run() OVERRIDE {
+ thread_ready_event_->Signal();
+ start_processing_event_->Wait();
+
+ for (int i = 0; i < num_create_destroy_cycles_; ++i) {
+ base::CVal<std::string> test_cval(test_cval_name_, valid_values_.first,
+ "Description");
+ test_cval = valid_values_.second;
+ }
+ }
+
+ private:
+ const char* test_cval_name_;
+ int num_create_destroy_cycles_;
+ std::pair<std::string, std::string> valid_values_;
+ base::WaitableEvent* thread_ready_event_;
+ base::WaitableEvent* start_processing_event_;
+};
+
+} // namespace
+
+// Tests that we can create and destroy cvals no problem while simultaneously
+// reading from them. The test creates two threads, a reader thread and a
+// creater/destroyer (and writer) thread. These both attempt to access the same
+// cval as fast as possible.
+TEST(CValTest, RemoveAndRead) {
+ const char* kTestCValName = "TestCVal";
+ const int kNumReadCycles = 10000;
+ const int kNuMCreateDestroyCycles = 10000;
+ const std::pair<std::string, std::string> valid_values("hello", "66");
+ base::WaitableEvent read_cval_thread_ready(true, false);
+ base::WaitableEvent create_destroy_cval_thread_ready(true, false);
+ base::WaitableEvent start_processing_event(true, false);
+
+ // Create and start both threads.
+ ReadCValThread read_cval_thread(kTestCValName, kNumReadCycles, valid_values,
+ &read_cval_thread_ready,
+ &start_processing_event);
+ CreateDestroyCValThread create_destroy_cval_thread(
+ kTestCValName, kNuMCreateDestroyCycles, valid_values,
+ &create_destroy_cval_thread_ready, &start_processing_event);
+ read_cval_thread.Start();
+ create_destroy_cval_thread.Start();
+
+ // Wait until both threads are initialized and ready.
+ read_cval_thread_ready.Wait();
+ create_destroy_cval_thread_ready.Wait();
+
+ // Signal for the processing/testing to begin.
+ start_processing_event.Signal();
+
+ // Wait for both threads to complete.
+ read_cval_thread.Join();
+ create_destroy_cval_thread.Join();
+}
+
} // namespace base
diff --git a/src/cobalt/bindings/bindings.gypi b/src/cobalt/bindings/bindings.gypi
index 9260d08..0db0d57 100644
--- a/src/cobalt/bindings/bindings.gypi
+++ b/src/cobalt/bindings/bindings.gypi
@@ -64,6 +64,20 @@
'../script/engine_variables.gypi',
'../../third_party/blink/Source/bindings/scripts/scripts.gypi',
],
+ 'variables': {
+ # Legend has it that experienced Chrome developers can actually nest
+ # variables up to four levels. Here, we keep things simple and only do
+ # three. We do this because "engine_variables.gypi" will create another
+ # variables scope and then branch on |javascript_engine|, which requires
+ # a default value to be provided one level lower.
+ 'variables': {
+ 'javascript_engine%': '<(default_javascript_engine)',
+ },
+ # Specify a default component for generated window IDL. This should be
+ # removed when the concept of 'components' in the blink IDL parsing scripts
+ # is refactored out, since it doesn't really apply to Cobalt.
+ 'window_component%': 'dom',
+ },
# Define these variables in the including .gyp file and their lists will get
# merged in, giving some control to how the bindings are built.
@@ -104,12 +118,6 @@
# Constructors will be an event in the unsupported property mechanism.
'unsupported_interface_idl_files': [],
- # Specify a default component for generated window IDL. This should be
- # removed when the concept of 'components' in the blink IDL parsing scripts
- # is refactored out, since it doesn't really apply to Cobalt.
- 'variables': {
- 'window_component%': 'dom',
- },
'window_component%': '<(window_component)',
'prefix': '<(generated_bindings_prefix)',
diff --git a/src/cobalt/bindings/contexts.py b/src/cobalt/bindings/contexts.py
index 702090e..d779ec5 100644
--- a/src/cobalt/bindings/contexts.py
+++ b/src/cobalt/bindings/contexts.py
@@ -86,6 +86,19 @@
return type_map[idl_type.base_type]
+def idl_string_type_to_cobalt(idl_type):
+ """Map IDL string type to C++ type."""
+ type_map = {
+ 'ByteString': 'std::vector<uint8_t>',
+ 'DOMString': 'std::string',
+ 'String': 'std::string',
+ 'StringOrNull': 'std::string',
+ 'USVString': 'std::string',
+ }
+ assert idl_type.is_string_type, 'Expected string type.'
+ return type_map[idl_type.name]
+
+
def cobalt_type_is_optional(idl_type):
"""Return True iff the idl_type should be wrapped by a base::optional<>.
@@ -235,7 +248,7 @@
if idl_type.is_primitive_type:
cobalt_type = idl_primitive_type_to_cobalt(idl_type)
elif idl_type.is_string_type:
- cobalt_type = 'std::string'
+ cobalt_type = idl_string_type_to_cobalt(idl_type)
elif idl_type.is_callback_interface:
cobalt_type = '::cobalt::script::CallbackInterfaceTraits<%s >' % (
get_interface_name(idl_type))
@@ -436,8 +449,9 @@
def attribute_context(self, interface, attribute, definitions):
"""Create template values for attribute bindings."""
- cobalt_name = attribute.extended_attributes.get(
- 'ImplementedAs', convert_to_cobalt_name(attribute.name))
+ cobalt_name = attribute.extended_attributes.get('ImplementedAs',
+ convert_to_cobalt_name(
+ attribute.name))
context = {
'idl_name':
attribute.name,
@@ -495,8 +509,10 @@
return {
'enumeration_name':
enumeration.name,
- 'value_pairs': [(convert_to_cobalt_enumeration_value(
- enumeration.name, value), value,) for value in enumeration.values],
+ 'value_pairs': [(
+ convert_to_cobalt_enumeration_value(enumeration.name, value),
+ value,
+ ) for value in enumeration.values],
}
def constant_context(self, constant):
@@ -538,9 +554,9 @@
[m for m in methods if m['is_static']])
non_static_method_overloads = method_overloads_by_name(
[m for m in methods if not m['is_static']])
- static_overload_contexts = get_overload_contexts(expression_generator, [
- contexts for _, contexts in static_method_overloads
- ])
+ static_overload_contexts = get_overload_contexts(
+ expression_generator,
+ [contexts for _, contexts in static_method_overloads])
non_static_overload_contexts = get_overload_contexts(
expression_generator,
[contexts for _, contexts in non_static_method_overloads])
diff --git a/src/cobalt/bindings/testing/bindings_test_base.h b/src/cobalt/bindings/testing/bindings_test_base.h
index ddb7ca5..f37639b 100644
--- a/src/cobalt/bindings/testing/bindings_test_base.h
+++ b/src/cobalt/bindings/testing/bindings_test_base.h
@@ -67,8 +67,8 @@
scoped_refptr<script::SourceCode> source =
script::SourceCode::CreateSourceCode(
script, base::SourceLocation("[object BindingsTestBase]", 1, 1));
- return global_environment_->EvaluateScript(source, out_result,
- false /*mute_errors*/);
+ return global_environment_->EvaluateScript(source, false /*mute_errors*/,
+ out_result);
}
bool EvaluateScript(const std::string& script,
@@ -79,7 +79,7 @@
script::SourceCode::CreateSourceCode(
script, base::SourceLocation("[object BindingsTestBase]", 1, 1));
return global_environment_->EvaluateScript(
- source, owning_object, out_opaque_handle, false /*mute_errors*/);
+ source, owning_object, false /*mute_errors*/, out_opaque_handle);
}
void CollectGarbage() { engine_->CollectGarbage(); }
diff --git a/src/cobalt/browser/application.cc b/src/cobalt/browser/application.cc
index 636ebf5..81c407e 100644
--- a/src/cobalt/browser/application.cc
+++ b/src/cobalt/browser/application.cc
@@ -363,21 +363,6 @@
&options->scratch_surface_cache_size_in_bytes);
}
-// Restrict navigation to a couple of whitelisted URLs by default.
-const char kYouTubeTvLocationPolicy[] =
- "h5vcc-location-src "
- "https://s.ytimg.com/yts/cobalt/ "
- "https://www.youtube.com/tv "
- "https://www.youtube.com/tv/ "
- "https://web-green-qa.youtube.com/tv "
- "https://web-green-qa.youtube.com/tv/ "
- "https://web-release-qa.youtube.com/tv "
- "https://web-release-qa.youtube.com/tv/ "
-#if defined(ENABLE_ABOUT_SCHEME)
- "about: "
-#endif
- "h5vcc:";
-
struct NonTrivialStaticFields {
NonTrivialStaticFields() : system_language(base::GetSystemLanguage()) {}
@@ -516,7 +501,6 @@
// User can specify an extra search path entry for files loaded via file://.
options.web_module_options.extra_web_file_dir = GetExtraWebFileDir();
SecurityFlags security_flags{csp::kCSPRequired, network::kHTTPSRequired};
- options.web_module_options.location_policy = kYouTubeTvLocationPolicy;
// Set callback to be notified when a navigation occurs that destroys the
// underlying WebModule.
options.web_module_recreated_callback =
@@ -610,13 +594,6 @@
options.web_module_options.require_csp = security_flags.csp_header_policy;
options.web_module_options.csp_enforcement_mode = dom::kCspEnforcementEnable;
- if (command_line->HasSwitch(browser::switches::kDisableNavigationWhitelist)) {
- LOG(ERROR) << "\n"
- << " *** Disabling the default navigation whitelist! ***\n"
- << " *** Do not run in this mode in production! ***";
- options.web_module_options.location_policy = "h5vcc-location-src *";
- }
-
options.requested_viewport_size = requested_viewport_size;
account_manager_.reset(new account::AccountManager());
browser_module_.reset(
diff --git a/src/cobalt/browser/browser_module.cc b/src/cobalt/browser/browser_module.cc
index a1f944d..b1d2a9e 100644
--- a/src/cobalt/browser/browser_module.cc
+++ b/src/cobalt/browser/browser_module.cc
@@ -223,6 +223,7 @@
new ResourceProviderArrayBufferAllocator(GetResourceProvider())),
array_buffer_cache_(new dom::ArrayBuffer::Cache(3 * 1024 * 1024)),
#endif // defined(ENABLE_GPU_ARRAY_BUFFER_ALLOCATOR)
+ can_play_type_handler_(media::MediaModule::CreateCanPlayTypeHandler()),
network_module_(&storage_manager_, event_dispatcher_,
options_.network_module_options),
web_module_loaded_(true /* manually_reset */,
@@ -255,6 +256,7 @@
render_timeout_count_(0),
#endif
on_error_retry_count_(0),
+ waiting_for_error_retry_(false),
will_quit_(false),
application_state_(initial_application_state),
splash_screen_cache_(new SplashScreenCache()),
@@ -354,9 +356,7 @@
BrowserModule::~BrowserModule() {
DCHECK_EQ(MessageLoop::current(), self_message_loop_);
- if (on_error_retry_timer_.IsRunning()) {
- on_error_retry_timer_.Stop();
- }
+ on_error_retry_timer_.Stop();
#if SB_HAS(CORE_DUMP_HANDLER_SUPPORT)
SbCoreDumpUnregisterHandler(BrowserModule::CoreDumpHandler, this);
#endif
@@ -384,9 +384,10 @@
return;
}
- if (on_error_retry_timer_.IsRunning()) {
- on_error_retry_timer_.Stop();
- }
+ // Clear error handling once we're told to navigate, either because it's the
+ // retry from the error or something decided we should navigate elsewhere.
+ on_error_retry_timer_.Stop();
+ waiting_for_error_retry_ = false;
// Navigations aren't allowed if the app is suspended. If this is the case,
// simply set the pending navigate url, which will cause the navigation to
@@ -483,8 +484,9 @@
base::Bind(&BrowserModule::OnError, base::Unretained(this)),
base::Bind(&BrowserModule::OnWindowClose, base::Unretained(this)),
base::Bind(&BrowserModule::OnWindowMinimize, base::Unretained(this)),
- media_module_.get(), &network_module_, viewport_size, video_pixel_ratio,
- GetResourceProvider(), kLayoutMaxRefreshFrequencyInHz, options));
+ can_play_type_handler_.get(), media_module_.get(), &network_module_,
+ viewport_size, video_pixel_ratio, GetResourceProvider(),
+ kLayoutMaxRefreshFrequencyInHz, options));
lifecycle_observers_.AddObserver(web_module_.get());
if (!web_module_recreated_callback_.is_null()) {
web_module_recreated_callback_.Run();
@@ -891,6 +893,7 @@
void BrowserModule::OnErrorRetry() {
++on_error_retry_count_;
on_error_retry_time_ = base::TimeTicks::Now();
+ waiting_for_error_retry_ = true;
TryURLHandlers(
GURL("h5vcc://network-failure?retry-url=" + pending_navigate_url_));
}
@@ -1236,7 +1239,7 @@
if (web_module_) {
web_module_->SetCamera3D(input_device_manager_->camera_3d());
- web_module_->SetMediaModule(media_module_.get());
+ web_module_->SetWebMediaPlayerFactory(media_module_.get());
web_module_->SetSize(size, video_pixel_ratio);
}
}
@@ -1335,8 +1338,8 @@
TRACE_EVENT0("cobalt::browser",
"BrowserModule::StartOrResumeInternalPostStateUpdate");
// If there's a navigation that's pending, then attempt to navigate to its
- // specified URL now.
- if (!pending_navigate_url_.empty()) {
+ // specified URL now, unless we're still waiting for an error retry.
+ if (!pending_navigate_url_.empty() && !waiting_for_error_retry_) {
Navigate(GURL(pending_navigate_url_));
}
}
diff --git a/src/cobalt/browser/browser_module.h b/src/cobalt/browser/browser_module.h
index 2ecdbcf..f3cf4a2 100644
--- a/src/cobalt/browser/browser_module.h
+++ b/src/cobalt/browser/browser_module.h
@@ -44,6 +44,8 @@
#include "cobalt/dom/wheel_event_init.h"
#include "cobalt/input/input_device_manager.h"
#include "cobalt/layout/layout_manager.h"
+#include "cobalt/media/can_play_type_handler.h"
+#include "cobalt/media/media_module.h"
#include "cobalt/network/network_module.h"
#include "cobalt/render_tree/resource_provider.h"
#include "cobalt/render_tree/resource_provider_stub.h"
@@ -390,6 +392,9 @@
// Controls all media playback related objects/resources.
scoped_ptr<media::MediaModule> media_module_;
+ // Allows checking if particular media type can be played.
+ scoped_ptr<media::CanPlayTypeHandler> can_play_type_handler_;
+
// Sets up the network component for requesting internet resources.
network::NetworkModule network_module_;
@@ -496,6 +501,11 @@
// when it is not already active.
base::OneShotTimer<BrowserModule> on_error_retry_timer_;
+ // Set when we've posted a system error for network failure until we receive
+ // the next navigation. This is used to suppress retrying the current URL on
+ // resume until the error retry occurs.
+ bool waiting_for_error_retry_;
+
// Set when the application is about to quit. May be set from a thread other
// than the one hosting this object, and read from another.
bool will_quit_;
diff --git a/src/cobalt/browser/debug_console.cc b/src/cobalt/browser/debug_console.cc
index ec0aba7..2f99e6f 100644
--- a/src/cobalt/browser/debug_console.cc
+++ b/src/cobalt/browser/debug_console.cc
@@ -188,15 +188,15 @@
base::Bind(&CreateDebugHub,
base::Bind(&DebugConsole::GetMode, base::Unretained(this)),
get_debug_server_callback);
- web_module_.reset(
- new WebModule(GURL(kInitialDebugConsoleUrl), initial_application_state,
- render_tree_produced_callback,
- base::Bind(&DebugConsole::OnError, base::Unretained(this)),
- WebModule::CloseCallback(), /* window_close_callback */
- base::Closure(), /* window_minimize_callback */
- &stub_media_module_, network_module, window_dimensions,
- 1.f /*video_pixel_ratio*/, resource_provider,
- layout_refresh_rate, web_module_options));
+ web_module_.reset(new WebModule(
+ GURL(kInitialDebugConsoleUrl), initial_application_state,
+ render_tree_produced_callback,
+ base::Bind(&DebugConsole::OnError, base::Unretained(this)),
+ WebModule::CloseCallback(), /* window_close_callback */
+ base::Closure(), /* window_minimize_callback */
+ NULL /* can_play_type_handler */, NULL /* web_media_player_factory */,
+ network_module, window_dimensions, 1.f /*video_pixel_ratio*/,
+ resource_provider, layout_refresh_rate, web_module_options));
}
DebugConsole::~DebugConsole() {}
diff --git a/src/cobalt/browser/debug_console.h b/src/cobalt/browser/debug_console.h
index 3889f9a..7d50520 100644
--- a/src/cobalt/browser/debug_console.h
+++ b/src/cobalt/browser/debug_console.h
@@ -26,7 +26,6 @@
#include "cobalt/browser/web_module.h"
#include "cobalt/debug/debug_hub.h"
#include "cobalt/dom/keyboard_event_init.h"
-#include "cobalt/media/media_module_stub.h"
#include "googleurl/src/gurl.h"
namespace cobalt {
@@ -86,8 +85,6 @@
LOG(ERROR) << error;
}
- media::MediaModuleStub stub_media_module_;
-
// The current console visibility mode. The mutex is required since the debug
// console's visibility mode may be accessed from both the WebModule thread
// and the DebugConsole's host thread.
diff --git a/src/cobalt/browser/lib/cobalt.def b/src/cobalt/browser/lib/cobalt.def
index 7a73eb4..845c307 100644
--- a/src/cobalt/browser/lib/cobalt.def
+++ b/src/cobalt/browser/lib/cobalt.def
@@ -12,6 +12,7 @@
CbLibMainSetCallbackRegistrationReadyCallback
CbLibMainSetOnCobaltInitializedCallback
CbLibMainSetHandleEventCallback
+ CbLibMainGetSbWindow
; From cobalt/render/rasterizer/lib/exported/graphics.h:
CbLibGraphicsSetContextCreatedCallback
@@ -21,10 +22,10 @@
CbLibGraphicsSetTargetMainTextureSize
; From cobalt/render/rasterizer/lib/exported/video.h:
- CbLibVideoSetOnUpdateProjectionType
+ CbLibVideoSetOnUpdateProjectionTypeAndStereoMode
CbLibVideoSetOnUpdateMeshes
- CbLibVideoSetOnUpdateStereoMode
CbLibVideoSetOnUpdateRgbTextureId
+ CbLibVideoSetOnUpdateAspectRatio
; Following GL functions are copied from libGLESv2.def and EGL from
; libEGL.def. We export these so that host-applications may use the same
diff --git a/src/cobalt/browser/lib/exported/main.h b/src/cobalt/browser/lib/exported/main.h
index 087cb52..ba867bf 100644
--- a/src/cobalt/browser/lib/exported/main.h
+++ b/src/cobalt/browser/lib/exported/main.h
@@ -20,6 +20,7 @@
#include "starboard/event.h"
#include "starboard/export.h"
+#include "starboard/window.h"
#ifdef __cplusplus
extern "C" {
@@ -46,6 +47,16 @@
SB_EXPORT_PLATFORM void CbLibMainSetHandleEventCallback(
void* context, CbLibMainHandleEventCallback callback);
+// Returns a reference to the system window's underlying Starboard window, or
+// nullptr if the system window does not exist.
+//
+// The system window may be destroyed and recreated during Cobalt's application
+// life-cycle E.G. if a Suspend/Resume event occurs. For this reason, clients
+// should not cache references returned by this call. A client which requires
+// long-term access to the system window should re-query the reference each time
+// it is needed.
+SB_EXPORT_PLATFORM SbWindow CbLibMainGetSbWindow();
+
#ifdef __cplusplus
} // extern "C"
#endif
diff --git a/src/cobalt/browser/lib/main.cc b/src/cobalt/browser/lib/main.cc
index 5e82dab..1780b3a 100644
--- a/src/cobalt/browser/lib/main.cc
+++ b/src/cobalt/browser/lib/main.cc
@@ -46,6 +46,8 @@
LOG(INFO) << "Preloading application.";
DCHECK(!g_application);
CHECK(g_callback_registration_ready);
+ // Register a default event handler up front.
+ CbLibMainSetHandleEventCallback(nullptr, nullptr);
g_callback_registration_ready(g_registration_ready_context);
g_application =
new cobalt::browser::Application(quit_closure, true /*should_preload*/);
@@ -57,6 +59,8 @@
LOG(INFO) << "Starting application.";
if (!g_application) {
CHECK(g_callback_registration_ready);
+ // Register a default event handler up front.
+ CbLibMainSetHandleEventCallback(nullptr, nullptr);
g_callback_registration_ready(g_registration_ready_context);
g_application = new cobalt::browser::Application(quit_closure,
false /*should_preload*/);
@@ -77,8 +81,17 @@
}
void HandleStarboardEvent(const SbEvent* starboard_event) {
- if (g_application && (g_handle_event_callback.Get().is_null() ||
- !g_handle_event_callback.Get().Run(starboard_event))) {
+ if (!g_application) {
+ return;
+ }
+
+ // TODO(dworsham): Host-generated input events will also be fed through the
+ // host callback, leading to re-entrancy issues. Set up a way of filtering
+ // them somehow.
+ //
+ // For now, works fine with YTVR as only input events are generated by the
+ // host and the host also ignores all input events sent its way.
+ if (!g_handle_event_callback.Get().Run(starboard_event)) {
g_application->HandleStarboardEvent(starboard_event);
}
}
@@ -102,6 +115,16 @@
void CbLibMainSetHandleEventCallback(void* context,
CbLibMainHandleEventCallback callback) {
- g_handle_event_callback.Get() =
- callback ? base::Bind(callback, context) : HandleEventCallback();
+ // If the user passes nullptr, provide a default event handler so that it is
+ // never actually null.
+ g_handle_event_callback.Get() = callback ?
+ base::Bind(callback, context) :
+ base::Bind([](const SbEvent*) {
+ return false;
+ });
+}
+
+SbWindow CbLibMainGetSbWindow() {
+ auto* primary_window = cobalt::system_window::SystemWindow::PrimaryWindow();
+ return primary_window ? primary_window->GetSbWindow() : nullptr;
}
diff --git a/src/cobalt/browser/splash_screen.cc b/src/cobalt/browser/splash_screen.cc
index 811baa0..0c4026b 100644
--- a/src/cobalt/browser/splash_screen.cc
+++ b/src/cobalt/browser/splash_screen.cc
@@ -100,9 +100,9 @@
*url_to_pass, initial_application_state, render_tree_produced_callback_,
base::Bind(&OnError), on_window_close,
base::Closure(), // window_minimize_callback
- &stub_media_module_, network_module, window_dimensions,
- 1.f /*video_pixel_ratio*/, resource_provider, layout_refresh_rate,
- web_module_options));
+ NULL /* can_play_type_handler */, NULL /* web_media_player_factory */,
+ network_module, window_dimensions, 1.f /*video_pixel_ratio*/,
+ resource_provider, layout_refresh_rate, web_module_options));
}
SplashScreen::~SplashScreen() {
diff --git a/src/cobalt/browser/splash_screen.h b/src/cobalt/browser/splash_screen.h
index f9315d2..bc21bbe 100644
--- a/src/cobalt/browser/splash_screen.h
+++ b/src/cobalt/browser/splash_screen.h
@@ -23,7 +23,6 @@
#include "cobalt/browser/lifecycle_observer.h"
#include "cobalt/browser/splash_screen_cache.h"
#include "cobalt/browser/web_module.h"
-#include "cobalt/media/media_module_stub.h"
#include "googleurl/src/gurl.h"
namespace cobalt {
@@ -80,8 +79,6 @@
void OnWindowClosed();
void OnWindowClosedInternal();
- media::MediaModuleStub stub_media_module_;
-
WebModule::OnRenderTreeProducedCallback render_tree_produced_callback_;
scoped_ptr<WebModule> web_module_;
diff --git a/src/cobalt/browser/switches.cc b/src/cobalt/browser/switches.cc
index 12bbc04..def7e22 100644
--- a/src/cobalt/browser/switches.cc
+++ b/src/cobalt/browser/switches.cc
@@ -137,10 +137,6 @@
// frames has been collected.
const char kFPSOverlay[] = "fps_overlay";
-// Disables the hard-coded navigation whitelist without disabling any other
-// security checks. This is enabled in production(gold) builds.
-const char kDisableNavigationWhitelist[] = "disable_navigation_whitelist";
-
// Determines the capacity of the image cache which manages image surfaces
// downloaded from a web page. While it depends on the platform, often (and
// ideally) these images are cached within GPU memory.
diff --git a/src/cobalt/browser/switches.h b/src/cobalt/browser/switches.h
index dd36528..812b1bc 100644
--- a/src/cobalt/browser/switches.h
+++ b/src/cobalt/browser/switches.h
@@ -48,7 +48,6 @@
extern const char kWebDriverPort[];
#endif // ENABLE_DEBUG_COMMAND_LINE_SWITCHES
-extern const char kDisableNavigationWhitelist[];
extern const char kFPSPrint[];
extern const char kFPSOverlay[];
extern const char kImageCacheSizeInBytes[];
diff --git a/src/cobalt/browser/testdata/mtm-demo/mtm.html b/src/cobalt/browser/testdata/mtm-demo/mtm.html
index e91a3cc..eeee431 100644
--- a/src/cobalt/browser/testdata/mtm-demo/mtm.html
+++ b/src/cobalt/browser/testdata/mtm-demo/mtm.html
@@ -21,6 +21,28 @@
background-color: white;
color: black;
}
+
+ @keyframes blink {
+ from {background-color: white;}
+ to {background-color: black;}
+ }
+
+ .spinner {
+ position: absolute;
+ left: 0;
+ bottom: 0;
+ animation: blink 1s infinite alternate;
+ width: 20px;
+ height: 20px;
+ }
+
+ #fps {
+ position: absolute;
+ left: 50px;
+ bottom: 0;
+ background-color: white;
+ color: black;
+ }
</style>
<script>
@@ -63,6 +85,37 @@
0x8017, camera3D.DOM_CAMERA_YAW, degreesPerSecond);
camera3D.createKeyMapping(
0x8018, camera3D.DOM_CAMERA_YAW, -degreesPerSecond);
+
+ // Update the frame rate counter at a regular interval.
+ function UpdateFPS() {
+ if ('h5vcc' in window && 'cVal' in window.h5vcc) {
+ // Query Cobalt for the average amount of time between the start of
+ // each frame. Translate that into a framerate and then update a
+ // framerate counter on the window.
+ var average_frame_time_in_us = window.h5vcc.cVal.getValue(
+ 'Renderer.Rasterize.DurationInterval.Avg');
+ if (!average_frame_time_in_us || average_frame_time_in_us <= 0) {
+ // In older versions of Cobalt use a different name for the framerate
+ // counter, so try falling back to that if the first fails.
+ average_frame_time_in_us = window.h5vcc.cVal.getValue(
+ 'Renderer.Rasterize.Duration.Avg');
+ }
+
+ if (average_frame_time_in_us && average_frame_time_in_us > 0) {
+ // Convert frame time into frame rate (by taking the inverse).
+ // We also multiply by 1000000 to convert from microseconds to
+ // seconds.
+ var average_frames_per_second =
+ Math.round(1000000.0 / average_frame_time_in_us);
+
+ // Update the display with our calculated frame rate.
+ var fps_counter = document.getElementById('fps');
+ fps_counter.innerHTML = 'FPS: ' + average_frames_per_second;
+ }
+ }
+ window.setTimeout(UpdateFPS, 1000);
+ }
+ window.setTimeout(UpdateFPS, 1000);
</script>
</head>
@@ -72,6 +125,14 @@
Use either the keyboard keys, direction keys, or analog joystick/thumbstick
to look around.
</div>
+ <!-- The spinner is required in order to get around an implementation detail
+ of the 'Renderer.Rasterize.DurationInterval.Avg' cval that we rely on
+ for measuring the framerate. In a nutshell, that cval is only updated
+ when a CSS animation is active, but not when a video is playing, even
+ though both of these things result in a continual re-rasterization of
+ the UI/video. -->
+ <div class="spinner"></div>
+ <div id="fps"></div>
</body>
</html>
diff --git a/src/cobalt/browser/web_module.cc b/src/cobalt/browser/web_module.cc
index 4026fb1..6a5599a 100644
--- a/src/cobalt/browser/web_module.cc
+++ b/src/cobalt/browser/web_module.cc
@@ -184,7 +184,8 @@
void SetSize(math::Size window_dimensions, float video_pixel_ratio);
void SetCamera3D(const scoped_refptr<input::Camera3D>& camera_3d);
- void SetMediaModule(media::MediaModule* media_module);
+ void SetWebMediaPlayerFactory(
+ media::WebMediaPlayerFactory* web_media_player_factory);
void SetImageCacheCapacity(int64_t bytes);
void SetRemoteTypefaceCacheCapacity(int64_t bytes);
void SetJavascriptGcThreshold(int64_t bytes);
@@ -527,8 +528,9 @@
dom_parser_.get(), fetcher_factory_.get(), &resource_provider_,
animated_image_tracker_.get(), image_cache_.get(),
reduced_image_cache_capacity_manager_.get(), remote_typeface_cache_.get(),
- mesh_cache_.get(), local_storage_database_.get(), data.media_module,
- data.media_module, execution_state_.get(), script_runner_.get(),
+ mesh_cache_.get(), local_storage_database_.get(),
+ data.can_play_type_handler, data.web_media_player_factory,
+ execution_state_.get(), script_runner_.get(),
global_environment_->script_value_factory(), media_source_registry_.get(),
web_module_stat_tracker_->dom_stat_tracker(), data.initial_url,
data.network_module->GetUserAgent(),
@@ -536,8 +538,7 @@
data.options.navigation_callback,
base::Bind(&WebModule::Impl::OnError, base::Unretained(this)),
data.network_module->cookie_jar(), data.network_module->GetPostSender(),
- data.options.location_policy, data.options.require_csp,
- data.options.csp_enforcement_mode,
+ data.options.require_csp, data.options.csp_enforcement_mode,
base::Bind(&WebModule::Impl::OnCspPolicyChanged, base::Unretained(this)),
base::Bind(&WebModule::Impl::OnRanAnimationFrameCallbacks,
base::Unretained(this)),
@@ -559,9 +560,9 @@
DCHECK(window_weak_);
environment_settings_.reset(new dom::DOMSettings(
- kDOMMaxElementDepth, fetcher_factory_.get(), data.network_module,
- data.media_module, window_, media_source_registry_.get(),
- blob_registry_.get(), data.media_module, javascript_engine_.get(),
+ kDOMMaxElementDepth, fetcher_factory_.get(), data.network_module, window_,
+ media_source_registry_.get(), blob_registry_.get(),
+ data.can_play_type_handler, javascript_engine_.get(),
global_environment_.get(), &mutation_observer_task_manager_,
data.options.dom_settings_options));
DCHECK(environment_settings_);
@@ -713,9 +714,10 @@
// JavaScript is being run. Track it in the global stats.
dom::GlobalStats::GetInstance()->StartJavaScriptEvent();
- // This should only be called for Cobalt javascript, errors not expected.
- *result = script_runner_->Execute(script_utf8, script_location, out_succeeded,
- true /*mute error reports*/);
+ // This should only be called for Cobalt JavaScript, error reports are
+ // allowed.
+ *result = script_runner_->Execute(script_utf8, script_location,
+ false /*mute_errors*/, out_succeeded);
// JavaScript is done running. Stop tracking it in the global stats.
dom::GlobalStats::GetInstance()->StopJavaScriptEvent();
@@ -863,11 +865,9 @@
window_->SetCamera3D(camera_3d);
}
-void WebModule::Impl::SetMediaModule(media::MediaModule* media_module) {
- window_->set_can_play_type_handler(media_module);
- window_->set_web_media_player_factory(media_module);
- environment_settings_->set_media_module(media_module);
- environment_settings_->set_can_play_type_handler(media_module);
+void WebModule::Impl::SetWebMediaPlayerFactory(
+ media::WebMediaPlayerFactory* web_media_player_factory) {
+ window_->set_web_media_player_factory(web_media_player_factory);
}
void WebModule::Impl::SetApplicationState(base::ApplicationState state) {
@@ -1048,16 +1048,18 @@
const OnErrorCallback& error_callback,
const CloseCallback& window_close_callback,
const base::Closure& window_minimize_callback,
- media::MediaModule* media_module, network::NetworkModule* network_module,
- const math::Size& window_dimensions, float video_pixel_ratio,
- render_tree::ResourceProvider* resource_provider, float layout_refresh_rate,
- const Options& options)
+ media::CanPlayTypeHandler* can_play_type_handler,
+ media::WebMediaPlayerFactory* web_media_player_factory,
+ network::NetworkModule* network_module, const math::Size& window_dimensions,
+ float video_pixel_ratio, render_tree::ResourceProvider* resource_provider,
+ float layout_refresh_rate, const Options& options)
: thread_(options.name.c_str()) {
ConstructionData construction_data(
initial_url, initial_application_state, render_tree_produced_callback,
error_callback, window_close_callback, window_minimize_callback,
- media_module, network_module, window_dimensions, video_pixel_ratio,
- resource_provider, kDOMMaxElementDepth, layout_refresh_rate, options);
+ can_play_type_handler, web_media_player_factory, network_module,
+ window_dimensions, video_pixel_ratio, resource_provider,
+ kDOMMaxElementDepth, layout_refresh_rate, options);
// Start the dedicated thread and create the internal implementation
// object on that thread.
@@ -1258,10 +1260,12 @@
base::Unretained(impl_.get()), camera_3d));
}
-void WebModule::SetMediaModule(media::MediaModule* media_module) {
+void WebModule::SetWebMediaPlayerFactory(
+ media::WebMediaPlayerFactory* web_media_player_factory) {
message_loop()->PostTask(
- FROM_HERE, base::Bind(&WebModule::Impl::SetMediaModule,
- base::Unretained(impl_.get()), media_module));
+ FROM_HERE,
+ base::Bind(&WebModule::Impl::SetWebMediaPlayerFactory,
+ base::Unretained(impl_.get()), web_media_player_factory));
}
void WebModule::SetImageCacheCapacity(int64_t bytes) {
diff --git a/src/cobalt/browser/web_module.h b/src/cobalt/browser/web_module.h
index 281664b..b46056f 100644
--- a/src/cobalt/browser/web_module.h
+++ b/src/cobalt/browser/web_module.h
@@ -49,7 +49,8 @@
#include "cobalt/layout/layout_manager.h"
#include "cobalt/loader/fetcher_factory.h"
#include "cobalt/math/size.h"
-#include "cobalt/media/media_module.h"
+#include "cobalt/media/can_play_type_handler.h"
+#include "cobalt/media/web_media_player_factory.h"
#include "cobalt/network/network_module.h"
#include "cobalt/render_tree/resource_provider.h"
#include "cobalt/script/global_environment.h"
@@ -122,12 +123,6 @@
// Options to customize DOMSettings.
dom::DOMSettings::Options dom_settings_options;
- // Location policy to enforce, formatted as a Content Security Policy
- // directive, e.g. "h5vcc-location-src 'self'"
- // This is used to implement a navigation jail, so that location
- // can't be changed from the whitelisted origins.
- std::string location_policy;
-
// Whether Cobalt is forbidden to render without receiving CSP headers.
csp::CSPHeaderPolicy require_csp;
@@ -213,7 +208,8 @@
const OnErrorCallback& error_callback,
const CloseCallback& window_close_callback,
const base::Closure& window_minimize_callback,
- media::MediaModule* media_module,
+ media::CanPlayTypeHandler* can_play_type_handler,
+ media::WebMediaPlayerFactory* web_media_player_factory,
network::NetworkModule* network_module,
const math::Size& window_dimensions, float video_pixel_ratio,
render_tree::ResourceProvider* resource_provider,
@@ -266,7 +262,8 @@
void SetSize(const math::Size& window_dimensions, float video_pixel_ratio);
void SetCamera3D(const scoped_refptr<input::Camera3D>& camera_3d);
- void SetMediaModule(media::MediaModule* media_module);
+ void SetWebMediaPlayerFactory(
+ media::WebMediaPlayerFactory* web_media_player_factory);
void SetImageCacheCapacity(int64_t bytes);
void SetRemoteTypefaceCacheCapacity(int64_t bytes);
void SetJavascriptGcThreshold(int64_t bytes);
@@ -294,7 +291,8 @@
const OnErrorCallback& error_callback,
const CloseCallback& window_close_callback,
const base::Closure& window_minimize_callback,
- media::MediaModule* media_module,
+ media::CanPlayTypeHandler* can_play_type_handler,
+ media::WebMediaPlayerFactory* web_media_player_factory,
network::NetworkModule* network_module,
const math::Size& window_dimensions, float video_pixel_ratio,
render_tree::ResourceProvider* resource_provider,
@@ -306,7 +304,8 @@
error_callback(error_callback),
window_close_callback(window_close_callback),
window_minimize_callback(window_minimize_callback),
- media_module(media_module),
+ can_play_type_handler(can_play_type_handler),
+ web_media_player_factory(web_media_player_factory),
network_module(network_module),
window_dimensions(window_dimensions),
video_pixel_ratio(video_pixel_ratio),
@@ -321,7 +320,8 @@
OnErrorCallback error_callback;
const CloseCallback& window_close_callback;
const base::Closure& window_minimize_callback;
- media::MediaModule* media_module;
+ media::CanPlayTypeHandler* can_play_type_handler;
+ media::WebMediaPlayerFactory* web_media_player_factory;
network::NetworkModule* network_module;
math::Size window_dimensions;
float video_pixel_ratio;
diff --git a/src/cobalt/build/build.id b/src/cobalt/build/build.id
index 6125516..d0d80b7 100644
--- a/src/cobalt/build/build.id
+++ b/src/cobalt/build/build.id
@@ -1 +1 @@
-104689
\ No newline at end of file
+108984
\ No newline at end of file
diff --git a/src/cobalt/build/config/base.gypi b/src/cobalt/build/config/base.gypi
index 867adb5..056ae29 100644
--- a/src/cobalt/build/config/base.gypi
+++ b/src/cobalt/build/config/base.gypi
@@ -462,9 +462,8 @@
'platform_libraries%': [],
# The only currently-supported Javascript engine is 'mozjs-45'.
- # TODO: Figure out how to massage gyp the right way to make this work
- # as expected, rather than requiring it to be set for each platform.
- #'javascript_engine%': 'mozjs-45',
+ 'default_javascript_engine': 'mozjs-45',
+ 'javascript_engine%': '<(default_javascript_engine)',
# Disable JIT and run in interpreter-only mode by default. It can be set
# to 1 to run in JIT mode. For SpiderMonkey in particular, we have found
diff --git a/src/cobalt/build/config/starboard.py b/src/cobalt/build/config/starboard.py
index 2af50cd..fdef871 100644
--- a/src/cobalt/build/config/starboard.py
+++ b/src/cobalt/build/config/starboard.py
@@ -16,6 +16,7 @@
import logging
import os
+import cobalt.tools.webdriver_benchmark_config as wb_config
from config.base import Configs
from config.base import PlatformConfigBase
@@ -89,3 +90,22 @@
'enable_vr': vr_enabled,
}
return variables
+
+ def WebdriverBenchmarksEnabled(self):
+ """Determines if webdriver benchmarks are enabled or not.
+
+ Returns:
+ True if webdriver benchmarks can run on this platform, False if not.
+ """
+ return False
+
+ def GetDefaultSampleSize(self):
+ return wb_config.STANDARD_SIZE
+
+ def GetWebdriverBenchmarksTargetParams(self):
+ """Gets command line params to pass to the Cobalt executable."""
+ return []
+
+ def GetWebdriverBenchmarksParams(self):
+ """Gets command line params to pass to the webdriver benchmark script."""
+ return []
diff --git a/src/cobalt/csp/content_security_policy.cc b/src/cobalt/csp/content_security_policy.cc
index 302af17..68163e5 100644
--- a/src/cobalt/csp/content_security_policy.cc
+++ b/src/cobalt/csp/content_security_policy.cc
@@ -212,11 +212,6 @@
AddPolicyFromHeaderValue(header, type, source);
}
-void ContentSecurityPolicy::SetNavigationPolicy(const std::string& policy) {
- navigation_policy_.reset(new DirectiveList(
- this, base::StringPiece(policy), kHeaderTypeEnforce, kHeaderSourceHTTP));
-}
-
bool ContentSecurityPolicy::UrlMatchesSelf(const GURL& url) const {
return self_source_->Matches(url, kDidNotRedirect);
}
@@ -493,16 +488,9 @@
const GURL& url, ContentSecurityPolicy::RedirectStatus redirect_status,
ContentSecurityPolicy::ReportingStatus reporting_status) const {
// Note that this is a Cobalt-specific policy to prevent navigation
- // to any unexpected URLs. Navigation is restrictive by default, as
- // opposed to the permissive policy for other directives.
-
- if (!navigation_policy_) {
- DLOG(ERROR) << "SetNavigationFallbackPolicy() was not called.";
- return false;
- }
- // TODO: Re-enable respecting the navigation whitelist.
- return navigation_policy_->AllowNavigateToSource(url, redirect_status,
- reporting_status);
+ // to any unexpected URLs.
+ FOR_ALL_POLICIES_3(AllowNavigateToSource, url, redirect_status,
+ reporting_status);
}
bool ContentSecurityPolicy::AllowStyleFromSource(
diff --git a/src/cobalt/csp/content_security_policy.h b/src/cobalt/csp/content_security_policy.h
index 95789a1..bb2e883 100644
--- a/src/cobalt/csp/content_security_policy.h
+++ b/src/cobalt/csp/content_security_policy.h
@@ -140,7 +140,6 @@
void OnReceiveHeaders(const ResponseHeaders& headers);
void OnReceiveHeader(const std::string& header, HeaderType header_type,
HeaderSource header_source);
- void SetNavigationPolicy(const std::string& header);
bool UrlMatchesSelf(const GURL& url) const;
bool SchemeMatchesSelf(const GURL& url) const;
@@ -261,7 +260,6 @@
HeaderSource source);
PolicyList policies_;
- scoped_ptr<DirectiveList> navigation_policy_;
scoped_ptr<Source> self_source_;
std::string self_scheme_;
std::string disable_eval_error_message_;
diff --git a/src/cobalt/debug/content/devtools/components_lazy_module.js b/src/cobalt/debug/content/devtools/components_lazy_module.js
index b81ba09..6aa87c5 100644
--- a/src/cobalt/debug/content/devtools/components_lazy_module.js
+++ b/src/cobalt/debug/content/devtools/components_lazy_module.js
@@ -101,7 +101,7 @@
WebInspector.FilmStripView.Dialog.prototype={_resize:function()
{if(!this._dialog){this._dialog=new WebInspector.Dialog();this.show(this._dialog.element);this._dialog.setWrapsContent(true);this._dialog.show();}
this._dialog.contentResized();},_keyDown:function(event)
-{switch(event.keyIdentifier){case"Left":if(WebInspector.isMac()&&event.metaKey)
+{switch(event.key){case"Left":if(WebInspector.isMac()&&event.metaKey)
this._onFirstFrame();else
this._onPrevFrame();break;case"Right":if(WebInspector.isMac()&&event.metaKey)
this._onLastFrame();else
diff --git a/src/cobalt/debug/content/devtools/devices_module.js b/src/cobalt/debug/content/devtools/devices_module.js
index ee075ba..dad1a0f 100644
--- a/src/cobalt/debug/content/devtools/devices_module.js
+++ b/src/cobalt/debug/content/devtools/devices_module.js
@@ -62,7 +62,7 @@
function updateViewMoreTitle()
{viewMore.textContent=pages.classList.contains("device-view-more-toggled")?WebInspector.UIString("View less tabs\u2026"):WebInspector.UIString("View more tabs\u2026");}
function newTabKeyDown(event)
-{if(event.keyIdentifier==="Enter"){event.consume(true);openNewTab();}}
+{if(event.key==="Enter"){event.consume(true);openNewTab();}}
function openNewTab()
{if(section.browser){InspectorFrontendHost.openRemotePage(section.browser.id,newTabInput.value.trim()||"about:blank");newTabInput.value="";}}},_updateBrowserSection:function(section,browser)
{if(!section.browser||section.browser.adbBrowserName!==browser.adbBrowserName||section.browser.adbBrowserVersion!==browser.adbBrowserVersion){if(browser.adbBrowserVersion)
diff --git a/src/cobalt/debug/content/devtools/devtools.js b/src/cobalt/debug/content/devtools/devtools.js
index 05c2b25..3faa580 100644
--- a/src/cobalt/debug/content/devtools/devtools.js
+++ b/src/cobalt/debug/content/devtools/devtools.js
@@ -219,7 +219,7 @@
},
/**
- * @param {{type: string, keyIdentifier: string, keyCode: number, modifiers: number}} event
+ * @param {{type: string, key: string, keyCode: number, modifiers: number}} event
*/
keyEventUnhandled: function(event)
{
diff --git a/src/cobalt/debug/content/devtools/devtools_extension_api.js b/src/cobalt/debug/content/devtools/devtools_extension_api.js
index b409652..9b575f7 100644
--- a/src/cobalt/debug/content/devtools/devtools_extension_api.js
+++ b/src/cobalt/debug/content/devtools/devtools_extension_api.js
@@ -805,14 +805,14 @@
{
const Esc = "U+001B";
// We only care about global hotkeys, not about random text
- if (!event.ctrlKey && !event.altKey && !event.metaKey && !/^F\d+$/.test(event.keyIdentifier) && event.keyIdentifier !== Esc)
+ if (!event.ctrlKey && !event.altKey && !event.metaKey && !/^F\d+$/.test(event.key) && event.key !== Esc)
return;
var requestPayload = {
eventType: event.type,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
metaKey: event.metaKey,
- keyIdentifier: event.keyIdentifier,
+ key: event.key,
location: event.location,
keyCode: event.keyCode
};
diff --git a/src/cobalt/debug/content/devtools/elements_module.js b/src/cobalt/debug/content/devtools/elements_module.js
index cb6558d..53917ab 100644
--- a/src/cobalt/debug/content/devtools/elements_module.js
+++ b/src/cobalt/debug/content/devtools/elements_module.js
@@ -58,8 +58,8 @@
return;var document=this._popover.element.ownerDocument;this._isHidden=true;this._popover.hide();if(this._scrollerElement)
this._scrollerElement.removeEventListener("scroll",this._repositionBound,false);document.removeEventListener("mousedown",this._hideProxy,false);document.defaultView.removeEventListener("resize",this._hideProxy,false);if(this._hiddenCallback)
this._hiddenCallback.call(null,!!commitEdit);WebInspector.setCurrentFocusElement(this._previousFocusElement);delete this._previousFocusElement;delete this._anchorElement;if(this._view){this._view.detach();this._view.contentElement.removeEventListener("keydown",this._boundOnKeyDown,false);this._view.contentElement.removeEventListener("focusout",this._boundFocusOut,false);delete this._view;}},_onKeyDown:function(event)
-{if(event.keyIdentifier==="Enter"){this.hide(true);event.consume(true);return;}
-if(event.keyIdentifier==="U+001B"){this.hide(false);event.consume(true);}},__proto__:WebInspector.Object.prototype}
+{if(event.key==="Enter"){this.hide(true);event.consume(true);return;}
+if(event.key==="U+001B"){this.hide(false);event.consume(true);}},__proto__:WebInspector.Object.prototype}
WebInspector.BezierPopoverIcon=function(treeElement,stylesPopoverHelper,text)
{this._treeElement=treeElement;this._stylesPopoverHelper=stylesPopoverHelper;this._createDOM(text);this._boundBezierChanged=this._bezierChanged.bind(this);}
WebInspector.BezierPopoverIcon.prototype={element:function()
@@ -220,7 +220,7 @@
format=this._originalFormat===cf.ShortHEX?cf.ShortHEX:cf.HEX;this._innerSetColor(undefined,"",format,WebInspector.Spectrum._ChangeSource.Other);},_inputChanged:function(event)
{function elementValue(element)
{return element.value;}
-var inputElement=(event.currentTarget);var arrowKeyOrMouseWheelEvent=(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"||event.type==="mousewheel");var pageKeyPressed=(event.keyIdentifier==="PageUp"||event.keyIdentifier==="PageDown");if(arrowKeyOrMouseWheelEvent||pageKeyPressed){var newValue=WebInspector.createReplacementString(inputElement.value,event);if(newValue){inputElement.value=newValue;inputElement.selectionStart=0;inputElement.selectionEnd=newValue.length;}
+var inputElement=(event.currentTarget);var arrowKeyOrMouseWheelEvent=(event.key==="Up"||event.key==="Down"||event.type==="mousewheel");var pageKeyPressed=(event.key==="PageUp"||event.key==="PageDown");if(arrowKeyOrMouseWheelEvent||pageKeyPressed){var newValue=WebInspector.createReplacementString(inputElement.value,event);if(newValue){inputElement.value=newValue;inputElement.selectionStart=0;inputElement.selectionEnd=newValue.length;}
event.consume(true);}
const cf=WebInspector.Color.Format;var colorString;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX){colorString=this._hexValue.value;}else{var format=this._colorFormat===cf.RGB?"rgba":"hsla";var values=this._textValues.map(elementValue).join(",");colorString=String.sprintf("%s(%s)",format,values);}
var color=WebInspector.Color.parse(colorString);if(!color)
@@ -775,8 +775,8 @@
{this._updateModifiedNodes();},handleShortcut:function(event)
{var node=this.selectedDOMNode();if(!node)
return;var treeElement=node[this._treeElementSymbol];if(!treeElement)
-return;if(WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)&&node.parentNode){if(event.keyIdentifier==="Up"&&node.previousSibling){node.moveTo(node.parentNode,node.previousSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;}
-if(event.keyIdentifier==="Down"&&node.nextSibling){node.moveTo(node.parentNode,node.nextSibling.nextSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;}}},toggleEditAsHTML:function(node,startEditing,callback)
+return;if(WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)&&node.parentNode){if(event.key==="Up"&&node.previousSibling){node.moveTo(node.parentNode,node.previousSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;}
+if(event.key==="Down"&&node.nextSibling){node.moveTo(node.parentNode,node.nextSibling.nextSibling,this.selectNodeAfterEdit.bind(this,treeElement.expanded));event.handled=true;return;}}},toggleEditAsHTML:function(node,startEditing,callback)
{var treeElement=node[this._treeElementSymbol];if(!treeElement||!treeElement.hasEditableNode())
return;if(node.pseudoType())
return;var parentNode=node.parentNode;var index=node.index;var wasExpanded=treeElement.expanded;treeElement.toggleEditAsHTML(editingFinished.bind(this),startEditing);function editingFinished(success)
@@ -1177,7 +1177,7 @@
{var input=createElement("input");input.placeholder=placeholder;function searchHandler()
{var regex=input.value?new RegExp(input.value.escapeForRegExp(),"i"):null;filterCallback(regex);container.classList.toggle("styles-filter-engaged",!!input.value);}
input.addEventListener("input",searchHandler,false);function keydownHandler(event)
-{var Esc="U+001B";if(event.keyIdentifier!==Esc||!input.value)
+{var Esc="U+001B";if(event.key!==Esc||!input.value)
return;event.consume(true);input.value="";searchHandler();}
input.addEventListener("keydown",keydownHandler,false);input.setFilterValue=setFilterValue;function setFilterValue(value)
{input.value=value;input.focus();searchHandler();}
@@ -1441,8 +1441,8 @@
var proxyElement=this._prompt.attachAndStartEditing(selectElement,blurListener.bind(this,context));proxyElement.addEventListener("keydown",this._editingNameValueKeyDown.bind(this,context),false);proxyElement.addEventListener("keypress",this._editingNameValueKeyPress.bind(this,context),false);proxyElement.addEventListener("input",this._editingNameValueInput.bind(this,context),false);if(isEditingName)
proxyElement.addEventListener("paste",pasteHandler.bind(this,context),false);selectElement.getComponentSelection().setBaseAndExtent(selectElement,0,selectElement,1);},_editingNameValueKeyDown:function(context,event)
{if(event.handled)
-return;var result;if(isEnterKey(event)){event.preventDefault();result="forward";}else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.keyIdentifier==="U+001B")
-result="cancel";else if(!context.isEditingName&&this._newProperty&&event.keyCode===WebInspector.KeyboardShortcut.Keys.Backspace.code){var selection=event.target.getComponentSelection();if(selection.isCollapsed&&!selection.focusOffset){event.preventDefault();result="backward";}}else if(event.keyIdentifier==="U+0009"){result=event.shiftKey?"backward":"forward";event.preventDefault();}
+return;var result;if(isEnterKey(event)){event.preventDefault();result="forward";}else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.key==="U+001B")
+result="cancel";else if(!context.isEditingName&&this._newProperty&&event.keyCode===WebInspector.KeyboardShortcut.Keys.Backspace.code){var selection=event.target.getComponentSelection();if(selection.isCollapsed&&!selection.focusOffset){event.preventDefault();result="backward";}}else if(event.key==="U+0009"){result=event.shiftKey?"backward":"forward";event.preventDefault();}
if(result){switch(result){case"cancel":this.editingCancelled(null,context);break;case"forward":case"backward":this.editingCommitted(event.target.textContent,context,result);break;}
event.consume();return;}},_editingNameValueKeyPress:function(context,event)
{function shouldCommitValueSemicolon(text,cursorPosition)
@@ -1510,7 +1510,7 @@
{WebInspector.TextPrompt.call(this,this._buildPropertyCompletions.bind(this),WebInspector.StyleValueDelimiters);this.setSuggestBoxEnabled(true);this._cssCompletions=cssCompletions;this._treeElement=treeElement;this._isEditingName=isEditingName;if(!isEditingName)
this.disableDefaultSuggestionForEmptyInput();}
WebInspector.StylesSidebarPane.CSSPropertyPrompt.prototype={onKeyDown:function(event)
-{switch(event.keyIdentifier){case"Up":case"Down":case"PageUp":case"PageDown":if(this._handleNameOrValueUpDown(event)){event.preventDefault();return;}
+{switch(event.key){case"Up":case"Down":case"PageUp":case"PageDown":if(this._handleNameOrValueUpDown(event)){event.preventDefault();return;}
break;case"Enter":if(this.autoCompleteElement&&!this.autoCompleteElement.textContent.length){this.tabKeyPressed();return;}
break;}
WebInspector.TextPrompt.prototype.onKeyDown.call(this,event);},onMouseWheel:function(event)
@@ -1697,8 +1697,8 @@
{var nodes=(event.data);this._breadcrumbs.updateNodes(nodes);},_crumbNodeSelected:function(event)
{var node=(event.data);this.selectDOMNode(node,true);},handleShortcut:function(event)
{function handleUndoRedo(treeOutline)
-{if(WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)&&!event.shiftKey&&event.keyIdentifier==="U+005A"){treeOutline.domModel().undo();event.handled=true;return;}
-var isRedoKey=WebInspector.isMac()?event.metaKey&&event.shiftKey&&event.keyIdentifier==="U+005A":event.ctrlKey&&event.keyIdentifier==="U+0059";if(isRedoKey){treeOutline.domModel().redo();event.handled=true;}}
+{if(WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)&&!event.shiftKey&&event.key==="U+005A"){treeOutline.domModel().undo();event.handled=true;return;}
+var isRedoKey=WebInspector.isMac()?event.metaKey&&event.shiftKey&&event.key==="U+005A":event.ctrlKey&&event.key==="U+0059";if(isRedoKey){treeOutline.domModel().redo();event.handled=true;}}
if(WebInspector.isEditing()&&event.keyCode!==WebInspector.KeyboardShortcut.Keys.F2.code)
return;var treeOutline=null;for(var i=0;i<this._treeOutlines.length;++i){if(this._treeOutlines[i].selectedDOMNode()===this._lastValidSelectedNode)
treeOutline=this._treeOutlines[i];}
diff --git a/src/cobalt/debug/content/devtools/inspector.js b/src/cobalt/debug/content/devtools/inspector.js
index 9f07d27..fd09fea 100644
--- a/src/cobalt/debug/content/devtools/inspector.js
+++ b/src/cobalt/debug/content/devtools/inspector.js
@@ -683,7 +683,7 @@
{var node=this.elementFromPoint(x,y);while(node&&node.shadowRoot)
node=node.shadowRoot.elementFromPoint(x,y);return node;}
function isEnterKey(event)
-{return event.keyCode!==229&&event.keyIdentifier==="Enter";}
+{return event.keyCode!==229&&event.key==="Enter";}
function isEscKey(event)
{return event.keyCode===27;}
function consumeEvent(e)
@@ -1683,11 +1683,11 @@
return false;},_treeKeyDown:function(event)
{if(event.target!==this._contentElement)
return;if(!this.selectedTreeElement||event.shiftKey||event.metaKey||event.ctrlKey)
-return;var handled=false;var nextSelectedElement;if(event.keyIdentifier==="Up"&&!event.altKey){handled=this.selectPrevious();}else if(event.keyIdentifier==="Down"&&!event.altKey){handled=this.selectNext();}else if(event.keyIdentifier==="Left"){if(this.selectedTreeElement.expanded){if(event.altKey)
+return;var handled=false;var nextSelectedElement;if(event.key==="Up"&&!event.altKey){handled=this.selectPrevious();}else if(event.key==="Down"&&!event.altKey){handled=this.selectNext();}else if(event.key==="Left"){if(this.selectedTreeElement.expanded){if(event.altKey)
this.selectedTreeElement.collapseRecursively();else
this.selectedTreeElement.collapse();handled=true;}else if(this.selectedTreeElement.parent&&!this.selectedTreeElement.parent.root){handled=true;if(this.selectedTreeElement.parent.selectable){nextSelectedElement=this.selectedTreeElement.parent;while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.parent;handled=nextSelectedElement?true:false;}else if(this.selectedTreeElement.parent)
-this.selectedTreeElement.parent.collapse();}}else if(event.keyIdentifier==="Right"){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else if(this.selectedTreeElement._expandable){handled=true;if(this.selectedTreeElement.expanded){nextSelectedElement=this.selectedTreeElement.firstChild();while(nextSelectedElement&&!nextSelectedElement.selectable)
+this.selectedTreeElement.parent.collapse();}}else if(event.key==="Right"){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else if(this.selectedTreeElement._expandable){handled=true;if(this.selectedTreeElement.expanded){nextSelectedElement=this.selectedTreeElement.firstChild();while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.nextSibling;handled=nextSelectedElement?true:false;}else{if(event.altKey)
this.selectedTreeElement.expandRecursively();else
this.selectedTreeElement.expand();}}}else if(event.keyCode===8||event.keyCode===46)
@@ -1907,7 +1907,7 @@
return result;},shortcutTitleForAction:function(actionId)
{var descriptors=this.shortcutDescriptorsForAction(actionId);if(descriptors.length)
return descriptors[0].name;},handleShortcut:function(event)
-{this.handleKey(WebInspector.KeyboardShortcut.makeKeyFromEvent(event),event.keyIdentifier,event);},handleKey:function(key,keyIdentifier,event)
+{this.handleKey(WebInspector.KeyboardShortcut.makeKeyFromEvent(event),event.key,event);},handleKey:function(key,key,event)
{var keyModifiers=key>>8;var actions=this._applicableActions(key);if(!actions.length)
return;if(WebInspector.GlassPane.DefaultFocusedViewStack.length>1){if(event&&!isPossiblyInputKey())
event.consume(true);return;}
@@ -1917,7 +1917,7 @@
{delete this._pendingActionTimer;var action=actions.shift();if(!action||handled)
return;action.execute().then(processNextAction.bind(this));}
function isPossiblyInputKey()
-{if(!event||!WebInspector.isEditing()||/^F\d+|Control|Shift|Alt|Meta|Win|U\+001B$/.test(keyIdentifier))
+{if(!event||!WebInspector.isEditing()||/^F\d+|Control|Shift|Alt|Meta|Win|U\+001B$/.test(key))
return false;if(!keyModifiers)
return true;var modifiers=WebInspector.KeyboardShortcut.Modifiers;if((keyModifiers&(modifiers.Ctrl|modifiers.Alt))===(modifiers.Ctrl|modifiers.Alt))
return WebInspector.isWin();return!hasModifier(modifiers.Ctrl)&&!hasModifier(modifiers.Alt)&&!hasModifier(modifiers.Meta);}
@@ -2165,7 +2165,7 @@
this._suggestBox.hide();var filterQuery=this.value();this._regex=null;this._filterInputElement.classList.remove("filter-text-invalid");if(filterQuery){if(this._supportRegex&&this._regexCheckBox.checked){try{this._regex=new RegExp(filterQuery,"i");}catch(e){this._filterInputElement.classList.add("filter-text-invalid");}}else{this._regex=createPlainTextSearchRegex(filterQuery,"i");}}
this._dispatchFilterChanged();},_dispatchFilterChanged:function()
{this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged,null);},_onInputKeyDown:function(event)
-{var handled=false;if(event.keyIdentifier==="U+0008"){this._suppressSuggestion=true;}else if(this._suggestBox.visible()){if(event.keyIdentifier==="U+001B"){this._cancelSuggestion();handled=true;}else if(event.keyIdentifier==="U+0009"){this._suggestBox.acceptSuggestion();this._valueChanged(true);handled=true;}else{handled=this._suggestBox.keyPressed((event));}}
+{var handled=false;if(event.key==="U+0008"){this._suppressSuggestion=true;}else if(this._suggestBox.visible()){if(event.key==="U+001B"){this._cancelSuggestion();handled=true;}else if(event.key==="U+0009"){this._suggestBox.acceptSuggestion();this._valueChanged(true);handled=true;}else{handled=this._suggestBox.keyPressed((event));}}
if(handled)
event.consume(true);return handled;},applySuggestion:function(suggestion,isIntermediateSuggestion)
{if(!this._suggestionBuilder)
@@ -2221,8 +2221,8 @@
{this._label.backgroundColor=backgroundColor;this._label.borderColor=borderColor;},__proto__:WebInspector.Object.prototype};WebInspector.ForwardedInputEventHandler=function()
{InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.KeyEventUnhandled,this._onKeyEventUnhandled,this);}
WebInspector.ForwardedInputEventHandler.prototype={_onKeyEventUnhandled:function(event)
-{var data=event.data;var type=(data.type);var keyIdentifier=(data.keyIdentifier);var keyCode=(data.keyCode);var modifiers=(data.modifiers);if(type!=="keydown")
-return;WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut,WebInspector.ShortcutRegistry.ForwardedShortcut.instance);WebInspector.shortcutRegistry.handleKey(WebInspector.KeyboardShortcut.makeKey(keyCode,modifiers),keyIdentifier);WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut,null);}}
+{var data=event.data;var type=(data.type);var key=(data.key);var keyCode=(data.keyCode);var modifiers=(data.modifiers);if(type!=="keydown")
+return;WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut,WebInspector.ShortcutRegistry.ForwardedShortcut.instance);WebInspector.shortcutRegistry.handleKey(WebInspector.KeyboardShortcut.makeKey(keyCode,modifiers),key);WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut,null);}}
WebInspector.forwardedEventHandler=new WebInspector.ForwardedInputEventHandler();;WebInspector.HistoryInput=function()
{}
WebInspector.HistoryInput.create=function()
@@ -2286,11 +2286,11 @@
{cleanUpAfterEditing();committedCallback(this,self.editorContent(editingContext),editingContext.oldText,context,moveDirection);}
function defaultFinishHandler(event)
{var isMetaOrCtrl=WebInspector.isMac()?event.metaKey&&!event.shiftKey&&!event.ctrlKey&&!event.altKey:event.ctrlKey&&!event.shiftKey&&!event.metaKey&&!event.altKey;if(isEnterKey(event)&&(event.isMetaOrCtrlForTest||!isMultiline||isMetaOrCtrl))
-return"commit";else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.keyIdentifier==="U+001B")
-return"cancel";else if(!isMultiline&&event.keyIdentifier==="U+0009")
+return"commit";else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.key==="U+001B")
+return"cancel";else if(!isMultiline&&event.key==="U+0009")
return"move-"+(event.shiftKey?"backward":"forward");return"";}
function handleEditingResult(result,event)
-{if(result==="commit"){editingCommitted.call(element);event.consume(true);}else if(result==="cancel"){editingCancelled.call(element);event.consume(true);}else if(result&&result.startsWith("move-")){moveDirection=result.substring(5);if(event.keyIdentifier!=="U+0009")
+{if(result==="commit"){editingCommitted.call(element);event.consume(true);}else if(result==="cancel"){editingCancelled.call(element);event.consume(true);}else if(result&&result.startsWith("move-")){moveDirection=result.substring(5);if(event.key!=="U+0009")
blurEventListener();}}
function pasteEventListener(event)
{var result=pasteCallback(event);handleEditingResult(result,event);}
@@ -2680,7 +2680,7 @@
apply();incrementForArrows(event);}
function incrementForArrows(event)
{if(!numeric)
-return;var increment=event.keyIdentifier==="Up"?1:event.keyIdentifier==="Down"?-1:0;if(!increment)
+return;var increment=event.key==="Up"?1:event.key==="Down"?-1:0;if(!increment)
return;if(event.shiftKey)
increment*=10;var value=inputElement.value;if(validatorCallback&&validatorCallback(value))
return;value=Number(value);if(clearForZero&&!value)
@@ -2789,7 +2789,7 @@
{var menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement._isCustom))
menuItemElement=menuItemElement.nextSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,false);},_menuKeyDown:function(event)
-{switch(event.keyIdentifier){case"Up":this._highlightPrevious();break;case"Down":this._highlightNext();break;case"Left":if(this._parentMenu){this._highlightMenuItem(null,false);this._parentMenu._hideSubMenu();}
+{switch(event.key){case"Up":this._highlightPrevious();break;case"Down":this._highlightNext();break;case"Left":if(this._parentMenu){this._highlightMenuItem(null,false);this._parentMenu._hideSubMenu();}
break;case"Right":if(!this._highlightedMenuItemElement)
break;if(this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._focus();this._subMenu._highlightNext();}
break;case"U+001B":this._discardMenu(false,event);break;case"Enter":if(!isEnterKey(event))
@@ -3174,7 +3174,7 @@
return;this._rowCountPerViewport=Math.floor(this._element.offsetHeight/this._element.firstChild.offsetHeight);},updateSuggestions:function(anchorBox,completions,selectedIndex,canShowForSingleItem,userEnteredText,asyncDetails)
{if(this._canShowBox(completions,canShowForSingleItem,userEnteredText)){this._updateItems(completions,userEnteredText,asyncDetails);this._show();this._updateBoxPosition(anchorBox);this._selectItem(selectedIndex,selectedIndex>0);delete this._rowCountPerViewport;}else
this.hide();},keyPressed:function(event)
-{switch(event.keyIdentifier){case"Up":return this.upKeyPressed();case"Down":return this.downKeyPressed();case"PageUp":return this.pageUpKeyPressed();case"PageDown":return this.pageDownKeyPressed();case"Enter":return this.enterKeyPressed();}
+{switch(event.key){case"Up":return this.upKeyPressed();case"Down":return this.downKeyPressed();case"PageUp":return this.pageUpKeyPressed();case"PageDown":return this.pageDownKeyPressed();case"Enter":return this.enterKeyPressed();}
return false;},upKeyPressed:function()
{return this._selectClosest(-1,true);},downKeyPressed:function()
{return this._selectClosest(1,true);},pageUpKeyPressed:function()
@@ -3488,7 +3488,7 @@
this._selectionTimeout=setTimeout(moveBackIfOutside.bind(this),100);},_updateAutoComplete:function(force)
{this.clearAutoComplete();this.autoCompleteSoon(force);},onMouseWheel:function(event)
{},onKeyDown:function(event)
-{var handled=false;delete this._needUpdateAutocomplete;switch(event.keyIdentifier){case"U+0009":handled=this.tabKeyPressed(event);break;case"Left":case"Home":this._removeSuggestionAids();break;case"Right":case"End":if(this.isCaretAtEndOfPrompt())
+{var handled=false;delete this._needUpdateAutocomplete;switch(event.key){case"U+0009":handled=this.tabKeyPressed(event);break;case"Left":case"Home":this._removeSuggestionAids();break;case"Right":case"End":if(this.isCaretAtEndOfPrompt())
handled=this.acceptAutoComplete();else
this._removeSuggestionAids();break;case"U+001B":if(this.isSuggestBoxVisible()){this._removeSuggestionAids();handled=true;}
break;case"U+0020":if(event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey){this._updateAutoComplete(true);handled=true;}
@@ -3588,7 +3588,7 @@
{if(this._historyOffset===1)
return undefined;--this._historyOffset;return this._currentHistoryItem();},_currentHistoryItem:function()
{return this._data[this._data.length-this._historyOffset];},onKeyDown:function(event)
-{var newText;var isPrevious;switch(event.keyIdentifier){case"Up":if(!this.isCaretOnFirstLine()||this.isSuggestBoxVisible())
+{var newText;var isPrevious;switch(event.key){case"Up":if(!this.isCaretOnFirstLine()||this.isSuggestBoxVisible())
break;newText=this._previous();isPrevious=true;break;case"Down":if(!this.isCaretOnLastLine()||this.isSuggestBoxVisible())
break;newText=this._next();break;case"U+0050":if(WebInspector.isMac()&&event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey){newText=this._previous();isPrevious=true;}
break;case"U+004E":if(WebInspector.isMac()&&event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey)
@@ -3660,23 +3660,23 @@
WebInspector.CSSNumberRegex=/^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;WebInspector.StyleValueDelimiters=" \xA0\t\n\"':;,/()";WebInspector._valueModificationDirection=function(event)
{var direction=null;if(event.type==="mousewheel"){if(event.wheelDeltaY>0)
direction="Up";else if(event.wheelDeltaY<0)
-direction="Down";}else{if(event.keyIdentifier==="Up"||event.keyIdentifier==="PageUp")
-direction="Up";else if(event.keyIdentifier==="Down"||event.keyIdentifier==="PageDown")
+direction="Down";}else{if(event.key==="Up"||event.key==="PageUp")
+direction="Up";else if(event.key==="Down"||event.key==="PageDown")
direction="Down";}
return direction;}
WebInspector._modifiedHexValue=function(hexString,event)
{var direction=WebInspector._valueModificationDirection(event);if(!direction)
return hexString;var number=parseInt(hexString,16);if(isNaN(number)||!isFinite(number))
-return hexString;var maxValue=Math.pow(16,hexString.length)-1;var arrowKeyOrMouseWheelEvent=(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"||event.type==="mousewheel");var delta;if(arrowKeyOrMouseWheelEvent)
+return hexString;var maxValue=Math.pow(16,hexString.length)-1;var arrowKeyOrMouseWheelEvent=(event.key==="Up"||event.key==="Down"||event.type==="mousewheel");var delta;if(arrowKeyOrMouseWheelEvent)
delta=(direction==="Up")?1:-1;else
-delta=(event.keyIdentifier==="PageUp")?16:-16;if(event.shiftKey)
+delta=(event.key==="PageUp")?16:-16;if(event.shiftKey)
delta*=16;var result=number+delta;if(result<0)
result=0;else if(result>maxValue)
return hexString;var resultString=result.toString(16).toUpperCase();for(var i=0,lengthDelta=hexString.length-resultString.length;i<lengthDelta;++i)
resultString="0"+resultString;return resultString;}
WebInspector._modifiedFloatNumber=function(number,event)
{var direction=WebInspector._valueModificationDirection(event);if(!direction)
-return number;var arrowKeyOrMouseWheelEvent=(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"||event.type==="mousewheel");var changeAmount=1;if(event.shiftKey&&!arrowKeyOrMouseWheelEvent)
+return number;var arrowKeyOrMouseWheelEvent=(event.key==="Up"||event.key==="Down"||event.type==="mousewheel");var changeAmount=1;if(event.shiftKey&&!arrowKeyOrMouseWheelEvent)
changeAmount=100;else if(event.shiftKey||!arrowKeyOrMouseWheelEvent)
changeAmount=10;else if(event.altKey)
changeAmount=0.1;if(direction==="Down")
@@ -3689,7 +3689,7 @@
WebInspector.handleElementValueModifications=function(event,element,finishHandler,suggestionHandler,customNumberHandler)
{function createRange()
{return document.createRange();}
-var arrowKeyOrMouseWheelEvent=(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"||event.type==="mousewheel");var pageKeyPressed=(event.keyIdentifier==="PageUp"||event.keyIdentifier==="PageDown");if(!arrowKeyOrMouseWheelEvent&&!pageKeyPressed)
+var arrowKeyOrMouseWheelEvent=(event.key==="Up"||event.key==="Down"||event.type==="mousewheel");var pageKeyPressed=(event.key==="PageUp"||event.key==="PageDown");if(!arrowKeyOrMouseWheelEvent&&!pageKeyPressed)
return false;var selection=element.getComponentSelection();if(!selection.rangeCount)
return false;var selectionRange=selection.getRangeAt(0);if(!selectionRange.commonAncestorContainer.isSelfOrDescendant(element))
return false;var originalValue=element.textContent;var wordRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,WebInspector.StyleValueDelimiters,element);var wordString=wordRange.toString();if(suggestionHandler&&suggestionHandler(wordString))
@@ -4140,7 +4140,7 @@
processingStartTime=Date.now();this._dispatcher[functionName].apply(this._dispatcher,params);if(InspectorBackendClass.Options.dumpInspectorTimeStats)
console.log("time-stats: "+messageObject.method+" = "+(Date.now()-processingStartTime));}}
InspectorBackendClass.Options={dumpInspectorTimeStats:false,dumpInspectorProtocolMessages:false,suppressRequestErrors:false}
-InspectorBackend=new InspectorBackendClass();;InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend",["testCallId","script"]);InspectorBackend.registerEvent("Inspector.inspect",["object","hints"]);InspectorBackend.registerEvent("Inspector.detached",["reason"]);InspectorBackend.registerEvent("Inspector.targetCrashed",[]);InspectorBackend.registerCommand("Inspector.enable",[],[],false);InspectorBackend.registerCommand("Inspector.disable",[],[],false);InspectorBackend.registerEnum("Memory.PressureLevel",{Moderate:"moderate",Critical:"critical"});InspectorBackend.registerCommand("Memory.getDOMCounters",[],["documents","nodes","jsEventListeners"],false);InspectorBackend.registerCommand("Memory.setPressureNotificationsSuppressed",[{"name":"suppressed","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Memory.simulatePressureNotification",[{"name":"level","type":"string","optional":false}],[],false);InspectorBackend.registerEnum("Page.ResourceType",{Document:"Document",Stylesheet:"Stylesheet",Image:"Image",Media:"Media",Font:"Font",Script:"Script",TextTrack:"TextTrack",XHR:"XHR",Fetch:"Fetch",EventSource:"EventSource",WebSocket:"WebSocket",Manifest:"Manifest",Other:"Other"});InspectorBackend.registerEnum("Page.DialogType",{Alert:"alert",Confirm:"confirm",Prompt:"prompt",Beforeunload:"beforeunload"});InspectorBackend.registerEvent("Page.domContentEventFired",["timestamp"]);InspectorBackend.registerEvent("Page.loadEventFired",["timestamp"]);InspectorBackend.registerEvent("Page.frameAttached",["frameId","parentFrameId"]);InspectorBackend.registerEvent("Page.frameNavigated",["frame"]);InspectorBackend.registerEvent("Page.frameDetached",["frameId"]);InspectorBackend.registerEvent("Page.frameStartedLoading",["frameId"]);InspectorBackend.registerEvent("Page.frameStoppedLoading",["frameId"]);InspectorBackend.registerEvent("Page.frameScheduledNavigation",["frameId","delay"]);InspectorBackend.registerEvent("Page.frameClearedScheduledNavigation",["frameId"]);InspectorBackend.registerEvent("Page.frameResized",[]);InspectorBackend.registerEvent("Page.javascriptDialogOpening",["message","type"]);InspectorBackend.registerEvent("Page.javascriptDialogClosed",["result"]);InspectorBackend.registerEvent("Page.screencastFrame",["data","metadata","sessionId"]);InspectorBackend.registerEvent("Page.screencastVisibilityChanged",["visible"]);InspectorBackend.registerEvent("Page.colorPicked",["color"]);InspectorBackend.registerEvent("Page.interstitialShown",[]);InspectorBackend.registerEvent("Page.interstitialHidden",[]);InspectorBackend.registerCommand("Page.enable",[],[],false);InspectorBackend.registerCommand("Page.disable",[],[],false);InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad",[{"name":"scriptSource","type":"string","optional":false}],["identifier"],false);InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad",[{"name":"identifier","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.reload",[{"name":"ignoreCache","type":"boolean","optional":true},{"name":"scriptToEvaluateOnLoad","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.navigate",[{"name":"url","type":"string","optional":false}],["frameId"],false);InspectorBackend.registerCommand("Page.getNavigationHistory",[],["currentIndex","entries"],false);InspectorBackend.registerCommand("Page.navigateToHistoryEntry",[{"name":"entryId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.getCookies",[],["cookies"],false);InspectorBackend.registerCommand("Page.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.getResourceTree",[],["frameTree"],false);InspectorBackend.registerCommand("Page.getResourceContent",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false}],["content","base64Encoded"],false);InspectorBackend.registerCommand("Page.searchInResource",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);InspectorBackend.registerCommand("Page.setDocumentContent",[{"name":"frameId","type":"string","optional":false},{"name":"html","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"fitWindow","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"offsetX","type":"number","optional":true},{"name":"offsetY","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.clearDeviceMetricsOverride",[],[],false);InspectorBackend.registerCommand("Page.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.clearGeolocationOverride",[],[],false);InspectorBackend.registerCommand("Page.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.clearDeviceOrientationOverride",[],[],false);InspectorBackend.registerCommand("Page.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.captureScreenshot",[],["data"],false);InspectorBackend.registerCommand("Page.startScreencast",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"maxWidth","type":"number","optional":true},{"name":"maxHeight","type":"number","optional":true},{"name":"everyNthFrame","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.stopScreencast",[],[],false);InspectorBackend.registerCommand("Page.screencastFrameAck",[{"name":"sessionId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.handleJavaScriptDialog",[{"name":"accept","type":"boolean","optional":false},{"name":"promptText","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.setColorPickerEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Page.setOverlayMessage",[{"name":"message","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Rendering.setShowPaintRects",[{"name":"result","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowDebugBorders",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowFPSCounter",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowScrollBottleneckRects",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerEvent("Emulation.viewportChanged",["viewport"]);InspectorBackend.registerCommand("Emulation.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"fitWindow","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"offsetX","type":"number","optional":true},{"name":"offsetY","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride",[],[],false);InspectorBackend.registerCommand("Emulation.resetScrollAndPageScaleFactor",[],[],false);InspectorBackend.registerCommand("Emulation.setPageScaleFactor",[{"name":"pageScaleFactor","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled",[{"name":"value","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.clearGeolocationOverride",[],[],false);InspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.setEmulatedMedia",[{"name":"media","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setCPUThrottlingRate",[{"name":"rate","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.canEmulate",[],["result"],false);InspectorBackend.registerEnum("Runtime.RemoteObjectType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEnum("Runtime.RemoteObjectSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.ObjectPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.PropertyPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Accessor:"accessor"});InspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.CallArgumentType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEvent("Runtime.executionContextCreated",["context"]);InspectorBackend.registerEvent("Runtime.executionContextDestroyed",["executionContextId"]);InspectorBackend.registerEvent("Runtime.executionContextsCleared",[]);InspectorBackend.registerCommand("Runtime.evaluate",[{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"contextId","type":"number","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown","exceptionDetails"],false);InspectorBackend.registerCommand("Runtime.callFunctionOn",[{"name":"objectId","type":"string","optional":false},{"name":"functionDeclaration","type":"string","optional":false},{"name":"arguments","type":"object","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown"],false);InspectorBackend.registerCommand("Runtime.getProperties",[{"name":"objectId","type":"string","optional":false},{"name":"ownProperties","type":"boolean","optional":true},{"name":"accessorPropertiesOnly","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","internalProperties","exceptionDetails"],false);InspectorBackend.registerCommand("Runtime.releaseObject",[{"name":"objectId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Runtime.releaseObjectGroup",[{"name":"objectGroup","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Runtime.run",[],[],false);InspectorBackend.registerCommand("Runtime.enable",[],[],false);InspectorBackend.registerCommand("Runtime.disable",[],[],false);InspectorBackend.registerCommand("Runtime.isRunRequired",[],["result"],false);InspectorBackend.registerCommand("Runtime.setCustomObjectFormatterEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerEnum("Console.ConsoleMessageSource",{XML:"xml",Javascript:"javascript",Network:"network",ConsoleAPI:"console-api",Storage:"storage",Appcache:"appcache",Rendering:"rendering",Security:"security",Other:"other",Deprecation:"deprecation"});InspectorBackend.registerEnum("Console.ConsoleMessageLevel",{Log:"log",Warning:"warning",Error:"error",Debug:"debug",Info:"info",RevokedError:"revokedError"});InspectorBackend.registerEnum("Console.ConsoleMessageType",{Log:"log",Dir:"dir",DirXML:"dirxml",Table:"table",Trace:"trace",Clear:"clear",StartGroup:"startGroup",StartGroupCollapsed:"startGroupCollapsed",EndGroup:"endGroup",Assert:"assert",Profile:"profile",ProfileEnd:"profileEnd"});InspectorBackend.registerEvent("Console.messageAdded",["message"]);InspectorBackend.registerEvent("Console.messageRepeatCountUpdated",["count","timestamp"]);InspectorBackend.registerEvent("Console.messagesCleared",[]);InspectorBackend.registerCommand("Console.enable",[],[],false);InspectorBackend.registerCommand("Console.disable",[],[],false);InspectorBackend.registerCommand("Console.clearMessages",[],[],false);InspectorBackend.registerEnum("Security.SecurityState",{Unknown:"unknown",Neutral:"neutral",Insecure:"insecure",Warning:"warning",Secure:"secure",Info:"info"});InspectorBackend.registerEvent("Security.securityStateChanged",["securityState","explanations","mixedContentStatus","schemeIsCryptographic"]);InspectorBackend.registerCommand("Security.enable",[],[],false);InspectorBackend.registerCommand("Security.disable",[],[],false);InspectorBackend.registerEnum("Network.ResourcePriority",{VeryLow:"VeryLow",Low:"Low",Medium:"Medium",High:"High",VeryHigh:"VeryHigh"});InspectorBackend.registerEnum("Network.RequestMixedContentType",{Blockable:"blockable",OptionallyBlockable:"optionally-blockable",None:"none"});InspectorBackend.registerEnum("Network.BlockedReason",{Csp:"csp",MixedContent:"mixed-content",Origin:"origin",Inspector:"inspector",Other:"other"});InspectorBackend.registerEnum("Network.InitiatorType",{Parser:"parser",Script:"script",Other:"other"});InspectorBackend.registerEvent("Network.requestWillBeSent",["requestId","frameId","loaderId","documentURL","request","timestamp","wallTime","initiator","redirectResponse","type"]);InspectorBackend.registerEvent("Network.requestServedFromCache",["requestId"]);InspectorBackend.registerEvent("Network.responseReceived",["requestId","frameId","loaderId","timestamp","type","response"]);InspectorBackend.registerEvent("Network.dataReceived",["requestId","timestamp","dataLength","encodedDataLength"]);InspectorBackend.registerEvent("Network.loadingFinished",["requestId","timestamp","encodedDataLength"]);InspectorBackend.registerEvent("Network.loadingFailed",["requestId","timestamp","type","errorText","canceled","blockedReason"]);InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest",["requestId","timestamp","wallTime","request"]);InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.webSocketCreated",["requestId","url"]);InspectorBackend.registerEvent("Network.webSocketClosed",["requestId","timestamp"]);InspectorBackend.registerEvent("Network.webSocketFrameReceived",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.webSocketFrameError",["requestId","timestamp","errorMessage"]);InspectorBackend.registerEvent("Network.webSocketFrameSent",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.eventSourceMessageReceived",["requestId","timestamp","eventName","eventId","data"]);InspectorBackend.registerCommand("Network.enable",[],[],false);InspectorBackend.registerCommand("Network.disable",[],[],false);InspectorBackend.registerCommand("Network.setUserAgentOverride",[{"name":"userAgent","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.setExtraHTTPHeaders",[{"name":"headers","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("Network.getResponseBody",[{"name":"requestId","type":"string","optional":false}],["body","base64Encoded"],false);InspectorBackend.registerCommand("Network.addBlockedURL",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.removeBlockedURL",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.replayXHR",[{"name":"requestId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.setMonitoringXHREnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Network.canClearBrowserCache",[],["result"],false);InspectorBackend.registerCommand("Network.clearBrowserCache",[],[],false);InspectorBackend.registerCommand("Network.canClearBrowserCookies",[],["result"],false);InspectorBackend.registerCommand("Network.clearBrowserCookies",[],[],false);InspectorBackend.registerCommand("Network.getCookies",[],["cookies"],false);InspectorBackend.registerCommand("Network.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.canEmulateNetworkConditions",[],["result"],false);InspectorBackend.registerCommand("Network.emulateNetworkConditions",[{"name":"offline","type":"boolean","optional":false},{"name":"latency","type":"number","optional":false},{"name":"downloadThroughput","type":"number","optional":false},{"name":"uploadThroughput","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Network.setCacheDisabled",[{"name":"cacheDisabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Network.setDataSizeLimitsForTest",[{"name":"maxTotalSize","type":"number","optional":false},{"name":"maxResourceSize","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Network.getCertificateDetails",[{"name":"certificateId","type":"number","optional":false}],["result"],false);InspectorBackend.registerCommand("Network.showCertificateViewer",[{"name":"certificateId","type":"number","optional":false}],[],false);InspectorBackend.registerEvent("Database.addDatabase",["database"]);InspectorBackend.registerCommand("Database.enable",[],[],false);InspectorBackend.registerCommand("Database.disable",[],[],false);InspectorBackend.registerCommand("Database.getDatabaseTableNames",[{"name":"databaseId","type":"string","optional":false}],["tableNames"],false);InspectorBackend.registerCommand("Database.executeSQL",[{"name":"databaseId","type":"string","optional":false},{"name":"query","type":"string","optional":false}],["columnNames","values","sqlError"],false);InspectorBackend.registerEnum("IndexedDB.KeyType",{Number:"number",String:"string",Date:"date",Array:"array"});InspectorBackend.registerEnum("IndexedDB.KeyPathType",{Null:"null",String:"string",Array:"array"});InspectorBackend.registerCommand("IndexedDB.enable",[],[],false);InspectorBackend.registerCommand("IndexedDB.disable",[],[],false);InspectorBackend.registerCommand("IndexedDB.requestDatabaseNames",[{"name":"securityOrigin","type":"string","optional":false}],["databaseNames"],false);InspectorBackend.registerCommand("IndexedDB.requestDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],["databaseWithObjectStores"],false);InspectorBackend.registerCommand("IndexedDB.requestData",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false},{"name":"indexName","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false},{"name":"keyRange","type":"object","optional":true}],["objectStoreDataEntries","hasMore"],false);InspectorBackend.registerCommand("IndexedDB.clearObjectStore",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CacheStorage.requestCacheNames",[{"name":"securityOrigin","type":"string","optional":false}],["caches"],false);InspectorBackend.registerCommand("CacheStorage.requestEntries",[{"name":"cacheId","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false}],["cacheDataEntries","hasMore"],false);InspectorBackend.registerCommand("CacheStorage.deleteCache",[{"name":"cacheId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CacheStorage.deleteEntry",[{"name":"cacheId","type":"string","optional":false},{"name":"request","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared",["storageId"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved",["storageId","key"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemAdded",["storageId","key","newValue"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated",["storageId","key","oldValue","newValue"]);InspectorBackend.registerCommand("DOMStorage.enable",[],[],false);InspectorBackend.registerCommand("DOMStorage.disable",[],[],false);InspectorBackend.registerCommand("DOMStorage.getDOMStorageItems",[{"name":"storageId","type":"object","optional":false}],["entries"],false);InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated",["frameId","manifestURL","status"]);InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated",["isNowOnline"]);InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests",[],["frameIds"],false);InspectorBackend.registerCommand("ApplicationCache.enable",[],[],false);InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame",[{"name":"frameId","type":"string","optional":false}],["manifestURL"],false);InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame",[{"name":"frameId","type":"string","optional":false}],["applicationCache"],false);InspectorBackend.registerCommand("FileSystem.enable",[],[],false);InspectorBackend.registerCommand("FileSystem.disable",[],[],false);InspectorBackend.registerCommand("FileSystem.requestFileSystemRoot",[{"name":"origin","type":"string","optional":false},{"name":"type","type":"string","optional":false}],["errorCode","root"],false);InspectorBackend.registerCommand("FileSystem.requestDirectoryContent",[{"name":"url","type":"string","optional":false}],["errorCode","entries"],false);InspectorBackend.registerCommand("FileSystem.requestMetadata",[{"name":"url","type":"string","optional":false}],["errorCode","metadata"],false);InspectorBackend.registerCommand("FileSystem.requestFileContent",[{"name":"url","type":"string","optional":false},{"name":"readAsText","type":"boolean","optional":false},{"name":"start","type":"number","optional":true},{"name":"end","type":"number","optional":true},{"name":"charset","type":"string","optional":true}],["errorCode","content","charset"],false);InspectorBackend.registerCommand("FileSystem.deleteEntry",[{"name":"url","type":"string","optional":false}],["errorCode"],false);InspectorBackend.registerEnum("DOM.PseudoType",{FirstLine:"first-line",FirstLetter:"first-letter",Before:"before",After:"after",Backdrop:"backdrop",Selection:"selection",FirstLineInherited:"first-line-inherited",Scrollbar:"scrollbar",ScrollbarThumb:"scrollbar-thumb",ScrollbarButton:"scrollbar-button",ScrollbarTrack:"scrollbar-track",ScrollbarTrackPiece:"scrollbar-track-piece",ScrollbarCorner:"scrollbar-corner",Resizer:"resizer",InputListButton:"input-list-button"});InspectorBackend.registerEnum("DOM.ShadowRootType",{UserAgent:"user-agent",Open:"open",Closed:"closed"});InspectorBackend.registerEnum("DOM.InspectMode",{SearchForNode:"searchForNode",SearchForUAShadowDOM:"searchForUAShadowDOM",ShowLayoutEditor:"showLayoutEditor",None:"none"});InspectorBackend.registerEvent("DOM.documentUpdated",[]);InspectorBackend.registerEvent("DOM.inspectNodeRequested",["backendNodeId"]);InspectorBackend.registerEvent("DOM.setChildNodes",["parentId","nodes"]);InspectorBackend.registerEvent("DOM.attributeModified",["nodeId","name","value"]);InspectorBackend.registerEvent("DOM.attributeRemoved",["nodeId","name"]);InspectorBackend.registerEvent("DOM.inlineStyleInvalidated",["nodeIds"]);InspectorBackend.registerEvent("DOM.characterDataModified",["nodeId","characterData"]);InspectorBackend.registerEvent("DOM.childNodeCountUpdated",["nodeId","childNodeCount"]);InspectorBackend.registerEvent("DOM.childNodeInserted",["parentNodeId","previousNodeId","node"]);InspectorBackend.registerEvent("DOM.childNodeRemoved",["parentNodeId","nodeId"]);InspectorBackend.registerEvent("DOM.shadowRootPushed",["hostId","root"]);InspectorBackend.registerEvent("DOM.shadowRootPopped",["hostId","rootId"]);InspectorBackend.registerEvent("DOM.pseudoElementAdded",["parentId","pseudoElement"]);InspectorBackend.registerEvent("DOM.pseudoElementRemoved",["parentId","pseudoElementId"]);InspectorBackend.registerEvent("DOM.distributedNodesUpdated",["insertionPointId","distributedNodes"]);InspectorBackend.registerEvent("DOM.nodeHighlightRequested",["nodeId"]);InspectorBackend.registerCommand("DOM.enable",[],[],false);InspectorBackend.registerCommand("DOM.disable",[],[],false);InspectorBackend.registerCommand("DOM.getDocument",[],["root"],false);InspectorBackend.registerCommand("DOM.requestChildNodes",[{"name":"nodeId","type":"number","optional":false},{"name":"depth","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("DOM.querySelector",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.querySelectorAll",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.setNodeName",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.setNodeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.removeNode",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setAttributeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setAttributesAsText",[{"name":"nodeId","type":"number","optional":false},{"name":"text","type":"string","optional":false},{"name":"name","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOM.removeAttribute",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.getOuterHTML",[{"name":"nodeId","type":"number","optional":false}],["outerHTML"],false);InspectorBackend.registerCommand("DOM.setOuterHTML",[{"name":"nodeId","type":"number","optional":false},{"name":"outerHTML","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.performSearch",[{"name":"query","type":"string","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["searchId","resultCount"],false);InspectorBackend.registerCommand("DOM.getSearchResults",[{"name":"searchId","type":"string","optional":false},{"name":"fromIndex","type":"number","optional":false},{"name":"toIndex","type":"number","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.discardSearchResults",[{"name":"searchId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.requestNode",[{"name":"objectId","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.setInspectMode",[{"name":"mode","type":"string","optional":false},{"name":"highlightConfig","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightRect",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightQuad",[{"name":"quad","type":"object","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightNode",[{"name":"highlightConfig","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOM.hideHighlight",[],[],false);InspectorBackend.registerCommand("DOM.highlightFrame",[{"name":"frameId","type":"string","optional":false},{"name":"contentColor","type":"object","optional":true},{"name":"contentOutlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend",[{"name":"path","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend",[{"name":"backendNodeIds","type":"object","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.setInspectedNode",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.resolveNode",[{"name":"nodeId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true}],["object"],false);InspectorBackend.registerCommand("DOM.getAttributes",[{"name":"nodeId","type":"number","optional":false}],["attributes"],false);InspectorBackend.registerCommand("DOM.copyTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);InspectorBackend.registerCommand("DOM.moveTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);InspectorBackend.registerCommand("DOM.undo",[],[],false);InspectorBackend.registerCommand("DOM.redo",[],[],false);InspectorBackend.registerCommand("DOM.markUndoableState",[],[],false);InspectorBackend.registerCommand("DOM.focus",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setFileInputFiles",[{"name":"nodeId","type":"number","optional":false},{"name":"files","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("DOM.getBoxModel",[{"name":"nodeId","type":"number","optional":false}],["model"],false);InspectorBackend.registerCommand("DOM.getNodeForLocation",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.getRelayoutBoundary",[{"name":"nodeId","type":"number","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.getHighlightObjectForTest",[{"name":"nodeId","type":"number","optional":false}],["highlight"],false);InspectorBackend.registerEnum("CSS.StyleSheetOrigin",{Injected:"injected",UserAgent:"user-agent",Inspector:"inspector",Regular:"regular"});InspectorBackend.registerEnum("CSS.CSSMediaSource",{MediaRule:"mediaRule",ImportRule:"importRule",LinkedSheet:"linkedSheet",InlineSheet:"inlineSheet"});InspectorBackend.registerEvent("CSS.mediaQueryResultChanged",[]);InspectorBackend.registerEvent("CSS.styleSheetChanged",["styleSheetId"]);InspectorBackend.registerEvent("CSS.styleSheetAdded",["header"]);InspectorBackend.registerEvent("CSS.styleSheetRemoved",["styleSheetId"]);InspectorBackend.registerEvent("CSS.layoutEditorChange",["styleSheetId","changeRange"]);InspectorBackend.registerCommand("CSS.enable",[],[],false);InspectorBackend.registerCommand("CSS.disable",[],[],false);InspectorBackend.registerCommand("CSS.getMatchedStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle","matchedCSSRules","pseudoElements","inherited"],false);InspectorBackend.registerCommand("CSS.getInlineStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle"],false);InspectorBackend.registerCommand("CSS.getComputedStyleForNode",[{"name":"nodeId","type":"number","optional":false}],["computedStyle"],false);InspectorBackend.registerCommand("CSS.getPlatformFontsForNode",[{"name":"nodeId","type":"number","optional":false}],["fonts"],false);InspectorBackend.registerCommand("CSS.getCSSAnimationsForNode",[{"name":"nodeId","type":"number","optional":false}],["cssKeyframesRules"],false);InspectorBackend.registerCommand("CSS.getStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false}],["text"],false);InspectorBackend.registerCommand("CSS.setStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"text","type":"string","optional":false}],["sourceMapURL"],false);InspectorBackend.registerCommand("CSS.setRuleSelector",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"selector","type":"string","optional":false}],["selectorList"],false);InspectorBackend.registerCommand("CSS.setStyleText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["style"],false);InspectorBackend.registerCommand("CSS.setMediaText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["media"],false);InspectorBackend.registerCommand("CSS.createStyleSheet",[{"name":"frameId","type":"string","optional":false}],["styleSheetId"],false);InspectorBackend.registerCommand("CSS.addRule",[{"name":"styleSheetId","type":"string","optional":false},{"name":"ruleText","type":"string","optional":false},{"name":"location","type":"object","optional":false}],["rule"],false);InspectorBackend.registerCommand("CSS.forcePseudoState",[{"name":"nodeId","type":"number","optional":false},{"name":"forcedPseudoClasses","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("CSS.getMediaQueries",[],["medias"],false);InspectorBackend.registerCommand("CSS.setEffectivePropertyValueForNode",[{"name":"nodeId","type":"number","optional":false},{"name":"propertyName","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CSS.getBackgroundColors",[{"name":"nodeId","type":"number","optional":false}],["backgroundColors"],false);InspectorBackend.registerCommand("IO.read",[{"name":"handle","type":"string","optional":false},{"name":"offset","type":"number","optional":true},{"name":"size","type":"number","optional":true}],["data","eof"],false);InspectorBackend.registerCommand("IO.close",[{"name":"handle","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("Timeline.eventRecorded",["record"]);InspectorBackend.registerCommand("Timeline.enable",[],[],false);InspectorBackend.registerCommand("Timeline.disable",[],[],false);InspectorBackend.registerCommand("Timeline.start",[{"name":"maxCallStackDepth","type":"number","optional":true},{"name":"bufferEvents","type":"boolean","optional":true},{"name":"liveEvents","type":"string","optional":true},{"name":"includeCounters","type":"boolean","optional":true},{"name":"includeGPUEvents","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Timeline.stop",[],[],false);InspectorBackend.registerEnum("Debugger.GeneratorObjectDetailsStatus",{Running:"running",Suspended:"suspended",Closed:"closed"});InspectorBackend.registerEnum("Debugger.ScopeType",{Global:"global",Local:"local",With:"with",Closure:"closure",Catch:"catch",Block:"block",Script:"script"});InspectorBackend.registerEnum("Debugger.PromiseDetailsStatus",{Pending:"pending",Resolved:"resolved",Rejected:"rejected"});InspectorBackend.registerEvent("Debugger.globalObjectCleared",[]);InspectorBackend.registerEvent("Debugger.scriptParsed",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","isContentScript","isInternalScript","isLiveEdit","sourceMapURL","hasSourceURL"]);InspectorBackend.registerEvent("Debugger.scriptFailedToParse",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","isContentScript","isInternalScript","sourceMapURL","hasSourceURL"]);InspectorBackend.registerEvent("Debugger.breakpointResolved",["breakpointId","location"]);InspectorBackend.registerEvent("Debugger.paused",["callFrames","reason","data","hitBreakpoints","asyncStackTrace"]);InspectorBackend.registerEvent("Debugger.resumed",[]);InspectorBackend.registerEvent("Debugger.promiseUpdated",["eventType","promise"]);InspectorBackend.registerEvent("Debugger.asyncOperationStarted",["operation"]);InspectorBackend.registerEvent("Debugger.asyncOperationCompleted",["id"]);InspectorBackend.registerCommand("Debugger.enable",[],[],false);InspectorBackend.registerCommand("Debugger.disable",[],[],false);InspectorBackend.registerCommand("Debugger.setBreakpointsActive",[{"name":"active","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.setSkipAllPauses",[{"name":"skipped","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.setBreakpointByUrl",[{"name":"lineNumber","type":"number","optional":false},{"name":"url","type":"string","optional":true},{"name":"urlRegex","type":"string","optional":true},{"name":"columnNumber","type":"number","optional":true},{"name":"condition","type":"string","optional":true}],["breakpointId","locations"],false);InspectorBackend.registerCommand("Debugger.setBreakpoint",[{"name":"location","type":"object","optional":false},{"name":"condition","type":"string","optional":true}],["breakpointId","actualLocation"],false);InspectorBackend.registerCommand("Debugger.removeBreakpoint",[{"name":"breakpointId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.continueToLocation",[{"name":"location","type":"object","optional":false},{"name":"interstatementLocation","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.stepOver",[],[],false);InspectorBackend.registerCommand("Debugger.stepInto",[],[],false);InspectorBackend.registerCommand("Debugger.stepOut",[],[],false);InspectorBackend.registerCommand("Debugger.pause",[],[],false);InspectorBackend.registerCommand("Debugger.resume",[],[],false);InspectorBackend.registerCommand("Debugger.stepIntoAsync",[],[],false);InspectorBackend.registerCommand("Debugger.searchInContent",[{"name":"scriptId","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);InspectorBackend.registerCommand("Debugger.canSetScriptSource",[],["result"],false);InspectorBackend.registerCommand("Debugger.setScriptSource",[{"name":"scriptId","type":"string","optional":false},{"name":"scriptSource","type":"string","optional":false},{"name":"preview","type":"boolean","optional":true}],["callFrames","stackChanged","asyncStackTrace"],true);InspectorBackend.registerCommand("Debugger.restartFrame",[{"name":"callFrameId","type":"string","optional":false}],["callFrames","asyncStackTrace"],false);InspectorBackend.registerCommand("Debugger.getScriptSource",[{"name":"scriptId","type":"string","optional":false}],["scriptSource"],false);InspectorBackend.registerCommand("Debugger.getFunctionDetails",[{"name":"functionId","type":"string","optional":false}],["details"],false);InspectorBackend.registerCommand("Debugger.getGeneratorObjectDetails",[{"name":"objectId","type":"string","optional":false}],["details"],false);InspectorBackend.registerCommand("Debugger.getCollectionEntries",[{"name":"objectId","type":"string","optional":false}],["entries"],false);InspectorBackend.registerCommand("Debugger.setPauseOnExceptions",[{"name":"state","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.evaluateOnCallFrame",[{"name":"callFrameId","type":"string","optional":false},{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.compileScript",[{"name":"expression","type":"string","optional":false},{"name":"sourceURL","type":"string","optional":false},{"name":"persistScript","type":"boolean","optional":false},{"name":"executionContextId","type":"number","optional":false}],["scriptId","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.runScript",[{"name":"scriptId","type":"string","optional":false},{"name":"executionContextId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true}],["result","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.setVariableValue",[{"name":"scopeNumber","type":"number","optional":false},{"name":"variableName","type":"string","optional":false},{"name":"newValue","type":"object","optional":false},{"name":"callFrameId","type":"string","optional":true},{"name":"functionObjectId","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.getStepInPositions",[{"name":"callFrameId","type":"string","optional":false}],["stepInPositions"],false);InspectorBackend.registerCommand("Debugger.getBacktrace",[],["callFrames","asyncStackTrace"],false);InspectorBackend.registerCommand("Debugger.skipStackFrames",[{"name":"script","type":"string","optional":true},{"name":"skipContentScripts","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth",[{"name":"maxDepth","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.enablePromiseTracker",[{"name":"captureStacks","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.disablePromiseTracker",[],[],false);InspectorBackend.registerCommand("Debugger.getPromiseById",[{"name":"promiseId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true}],["promise"],false);InspectorBackend.registerCommand("Debugger.flushAsyncOperationEvents",[],[],false);InspectorBackend.registerCommand("Debugger.setAsyncOperationBreakpoint",[{"name":"operationId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.removeAsyncOperationBreakpoint",[{"name":"operationId","type":"number","optional":false}],[],false);InspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType",{SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed"});InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.getEventListeners",[{"name":"objectId","type":"string","optional":false}],["listeners"],false);InspectorBackend.registerEvent("Profiler.consoleProfileStarted",["id","location","title"]);InspectorBackend.registerEvent("Profiler.consoleProfileFinished",["id","location","profile","title"]);InspectorBackend.registerCommand("Profiler.enable",[],[],false);InspectorBackend.registerCommand("Profiler.disable",[],[],false);InspectorBackend.registerCommand("Profiler.setSamplingInterval",[{"name":"interval","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Profiler.start",[],[],false);InspectorBackend.registerCommand("Profiler.stop",[],["profile"],false);InspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk",["chunk"]);InspectorBackend.registerEvent("HeapProfiler.resetProfiles",[]);InspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress",["done","total","finished"]);InspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId",["lastSeenObjectId","timestamp"]);InspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate",["statsUpdate"]);InspectorBackend.registerCommand("HeapProfiler.enable",[],[],false);InspectorBackend.registerCommand("HeapProfiler.disable",[],[],false);InspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects",[{"name":"trackAllocations","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.collectGarbage",[],[],false);InspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId",[{"name":"objectId","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true}],["result"],false);InspectorBackend.registerCommand("HeapProfiler.addInspectedHeapObject",[{"name":"heapObjectId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("HeapProfiler.getHeapObjectId",[{"name":"objectId","type":"string","optional":false}],["heapSnapshotObjectId"],false);InspectorBackend.registerEvent("Worker.workerCreated",["workerId","url","inspectorConnected"]);InspectorBackend.registerEvent("Worker.workerTerminated",["workerId"]);InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker",["workerId","message"]);InspectorBackend.registerCommand("Worker.enable",[],[],false);InspectorBackend.registerCommand("Worker.disable",[],[],false);InspectorBackend.registerCommand("Worker.sendMessageToWorker",[{"name":"workerId","type":"string","optional":false},{"name":"message","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.connectToWorker",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.disconnectFromWorker",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers",[{"name":"value","type":"boolean","optional":false}],[],false);InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus",{Stopped:"stopped",Starting:"starting",Running:"running",Stopping:"stopping"});InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus",{New:"new",Installing:"installing",Installed:"installed",Activating:"activating",Activated:"activated",Redundant:"redundant"});InspectorBackend.registerEvent("ServiceWorker.workerCreated",["workerId","url","versionId"]);InspectorBackend.registerEvent("ServiceWorker.workerTerminated",["workerId"]);InspectorBackend.registerEvent("ServiceWorker.dispatchMessage",["workerId","message"]);InspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated",["registrations"]);InspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated",["versions"]);InspectorBackend.registerEvent("ServiceWorker.workerErrorReported",["errorMessage"]);InspectorBackend.registerEvent("ServiceWorker.debugOnStartUpdated",["debugOnStart"]);InspectorBackend.registerCommand("ServiceWorker.enable",[],[],false);InspectorBackend.registerCommand("ServiceWorker.disable",[],[],false);InspectorBackend.registerCommand("ServiceWorker.sendMessage",[{"name":"workerId","type":"string","optional":false},{"name":"message","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.stop",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.unregister",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.updateRegistration",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.startWorker",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.stopWorker",[{"name":"versionId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.inspectWorker",[{"name":"versionId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.setDebugOnStart",[{"name":"debugOnStart","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.setForceUpdateOnPageLoad",[{"name":"registrationId","type":"string","optional":false},{"name":"forceUpdateOnPageLoad","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.deliverPushMessage",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"data","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.getTargetInfo",[{"name":"targetId","type":"string","optional":false}],["targetInfo"],false);InspectorBackend.registerCommand("ServiceWorker.activateTarget",[{"name":"targetId","type":"string","optional":false}],[],false);InspectorBackend.registerEnum("Input.TouchPointState",{TouchPressed:"touchPressed",TouchReleased:"touchReleased",TouchMoved:"touchMoved",TouchStationary:"touchStationary",TouchCancelled:"touchCancelled"});InspectorBackend.registerEnum("Input.GestureSourceType",{Default:"default",Touch:"touch",Mouse:"mouse"});InspectorBackend.registerCommand("Input.dispatchKeyEvent",[{"name":"type","type":"string","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"text","type":"string","optional":true},{"name":"unmodifiedText","type":"string","optional":true},{"name":"keyIdentifier","type":"string","optional":true},{"name":"code","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"windowsVirtualKeyCode","type":"number","optional":true},{"name":"nativeVirtualKeyCode","type":"number","optional":true},{"name":"autoRepeat","type":"boolean","optional":true},{"name":"isKeypad","type":"boolean","optional":true},{"name":"isSystemKey","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Input.dispatchMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"button","type":"string","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.dispatchTouchEvent",[{"name":"type","type":"string","optional":false},{"name":"touchPoints","type":"object","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"timestamp","type":"number","optional":false},{"name":"button","type":"string","optional":false},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true},{"name":"modifiers","type":"number","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizePinchGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"scaleFactor","type":"number","optional":false},{"name":"relativeSpeed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizeScrollGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"xDistance","type":"number","optional":true},{"name":"yDistance","type":"number","optional":true},{"name":"xOverscroll","type":"number","optional":true},{"name":"yOverscroll","type":"number","optional":true},{"name":"preventFling","type":"boolean","optional":true},{"name":"speed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true},{"name":"repeatCount","type":"number","optional":true},{"name":"repeatDelayMs","type":"number","optional":true},{"name":"interactionMarkerName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizeTapGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"duration","type":"number","optional":true},{"name":"tapCount","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);InspectorBackend.registerEnum("LayerTree.ScrollRectType",{RepaintsOnScroll:"RepaintsOnScroll",TouchEventHandler:"TouchEventHandler",WheelEventHandler:"WheelEventHandler"});InspectorBackend.registerEvent("LayerTree.layerTreeDidChange",["layers"]);InspectorBackend.registerEvent("LayerTree.layerPainted",["layerId","clip"]);InspectorBackend.registerCommand("LayerTree.enable",[],[],false);InspectorBackend.registerCommand("LayerTree.disable",[],[],false);InspectorBackend.registerCommand("LayerTree.compositingReasons",[{"name":"layerId","type":"string","optional":false}],["compositingReasons"],false);InspectorBackend.registerCommand("LayerTree.makeSnapshot",[{"name":"layerId","type":"string","optional":false}],["snapshotId"],false);InspectorBackend.registerCommand("LayerTree.loadSnapshot",[{"name":"tiles","type":"object","optional":false}],["snapshotId"],false);InspectorBackend.registerCommand("LayerTree.releaseSnapshot",[{"name":"snapshotId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("LayerTree.profileSnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"minRepeatCount","type":"number","optional":true},{"name":"minDuration","type":"number","optional":true},{"name":"clipRect","type":"object","optional":true}],["timings"],false);InspectorBackend.registerCommand("LayerTree.replaySnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"fromStep","type":"number","optional":true},{"name":"toStep","type":"number","optional":true},{"name":"scale","type":"number","optional":true}],["dataURL"],false);InspectorBackend.registerCommand("LayerTree.snapshotCommandLog",[{"name":"snapshotId","type":"string","optional":false}],["commandLog"],false);InspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride",[],[],false);InspectorBackend.registerEnum("ScreenOrientation.OrientationType",{PortraitPrimary:"portraitPrimary",PortraitSecondary:"portraitSecondary",LandscapePrimary:"landscapePrimary",LandscapeSecondary:"landscapeSecondary"});InspectorBackend.registerCommand("ScreenOrientation.setScreenOrientationOverride",[{"name":"angle","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ScreenOrientation.clearScreenOrientationOverride",[],[],false);InspectorBackend.registerEvent("Tracing.dataCollected",["value"]);InspectorBackend.registerEvent("Tracing.tracingComplete",["stream"]);InspectorBackend.registerEvent("Tracing.bufferUsage",["percentFull","eventCount","value"]);InspectorBackend.registerCommand("Tracing.start",[{"name":"categories","type":"string","optional":true},{"name":"options","type":"string","optional":true},{"name":"bufferUsageReportingInterval","type":"number","optional":true},{"name":"transferMode","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Tracing.end",[],[],false);InspectorBackend.registerCommand("Tracing.getCategories",[],["categories"],false);InspectorBackend.registerCommand("Tracing.requestMemoryDump",[],["dumpGuid","success"],false);InspectorBackend.registerEnum("Animation.AnimationType",{CSSTransition:"CSSTransition",CSSAnimation:"CSSAnimation",WebAnimation:"WebAnimation"});InspectorBackend.registerEvent("Animation.animationCreated",["id"]);InspectorBackend.registerEvent("Animation.animationStarted",["animation"]);InspectorBackend.registerEvent("Animation.animationCanceled",["id"]);InspectorBackend.registerCommand("Animation.enable",[],[],false);InspectorBackend.registerCommand("Animation.disable",[],[],false);InspectorBackend.registerCommand("Animation.getPlaybackRate",[],["playbackRate"],false);InspectorBackend.registerCommand("Animation.setPlaybackRate",[{"name":"playbackRate","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.getCurrentTime",[{"name":"id","type":"string","optional":false}],["currentTime"],false);InspectorBackend.registerCommand("Animation.setPaused",[{"name":"animations","type":"object","optional":false},{"name":"paused","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Animation.setTiming",[{"name":"animationId","type":"string","optional":false},{"name":"duration","type":"number","optional":false},{"name":"delay","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.seekAnimations",[{"name":"animations","type":"object","optional":false},{"name":"currentTime","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.releaseAnimations",[{"name":"animations","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("Animation.resolveAnimation",[{"name":"animationId","type":"string","optional":false}],["remoteObject"],false);InspectorBackend.registerEnum("Accessibility.AXValueType",{Boolean:"boolean",Tristate:"tristate",BooleanOrUndefined:"booleanOrUndefined",Idref:"idref",IdrefList:"idrefList",Integer:"integer",Node:"node",NodeList:"nodeList",Number:"number",String:"string",ComputedString:"computedString",Token:"token",TokenList:"tokenList",DomRelation:"domRelation",Role:"role",InternalRole:"internalRole",ValueUndefined:"valueUndefined"});InspectorBackend.registerEnum("Accessibility.AXValueSourceType",{Attribute:"attribute",Implicit:"implicit",Style:"style",Contents:"contents",Placeholder:"placeholder",RelatedElement:"relatedElement"});InspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType",{Figcaption:"figcaption",Label:"label",Labelfor:"labelfor",Labelwrapped:"labelwrapped",Legend:"legend",Tablecaption:"tablecaption",Title:"title",Other:"other"});InspectorBackend.registerEnum("Accessibility.AXGlobalStates",{Disabled:"disabled",Hidden:"hidden",HiddenRoot:"hiddenRoot",Invalid:"invalid"});InspectorBackend.registerEnum("Accessibility.AXLiveRegionAttributes",{Live:"live",Atomic:"atomic",Relevant:"relevant",Busy:"busy",Root:"root"});InspectorBackend.registerEnum("Accessibility.AXWidgetAttributes",{Autocomplete:"autocomplete",Haspopup:"haspopup",Level:"level",Multiselectable:"multiselectable",Orientation:"orientation",Multiline:"multiline",Readonly:"readonly",Required:"required",Valuemin:"valuemin",Valuemax:"valuemax",Valuetext:"valuetext"});InspectorBackend.registerEnum("Accessibility.AXWidgetStates",{Checked:"checked",Expanded:"expanded",Pressed:"pressed",Selected:"selected"});InspectorBackend.registerEnum("Accessibility.AXRelationshipAttributes",{Activedescendant:"activedescendant",Flowto:"flowto",Controls:"controls",Describedby:"describedby",Labelledby:"labelledby",Owns:"owns"});InspectorBackend.registerCommand("Accessibility.getAXNode",[{"name":"nodeId","type":"number","optional":false}],["accessibilityNode"],false);;WebInspector.InspectorBackendHostedMode={};WebInspector.InspectorBackendHostedMode.loadFromJSONIfNeeded=function(jsonUrl)
+InspectorBackend=new InspectorBackendClass();;InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend",["testCallId","script"]);InspectorBackend.registerEvent("Inspector.inspect",["object","hints"]);InspectorBackend.registerEvent("Inspector.detached",["reason"]);InspectorBackend.registerEvent("Inspector.targetCrashed",[]);InspectorBackend.registerCommand("Inspector.enable",[],[],false);InspectorBackend.registerCommand("Inspector.disable",[],[],false);InspectorBackend.registerEnum("Memory.PressureLevel",{Moderate:"moderate",Critical:"critical"});InspectorBackend.registerCommand("Memory.getDOMCounters",[],["documents","nodes","jsEventListeners"],false);InspectorBackend.registerCommand("Memory.setPressureNotificationsSuppressed",[{"name":"suppressed","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Memory.simulatePressureNotification",[{"name":"level","type":"string","optional":false}],[],false);InspectorBackend.registerEnum("Page.ResourceType",{Document:"Document",Stylesheet:"Stylesheet",Image:"Image",Media:"Media",Font:"Font",Script:"Script",TextTrack:"TextTrack",XHR:"XHR",Fetch:"Fetch",EventSource:"EventSource",WebSocket:"WebSocket",Manifest:"Manifest",Other:"Other"});InspectorBackend.registerEnum("Page.DialogType",{Alert:"alert",Confirm:"confirm",Prompt:"prompt",Beforeunload:"beforeunload"});InspectorBackend.registerEvent("Page.domContentEventFired",["timestamp"]);InspectorBackend.registerEvent("Page.loadEventFired",["timestamp"]);InspectorBackend.registerEvent("Page.frameAttached",["frameId","parentFrameId"]);InspectorBackend.registerEvent("Page.frameNavigated",["frame"]);InspectorBackend.registerEvent("Page.frameDetached",["frameId"]);InspectorBackend.registerEvent("Page.frameStartedLoading",["frameId"]);InspectorBackend.registerEvent("Page.frameStoppedLoading",["frameId"]);InspectorBackend.registerEvent("Page.frameScheduledNavigation",["frameId","delay"]);InspectorBackend.registerEvent("Page.frameClearedScheduledNavigation",["frameId"]);InspectorBackend.registerEvent("Page.frameResized",[]);InspectorBackend.registerEvent("Page.javascriptDialogOpening",["message","type"]);InspectorBackend.registerEvent("Page.javascriptDialogClosed",["result"]);InspectorBackend.registerEvent("Page.screencastFrame",["data","metadata","sessionId"]);InspectorBackend.registerEvent("Page.screencastVisibilityChanged",["visible"]);InspectorBackend.registerEvent("Page.colorPicked",["color"]);InspectorBackend.registerEvent("Page.interstitialShown",[]);InspectorBackend.registerEvent("Page.interstitialHidden",[]);InspectorBackend.registerCommand("Page.enable",[],[],false);InspectorBackend.registerCommand("Page.disable",[],[],false);InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad",[{"name":"scriptSource","type":"string","optional":false}],["identifier"],false);InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad",[{"name":"identifier","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.reload",[{"name":"ignoreCache","type":"boolean","optional":true},{"name":"scriptToEvaluateOnLoad","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.navigate",[{"name":"url","type":"string","optional":false}],["frameId"],false);InspectorBackend.registerCommand("Page.getNavigationHistory",[],["currentIndex","entries"],false);InspectorBackend.registerCommand("Page.navigateToHistoryEntry",[{"name":"entryId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.getCookies",[],["cookies"],false);InspectorBackend.registerCommand("Page.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.getResourceTree",[],["frameTree"],false);InspectorBackend.registerCommand("Page.getResourceContent",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false}],["content","base64Encoded"],false);InspectorBackend.registerCommand("Page.searchInResource",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);InspectorBackend.registerCommand("Page.setDocumentContent",[{"name":"frameId","type":"string","optional":false},{"name":"html","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Page.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"fitWindow","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"offsetX","type":"number","optional":true},{"name":"offsetY","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.clearDeviceMetricsOverride",[],[],false);InspectorBackend.registerCommand("Page.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.clearGeolocationOverride",[],[],false);InspectorBackend.registerCommand("Page.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.clearDeviceOrientationOverride",[],[],false);InspectorBackend.registerCommand("Page.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.captureScreenshot",[],["data"],false);InspectorBackend.registerCommand("Page.startScreencast",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"maxWidth","type":"number","optional":true},{"name":"maxHeight","type":"number","optional":true},{"name":"everyNthFrame","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Page.stopScreencast",[],[],false);InspectorBackend.registerCommand("Page.screencastFrameAck",[{"name":"sessionId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Page.handleJavaScriptDialog",[{"name":"accept","type":"boolean","optional":false},{"name":"promptText","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Page.setColorPickerEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Page.setOverlayMessage",[{"name":"message","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Rendering.setShowPaintRects",[{"name":"result","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowDebugBorders",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowFPSCounter",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Rendering.setShowScrollBottleneckRects",[{"name":"show","type":"boolean","optional":false}],[],false);InspectorBackend.registerEvent("Emulation.viewportChanged",["viewport"]);InspectorBackend.registerCommand("Emulation.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"fitWindow","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"offsetX","type":"number","optional":true},{"name":"offsetY","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride",[],[],false);InspectorBackend.registerCommand("Emulation.resetScrollAndPageScaleFactor",[],[],false);InspectorBackend.registerCommand("Emulation.setPageScaleFactor",[{"name":"pageScaleFactor","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled",[{"name":"value","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.clearGeolocationOverride",[],[],false);InspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Emulation.setEmulatedMedia",[{"name":"media","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.setCPUThrottlingRate",[{"name":"rate","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Emulation.canEmulate",[],["result"],false);InspectorBackend.registerEnum("Runtime.RemoteObjectType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEnum("Runtime.RemoteObjectSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.ObjectPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.PropertyPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Accessor:"accessor"});InspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Iterator:"iterator",Generator:"generator",Error:"error"});InspectorBackend.registerEnum("Runtime.CallArgumentType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol"});InspectorBackend.registerEvent("Runtime.executionContextCreated",["context"]);InspectorBackend.registerEvent("Runtime.executionContextDestroyed",["executionContextId"]);InspectorBackend.registerEvent("Runtime.executionContextsCleared",[]);InspectorBackend.registerCommand("Runtime.evaluate",[{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"contextId","type":"number","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown","exceptionDetails"],false);InspectorBackend.registerCommand("Runtime.callFunctionOn",[{"name":"objectId","type":"string","optional":false},{"name":"functionDeclaration","type":"string","optional":false},{"name":"arguments","type":"object","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown"],false);InspectorBackend.registerCommand("Runtime.getProperties",[{"name":"objectId","type":"string","optional":false},{"name":"ownProperties","type":"boolean","optional":true},{"name":"accessorPropertiesOnly","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","internalProperties","exceptionDetails"],false);InspectorBackend.registerCommand("Runtime.releaseObject",[{"name":"objectId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Runtime.releaseObjectGroup",[{"name":"objectGroup","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Runtime.run",[],[],false);InspectorBackend.registerCommand("Runtime.enable",[],[],false);InspectorBackend.registerCommand("Runtime.disable",[],[],false);InspectorBackend.registerCommand("Runtime.isRunRequired",[],["result"],false);InspectorBackend.registerCommand("Runtime.setCustomObjectFormatterEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerEnum("Console.ConsoleMessageSource",{XML:"xml",Javascript:"javascript",Network:"network",ConsoleAPI:"console-api",Storage:"storage",Appcache:"appcache",Rendering:"rendering",Security:"security",Other:"other",Deprecation:"deprecation"});InspectorBackend.registerEnum("Console.ConsoleMessageLevel",{Log:"log",Warning:"warning",Error:"error",Debug:"debug",Info:"info",RevokedError:"revokedError"});InspectorBackend.registerEnum("Console.ConsoleMessageType",{Log:"log",Dir:"dir",DirXML:"dirxml",Table:"table",Trace:"trace",Clear:"clear",StartGroup:"startGroup",StartGroupCollapsed:"startGroupCollapsed",EndGroup:"endGroup",Assert:"assert",Profile:"profile",ProfileEnd:"profileEnd"});InspectorBackend.registerEvent("Console.messageAdded",["message"]);InspectorBackend.registerEvent("Console.messageRepeatCountUpdated",["count","timestamp"]);InspectorBackend.registerEvent("Console.messagesCleared",[]);InspectorBackend.registerCommand("Console.enable",[],[],false);InspectorBackend.registerCommand("Console.disable",[],[],false);InspectorBackend.registerCommand("Console.clearMessages",[],[],false);InspectorBackend.registerEnum("Security.SecurityState",{Unknown:"unknown",Neutral:"neutral",Insecure:"insecure",Warning:"warning",Secure:"secure",Info:"info"});InspectorBackend.registerEvent("Security.securityStateChanged",["securityState","explanations","mixedContentStatus","schemeIsCryptographic"]);InspectorBackend.registerCommand("Security.enable",[],[],false);InspectorBackend.registerCommand("Security.disable",[],[],false);InspectorBackend.registerEnum("Network.ResourcePriority",{VeryLow:"VeryLow",Low:"Low",Medium:"Medium",High:"High",VeryHigh:"VeryHigh"});InspectorBackend.registerEnum("Network.RequestMixedContentType",{Blockable:"blockable",OptionallyBlockable:"optionally-blockable",None:"none"});InspectorBackend.registerEnum("Network.BlockedReason",{Csp:"csp",MixedContent:"mixed-content",Origin:"origin",Inspector:"inspector",Other:"other"});InspectorBackend.registerEnum("Network.InitiatorType",{Parser:"parser",Script:"script",Other:"other"});InspectorBackend.registerEvent("Network.requestWillBeSent",["requestId","frameId","loaderId","documentURL","request","timestamp","wallTime","initiator","redirectResponse","type"]);InspectorBackend.registerEvent("Network.requestServedFromCache",["requestId"]);InspectorBackend.registerEvent("Network.responseReceived",["requestId","frameId","loaderId","timestamp","type","response"]);InspectorBackend.registerEvent("Network.dataReceived",["requestId","timestamp","dataLength","encodedDataLength"]);InspectorBackend.registerEvent("Network.loadingFinished",["requestId","timestamp","encodedDataLength"]);InspectorBackend.registerEvent("Network.loadingFailed",["requestId","timestamp","type","errorText","canceled","blockedReason"]);InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest",["requestId","timestamp","wallTime","request"]);InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.webSocketCreated",["requestId","url"]);InspectorBackend.registerEvent("Network.webSocketClosed",["requestId","timestamp"]);InspectorBackend.registerEvent("Network.webSocketFrameReceived",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.webSocketFrameError",["requestId","timestamp","errorMessage"]);InspectorBackend.registerEvent("Network.webSocketFrameSent",["requestId","timestamp","response"]);InspectorBackend.registerEvent("Network.eventSourceMessageReceived",["requestId","timestamp","eventName","eventId","data"]);InspectorBackend.registerCommand("Network.enable",[],[],false);InspectorBackend.registerCommand("Network.disable",[],[],false);InspectorBackend.registerCommand("Network.setUserAgentOverride",[{"name":"userAgent","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.setExtraHTTPHeaders",[{"name":"headers","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("Network.getResponseBody",[{"name":"requestId","type":"string","optional":false}],["body","base64Encoded"],false);InspectorBackend.registerCommand("Network.addBlockedURL",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.removeBlockedURL",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.replayXHR",[{"name":"requestId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.setMonitoringXHREnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Network.canClearBrowserCache",[],["result"],false);InspectorBackend.registerCommand("Network.clearBrowserCache",[],[],false);InspectorBackend.registerCommand("Network.canClearBrowserCookies",[],["result"],false);InspectorBackend.registerCommand("Network.clearBrowserCookies",[],[],false);InspectorBackend.registerCommand("Network.getCookies",[],["cookies"],false);InspectorBackend.registerCommand("Network.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Network.canEmulateNetworkConditions",[],["result"],false);InspectorBackend.registerCommand("Network.emulateNetworkConditions",[{"name":"offline","type":"boolean","optional":false},{"name":"latency","type":"number","optional":false},{"name":"downloadThroughput","type":"number","optional":false},{"name":"uploadThroughput","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Network.setCacheDisabled",[{"name":"cacheDisabled","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Network.setDataSizeLimitsForTest",[{"name":"maxTotalSize","type":"number","optional":false},{"name":"maxResourceSize","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Network.getCertificateDetails",[{"name":"certificateId","type":"number","optional":false}],["result"],false);InspectorBackend.registerCommand("Network.showCertificateViewer",[{"name":"certificateId","type":"number","optional":false}],[],false);InspectorBackend.registerEvent("Database.addDatabase",["database"]);InspectorBackend.registerCommand("Database.enable",[],[],false);InspectorBackend.registerCommand("Database.disable",[],[],false);InspectorBackend.registerCommand("Database.getDatabaseTableNames",[{"name":"databaseId","type":"string","optional":false}],["tableNames"],false);InspectorBackend.registerCommand("Database.executeSQL",[{"name":"databaseId","type":"string","optional":false},{"name":"query","type":"string","optional":false}],["columnNames","values","sqlError"],false);InspectorBackend.registerEnum("IndexedDB.KeyType",{Number:"number",String:"string",Date:"date",Array:"array"});InspectorBackend.registerEnum("IndexedDB.KeyPathType",{Null:"null",String:"string",Array:"array"});InspectorBackend.registerCommand("IndexedDB.enable",[],[],false);InspectorBackend.registerCommand("IndexedDB.disable",[],[],false);InspectorBackend.registerCommand("IndexedDB.requestDatabaseNames",[{"name":"securityOrigin","type":"string","optional":false}],["databaseNames"],false);InspectorBackend.registerCommand("IndexedDB.requestDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],["databaseWithObjectStores"],false);InspectorBackend.registerCommand("IndexedDB.requestData",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false},{"name":"indexName","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false},{"name":"keyRange","type":"object","optional":true}],["objectStoreDataEntries","hasMore"],false);InspectorBackend.registerCommand("IndexedDB.clearObjectStore",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CacheStorage.requestCacheNames",[{"name":"securityOrigin","type":"string","optional":false}],["caches"],false);InspectorBackend.registerCommand("CacheStorage.requestEntries",[{"name":"cacheId","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false}],["cacheDataEntries","hasMore"],false);InspectorBackend.registerCommand("CacheStorage.deleteCache",[{"name":"cacheId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CacheStorage.deleteEntry",[{"name":"cacheId","type":"string","optional":false},{"name":"request","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared",["storageId"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved",["storageId","key"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemAdded",["storageId","key","newValue"]);InspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated",["storageId","key","oldValue","newValue"]);InspectorBackend.registerCommand("DOMStorage.enable",[],[],false);InspectorBackend.registerCommand("DOMStorage.disable",[],[],false);InspectorBackend.registerCommand("DOMStorage.getDOMStorageItems",[{"name":"storageId","type":"object","optional":false}],["entries"],false);InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated",["frameId","manifestURL","status"]);InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated",["isNowOnline"]);InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests",[],["frameIds"],false);InspectorBackend.registerCommand("ApplicationCache.enable",[],[],false);InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame",[{"name":"frameId","type":"string","optional":false}],["manifestURL"],false);InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame",[{"name":"frameId","type":"string","optional":false}],["applicationCache"],false);InspectorBackend.registerCommand("FileSystem.enable",[],[],false);InspectorBackend.registerCommand("FileSystem.disable",[],[],false);InspectorBackend.registerCommand("FileSystem.requestFileSystemRoot",[{"name":"origin","type":"string","optional":false},{"name":"type","type":"string","optional":false}],["errorCode","root"],false);InspectorBackend.registerCommand("FileSystem.requestDirectoryContent",[{"name":"url","type":"string","optional":false}],["errorCode","entries"],false);InspectorBackend.registerCommand("FileSystem.requestMetadata",[{"name":"url","type":"string","optional":false}],["errorCode","metadata"],false);InspectorBackend.registerCommand("FileSystem.requestFileContent",[{"name":"url","type":"string","optional":false},{"name":"readAsText","type":"boolean","optional":false},{"name":"start","type":"number","optional":true},{"name":"end","type":"number","optional":true},{"name":"charset","type":"string","optional":true}],["errorCode","content","charset"],false);InspectorBackend.registerCommand("FileSystem.deleteEntry",[{"name":"url","type":"string","optional":false}],["errorCode"],false);InspectorBackend.registerEnum("DOM.PseudoType",{FirstLine:"first-line",FirstLetter:"first-letter",Before:"before",After:"after",Backdrop:"backdrop",Selection:"selection",FirstLineInherited:"first-line-inherited",Scrollbar:"scrollbar",ScrollbarThumb:"scrollbar-thumb",ScrollbarButton:"scrollbar-button",ScrollbarTrack:"scrollbar-track",ScrollbarTrackPiece:"scrollbar-track-piece",ScrollbarCorner:"scrollbar-corner",Resizer:"resizer",InputListButton:"input-list-button"});InspectorBackend.registerEnum("DOM.ShadowRootType",{UserAgent:"user-agent",Open:"open",Closed:"closed"});InspectorBackend.registerEnum("DOM.InspectMode",{SearchForNode:"searchForNode",SearchForUAShadowDOM:"searchForUAShadowDOM",ShowLayoutEditor:"showLayoutEditor",None:"none"});InspectorBackend.registerEvent("DOM.documentUpdated",[]);InspectorBackend.registerEvent("DOM.inspectNodeRequested",["backendNodeId"]);InspectorBackend.registerEvent("DOM.setChildNodes",["parentId","nodes"]);InspectorBackend.registerEvent("DOM.attributeModified",["nodeId","name","value"]);InspectorBackend.registerEvent("DOM.attributeRemoved",["nodeId","name"]);InspectorBackend.registerEvent("DOM.inlineStyleInvalidated",["nodeIds"]);InspectorBackend.registerEvent("DOM.characterDataModified",["nodeId","characterData"]);InspectorBackend.registerEvent("DOM.childNodeCountUpdated",["nodeId","childNodeCount"]);InspectorBackend.registerEvent("DOM.childNodeInserted",["parentNodeId","previousNodeId","node"]);InspectorBackend.registerEvent("DOM.childNodeRemoved",["parentNodeId","nodeId"]);InspectorBackend.registerEvent("DOM.shadowRootPushed",["hostId","root"]);InspectorBackend.registerEvent("DOM.shadowRootPopped",["hostId","rootId"]);InspectorBackend.registerEvent("DOM.pseudoElementAdded",["parentId","pseudoElement"]);InspectorBackend.registerEvent("DOM.pseudoElementRemoved",["parentId","pseudoElementId"]);InspectorBackend.registerEvent("DOM.distributedNodesUpdated",["insertionPointId","distributedNodes"]);InspectorBackend.registerEvent("DOM.nodeHighlightRequested",["nodeId"]);InspectorBackend.registerCommand("DOM.enable",[],[],false);InspectorBackend.registerCommand("DOM.disable",[],[],false);InspectorBackend.registerCommand("DOM.getDocument",[],["root"],false);InspectorBackend.registerCommand("DOM.requestChildNodes",[{"name":"nodeId","type":"number","optional":false},{"name":"depth","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("DOM.querySelector",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.querySelectorAll",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.setNodeName",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.setNodeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.removeNode",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setAttributeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setAttributesAsText",[{"name":"nodeId","type":"number","optional":false},{"name":"text","type":"string","optional":false},{"name":"name","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOM.removeAttribute",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.getOuterHTML",[{"name":"nodeId","type":"number","optional":false}],["outerHTML"],false);InspectorBackend.registerCommand("DOM.setOuterHTML",[{"name":"nodeId","type":"number","optional":false},{"name":"outerHTML","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.performSearch",[{"name":"query","type":"string","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["searchId","resultCount"],false);InspectorBackend.registerCommand("DOM.getSearchResults",[{"name":"searchId","type":"string","optional":false},{"name":"fromIndex","type":"number","optional":false},{"name":"toIndex","type":"number","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.discardSearchResults",[{"name":"searchId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOM.requestNode",[{"name":"objectId","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.setInspectMode",[{"name":"mode","type":"string","optional":false},{"name":"highlightConfig","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightRect",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightQuad",[{"name":"quad","type":"object","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.highlightNode",[{"name":"highlightConfig","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOM.hideHighlight",[],[],false);InspectorBackend.registerCommand("DOM.highlightFrame",[{"name":"frameId","type":"string","optional":false},{"name":"contentColor","type":"object","optional":true},{"name":"contentOutlineColor","type":"object","optional":true}],[],false);InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend",[{"name":"path","type":"string","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend",[{"name":"backendNodeIds","type":"object","optional":false}],["nodeIds"],false);InspectorBackend.registerCommand("DOM.setInspectedNode",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.resolveNode",[{"name":"nodeId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true}],["object"],false);InspectorBackend.registerCommand("DOM.getAttributes",[{"name":"nodeId","type":"number","optional":false}],["attributes"],false);InspectorBackend.registerCommand("DOM.copyTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);InspectorBackend.registerCommand("DOM.moveTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);InspectorBackend.registerCommand("DOM.undo",[],[],false);InspectorBackend.registerCommand("DOM.redo",[],[],false);InspectorBackend.registerCommand("DOM.markUndoableState",[],[],false);InspectorBackend.registerCommand("DOM.focus",[{"name":"nodeId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DOM.setFileInputFiles",[{"name":"nodeId","type":"number","optional":false},{"name":"files","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("DOM.getBoxModel",[{"name":"nodeId","type":"number","optional":false}],["model"],false);InspectorBackend.registerCommand("DOM.getNodeForLocation",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.getRelayoutBoundary",[{"name":"nodeId","type":"number","optional":false}],["nodeId"],false);InspectorBackend.registerCommand("DOM.getHighlightObjectForTest",[{"name":"nodeId","type":"number","optional":false}],["highlight"],false);InspectorBackend.registerEnum("CSS.StyleSheetOrigin",{Injected:"injected",UserAgent:"user-agent",Inspector:"inspector",Regular:"regular"});InspectorBackend.registerEnum("CSS.CSSMediaSource",{MediaRule:"mediaRule",ImportRule:"importRule",LinkedSheet:"linkedSheet",InlineSheet:"inlineSheet"});InspectorBackend.registerEvent("CSS.mediaQueryResultChanged",[]);InspectorBackend.registerEvent("CSS.styleSheetChanged",["styleSheetId"]);InspectorBackend.registerEvent("CSS.styleSheetAdded",["header"]);InspectorBackend.registerEvent("CSS.styleSheetRemoved",["styleSheetId"]);InspectorBackend.registerEvent("CSS.layoutEditorChange",["styleSheetId","changeRange"]);InspectorBackend.registerCommand("CSS.enable",[],[],false);InspectorBackend.registerCommand("CSS.disable",[],[],false);InspectorBackend.registerCommand("CSS.getMatchedStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle","matchedCSSRules","pseudoElements","inherited"],false);InspectorBackend.registerCommand("CSS.getInlineStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle"],false);InspectorBackend.registerCommand("CSS.getComputedStyleForNode",[{"name":"nodeId","type":"number","optional":false}],["computedStyle"],false);InspectorBackend.registerCommand("CSS.getPlatformFontsForNode",[{"name":"nodeId","type":"number","optional":false}],["fonts"],false);InspectorBackend.registerCommand("CSS.getCSSAnimationsForNode",[{"name":"nodeId","type":"number","optional":false}],["cssKeyframesRules"],false);InspectorBackend.registerCommand("CSS.getStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false}],["text"],false);InspectorBackend.registerCommand("CSS.setStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"text","type":"string","optional":false}],["sourceMapURL"],false);InspectorBackend.registerCommand("CSS.setRuleSelector",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"selector","type":"string","optional":false}],["selectorList"],false);InspectorBackend.registerCommand("CSS.setStyleText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["style"],false);InspectorBackend.registerCommand("CSS.setMediaText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["media"],false);InspectorBackend.registerCommand("CSS.createStyleSheet",[{"name":"frameId","type":"string","optional":false}],["styleSheetId"],false);InspectorBackend.registerCommand("CSS.addRule",[{"name":"styleSheetId","type":"string","optional":false},{"name":"ruleText","type":"string","optional":false},{"name":"location","type":"object","optional":false}],["rule"],false);InspectorBackend.registerCommand("CSS.forcePseudoState",[{"name":"nodeId","type":"number","optional":false},{"name":"forcedPseudoClasses","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("CSS.getMediaQueries",[],["medias"],false);InspectorBackend.registerCommand("CSS.setEffectivePropertyValueForNode",[{"name":"nodeId","type":"number","optional":false},{"name":"propertyName","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("CSS.getBackgroundColors",[{"name":"nodeId","type":"number","optional":false}],["backgroundColors"],false);InspectorBackend.registerCommand("IO.read",[{"name":"handle","type":"string","optional":false},{"name":"offset","type":"number","optional":true},{"name":"size","type":"number","optional":true}],["data","eof"],false);InspectorBackend.registerCommand("IO.close",[{"name":"handle","type":"string","optional":false}],[],false);InspectorBackend.registerEvent("Timeline.eventRecorded",["record"]);InspectorBackend.registerCommand("Timeline.enable",[],[],false);InspectorBackend.registerCommand("Timeline.disable",[],[],false);InspectorBackend.registerCommand("Timeline.start",[{"name":"maxCallStackDepth","type":"number","optional":true},{"name":"bufferEvents","type":"boolean","optional":true},{"name":"liveEvents","type":"string","optional":true},{"name":"includeCounters","type":"boolean","optional":true},{"name":"includeGPUEvents","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Timeline.stop",[],[],false);InspectorBackend.registerEnum("Debugger.GeneratorObjectDetailsStatus",{Running:"running",Suspended:"suspended",Closed:"closed"});InspectorBackend.registerEnum("Debugger.ScopeType",{Global:"global",Local:"local",With:"with",Closure:"closure",Catch:"catch",Block:"block",Script:"script"});InspectorBackend.registerEnum("Debugger.PromiseDetailsStatus",{Pending:"pending",Resolved:"resolved",Rejected:"rejected"});InspectorBackend.registerEvent("Debugger.globalObjectCleared",[]);InspectorBackend.registerEvent("Debugger.scriptParsed",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","isContentScript","isInternalScript","isLiveEdit","sourceMapURL","hasSourceURL"]);InspectorBackend.registerEvent("Debugger.scriptFailedToParse",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","isContentScript","isInternalScript","sourceMapURL","hasSourceURL"]);InspectorBackend.registerEvent("Debugger.breakpointResolved",["breakpointId","location"]);InspectorBackend.registerEvent("Debugger.paused",["callFrames","reason","data","hitBreakpoints","asyncStackTrace"]);InspectorBackend.registerEvent("Debugger.resumed",[]);InspectorBackend.registerEvent("Debugger.promiseUpdated",["eventType","promise"]);InspectorBackend.registerEvent("Debugger.asyncOperationStarted",["operation"]);InspectorBackend.registerEvent("Debugger.asyncOperationCompleted",["id"]);InspectorBackend.registerCommand("Debugger.enable",[],[],false);InspectorBackend.registerCommand("Debugger.disable",[],[],false);InspectorBackend.registerCommand("Debugger.setBreakpointsActive",[{"name":"active","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.setSkipAllPauses",[{"name":"skipped","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.setBreakpointByUrl",[{"name":"lineNumber","type":"number","optional":false},{"name":"url","type":"string","optional":true},{"name":"urlRegex","type":"string","optional":true},{"name":"columnNumber","type":"number","optional":true},{"name":"condition","type":"string","optional":true}],["breakpointId","locations"],false);InspectorBackend.registerCommand("Debugger.setBreakpoint",[{"name":"location","type":"object","optional":false},{"name":"condition","type":"string","optional":true}],["breakpointId","actualLocation"],false);InspectorBackend.registerCommand("Debugger.removeBreakpoint",[{"name":"breakpointId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.continueToLocation",[{"name":"location","type":"object","optional":false},{"name":"interstatementLocation","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.stepOver",[],[],false);InspectorBackend.registerCommand("Debugger.stepInto",[],[],false);InspectorBackend.registerCommand("Debugger.stepOut",[],[],false);InspectorBackend.registerCommand("Debugger.pause",[],[],false);InspectorBackend.registerCommand("Debugger.resume",[],[],false);InspectorBackend.registerCommand("Debugger.stepIntoAsync",[],[],false);InspectorBackend.registerCommand("Debugger.searchInContent",[{"name":"scriptId","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);InspectorBackend.registerCommand("Debugger.canSetScriptSource",[],["result"],false);InspectorBackend.registerCommand("Debugger.setScriptSource",[{"name":"scriptId","type":"string","optional":false},{"name":"scriptSource","type":"string","optional":false},{"name":"preview","type":"boolean","optional":true}],["callFrames","stackChanged","asyncStackTrace"],true);InspectorBackend.registerCommand("Debugger.restartFrame",[{"name":"callFrameId","type":"string","optional":false}],["callFrames","asyncStackTrace"],false);InspectorBackend.registerCommand("Debugger.getScriptSource",[{"name":"scriptId","type":"string","optional":false}],["scriptSource"],false);InspectorBackend.registerCommand("Debugger.getFunctionDetails",[{"name":"functionId","type":"string","optional":false}],["details"],false);InspectorBackend.registerCommand("Debugger.getGeneratorObjectDetails",[{"name":"objectId","type":"string","optional":false}],["details"],false);InspectorBackend.registerCommand("Debugger.getCollectionEntries",[{"name":"objectId","type":"string","optional":false}],["entries"],false);InspectorBackend.registerCommand("Debugger.setPauseOnExceptions",[{"name":"state","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.evaluateOnCallFrame",[{"name":"callFrameId","type":"string","optional":false},{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","wasThrown","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.compileScript",[{"name":"expression","type":"string","optional":false},{"name":"sourceURL","type":"string","optional":false},{"name":"persistScript","type":"boolean","optional":false},{"name":"executionContextId","type":"number","optional":false}],["scriptId","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.runScript",[{"name":"scriptId","type":"string","optional":false},{"name":"executionContextId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"doNotPauseOnExceptionsAndMuteConsole","type":"boolean","optional":true}],["result","exceptionDetails"],false);InspectorBackend.registerCommand("Debugger.setVariableValue",[{"name":"scopeNumber","type":"number","optional":false},{"name":"variableName","type":"string","optional":false},{"name":"newValue","type":"object","optional":false},{"name":"callFrameId","type":"string","optional":true},{"name":"functionObjectId","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.getStepInPositions",[{"name":"callFrameId","type":"string","optional":false}],["stepInPositions"],false);InspectorBackend.registerCommand("Debugger.getBacktrace",[],["callFrames","asyncStackTrace"],false);InspectorBackend.registerCommand("Debugger.skipStackFrames",[{"name":"script","type":"string","optional":true},{"name":"skipContentScripts","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth",[{"name":"maxDepth","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.enablePromiseTracker",[{"name":"captureStacks","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Debugger.disablePromiseTracker",[],[],false);InspectorBackend.registerCommand("Debugger.getPromiseById",[{"name":"promiseId","type":"number","optional":false},{"name":"objectGroup","type":"string","optional":true}],["promise"],false);InspectorBackend.registerCommand("Debugger.flushAsyncOperationEvents",[],[],false);InspectorBackend.registerCommand("Debugger.setAsyncOperationBreakpoint",[{"name":"operationId","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Debugger.removeAsyncOperationBreakpoint",[{"name":"operationId","type":"number","optional":false}],[],false);InspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType",{SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed"});InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("DOMDebugger.getEventListeners",[{"name":"objectId","type":"string","optional":false}],["listeners"],false);InspectorBackend.registerEvent("Profiler.consoleProfileStarted",["id","location","title"]);InspectorBackend.registerEvent("Profiler.consoleProfileFinished",["id","location","profile","title"]);InspectorBackend.registerCommand("Profiler.enable",[],[],false);InspectorBackend.registerCommand("Profiler.disable",[],[],false);InspectorBackend.registerCommand("Profiler.setSamplingInterval",[{"name":"interval","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Profiler.start",[],[],false);InspectorBackend.registerCommand("Profiler.stop",[],["profile"],false);InspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk",["chunk"]);InspectorBackend.registerEvent("HeapProfiler.resetProfiles",[]);InspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress",["done","total","finished"]);InspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId",["lastSeenObjectId","timestamp"]);InspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate",["statsUpdate"]);InspectorBackend.registerCommand("HeapProfiler.enable",[],[],false);InspectorBackend.registerCommand("HeapProfiler.disable",[],[],false);InspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects",[{"name":"trackAllocations","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("HeapProfiler.collectGarbage",[],[],false);InspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId",[{"name":"objectId","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true}],["result"],false);InspectorBackend.registerCommand("HeapProfiler.addInspectedHeapObject",[{"name":"heapObjectId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("HeapProfiler.getHeapObjectId",[{"name":"objectId","type":"string","optional":false}],["heapSnapshotObjectId"],false);InspectorBackend.registerEvent("Worker.workerCreated",["workerId","url","inspectorConnected"]);InspectorBackend.registerEvent("Worker.workerTerminated",["workerId"]);InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker",["workerId","message"]);InspectorBackend.registerCommand("Worker.enable",[],[],false);InspectorBackend.registerCommand("Worker.disable",[],[],false);InspectorBackend.registerCommand("Worker.sendMessageToWorker",[{"name":"workerId","type":"string","optional":false},{"name":"message","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.connectToWorker",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.disconnectFromWorker",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers",[{"name":"value","type":"boolean","optional":false}],[],false);InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus",{Stopped:"stopped",Starting:"starting",Running:"running",Stopping:"stopping"});InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus",{New:"new",Installing:"installing",Installed:"installed",Activating:"activating",Activated:"activated",Redundant:"redundant"});InspectorBackend.registerEvent("ServiceWorker.workerCreated",["workerId","url","versionId"]);InspectorBackend.registerEvent("ServiceWorker.workerTerminated",["workerId"]);InspectorBackend.registerEvent("ServiceWorker.dispatchMessage",["workerId","message"]);InspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated",["registrations"]);InspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated",["versions"]);InspectorBackend.registerEvent("ServiceWorker.workerErrorReported",["errorMessage"]);InspectorBackend.registerEvent("ServiceWorker.debugOnStartUpdated",["debugOnStart"]);InspectorBackend.registerCommand("ServiceWorker.enable",[],[],false);InspectorBackend.registerCommand("ServiceWorker.disable",[],[],false);InspectorBackend.registerCommand("ServiceWorker.sendMessage",[{"name":"workerId","type":"string","optional":false},{"name":"message","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.stop",[{"name":"workerId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.unregister",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.updateRegistration",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.startWorker",[{"name":"scopeURL","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.stopWorker",[{"name":"versionId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.inspectWorker",[{"name":"versionId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.setDebugOnStart",[{"name":"debugOnStart","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.setForceUpdateOnPageLoad",[{"name":"registrationId","type":"string","optional":false},{"name":"forceUpdateOnPageLoad","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.deliverPushMessage",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"data","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ServiceWorker.getTargetInfo",[{"name":"targetId","type":"string","optional":false}],["targetInfo"],false);InspectorBackend.registerCommand("ServiceWorker.activateTarget",[{"name":"targetId","type":"string","optional":false}],[],false);InspectorBackend.registerEnum("Input.TouchPointState",{TouchPressed:"touchPressed",TouchReleased:"touchReleased",TouchMoved:"touchMoved",TouchStationary:"touchStationary",TouchCancelled:"touchCancelled"});InspectorBackend.registerEnum("Input.GestureSourceType",{Default:"default",Touch:"touch",Mouse:"mouse"});InspectorBackend.registerCommand("Input.dispatchKeyEvent",[{"name":"type","type":"string","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"text","type":"string","optional":true},{"name":"unmodifiedText","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"code","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"windowsVirtualKeyCode","type":"number","optional":true},{"name":"nativeVirtualKeyCode","type":"number","optional":true},{"name":"autoRepeat","type":"boolean","optional":true},{"name":"isKeypad","type":"boolean","optional":true},{"name":"isSystemKey","type":"boolean","optional":true}],[],false);InspectorBackend.registerCommand("Input.dispatchMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"button","type":"string","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.dispatchTouchEvent",[{"name":"type","type":"string","optional":false},{"name":"touchPoints","type":"object","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"timestamp","type":"number","optional":false},{"name":"button","type":"string","optional":false},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true},{"name":"modifiers","type":"number","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizePinchGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"scaleFactor","type":"number","optional":false},{"name":"relativeSpeed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizeScrollGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"xDistance","type":"number","optional":true},{"name":"yDistance","type":"number","optional":true},{"name":"xOverscroll","type":"number","optional":true},{"name":"yOverscroll","type":"number","optional":true},{"name":"preventFling","type":"boolean","optional":true},{"name":"speed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true},{"name":"repeatCount","type":"number","optional":true},{"name":"repeatDelayMs","type":"number","optional":true},{"name":"interactionMarkerName","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Input.synthesizeTapGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"duration","type":"number","optional":true},{"name":"tapCount","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);InspectorBackend.registerEnum("LayerTree.ScrollRectType",{RepaintsOnScroll:"RepaintsOnScroll",TouchEventHandler:"TouchEventHandler",WheelEventHandler:"WheelEventHandler"});InspectorBackend.registerEvent("LayerTree.layerTreeDidChange",["layers"]);InspectorBackend.registerEvent("LayerTree.layerPainted",["layerId","clip"]);InspectorBackend.registerCommand("LayerTree.enable",[],[],false);InspectorBackend.registerCommand("LayerTree.disable",[],[],false);InspectorBackend.registerCommand("LayerTree.compositingReasons",[{"name":"layerId","type":"string","optional":false}],["compositingReasons"],false);InspectorBackend.registerCommand("LayerTree.makeSnapshot",[{"name":"layerId","type":"string","optional":false}],["snapshotId"],false);InspectorBackend.registerCommand("LayerTree.loadSnapshot",[{"name":"tiles","type":"object","optional":false}],["snapshotId"],false);InspectorBackend.registerCommand("LayerTree.releaseSnapshot",[{"name":"snapshotId","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("LayerTree.profileSnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"minRepeatCount","type":"number","optional":true},{"name":"minDuration","type":"number","optional":true},{"name":"clipRect","type":"object","optional":true}],["timings"],false);InspectorBackend.registerCommand("LayerTree.replaySnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"fromStep","type":"number","optional":true},{"name":"toStep","type":"number","optional":true},{"name":"scale","type":"number","optional":true}],["dataURL"],false);InspectorBackend.registerCommand("LayerTree.snapshotCommandLog",[{"name":"snapshotId","type":"string","optional":false}],["commandLog"],false);InspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride",[],[],false);InspectorBackend.registerEnum("ScreenOrientation.OrientationType",{PortraitPrimary:"portraitPrimary",PortraitSecondary:"portraitSecondary",LandscapePrimary:"landscapePrimary",LandscapeSecondary:"landscapeSecondary"});InspectorBackend.registerCommand("ScreenOrientation.setScreenOrientationOverride",[{"name":"angle","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);InspectorBackend.registerCommand("ScreenOrientation.clearScreenOrientationOverride",[],[],false);InspectorBackend.registerEvent("Tracing.dataCollected",["value"]);InspectorBackend.registerEvent("Tracing.tracingComplete",["stream"]);InspectorBackend.registerEvent("Tracing.bufferUsage",["percentFull","eventCount","value"]);InspectorBackend.registerCommand("Tracing.start",[{"name":"categories","type":"string","optional":true},{"name":"options","type":"string","optional":true},{"name":"bufferUsageReportingInterval","type":"number","optional":true},{"name":"transferMode","type":"string","optional":true}],[],false);InspectorBackend.registerCommand("Tracing.end",[],[],false);InspectorBackend.registerCommand("Tracing.getCategories",[],["categories"],false);InspectorBackend.registerCommand("Tracing.requestMemoryDump",[],["dumpGuid","success"],false);InspectorBackend.registerEnum("Animation.AnimationType",{CSSTransition:"CSSTransition",CSSAnimation:"CSSAnimation",WebAnimation:"WebAnimation"});InspectorBackend.registerEvent("Animation.animationCreated",["id"]);InspectorBackend.registerEvent("Animation.animationStarted",["animation"]);InspectorBackend.registerEvent("Animation.animationCanceled",["id"]);InspectorBackend.registerCommand("Animation.enable",[],[],false);InspectorBackend.registerCommand("Animation.disable",[],[],false);InspectorBackend.registerCommand("Animation.getPlaybackRate",[],["playbackRate"],false);InspectorBackend.registerCommand("Animation.setPlaybackRate",[{"name":"playbackRate","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.getCurrentTime",[{"name":"id","type":"string","optional":false}],["currentTime"],false);InspectorBackend.registerCommand("Animation.setPaused",[{"name":"animations","type":"object","optional":false},{"name":"paused","type":"boolean","optional":false}],[],false);InspectorBackend.registerCommand("Animation.setTiming",[{"name":"animationId","type":"string","optional":false},{"name":"duration","type":"number","optional":false},{"name":"delay","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.seekAnimations",[{"name":"animations","type":"object","optional":false},{"name":"currentTime","type":"number","optional":false}],[],false);InspectorBackend.registerCommand("Animation.releaseAnimations",[{"name":"animations","type":"object","optional":false}],[],false);InspectorBackend.registerCommand("Animation.resolveAnimation",[{"name":"animationId","type":"string","optional":false}],["remoteObject"],false);InspectorBackend.registerEnum("Accessibility.AXValueType",{Boolean:"boolean",Tristate:"tristate",BooleanOrUndefined:"booleanOrUndefined",Idref:"idref",IdrefList:"idrefList",Integer:"integer",Node:"node",NodeList:"nodeList",Number:"number",String:"string",ComputedString:"computedString",Token:"token",TokenList:"tokenList",DomRelation:"domRelation",Role:"role",InternalRole:"internalRole",ValueUndefined:"valueUndefined"});InspectorBackend.registerEnum("Accessibility.AXValueSourceType",{Attribute:"attribute",Implicit:"implicit",Style:"style",Contents:"contents",Placeholder:"placeholder",RelatedElement:"relatedElement"});InspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType",{Figcaption:"figcaption",Label:"label",Labelfor:"labelfor",Labelwrapped:"labelwrapped",Legend:"legend",Tablecaption:"tablecaption",Title:"title",Other:"other"});InspectorBackend.registerEnum("Accessibility.AXGlobalStates",{Disabled:"disabled",Hidden:"hidden",HiddenRoot:"hiddenRoot",Invalid:"invalid"});InspectorBackend.registerEnum("Accessibility.AXLiveRegionAttributes",{Live:"live",Atomic:"atomic",Relevant:"relevant",Busy:"busy",Root:"root"});InspectorBackend.registerEnum("Accessibility.AXWidgetAttributes",{Autocomplete:"autocomplete",Haspopup:"haspopup",Level:"level",Multiselectable:"multiselectable",Orientation:"orientation",Multiline:"multiline",Readonly:"readonly",Required:"required",Valuemin:"valuemin",Valuemax:"valuemax",Valuetext:"valuetext"});InspectorBackend.registerEnum("Accessibility.AXWidgetStates",{Checked:"checked",Expanded:"expanded",Pressed:"pressed",Selected:"selected"});InspectorBackend.registerEnum("Accessibility.AXRelationshipAttributes",{Activedescendant:"activedescendant",Flowto:"flowto",Controls:"controls",Describedby:"describedby",Labelledby:"labelledby",Owns:"owns"});InspectorBackend.registerCommand("Accessibility.getAXNode",[{"name":"nodeId","type":"number","optional":false}],["accessibilityNode"],false);;WebInspector.InspectorBackendHostedMode={};WebInspector.InspectorBackendHostedMode.loadFromJSONIfNeeded=function(jsonUrl)
{if(InspectorBackend.isInitialized())
return;var xhr=new XMLHttpRequest();xhr.open("GET",jsonUrl,false);xhr.send(null);var schema=JSON.parse(xhr.responseText);var code=WebInspector.InspectorBackendHostedMode.generateCommands(schema);eval(code);}
WebInspector.InspectorBackendHostedMode.generateCommands=function(schema)
@@ -8829,11 +8829,11 @@
panelIndex=event.keyCode-0x61;if(panelIndex!==-1){var panelName=this._tabbedPane.allTabs()[panelIndex];if(panelName){if(!WebInspector.Dialog.hasInstance()&&!this._currentPanelLocked)
this.showPanel(panelName);event.consume(true);}
return;}}
-if(!WebInspector.isWin()||(!this._openBracketIdentifiers[event.keyIdentifier]&&!this._closeBracketIdentifiers[event.keyIdentifier])){this._keyDownInternal(event);return;}
+if(!WebInspector.isWin()||(!this._openBracketIdentifiers[event.key]&&!this._closeBracketIdentifiers[event.key])){this._keyDownInternal(event);return;}
this._keyDownTimer=setTimeout(this._keyDownInternal.bind(this,event),0);},_keyDownInternal:function(event)
{if(this._currentPanelLocked)
-return;var direction=0;if(this._openBracketIdentifiers[event.keyIdentifier])
-direction=-1;if(this._closeBracketIdentifiers[event.keyIdentifier])
+return;var direction=0;if(this._openBracketIdentifiers[event.key])
+direction=-1;if(this._closeBracketIdentifiers[event.key])
direction=1;if(!direction)
return;if(!event.shiftKey&&!event.altKey){if(!WebInspector.Dialog.hasInstance())
this._changePanelInDirection(direction);event.consume(true);return;}
@@ -9052,7 +9052,7 @@
{var userInput=this._prompt.text();if(userInput===originalContent){this._editingCancelled();return;}
this._editingEnded();this._applyExpression(userInput);},_promptKeyDown:function(originalContent,event)
{if(isEnterKey(event)){event.consume(true);this._editingCommitted(originalContent);return;}
-if(event.keyIdentifier==="U+001B"){event.consume();this._editingCancelled();return;}},_applyExpression:function(expression)
+if(event.key==="U+001B"){event.consume();this._editingCancelled();return;}},_applyExpression:function(expression)
{var property=WebInspector.RemoteObject.toCallArgument(this.property.symbol||this.property.name);expression=expression.trim();if(expression)
this.property.parentObject.setPropertyValue(property,expression,callback.bind(this));else
this.property.parentObject.deleteProperty(property,callback.bind(this));function callback(error)
@@ -9577,8 +9577,8 @@
extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback)
{extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}}
var keyboardEventRequestQueue=[];var forwardTimer=null;function forwardKeyboardEvent(event)
-{const Esc="U+001B";if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.keyIdentifier)&&event.keyIdentifier!==Esc)
-return;var requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,keyIdentifier:event.keyIdentifier,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer)
+{const Esc="U+001B";if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.key)&&event.key!==Esc)
+return;var requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,key:event.key,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer)
forwardTimer=setTimeout(forwardEventQueue,0);}
function forwardEventQueue()
{forwardTimer=null;var request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];}
@@ -9735,10 +9735,10 @@
{var auditRun=(this._clientObjects[message.resultId]);if(!auditRun)
return this._status.E_NOTFOUND(message.resultId);auditRun.done();},_onForwardKeyboardEvent:function(message)
{const Esc="U+001B";message.entries.forEach(handleEventEntry);function handleEventEntry(entry)
-{if(!entry.ctrlKey&&!entry.altKey&&!entry.metaKey&&!/^F\d+$/.test(entry.keyIdentifier)&&entry.keyIdentifier!==Esc)
-return;var event=new window.KeyboardEvent(entry.eventType,{keyIdentifier:entry.keyIdentifier,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);}
+{if(!entry.ctrlKey&&!entry.altKey&&!entry.metaKey&&!/^F\d+$/.test(entry.key)&&entry.key!==Esc)
+return;var event=new window.KeyboardEvent(entry.eventType,{key:entry.key,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);}
function keyCodeForEntry(entry)
-{var keyCode=entry.keyCode;if(!keyCode){var match=entry.keyIdentifier.match(/^U\+([\dA-Fa-f]+)$/);if(match)
+{var keyCode=entry.keyCode;if(!keyCode){var match=entry.key.match(/^U\+([\dA-Fa-f]+)$/);if(match)
keyCode=parseInt(match[1],16);}
return keyCode||0;}},_dispatchCallback:function(requestId,port,result)
{if(requestId)
@@ -10806,8 +10806,8 @@
{if(WebInspector.targetManager.targets().length>=n)
callback.call(null);else
this.addSniffer(WebInspector.TargetManager.prototype,"addTarget",checkTargets.bind(this));}}
-TestSuite.createKeyEvent=function(keyIdentifier)
-{var evt=document.createEvent("KeyboardEvent");evt.initKeyboardEvent("keydown",true,true,null,keyIdentifier,"");return evt;};return new TestSuite();}
+TestSuite.createKeyEvent=function(key)
+{var evt=document.createEvent("KeyboardEvent");evt.initKeyboardEvent("keydown",true,true,null,key,"");return evt;};return new TestSuite();}
if(window.uiTests){WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.InspectorAgentEnabledForTests,window.uiTests.testSuiteReady.bind(null,createTestSuite));};WebInspector.OverlayController=function()
{WebInspector.moduleSetting("disablePausedStateOverlay").addChangeListener(this._updateOverlayMessage,this);WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel,WebInspector.DebuggerModel.Events.DebuggerPaused,this._updateOverlayMessage,this);WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel,WebInspector.DebuggerModel.Events.DebuggerResumed,this._updateOverlayMessage,this);WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel,WebInspector.DebuggerModel.Events.GlobalObjectCleared,this._updateOverlayMessage,this);}
WebInspector.OverlayController.prototype={_updateOverlayMessage:function(event)
diff --git a/src/cobalt/debug/content/devtools/network_module.js b/src/cobalt/debug/content/devtools/network_module.js
index 45c3ed8..563bdd6 100644
--- a/src/cobalt/debug/content/devtools/network_module.js
+++ b/src/cobalt/debug/content/devtools/network_module.js
@@ -11,7 +11,7 @@
onAccept(text);else
this._update();}
function keydown(event)
-{if(isEnterKey(event)){event.consume();commit.call(this);}else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.keyIdentifier==="U+001B"){event.consume();finish.call(this);this._update();}}},_addBlockedURL:function(url)
+{if(isEnterKey(event)){event.consume();commit.call(this);}else if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.key==="U+001B"){event.consume();finish.call(this);this._update();}}},_addBlockedURL:function(url)
{var blocked=this._blockedURLsSetting.get();blocked.push(url);this._blockedURLsSetting.set(blocked);},_removeBlockedURL:function(index)
{var blocked=this._blockedURLsSetting.get();blocked.splice(index,1);this._blockedURLsSetting.set(blocked);},_changeBlockedURL:function(index,url)
{var blocked=this._blockedURLsSetting.get();blocked.splice(index,1,url);this._blockedURLsSetting.set(blocked);},_removeAll:function()
@@ -678,7 +678,7 @@
WebInspector.RequestHeadersView.prototype={_updateFilter:function()
{var text=this._filterInput.value;this._requestHeaderFilterSetting.set(text);this._filterRegex=text?new RegExp(text.escapeForRegExp(),"i"):null;this._updateHeaders();},_onFilterKeyDown:function(event)
{var text=this._filterInput.value;if(!text)
-return;if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.keyIdentifier==="U+001B"){event.consume(true);this._filterInput.value="";this._updateFilter();}},_updateHeaders:function()
+return;if(event.keyCode===WebInspector.KeyboardShortcut.Keys.Esc.code||event.key==="U+001B"){event.consume(true);this._filterInput.value="";this._updateFilter();}},_updateHeaders:function()
{this._refreshRequestHeaders();this._refreshResponseHeaders();},wasShown:function()
{this._request.addEventListener(WebInspector.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.addEventListener(WebInspector.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.addEventListener(WebInspector.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.addEventListener(WebInspector.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);this._refreshURL();this._refreshQueryString();this._updateHeaders();this._refreshHTTPInformation();this._refreshRemoteAddress();},willHide:function()
{this._request.removeEventListener(WebInspector.NetworkRequest.Events.RemoteAddressChanged,this._refreshRemoteAddress,this);this._request.removeEventListener(WebInspector.NetworkRequest.Events.RequestHeadersChanged,this._refreshRequestHeaders,this);this._request.removeEventListener(WebInspector.NetworkRequest.Events.ResponseHeadersChanged,this._refreshResponseHeaders,this);this._request.removeEventListener(WebInspector.NetworkRequest.Events.FinishedLoading,this._refreshHTTPInformation,this);},_formatHeader:function(name,value)
diff --git a/src/cobalt/debug/content/devtools/profiler_module.js b/src/cobalt/debug/content/devtools/profiler_module.js
index 912654d..c234603 100644
--- a/src/cobalt/debug/content/devtools/profiler_module.js
+++ b/src/cobalt/debug/content/devtools/profiler_module.js
@@ -62,8 +62,8 @@
{WebInspector.PanelWithSidebar.call(this,"profiles");this.registerRequiredCSS("ui/panelEnablerView.css");this.registerRequiredCSS("profiler/heapProfiler.css");this.registerRequiredCSS("profiler/profilesPanel.css");this.registerRequiredCSS("components/objectValue.css");var mainContainer=new WebInspector.VBox();this.splitWidget().setMainWidget(mainContainer);this.profilesItemTreeElement=new WebInspector.ProfilesSidebarTreeElement(this);this._sidebarTree=new TreeOutline();this._sidebarTree.element.classList.add("sidebar-tree");this.panelSidebarElement().appendChild(this._sidebarTree.element);this.setDefaultFocusedElement(this._sidebarTree.element);this._sidebarTree.appendChild(this.profilesItemTreeElement);this.profileViews=createElement("div");this.profileViews.id="profile-views";this.profileViews.classList.add("vbox");mainContainer.element.appendChild(this.profileViews);this._toolbarElement=createElementWithClass("div","profiles-toolbar");mainContainer.element.insertBefore(this._toolbarElement,mainContainer.element.firstChild);this.panelSidebarElement().classList.add("profiles-sidebar-tree-box");var toolbarContainerLeft=createElementWithClass("div","profiles-toolbar");this.panelSidebarElement().insertBefore(toolbarContainerLeft,this.panelSidebarElement().firstChild);var toolbar=new WebInspector.Toolbar("",toolbarContainerLeft);this._toggleRecordAction=WebInspector.actionRegistry.action("profiler.toggle-recording");toolbar.appendToolbarItem(WebInspector.Toolbar.createActionButton(this._toggleRecordAction));this.clearResultsButton=new WebInspector.ToolbarButton(WebInspector.UIString("Clear all profiles"),"clear-toolbar-item");this.clearResultsButton.addEventListener("click",this._reset,this);toolbar.appendToolbarItem(this.clearResultsButton);this._profileTypeToolbar=new WebInspector.Toolbar("",this._toolbarElement);this._profileViewToolbar=new WebInspector.Toolbar("",this._toolbarElement);this._profileGroups={};this._launcherView=new WebInspector.MultiProfileLauncherView(this);this._launcherView.addEventListener(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected,this._onProfileTypeSelected,this);this._profileToView=[];this._typeIdToSidebarSection={};var types=WebInspector.ProfileTypeRegistry.instance.profileTypes();for(var i=0;i<types.length;i++)
this._registerProfileType(types[i]);this._launcherView.restoreSelectedProfileType();this.profilesItemTreeElement.select();this._showLauncherView();this._createFileSelectorElement();this.element.addEventListener("contextmenu",this._handleContextMenuEvent.bind(this),true);this.contentElement.addEventListener("keydown",this._onKeyDown.bind(this),false);WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged,this);}
WebInspector.ProfilesPanel.prototype={_onKeyDown:function(event)
-{var handled=false;if(event.keyIdentifier==="Down"&&!event.altKey)
-handled=this._sidebarTree.selectNext();else if(event.keyIdentifier==="Up"&&!event.altKey)
+{var handled=false;if(event.key==="Down"&&!event.altKey)
+handled=this._sidebarTree.selectNext();else if(event.key==="Up"&&!event.altKey)
handled=this._sidebarTree.selectPrevious();if(handled)
event.consume(true);},searchableView:function()
{return this.visibleView&&this.visibleView.searchableView?this.visibleView.searchableView():null;},_createFileSelectorElement:function()
diff --git a/src/cobalt/debug/content/devtools/sources_module.js b/src/cobalt/debug/content/devtools/sources_module.js
index 427b837..dfe1b58 100644
--- a/src/cobalt/debug/content/devtools/sources_module.js
+++ b/src/cobalt/debug/content/devtools/sources_module.js
@@ -156,7 +156,7 @@
{if(!this._statusMessageElement)
this._statusMessageElement=this.element.createChild("div","callstack-info status");if(typeof status==="string"){this._statusMessageElement.textContent=status;}else{this._statusMessageElement.removeChildren();this._statusMessageElement.appendChild(status);}},_keyDown:function(event)
{if(event.altKey||event.shiftKey||event.metaKey||event.ctrlKey)
-return;if(event.keyIdentifier==="Up"&&this._selectPreviousCallFrameOnStack()||event.keyIdentifier==="Down"&&this._selectNextCallFrameOnStack())
+return;if(event.key==="Up"&&this._selectPreviousCallFrameOnStack()||event.key==="Down"&&this._selectNextCallFrameOnStack())
event.consume(true);},__proto__:WebInspector.SidebarPane.prototype}
WebInspector.CallStackSidebarPane.CallFrame=function(callFrame,asyncCallFrame)
{WebInspector.UIList.Item.call(this,WebInspector.beautifyFunctionName(callFrame.functionName),"");WebInspector.debuggerWorkspaceBinding.createCallFrameLiveLocation(callFrame,this._update.bind(this));this._callFrame=callFrame;this._asyncCallFrame=asyncCallFrame;}
@@ -549,7 +549,7 @@
this.textEditor.removeHighlight(this._popoverAnchorBox._highlightDescriptor);delete this._popoverAnchorBox;},_addBreakpointDecoration:function(lineNumber,columnNumber,condition,enabled,mutedWhileEditing)
{var breakpoint={condition:condition,enabled:enabled,columnNumber:columnNumber};this.textEditor.setAttribute(lineNumber,"breakpoint",breakpoint);var disabled=!enabled||mutedWhileEditing;this.textEditor.addBreakpoint(lineNumber,disabled,!!condition);},_removeBreakpointDecoration:function(lineNumber)
{this.textEditor.removeAttribute(lineNumber,"breakpoint");this.textEditor.removeBreakpoint(lineNumber);},_onKeyDown:function(event)
-{if(event.keyIdentifier==="U+001B"){if(this._popoverHelper.isPopoverVisible()){this._popoverHelper.hidePopover();event.consume();}}},_editBreakpointCondition:function(lineNumber,breakpoint)
+{if(event.key==="U+001B"){if(this._popoverHelper.isPopoverVisible()){this._popoverHelper.hidePopover();event.consume();}}},_editBreakpointCondition:function(lineNumber,breakpoint)
{this._conditionElement=this._createConditionElement(lineNumber);this.textEditor.addDecoration(lineNumber,this._conditionElement);function finishEditing(committed,element,newText)
{this.textEditor.removeDecoration(lineNumber,this._conditionElement);delete this._conditionEditorElement;delete this._conditionElement;if(!committed)
return;if(breakpoint)
diff --git a/src/cobalt/debug/content/devtools/toolbox.js b/src/cobalt/debug/content/devtools/toolbox.js
index 4a470cb..33deec8 100644
--- a/src/cobalt/debug/content/devtools/toolbox.js
+++ b/src/cobalt/debug/content/devtools/toolbox.js
@@ -683,7 +683,7 @@
{var node=this.elementFromPoint(x,y);while(node&&node.shadowRoot)
node=node.shadowRoot.elementFromPoint(x,y);return node;}
function isEnterKey(event)
-{return event.keyCode!==229&&event.keyIdentifier==="Enter";}
+{return event.keyCode!==229&&event.key==="Enter";}
function isEscKey(event)
{return event.keyCode===27;}
function consumeEvent(e)
diff --git a/src/cobalt/debug/content/devtools/ui_lazy_module.js b/src/cobalt/debug/content/devtools/ui_lazy_module.js
index a980922..9c76e80 100644
--- a/src/cobalt/debug/content/devtools/ui_lazy_module.js
+++ b/src/cobalt/debug/content/devtools/ui_lazy_module.js
@@ -111,12 +111,12 @@
this.creationNode.makeNormal();var emptyData={};for(var column in this._columns)
emptyData[column]=null;this.creationNode=new WebInspector.CreationDataGridNode(emptyData,hasChildren);this.rootNode().appendChild(this.creationNode);},_keyDown:function(event)
{if(!this.selectedNode||event.shiftKey||event.metaKey||event.ctrlKey||this._editing)
-return;var handled=false;var nextSelectedNode;if(event.keyIdentifier==="Up"&&!event.altKey){nextSelectedNode=this.selectedNode.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
-nextSelectedNode=nextSelectedNode.traversePreviousNode(true);handled=nextSelectedNode?true:false;}else if(event.keyIdentifier==="Down"&&!event.altKey){nextSelectedNode=this.selectedNode.traverseNextNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
-nextSelectedNode=nextSelectedNode.traverseNextNode(true);handled=nextSelectedNode?true:false;}else if(event.keyIdentifier==="Left"){if(this.selectedNode.expanded){if(event.altKey)
+return;var handled=false;var nextSelectedNode;if(event.key==="Up"&&!event.altKey){nextSelectedNode=this.selectedNode.traversePreviousNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
+nextSelectedNode=nextSelectedNode.traversePreviousNode(true);handled=nextSelectedNode?true:false;}else if(event.key==="Down"&&!event.altKey){nextSelectedNode=this.selectedNode.traverseNextNode(true);while(nextSelectedNode&&!nextSelectedNode.selectable)
+nextSelectedNode=nextSelectedNode.traverseNextNode(true);handled=nextSelectedNode?true:false;}else if(event.key==="Left"){if(this.selectedNode.expanded){if(event.altKey)
this.selectedNode.collapseRecursively();else
this.selectedNode.collapse();handled=true;}else if(this.selectedNode.parent&&!this.selectedNode.parent._isRoot){handled=true;if(this.selectedNode.parent.selectable){nextSelectedNode=this.selectedNode.parent;handled=nextSelectedNode?true:false;}else if(this.selectedNode.parent)
-this.selectedNode.parent.collapse();}}else if(event.keyIdentifier==="Right"){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];handled=nextSelectedNode?true:false;}else{if(event.altKey)
+this.selectedNode.parent.collapse();}}else if(event.key==="Right"){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];handled=nextSelectedNode?true:false;}else{if(event.altKey)
this.selectedNode.expandRecursively();else
this.selectedNode.expand();}}}else if(event.keyCode===8||event.keyCode===46){if(this._deleteCallback){handled=true;this._deleteCallback(this.selectedNode);}}else if(isEnterKey(event)){if(this._editCallback){handled=true;this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]);}}
if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();}
diff --git a/src/cobalt/debug/debug_script_runner.cc b/src/cobalt/debug/debug_script_runner.cc
index 36a44ca..833d5ca 100644
--- a/src/cobalt/debug/debug_script_runner.cc
+++ b/src/cobalt/debug/debug_script_runner.cc
@@ -82,8 +82,8 @@
script::SourceCode::CreateSourceCode(js_code, GetInlineSourceLocation());
ForceEnableEval();
- bool succeeded = global_environment_->EvaluateScript(source_code, result,
- false /*mute_errors*/);
+ bool succeeded = global_environment_->EvaluateScript(
+ source_code, false /*mute_errors*/, result);
SetEvalAllowedFromCsp();
return succeeded;
}
diff --git a/src/cobalt/dom/csp_delegate.cc b/src/cobalt/dom/csp_delegate.cc
index 0bcf6f0..b9afec6 100644
--- a/src/cobalt/dom/csp_delegate.cc
+++ b/src/cobalt/dom/csp_delegate.cc
@@ -25,9 +25,8 @@
CspDelegateSecure::CspDelegateSecure(
scoped_ptr<CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback) {
- location_policy_ = location_policy;
require_csp_ = require_csp;
was_header_received_ = false;
policy_changed_callback_ = policy_changed_callback;
@@ -39,7 +38,6 @@
base::Unretained(reporter_.get()));
}
csp_.reset(new csp::ContentSecurityPolicy(url, violation_callback));
- SetLocationPolicy(location_policy_);
}
CspDelegateSecure::~CspDelegateSecure() {}
@@ -177,18 +175,5 @@
}
}
-void CspDelegateSecure::SetLocationPolicy(const std::string& policy) {
- if (!policy.length()) {
- return;
- }
-
- if (policy.find(csp::ContentSecurityPolicy::kLocationSrc) ==
- std::string::npos) {
- LOG(FATAL) << csp::ContentSecurityPolicy::kLocationSrc << " not found in "
- << policy;
- }
- csp_->SetNavigationPolicy(policy);
-}
-
} // namespace dom
} // namespace cobalt
diff --git a/src/cobalt/dom/csp_delegate.h b/src/cobalt/dom/csp_delegate.h
index 17a797c..af05789 100644
--- a/src/cobalt/dom/csp_delegate.h
+++ b/src/cobalt/dom/csp_delegate.h
@@ -104,8 +104,7 @@
class CspDelegateSecure : public CspDelegate {
public:
CspDelegateSecure(scoped_ptr<CspViolationReporter> violation_reporter,
- const GURL& url, const std::string& location_policy,
- csp::CSPHeaderPolicy require_csp,
+ const GURL& url, csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback);
~CspDelegateSecure();
@@ -142,9 +141,6 @@
scoped_ptr<csp::ContentSecurityPolicy> csp_;
- // Hardcoded policy to restrict navigation.
- std::string location_policy_;
-
// Helper class to send violation events to any reporting endpoints.
scoped_ptr<CspViolationReporter> reporter_;
diff --git a/src/cobalt/dom/csp_delegate_factory.cc b/src/cobalt/dom/csp_delegate_factory.cc
index e20c061..83c7f19 100644
--- a/src/cobalt/dom/csp_delegate_factory.cc
+++ b/src/cobalt/dom/csp_delegate_factory.cc
@@ -45,8 +45,7 @@
CspDelegate* CreateInsecureDelegate(
scoped_ptr<CspViolationReporter> /*violation_reporter*/,
- const GURL& /*url*/, const std::string& /*location_policy*/,
- csp::CSPHeaderPolicy /*requre_csp*/,
+ const GURL& /*url*/, csp::CSPHeaderPolicy /*requre_csp*/,
const base::Closure& /*policy_changed_callback*/,
int insecure_allowed_token) {
if (InsecureAllowed(insecure_allowed_token)) {
@@ -59,11 +58,11 @@
CspDelegate* CreateSecureDelegate(
scoped_ptr<CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback,
int /*insecure_allowed_token*/) {
- return new CspDelegateSecure(violation_reporter.Pass(), url, location_policy,
- require_csp, policy_changed_callback);
+ return new CspDelegateSecure(violation_reporter.Pass(), url, require_csp,
+ policy_changed_callback);
}
} // namespace
@@ -87,11 +86,11 @@
scoped_ptr<CspDelegate> CspDelegateFactory::Create(
CspEnforcementType type,
scoped_ptr<CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback, int insecure_allowed_token) {
- scoped_ptr<CspDelegate> delegate(method_[type](
- violation_reporter.Pass(), url, location_policy, require_csp,
- policy_changed_callback, insecure_allowed_token));
+ scoped_ptr<CspDelegate> delegate(
+ method_[type](violation_reporter.Pass(), url, require_csp,
+ policy_changed_callback, insecure_allowed_token));
return delegate.Pass();
}
diff --git a/src/cobalt/dom/csp_delegate_factory.h b/src/cobalt/dom/csp_delegate_factory.h
index c732d37..c3d8953 100644
--- a/src/cobalt/dom/csp_delegate_factory.h
+++ b/src/cobalt/dom/csp_delegate_factory.h
@@ -44,13 +44,14 @@
scoped_ptr<CspDelegate> Create(
CspEnforcementType type,
scoped_ptr<CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback,
int insecure_allowed_token = 0);
typedef CspDelegate* (*CspDelegateCreator)(
- scoped_ptr<CspViolationReporter> violation_reporter, const GURL&,
- const std::string&, csp::CSPHeaderPolicy, const base::Closure&, int);
+ scoped_ptr<CspViolationReporter> violation_reporter, const GURL& url,
+ csp::CSPHeaderPolicy require_csp,
+ const base::Closure& policy_chagned_callback, int insecure_allowed_token);
#if !defined(COBALT_FORCE_CSP)
// Allow tests to have the factory create a different delegate type.
diff --git a/src/cobalt/dom/csp_delegate_test.cc b/src/cobalt/dom/csp_delegate_test.cc
index f1df142..1eb815a 100644
--- a/src/cobalt/dom/csp_delegate_test.cc
+++ b/src/cobalt/dom/csp_delegate_test.cc
@@ -107,9 +107,8 @@
mock_reporter_ = new StrictMock<MockViolationReporter>();
scoped_ptr<CspViolationReporter> reporter(mock_reporter_);
- csp_delegate_.reset(
- new CspDelegateSecure(reporter.Pass(), origin, default_navigation_policy,
- csp::kCSPRequired, base::Closure()));
+ csp_delegate_.reset(new CspDelegateSecure(
+ reporter.Pass(), origin, csp::kCSPRequired, base::Closure()));
std::string policy =
base::StringPrintf("default-src none; %s 'self'", GetParam().directive);
csp_delegate_->OnReceiveHeader(policy, csp::kHeaderTypeEnforce,
@@ -139,7 +138,7 @@
TEST(CspDelegateFactoryTest, Secure) {
scoped_ptr<CspDelegate> delegate = CspDelegateFactory::GetInstance()->Create(
kCspEnforcementEnable, scoped_ptr<CspViolationReporter>(), GURL(),
- std::string(), csp::kCSPRequired, base::Closure());
+ csp::kCSPRequired, base::Closure());
EXPECT_TRUE(delegate != NULL);
}
@@ -152,7 +151,7 @@
scoped_ptr<CspDelegate> delegate =
CspDelegateFactory::GetInstance()->Create(
kCspEnforcementDisable, scoped_ptr<CspViolationReporter>(), GURL(),
- std::string(), csp::kCSPRequired, base::Closure());
+ csp::kCSPRequired, base::Closure());
scoped_ptr<CspDelegate> empty_delegate;
EXPECT_EQ(empty_delegate, delegate.get());
@@ -166,7 +165,7 @@
int token = CspDelegateFactory::GetInstance()->GetInsecureAllowedToken();
scoped_ptr<CspDelegate> delegate = CspDelegateFactory::GetInstance()->Create(
kCspEnforcementDisable, scoped_ptr<CspViolationReporter>(), GURL(),
- std::string(), csp::kCSPRequired, base::Closure(), token);
+ csp::kCSPRequired, base::Closure(), token);
EXPECT_TRUE(delegate != NULL);
}
diff --git a/src/cobalt/dom/custom_event_test.cc b/src/cobalt/dom/custom_event_test.cc
index 6712aff..3f87356 100644
--- a/src/cobalt/dom/custom_event_test.cc
+++ b/src/cobalt/dom/custom_event_test.cc
@@ -26,7 +26,6 @@
#include "cobalt/dom/window.h"
#include "cobalt/dom_parser/parser.h"
#include "cobalt/loader/fetcher_factory.h"
-#include "cobalt/media/media_module_stub.h"
#include "cobalt/media_session/media_session.h"
#include "cobalt/network/network_module.h"
#include "cobalt/script/global_environment.h"
@@ -59,18 +58,15 @@
dom_parser_(new dom_parser::Parser(mock_error_callback_)),
fetcher_factory_(new loader::FetcherFactory(&network_module_)),
local_storage_database_(NULL),
- stub_media_module_(new media::MediaModuleStub()),
url_("about:blank"),
window_(new Window(
1920, 1080, 1.f, base::kApplicationStateStarted, css_parser_.get(),
dom_parser_.get(), fetcher_factory_.get(), NULL, NULL, NULL, NULL,
- NULL, NULL, &local_storage_database_, stub_media_module_.get(),
- stub_media_module_.get(), NULL, NULL, NULL, NULL, NULL, url_, "",
- "en-US", base::Callback<void(const GURL&)>(),
+ NULL, NULL, &local_storage_database_, NULL, NULL, NULL, NULL, NULL,
+ NULL, NULL, url_, "", "en-US", base::Callback<void(const GURL&)>(),
base::Bind(&MockErrorCallback::Run,
base::Unretained(&mock_error_callback_)),
- NULL, network_bridge::PostSender(),
- std::string() /* default security policy */, csp::kCSPRequired,
+ NULL, network_bridge::PostSender(), csp::kCSPRequired,
kCspEnforcementEnable, base::Closure() /* csp_policy_changed */,
base::Closure() /* ran_animation_frame_callbacks */,
dom::Window::CloseCallback() /* window_close */,
@@ -95,7 +91,6 @@
network::NetworkModule network_module_;
scoped_ptr<loader::FetcherFactory> fetcher_factory_;
dom::LocalStorageDatabase local_storage_database_;
- scoped_ptr<media::MediaModule> stub_media_module_;
GURL url_;
const scoped_refptr<Window> window_;
};
@@ -110,8 +105,8 @@
global_environment_->EnableEval();
global_environment_->SetReportEvalCallback(base::Closure());
- bool succeeded = global_environment_->EvaluateScript(source_code, result,
- false /*mute_errors*/);
+ bool succeeded = global_environment_->EvaluateScript(
+ source_code, false /*mute_errors*/, result);
return succeeded;
}
} // namespace
diff --git a/src/cobalt/dom/document.cc b/src/cobalt/dom/document.cc
index 3249b8c..dd57f18 100644
--- a/src/cobalt/dom/document.cc
+++ b/src/cobalt/dom/document.cc
@@ -107,7 +107,7 @@
csp_delegate_ =
CspDelegateFactory::GetInstance()
->Create(options.csp_enforcement_mode, violation_reporter.Pass(),
- options.url, options.location_policy, options.require_csp,
+ options.url, options.require_csp,
options.csp_policy_changed_callback,
options.csp_insecure_allowed_token)
.Pass();
@@ -123,7 +123,7 @@
html_element_context_->resource_provider(),
html_element_context_->remote_typeface_cache(),
base::Bind(&Document::OnTypefaceLoadEvent, base::Unretained(this)),
- html_element_context_->language()));
+ html_element_context_->language(), location_));
if (HasBrowsingContext()) {
if (html_element_context_->remote_typeface_cache()) {
diff --git a/src/cobalt/dom/document.h b/src/cobalt/dom/document.h
index 52a5d30..d9097bf 100644
--- a/src/cobalt/dom/document.h
+++ b/src/cobalt/dom/document.h
@@ -110,7 +110,6 @@
const base::optional<math::Size>& viewport_size,
network_bridge::CookieJar* cookie_jar,
const network_bridge::PostSender& post_sender,
- const std::string& location_policy,
csp::CSPHeaderPolicy require_csp,
CspEnforcementType csp_enforcement_mode,
const base::Closure& csp_policy_changed_callback,
@@ -124,7 +123,6 @@
viewport_size(viewport_size),
cookie_jar(cookie_jar),
post_sender(post_sender),
- location_policy(location_policy),
require_csp(require_csp),
csp_enforcement_mode(csp_enforcement_mode),
csp_policy_changed_callback(csp_policy_changed_callback),
@@ -140,7 +138,6 @@
base::optional<math::Size> viewport_size;
network_bridge::CookieJar* cookie_jar;
network_bridge::PostSender post_sender;
- std::string location_policy;
csp::CSPHeaderPolicy require_csp;
CspEnforcementType csp_enforcement_mode;
base::Closure csp_policy_changed_callback;
diff --git a/src/cobalt/dom/dom_exception.cc b/src/cobalt/dom/dom_exception.cc
index e299285..a1ec7fb 100644
--- a/src/cobalt/dom/dom_exception.cc
+++ b/src/cobalt/dom/dom_exception.cc
@@ -25,7 +25,9 @@
return "";
case DOMException::kIndexSizeErr:
return "IndexSizeError";
- case DOMException::kNoModificationAllowedError:
+ case DOMException::kInvalidCharacterErr:
+ return "InvalidCharacterError";
+ case DOMException::kNoModificationAllowedErr:
return "NoModificationAllowedError";
case DOMException::kNotFoundErr:
return "NotFoundError";
diff --git a/src/cobalt/dom/dom_exception.h b/src/cobalt/dom/dom_exception.h
index ad45aca..a4d283c 100644
--- a/src/cobalt/dom/dom_exception.h
+++ b/src/cobalt/dom/dom_exception.h
@@ -32,7 +32,8 @@
// If the error name does not have a corresponding code, set the code to 0.
kNone = 0,
kIndexSizeErr = 1,
- kNoModificationAllowedError = 7,
+ kInvalidCharacterErr = 5,
+ kNoModificationAllowedErr = 7,
kNotFoundErr = 8,
kNotSupportedErr = 9,
kInvalidStateErr = 11,
diff --git a/src/cobalt/dom/dom_settings.cc b/src/cobalt/dom/dom_settings.cc
index fab84d0..7558525 100644
--- a/src/cobalt/dom/dom_settings.cc
+++ b/src/cobalt/dom/dom_settings.cc
@@ -23,8 +23,7 @@
DOMSettings::DOMSettings(
const int max_dom_element_depth, loader::FetcherFactory* fetcher_factory,
- network::NetworkModule* network_module, media::MediaModule* media_module,
- const scoped_refptr<Window>& window,
+ network::NetworkModule* network_module, const scoped_refptr<Window>& window,
MediaSourceRegistry* media_source_registry, Blob::Registry* blob_registry,
media::CanPlayTypeHandler* can_play_type_handler,
script::JavaScriptEngine* engine,
@@ -35,7 +34,6 @@
microphone_options_(options.microphone_options),
fetcher_factory_(fetcher_factory),
network_module_(network_module),
- media_module_(media_module),
window_(window),
array_buffer_allocator_(options.array_buffer_allocator),
array_buffer_cache_(options.array_buffer_cache),
diff --git a/src/cobalt/dom/dom_settings.h b/src/cobalt/dom/dom_settings.h
index 6d9d65e..689987f 100644
--- a/src/cobalt/dom/dom_settings.h
+++ b/src/cobalt/dom/dom_settings.h
@@ -23,7 +23,6 @@
#include "cobalt/dom/url_registry.h"
#include "cobalt/dom/url_utils.h"
#include "cobalt/media/can_play_type_handler.h"
-#include "cobalt/media/media_module.h"
#include "cobalt/script/environment_settings.h"
#include "cobalt/speech/microphone.h"
@@ -68,7 +67,6 @@
DOMSettings(const int max_dom_element_depth,
loader::FetcherFactory* fetcher_factory,
network::NetworkModule* network_module,
- media::MediaModule* media_module,
const scoped_refptr<Window>& window,
MediaSourceRegistry* media_source_registry,
Blob::Registry* blob_registry,
@@ -101,10 +99,6 @@
network_module_ = network_module;
}
network::NetworkModule* network_module() const { return network_module_; }
- media::MediaModule* media_module() const { return media_module_; }
- void set_media_module(media::MediaModule* media_module) {
- media_module_ = media_module;
- }
script::JavaScriptEngine* javascript_engine() const {
return javascript_engine_;
}
@@ -117,10 +111,6 @@
media::CanPlayTypeHandler* can_play_type_handler() const {
return can_play_type_handler_;
}
- void set_can_play_type_handler(
- media::CanPlayTypeHandler* can_play_type_handler) {
- can_play_type_handler_ = can_play_type_handler;
- }
MutationObserverTaskManager* mutation_observer_task_manager() const {
return mutation_observer_task_manager_;
}
@@ -137,7 +127,6 @@
const speech::Microphone::Options microphone_options_;
loader::FetcherFactory* fetcher_factory_;
network::NetworkModule* network_module_;
- media::MediaModule* media_module_;
scoped_refptr<Window> window_;
ArrayBuffer::Allocator* array_buffer_allocator_;
ArrayBuffer::Cache* array_buffer_cache_;
diff --git a/src/cobalt/dom/error_event_test.cc b/src/cobalt/dom/error_event_test.cc
index 7995e45..8134972 100644
--- a/src/cobalt/dom/error_event_test.cc
+++ b/src/cobalt/dom/error_event_test.cc
@@ -26,7 +26,6 @@
#include "cobalt/dom/window.h"
#include "cobalt/dom_parser/parser.h"
#include "cobalt/loader/fetcher_factory.h"
-#include "cobalt/media/media_module_stub.h"
#include "cobalt/media_session/media_session.h"
#include "cobalt/network/network_module.h"
#include "cobalt/script/global_environment.h"
@@ -59,18 +58,15 @@
dom_parser_(new dom_parser::Parser(mock_error_callback_)),
fetcher_factory_(new loader::FetcherFactory(&network_module_)),
local_storage_database_(NULL),
- stub_media_module_(new media::MediaModuleStub()),
url_("about:blank"),
window_(new Window(
1920, 1080, 1.f, base::kApplicationStateStarted, css_parser_.get(),
dom_parser_.get(), fetcher_factory_.get(), NULL, NULL, NULL, NULL,
- NULL, NULL, &local_storage_database_, stub_media_module_.get(),
- stub_media_module_.get(), NULL, NULL, NULL, NULL, NULL, url_, "",
- "en-US", base::Callback<void(const GURL&)>(),
+ NULL, NULL, &local_storage_database_, NULL, NULL, NULL, NULL, NULL,
+ NULL, NULL, url_, "", "en-US", base::Callback<void(const GURL&)>(),
base::Bind(&MockErrorCallback::Run,
base::Unretained(&mock_error_callback_)),
- NULL, network_bridge::PostSender(),
- std::string() /* default security policy */, csp::kCSPRequired,
+ NULL, network_bridge::PostSender(), csp::kCSPRequired,
kCspEnforcementEnable, base::Closure() /* csp_policy_changed */,
base::Closure() /* ran_animation_frame_callbacks */,
dom::Window::CloseCallback() /* window_close */,
@@ -95,7 +91,6 @@
network::NetworkModule network_module_;
scoped_ptr<loader::FetcherFactory> fetcher_factory_;
dom::LocalStorageDatabase local_storage_database_;
- scoped_ptr<media::MediaModule> stub_media_module_;
GURL url_;
const scoped_refptr<Window> window_;
};
@@ -110,8 +105,8 @@
global_environment_->EnableEval();
global_environment_->SetReportEvalCallback(base::Closure());
- bool succeeded = global_environment_->EvaluateScript(source_code, result,
- false /*mute_errors*/);
+ bool succeeded = global_environment_->EvaluateScript(
+ source_code, false /*mute_errors*/, result);
return succeeded;
}
} // namespace
diff --git a/src/cobalt/dom/event.h b/src/cobalt/dom/event.h
index 62c00ac..99c125b 100644
--- a/src/cobalt/dom/event.h
+++ b/src/cobalt/dom/event.h
@@ -40,7 +40,13 @@
// Web API: Event
// EventPhase values as defined by Web API Event.eventPhase.
//
- enum EventPhase { kNone, kCapturingPhase, kAtTarget, kBubblingPhase };
+ typedef uint16 EventPhase;
+ enum EventPhaseInternal : uint16 {
+ kNone,
+ kCapturingPhase,
+ kAtTarget,
+ kBubblingPhase
+ };
// Custom, not in any spec.
//
diff --git a/src/cobalt/dom/font_cache.cc b/src/cobalt/dom/font_cache.cc
index 4fff414..4709e95 100644
--- a/src/cobalt/dom/font_cache.cc
+++ b/src/cobalt/dom/font_cache.cc
@@ -43,14 +43,16 @@
FontCache::FontCache(render_tree::ResourceProvider** resource_provider,
loader::font::RemoteTypefaceCache* remote_typeface_cache,
const base::Closure& external_typeface_load_event_callback,
- const std::string& language)
+ const std::string& language,
+ scoped_refptr<Location> document_location)
: resource_provider_(resource_provider),
remote_typeface_cache_(remote_typeface_cache),
external_typeface_load_event_callback_(
external_typeface_load_event_callback),
language_(language),
font_face_map_(new FontFaceMap()),
- last_inactive_process_time_(base::TimeTicks::Now()) {}
+ last_inactive_process_time_(base::TimeTicks::Now()),
+ document_location_(document_location) {}
void FontCache::SetFontFaceMap(scoped_ptr<FontFaceMap> font_face_map) {
DCHECK(thread_checker_.CalledOnValidThread());
@@ -308,7 +310,9 @@
// Retrieve the font from the remote typeface cache, potentially triggering a
// load.
scoped_refptr<loader::font::CachedRemoteTypeface> cached_remote_typeface =
- remote_typeface_cache_->CreateCachedResource(url);
+ remote_typeface_cache_->CreateCachedResource(
+ url, document_location_ ? document_location_->OriginObject()
+ : loader::Origin());
RequestedRemoteTypefaceMap::iterator requested_remote_typeface_iterator =
requested_remote_typeface_cache_.find(url);
diff --git a/src/cobalt/dom/font_cache.h b/src/cobalt/dom/font_cache.h
index e90adf9..048e50b 100644
--- a/src/cobalt/dom/font_cache.h
+++ b/src/cobalt/dom/font_cache.h
@@ -27,6 +27,7 @@
#include "base/timer.h"
#include "cobalt/dom/font_face.h"
#include "cobalt/dom/font_list.h"
+#include "cobalt/dom/location.h"
#include "cobalt/loader/font/remote_typeface_cache.h"
#include "cobalt/render_tree/font.h"
#include "cobalt/render_tree/glyph.h"
@@ -173,7 +174,8 @@
FontCache(render_tree::ResourceProvider** resource_provider,
loader::font::RemoteTypefaceCache* remote_typeface_cache,
const base::Closure& external_typeface_load_event_callback,
- const std::string& language);
+ const std::string& language,
+ scoped_refptr<Location> document_location);
// Set a new font face map. If it matches the old font face map then nothing
// is done. Otherwise, it is updated with the new value and the remote
@@ -324,6 +326,10 @@
// Thread checker used to verify safe thread usage of the font cache.
base::ThreadChecker thread_checker_;
+
+ // Font cache's corresponding document's location object. It can provide
+ // document's origin.
+ scoped_refptr<Location> document_location_;
};
} // namespace dom
diff --git a/src/cobalt/dom/font_cache_test.cc b/src/cobalt/dom/font_cache_test.cc
index 0f1f1dd..3e0cd89 100644
--- a/src/cobalt/dom/font_cache_test.cc
+++ b/src/cobalt/dom/font_cache_test.cc
@@ -87,7 +87,7 @@
ALLOW_THIS_IN_INITIALIZER_LIST(base::Bind(
&FontCacheTest::DummyOnTypefaceLoadEvent,
base::Unretained(this))),
- "en-US")) {}
+ "en-US", NULL)) {}
TEST_F(FontCacheTest, FindPostscriptFont) {
const std::string family_name("Dancing Script");
diff --git a/src/cobalt/dom/html_element.cc b/src/cobalt/dom/html_element.cc
index 4bb3606..e82e801 100644
--- a/src/cobalt/dom/html_element.cc
+++ b/src/cobalt/dom/html_element.cc
@@ -1408,7 +1408,7 @@
scoped_refptr<loader::image::CachedImage> cached_image =
html_element_context()->image_cache()->CreateCachedResource(
- absolute_url);
+ absolute_url, loader::Origin());
base::Closure loaded_callback = base::Bind(
&HTMLElement::OnBackgroundImageLoaded, base::Unretained(this));
cached_images.push_back(
diff --git a/src/cobalt/dom/html_element_context.h b/src/cobalt/dom/html_element_context.h
index d7054db..7847423 100644
--- a/src/cobalt/dom/html_element_context.h
+++ b/src/cobalt/dom/html_element_context.h
@@ -77,10 +77,6 @@
media::CanPlayTypeHandler* can_play_type_handler() {
return can_play_type_handler_;
}
- void set_can_play_type_handler(
- media::CanPlayTypeHandler* can_play_type_handler) {
- can_play_type_handler_ = can_play_type_handler;
- }
media::WebMediaPlayerFactory* web_media_player_factory() {
return web_media_player_factory_;
}
diff --git a/src/cobalt/dom/html_image_element.cc b/src/cobalt/dom/html_image_element.cc
index 4d8dfce..ffd4b5a 100644
--- a/src/cobalt/dom/html_image_element.cc
+++ b/src/cobalt/dom/html_image_element.cc
@@ -112,10 +112,11 @@
// the img element to the completely available state, update the
// presentation of the image appropriately, queue a task to fire a simple
// event named load at the img element, and abort these steps.
- cached_image = node_document()
- ->html_element_context()
- ->image_cache()
- ->CreateCachedResource(selected_source);
+ cached_image =
+ node_document()
+ ->html_element_context()
+ ->image_cache()
+ ->CreateCachedResource(selected_source, loader::Origin());
if (cached_image->TryGetResource()) {
PreventGarbageCollectionUntilEventIsDispatched(base::Tokens::load());
return;
diff --git a/src/cobalt/dom/html_link_element.cc b/src/cobalt/dom/html_link_element.cc
index e18a057..90f006c 100644
--- a/src/cobalt/dom/html_link_element.cc
+++ b/src/cobalt/dom/html_link_element.cc
@@ -140,7 +140,7 @@
base::Bind(
&loader::FetcherFactory::CreateSecureFetcher,
base::Unretained(document->html_element_context()->fetcher_factory()),
- absolute_url_, csp_callback),
+ absolute_url_, csp_callback, loader::kNoCORSMode, loader::Origin()),
scoped_ptr<loader::Decoder>(new loader::TextDecoder(
base::Bind(&HTMLLinkElement::OnLoadingDone, base::Unretained(this)))),
base::Bind(&HTMLLinkElement::OnLoadingError, base::Unretained(this))));
diff --git a/src/cobalt/dom/html_media_element.cc b/src/cobalt/dom/html_media_element.cc
index 429e3e3..9ee8083 100644
--- a/src/cobalt/dom/html_media_element.cc
+++ b/src/cobalt/dom/html_media_element.cc
@@ -207,11 +207,7 @@
std::string HTMLMediaElement::CanPlayType(const std::string& mime_type,
const std::string& key_system) {
- if (!html_element_context()->can_play_type_handler()) {
- DLOG(ERROR) << __FUNCTION__ << "(" << mime_type << ", " << key_system
- << "): Media playback in PRELOADING is not supported.";
- return "";
- }
+ DCHECK(html_element_context()->can_play_type_handler());
#if defined(COBALT_MEDIA_SOURCE_2016)
DLOG_IF(ERROR, !key_system.empty())
@@ -953,6 +949,10 @@
if (url.is_empty()) {
return;
}
+#if SB_HAS(PLAYER_WITH_URL)
+ // TODO: Investigate if we have to support csp for url player.
+ player_->LoadUrl(url);
+#else // SB_HAS(PLAYER_WITH_URL)
if (url.spec() == SourceURL()) {
player_->LoadMediaSource();
} else {
@@ -966,6 +966,7 @@
player_->LoadProgressive(url, data_source.Pass(),
WebMediaPlayer::kCORSModeUnspecified);
}
+#endif // SB_HAS(PLAYER_WITH_URL)
}
void HTMLMediaElement::ClearMediaPlayer() {
@@ -1125,6 +1126,8 @@
}
void HTMLMediaElement::ScheduleOwnEvent(base::Token event_name) {
+ LOG_IF(INFO, event_name == base::Tokens::error())
+ << "onerror event fired with error " << (error_ ? error_->code() : 0);
MLOG() << event_name;
scoped_refptr<Event> event =
new Event(event_name, Event::kNotBubbles, Event::kCancelable);
@@ -1528,7 +1531,7 @@
EndProcessingMediaPlayerCallback();
}
-void HTMLMediaElement::TimeChanged() {
+void HTMLMediaElement::TimeChanged(bool eos_played) {
DCHECK(player_);
if (!player_) {
return;
@@ -1554,8 +1557,9 @@
// When the current playback position reaches the end of the media resource
// when the direction of playback is forwards, then the user agent must follow
// these steps:
- if (!SbDoubleIsNan(dur) && (0.0f != dur) && now >= dur &&
- playback_rate_ > 0) {
+ eos_played |=
+ !SbDoubleIsNan(dur) && (0.0f != dur) && now >= dur && playback_rate_ > 0;
+ if (eos_played) {
// If the media element has a loop attribute specified and does not have a
// current media controller,
if (loop()) {
@@ -1689,12 +1693,14 @@
// https://www.w3.org/TR/eme-initdata-registry/#registry.
std::string ToInitDataTypeString(media::EmeInitDataType init_data_type) {
switch (init_data_type) {
- case media::kEmeInitDataTypeWebM:
- return "webm";
case media::kEmeInitDataTypeCenc:
return "cenc";
+ case media::kEmeInitDataTypeFairplay:
+ return "fairplay";
case media::kEmeInitDataTypeKeyIds:
return "keyids";
+ case media::kEmeInitDataTypeWebM:
+ return "webm";
default:
LOG(WARNING) << "Unknown EME initialization data type.";
return "";
diff --git a/src/cobalt/dom/html_media_element.h b/src/cobalt/dom/html_media_element.h
index b3d1f0d..31314e3 100644
--- a/src/cobalt/dom/html_media_element.h
+++ b/src/cobalt/dom/html_media_element.h
@@ -231,7 +231,7 @@
// WebMediaPlayerClient methods
void NetworkStateChanged() OVERRIDE;
void ReadyStateChanged() OVERRIDE;
- void TimeChanged() OVERRIDE;
+ void TimeChanged(bool eos_played) OVERRIDE;
void DurationChanged() OVERRIDE;
void OutputModeChanged() OVERRIDE;
void PlaybackStateChanged() OVERRIDE;
diff --git a/src/cobalt/dom/html_script_element.cc b/src/cobalt/dom/html_script_element.cc
index 3baa07f..fd4a4b7 100644
--- a/src/cobalt/dom/html_script_element.cc
+++ b/src/cobalt/dom/html_script_element.cc
@@ -257,7 +257,7 @@
base::Bind(
&loader::FetcherFactory::CreateSecureFetcher,
base::Unretained(html_element_context()->fetcher_factory()), url_,
- csp_callback),
+ csp_callback, loader::kNoCORSMode, loader::Origin()),
base::Bind(&loader::TextDecoder::Create,
base::Bind(&HTMLScriptElement::OnSyncLoadingDone,
base::Unretained(this))),
@@ -298,7 +298,7 @@
base::Bind(
&loader::FetcherFactory::CreateSecureFetcher,
base::Unretained(html_element_context()->fetcher_factory()), url_,
- csp_callback),
+ csp_callback, loader::kNoCORSMode, loader::Origin()),
scoped_ptr<loader::Decoder>(new loader::TextDecoder(base::Bind(
&HTMLScriptElement::OnLoadingDone, base::Unretained(this)))),
base::Bind(&HTMLScriptElement::OnLoadingError,
@@ -323,7 +323,7 @@
base::Bind(
&loader::FetcherFactory::CreateSecureFetcher,
base::Unretained(html_element_context()->fetcher_factory()), url_,
- csp_callback),
+ csp_callback, loader::kNoCORSMode, loader::Origin()),
scoped_ptr<loader::Decoder>(new loader::TextDecoder(base::Bind(
&HTMLScriptElement::OnLoadingDone, base::Unretained(this)))),
base::Bind(&HTMLScriptElement::OnLoadingError,
@@ -533,7 +533,7 @@
bool mute_errors =
fetched_last_url_origin_ != document_->location()->OriginObject();
html_element_context()->script_runner()->Execute(
- content, script_location, NULL /* output: succeeded */, mute_errors);
+ content, script_location, mute_errors, NULL /*out_succeeded*/);
// 5. 6. Not needed by Cobalt.
diff --git a/src/cobalt/dom/node.h b/src/cobalt/dom/node.h
index c1ceb48..ff2f36c 100644
--- a/src/cobalt/dom/node.h
+++ b/src/cobalt/dom/node.h
@@ -91,10 +91,10 @@
public:
// Web API: Node
// NodeType values as defined by Web API Node.nodeType.
- typedef uint16 NodeType; // Work around lack of strongly-typed enums
- // in C++03.
- enum NodeTypeInternal { // A name is given only to pacify the compiler.
- // Use |NodeType| instead.
+ // Work around lack of strongly-typed enums in C++03.
+ typedef uint16 NodeType;
+ // A name that is given only to pacify the compiler. Use |NodeType| instead.
+ enum NodeTypeInternal : uint16 {
kElementNode = 1,
kTextNode = 3,
kCdataSectionNode = 4,
diff --git a/src/cobalt/dom/testing/stub_script_runner.cc b/src/cobalt/dom/testing/stub_script_runner.cc
index 8ad635a..9158225 100644
--- a/src/cobalt/dom/testing/stub_script_runner.cc
+++ b/src/cobalt/dom/testing/stub_script_runner.cc
@@ -20,7 +20,7 @@
std::string StubScriptRunner::Execute(
const std::string& script_utf8, const base::SourceLocation& script_location,
- bool* out_succeeded, bool mute_errors) {
+ bool mute_errors, bool* out_succeeded) {
UNREFERENCED_PARAMETER(script_utf8);
UNREFERENCED_PARAMETER(script_location);
UNREFERENCED_PARAMETER(mute_errors);
diff --git a/src/cobalt/dom/testing/stub_script_runner.h b/src/cobalt/dom/testing/stub_script_runner.h
index fb42205..8b74fc7 100644
--- a/src/cobalt/dom/testing/stub_script_runner.h
+++ b/src/cobalt/dom/testing/stub_script_runner.h
@@ -27,7 +27,7 @@
public:
std::string Execute(const std::string& script_utf8,
const base::SourceLocation& script_location,
- bool* out_succeeded, bool mute_errors) OVERRIDE;
+ bool mute_errors, bool* out_succeeded) OVERRIDE;
};
} // namespace testing
diff --git a/src/cobalt/dom/testing/stub_window.h b/src/cobalt/dom/testing/stub_window.h
index 32ef4f9..c437133 100644
--- a/src/cobalt/dom/testing/stub_window.h
+++ b/src/cobalt/dom/testing/stub_window.h
@@ -25,7 +25,6 @@
#include "cobalt/dom/window.h"
#include "cobalt/dom_parser/parser.h"
#include "cobalt/loader/fetcher_factory.h"
-#include "cobalt/media/media_module_stub.h"
#include "cobalt/media_session/media_session.h"
#include "cobalt/network/network_module.h"
#include "cobalt/script/global_environment.h"
@@ -46,7 +45,6 @@
dom_parser_(new dom_parser::Parser(base::Bind(&StubErrorCallback))),
fetcher_factory_(new loader::FetcherFactory(&network_module_)),
local_storage_database_(NULL),
- stub_media_module_(new media::MediaModuleStub()),
url_("about:blank"),
dom_stat_tracker_(new dom::DomStatTracker("StubWindow")) {
engine_ = script::JavaScriptEngine::CreateEngine();
@@ -54,12 +52,10 @@
window_ = new dom::Window(
1920, 1080, 1.f, base::kApplicationStateStarted, css_parser_.get(),
dom_parser_.get(), fetcher_factory_.get(), NULL, NULL, NULL, NULL, NULL,
- NULL, &local_storage_database_, stub_media_module_.get(),
- stub_media_module_.get(), NULL, NULL, NULL, NULL,
+ NULL, &local_storage_database_, NULL, NULL, NULL, NULL, NULL, NULL,
dom_stat_tracker_.get(), url_, "", "en-US",
base::Callback<void(const GURL&)>(), base::Bind(&StubErrorCallback),
- NULL, network_bridge::PostSender(),
- std::string() /* default security policy */, csp::kCSPRequired,
+ NULL, network_bridge::PostSender(), csp::kCSPRequired,
dom::kCspEnforcementEnable, base::Closure() /* csp_policy_changed */,
base::Closure() /* ran_animation_frame_callbacks */,
dom::Window::CloseCallback() /* window_close */,
@@ -82,7 +78,6 @@
network::NetworkModule network_module_;
scoped_ptr<loader::FetcherFactory> fetcher_factory_;
dom::LocalStorageDatabase local_storage_database_;
- scoped_ptr<media::MediaModule> stub_media_module_;
GURL url_;
scoped_ptr<dom::DomStatTracker> dom_stat_tracker_;
script::EnvironmentSettings environment_settings_;
diff --git a/src/cobalt/dom/window.cc b/src/cobalt/dom/window.cc
index e5a0eda..9d0a291 100644
--- a/src/cobalt/dom/window.cc
+++ b/src/cobalt/dom/window.cc
@@ -98,7 +98,6 @@
const base::Callback<void(const std::string&)>& error_callback,
network_bridge::CookieJar* cookie_jar,
const network_bridge::PostSender& post_sender,
- const std::string& default_security_policy,
csp::CSPHeaderPolicy require_csp,
CspEnforcementType csp_enforcement_mode,
const base::Closure& csp_policy_changed_callback,
@@ -137,10 +136,9 @@
base::Bind(&Window::FireHashChangeEvent, base::Unretained(this)),
performance_->timing()->GetNavigationStartClock(),
navigation_callback, ParseUserAgentStyleSheet(css_parser),
- math::Size(width_, height_), cookie_jar, post_sender,
- default_security_policy, require_csp, csp_enforcement_mode,
- csp_policy_changed_callback, csp_insecure_allowed_token,
- dom_max_element_depth)))),
+ math::Size(width_, height_), cookie_jar, post_sender, require_csp,
+ csp_enforcement_mode, csp_policy_changed_callback,
+ csp_insecure_allowed_token, dom_max_element_depth)))),
document_loader_(NULL),
history_(new History()),
navigator_(new Navigator(user_agent, language, media_session,
@@ -291,16 +289,24 @@
scoped_refptr<Crypto> Window::crypto() const { return crypto_; }
-std::string Window::Btoa(const std::string& string_to_encode) {
+std::string Window::Btoa(const std::string& string_to_encode,
+ script::ExceptionState* exception_state) {
std::string output;
- base::Base64Encode(string_to_encode, &output);
+ if (!base::Base64Encode(string_to_encode, &output)) {
+ DOMException::Raise(DOMException::kInvalidCharacterErr, exception_state);
+ return std::string();
+ }
return output;
}
-std::string Window::Atob(const std::string& encoded_string) {
+std::vector<uint8_t> Window::Atob(const std::string& encoded_string,
+ script::ExceptionState* exception_state) {
std::string output;
- base::Base64Decode(encoded_string, &output);
- return output;
+ if (!base::Base64Decode(encoded_string, &output)) {
+ DOMException::Raise(DOMException::kInvalidCharacterErr, exception_state);
+ return {};
+ }
+ return {output.begin(), output.end()};
}
int Window::SetTimeout(const WindowTimers::TimerCallbackArg& handler,
diff --git a/src/cobalt/dom/window.h b/src/cobalt/dom/window.h
index b1fa459..93c0e32 100644
--- a/src/cobalt/dom/window.h
+++ b/src/cobalt/dom/window.h
@@ -16,6 +16,7 @@
#define COBALT_DOM_WINDOW_H_
#include <string>
+#include <vector>
#include "base/callback.h"
#include "base/hash_tables.h"
@@ -110,10 +111,7 @@
typedef base::Callback<void(base::TimeDelta)> CloseCallback;
typedef UrlRegistry<MediaSource> MediaSourceRegistry;
typedef base::Callback<bool(const GURL&, const std::string&)> CacheCallback;
- enum ClockType {
- kClockTypeTestRunner,
- kClockTypeSystemTime
- };
+ enum ClockType { kClockTypeTestRunner, kClockTypeSystemTime };
Window(
int width, int height, float device_pixel_ratio,
@@ -140,7 +138,6 @@
const base::Callback<void(const std::string&)>& error_callback,
network_bridge::CookieJar* cookie_jar,
const network_bridge::PostSender& post_sender,
- const std::string& default_security_policy,
csp::CSPHeaderPolicy require_csp,
dom::CspEnforcementType csp_enforcement_mode,
const base::Closure& csp_policy_changed_callback,
@@ -235,9 +232,11 @@
scoped_refptr<Crypto> crypto() const;
// base64 encoding and decoding
- std::string Btoa(const std::string& string_to_encode);
+ std::string Btoa(const std::string& string_to_encode,
+ script::ExceptionState* exception_state);
- std::string Atob(const std::string& encoded_string);
+ std::vector<uint8_t> Atob(const std::string& encoded_string,
+ script::ExceptionState* exception_state);
// Web API: WindowTimers (implements)
// https://www.w3.org/TR/html5/webappapis.html#timers
@@ -306,11 +305,6 @@
void SetCamera3D(const scoped_refptr<input::Camera3D>& camera_3d);
- void set_can_play_type_handler(
- media::CanPlayTypeHandler* can_play_type_handler) {
- html_element_context_->set_can_play_type_handler(can_play_type_handler);
- }
-
void set_web_media_player_factory(
media::WebMediaPlayerFactory* web_media_player_factory) {
html_element_context_->set_web_media_player_factory(
diff --git a/src/cobalt/dom/window.idl b/src/cobalt/dom/window.idl
index 8749653..77a3df6 100644
--- a/src/cobalt/dom/window.idl
+++ b/src/cobalt/dom/window.idl
@@ -36,9 +36,10 @@
// the user agent
readonly attribute Navigator navigator;
- // base64 encoding and decoding
- DOMString btoa(DOMString string_to_encode);
- DOMString atob(DOMString encoded_string);
+ // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
+ [RaisesException] DOMString btoa(DOMString stringToEncode);
+ // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
+ [RaisesException] ByteString atob(DOMString encodedString);
// Custom, not in any spec.
//
diff --git a/src/cobalt/dom/window_test.cc b/src/cobalt/dom/window_test.cc
index 65a8c1d..04b2ef9 100644
--- a/src/cobalt/dom/window_test.cc
+++ b/src/cobalt/dom/window_test.cc
@@ -24,7 +24,6 @@
#include "cobalt/dom/screen.h"
#include "cobalt/dom_parser/parser.h"
#include "cobalt/loader/fetcher_factory.h"
-#include "cobalt/media/media_module_stub.h"
#include "cobalt/media_session/media_session.h"
#include "cobalt/network/network_module.h"
#include "cobalt/network_bridge/net_poster.h"
@@ -48,18 +47,15 @@
dom_parser_(new dom_parser::Parser(mock_error_callback_)),
fetcher_factory_(new loader::FetcherFactory(&network_module_)),
local_storage_database_(NULL),
- stub_media_module_(new media::MediaModuleStub()),
url_("about:blank"),
window_(new Window(
1920, 1080, 1.f, base::kApplicationStateStarted, css_parser_.get(),
dom_parser_.get(), fetcher_factory_.get(), NULL, NULL, NULL, NULL,
- NULL, NULL, &local_storage_database_, stub_media_module_.get(),
- stub_media_module_.get(), NULL, NULL, NULL, NULL, NULL, url_, "",
- "en-US", base::Callback<void(const GURL &)>(),
+ NULL, NULL, &local_storage_database_, NULL, NULL, NULL, NULL, NULL,
+ NULL, NULL, url_, "", "en-US", base::Callback<void(const GURL &)>(),
base::Bind(&MockErrorCallback::Run,
base::Unretained(&mock_error_callback_)),
- NULL, network_bridge::PostSender(),
- std::string() /* default security policy */, csp::kCSPRequired,
+ NULL, network_bridge::PostSender(), csp::kCSPRequired,
kCspEnforcementEnable, base::Closure() /* csp_policy_changed */,
base::Closure() /* ran_animation_frame_callbacks */,
dom::Window::CloseCallback() /* window_close */,
@@ -74,7 +70,6 @@
network::NetworkModule network_module_;
scoped_ptr<loader::FetcherFactory> fetcher_factory_;
dom::LocalStorageDatabase local_storage_database_;
- scoped_ptr<media::MediaModule> stub_media_module_;
GURL url_;
scoped_refptr<Window> window_;
};
diff --git a/src/cobalt/layout/box.cc b/src/cobalt/layout/box.cc
index c8ed055..1453801 100644
--- a/src/cobalt/layout/box.cc
+++ b/src/cobalt/layout/box.cc
@@ -1357,9 +1357,10 @@
}
namespace {
-bool AllBorderSidesShareSameProperties(const Border& border) {
- return border.left == border.top && border.left == border.right &&
- border.left == border.bottom;
+bool AllBorderSidesShareSameStyle(const Border& border) {
+ return border.left.style == border.top.style &&
+ border.left.style == border.right.style &&
+ border.left.style == border.bottom.style;
}
} // namespace
@@ -1381,10 +1382,10 @@
&rect_node_builder);
if (rounded_corners &&
- !AllBorderSidesShareSameProperties(*rect_node_builder.border)) {
+ !AllBorderSidesShareSameStyle(*rect_node_builder.border)) {
LOG(WARNING)
<< "Cobalt does not support rounded corners borders whose edges do not "
- "all share the same properties.";
+ "all share the same style.";
return;
}
diff --git a/src/cobalt/layout/topmost_event_target.cc b/src/cobalt/layout/topmost_event_target.cc
index f825db7..502701e 100644
--- a/src/cobalt/layout/topmost_event_target.cc
+++ b/src/cobalt/layout/topmost_event_target.cc
@@ -362,7 +362,7 @@
pointer_state->ClearPendingPointerCaptureTargetOverride(
pointer_event->pointer_id());
}
- if (target_element) {
+ if (target_element && !is_touchpad_event) {
SendCompatibilityMappingMouseEvent(target_element, event, pointer_event,
event_init,
&mouse_event_prevent_flags_);
diff --git a/src/cobalt/layout/used_style.cc b/src/cobalt/layout/used_style.cc
index 323425d..ecb861e 100644
--- a/src/cobalt/layout/used_style.cc
+++ b/src/cobalt/layout/used_style.cc
@@ -472,7 +472,8 @@
DCHECK(animated_image_tracker_);
DCHECK(image_cache_);
scoped_refptr<loader::image::Image> image =
- image_cache_->CreateCachedResource(url)->TryGetResource();
+ image_cache_->CreateCachedResource(url, loader::Origin())
+ ->TryGetResource();
if (image && image->IsAnimated()) {
loader::image::AnimatedImage* animated_image =
base::polymorphic_downcast<loader::image::AnimatedImage*>(image.get());
@@ -484,7 +485,8 @@
scoped_refptr<loader::mesh::MeshProjection>
UsedStyleProvider::ResolveURLToMeshProjection(const GURL& url) {
DCHECK(mesh_cache_);
- return mesh_cache_->CreateCachedResource(url)->TryGetResource();
+ return mesh_cache_->CreateCachedResource(url, loader::Origin())
+ ->TryGetResource();
}
void UsedStyleProvider::UpdateAnimatedImages() {
diff --git a/src/cobalt/layout_tests/layout_snapshot.cc b/src/cobalt/layout_tests/layout_snapshot.cc
index 1fe1c7e..49c1a6f 100644
--- a/src/cobalt/layout_tests/layout_snapshot.cc
+++ b/src/cobalt/layout_tests/layout_snapshot.cc
@@ -20,7 +20,6 @@
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "cobalt/browser/web_module.h"
-#include "cobalt/media/media_module_stub.h"
#include "cobalt/network/network_module.h"
#include "cobalt/render_tree/resource_provider.h"
@@ -64,10 +63,6 @@
net_options.https_requirement = network::kHTTPSOptional;
network::NetworkModule network_module(net_options);
- // We do not support a media module in this mode.
- scoped_ptr<media::MediaModule> stub_media_module(
- new media::MediaModuleStub());
-
// Use 128M of image cache to minimize the effect of image loading.
const size_t kImageCacheCapacity = 128 * 1024 * 1024;
@@ -87,7 +82,8 @@
MessageLoop::current()),
base::Bind(&WebModuleErrorCallback, &run_loop, MessageLoop::current()),
browser::WebModule::CloseCallback() /* window_close_callback */,
- base::Closure() /* window_minimize_callback */, stub_media_module.get(),
+ base::Closure() /* window_minimize_callback */,
+ NULL /* can_play_type_handler */, NULL /* web_media_player_factory */,
&network_module, viewport_size, 1.f, resource_provider, 60.0f,
web_module_options);
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..de9ab45
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners.html
new file mode 100644
index 0000000..1fc226b
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-2-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 2 different color values for the edges of a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: 25px solid;
+ border-color: #00FFFF #FF7F50;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..ebf6ff0
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners.html
new file mode 100644
index 0000000..eb6b3e8
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-3-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 3 different color values for the edges of a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: 25px solid;
+ border-color: #00FFFF #FF7F50 #FF69B4;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths-expected.png
new file mode 100644
index 0000000..2d7ff36
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths.html
new file mode 100644
index 0000000..9de0f5d
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different color values, width values and radius values for the edges
+ | of a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ | https://www.w3.org/TR/css3-background/#border-radius
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid;
+ border-color: #00FFFF #FF7F50 #FF69B4 #FAFAD2;
+ border-width: 10px 50px 30px 80px;
+ border-radius: 30px 80px 100px 150px;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-expected.png
new file mode 100644
index 0000000..2f4ba67
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners.html
new file mode 100644
index 0000000..071f22c
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-different-rounded-corners.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different color values and radius values for the edges of a
+ | rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ | https://www.w3.org/TR/css3-background/#border-radius
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: 25px solid;
+ border-color: #00FFFF #FF7F50 #FF69B4 #FAFAD2;
+ border-radius: 30px 80px 100px 150px;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths-expected.png
new file mode 100644
index 0000000..06f8d8b
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths.html
new file mode 100644
index 0000000..c841fa5
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-and-different-border-widths.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different color values and width values for the edges of a rounded
+ | corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid;
+ border-color: #00FFFF #FF7F50 #FF69B4 #FAFAD2;
+ border-width: 10px 50px 30px 80px;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..7349035
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners.html
new file mode 100644
index 0000000..76c10f5
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-1-border-color-4-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different color values for the edges of a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-color
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: 25px solid;
+ border-color: #00FFFF #FF7F50 #FF69B4 #FAFAD2;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..6172080
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners.html
new file mode 100644
index 0000000..c092ca5
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-2-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 2 different width values for a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid #00FFFF;
+ border-width: 80px 10px;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..b193ed0
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners.html
new file mode 100644
index 0000000..7693fff
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-3-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 3 different width values for a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid #00FFFF;
+ border-width: 80px 50px 10px;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners-expected.png
new file mode 100644
index 0000000..3da6c2c
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners.html
new file mode 100644
index 0000000..4a33512
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-different-rounded-corners.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different width values and radius values for the edges of a
+ | rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ | https://www.w3.org/TR/css3-background/#border-radius
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid #00FFFF;
+ border-width: 10px 50px 30px 80px;
+ border-radius: 30px 80px 100px 150px;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners-expected.png b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners-expected.png
new file mode 100644
index 0000000..2786077
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners-expected.png
Binary files differ
diff --git a/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners.html b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners.html
new file mode 100644
index 0000000..0fb7b3f
--- /dev/null
+++ b/src/cobalt/layout_tests/testdata/css3-background/4-3-border-width-4-values-with-rounded-corners.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<!--
+ | Setting 4 different width values for a rounded corners border.
+ | https://www.w3.org/TR/css3-background/#the-border-width
+ -->
+<html>
+<head>
+ <style>
+ div {
+ border: solid #00FFFF;
+ border-width: 10px 50px 30px 80px;
+ border-radius: 50%;
+ height: 200px;
+ width: 400px;
+ }
+ </style>
+</head>
+<body>
+ <div></div>
+</body>
+</html>
diff --git a/src/cobalt/layout_tests/testdata/css3-background/layout_tests.txt b/src/cobalt/layout_tests/testdata/css3-background/layout_tests.txt
index 03230b9..9b39a9e 100644
--- a/src/cobalt/layout_tests/testdata/css3-background/layout_tests.txt
+++ b/src/cobalt/layout_tests/testdata/css3-background/layout_tests.txt
@@ -73,6 +73,16 @@
4-0-border-width-with-solid-border-style
4-0-different-border-styles-with-different-border-widths
4-0-different-border-widths-with-solid-border-style
+4-1-border-color-2-values-with-rounded-corners
+4-1-border-color-3-values-with-rounded-corners
+4-1-border-color-4-values-with-different-rounded-corners
+4-1-border-color-4-values-with-different-rounded-corners-and-different-border-widths
+4-1-border-color-4-values-with-rounded-corners
+4-1-border-color-4-values-with-rounded-corners-and-different-border-widths
+4-3-border-width-2-values-with-rounded-corners
+4-3-border-width-3-values-with-rounded-corners
+4-3-border-width-4-values-with-different-rounded-corners
+4-3-border-width-4-values-with-rounded-corners
5-0-border-radius-2-values-with-background-color
5-0-border-radius-2-values-with-border-only
5-0-border-radius-3-values-with-background-color
diff --git a/src/cobalt/layout_tests/web_platform_test_parser.cc b/src/cobalt/layout_tests/web_platform_test_parser.cc
index 83dc8bb..68e7185 100644
--- a/src/cobalt/layout_tests/web_platform_test_parser.cc
+++ b/src/cobalt/layout_tests/web_platform_test_parser.cc
@@ -110,7 +110,7 @@
bool success = global_environment->EvaluateScript(
script::SourceCode::CreateSourceCode(
precondition, base::SourceLocation(__FILE__, __LINE__, 1)),
- &result, false /*mute_errors*/);
+ false /*mute_errors*/, &result);
if (!success) {
DLOG(ERROR) << "Failed to evaluate precondition: "
diff --git a/src/cobalt/layout_tests/web_platform_tests.cc b/src/cobalt/layout_tests/web_platform_tests.cc
index 2b0a60a..2199ea1 100644
--- a/src/cobalt/layout_tests/web_platform_tests.cc
+++ b/src/cobalt/layout_tests/web_platform_tests.cc
@@ -46,23 +46,22 @@
public:
CspDelegatePermissive(
scoped_ptr<dom::CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback)
- : dom::CspDelegateSecure(violation_reporter.Pass(), url, location_policy,
- require_csp, policy_changed_callback) {
+ : dom::CspDelegateSecure(violation_reporter.Pass(), url, require_csp,
+ policy_changed_callback) {
// Lies, but some checks in our parent require this.
was_header_received_ = true;
}
static CspDelegate* Create(
scoped_ptr<dom::CspViolationReporter> violation_reporter, const GURL& url,
- const std::string& location_policy, csp::CSPHeaderPolicy require_csp,
+ csp::CSPHeaderPolicy require_csp,
const base::Closure& policy_changed_callback,
int insecure_allowed_token) {
UNREFERENCED_PARAMETER(insecure_allowed_token);
return new CspDelegatePermissive(violation_reporter.Pass(), url,
- location_policy, require_csp,
- policy_changed_callback);
+ require_csp, policy_changed_callback);
}
bool OnReceiveHeaders(const csp::ResponseHeaders& headers) OVERRIDE {
@@ -160,6 +159,8 @@
options.output_resolution_override = kDefaultViewportSize;
scoped_ptr<media::MediaModule> media_module(
media::MediaModule::Create(NULL, &resource_provider, options));
+ scoped_ptr<media::CanPlayTypeHandler> can_play_type_handler(
+ media::MediaModule::CreateCanPlayTypeHandler());
dom::CspDelegateFactory::GetInstance()->OverrideCreator(
dom::kCspEnforcementEnable, CspDelegatePermissive::Create);
@@ -179,9 +180,9 @@
MessageLoop::current()),
base::Bind(&WebModuleErrorCallback, &run_loop, MessageLoop::current()),
browser::WebModule::CloseCallback() /* window_close_callback */,
- base::Closure() /* window_minimize_callback */, media_module.get(),
- &network_module, kDefaultViewportSize, 1.f, &resource_provider, 60.0f,
- web_module_options);
+ base::Closure() /* window_minimize_callback */,
+ can_play_type_handler.get(), media_module.get(), &network_module,
+ kDefaultViewportSize, 1.f, &resource_provider, 60.0f, web_module_options);
run_loop.Run();
const std::string extract_results =
"document.getElementById(\"__testharness__results__\").textContent;";
@@ -324,17 +325,15 @@
INSTANTIATE_TEST_CASE_P(
fetch, WebPlatformTest,
- ::testing::ValuesIn(EnumerateWebPlatformTests("fetch",
- "'fetch' in this")));
+ ::testing::ValuesIn(EnumerateWebPlatformTests("fetch", "'fetch' in this")));
INSTANTIATE_TEST_CASE_P(
mediasession, WebPlatformTest,
::testing::ValuesIn(EnumerateWebPlatformTests("mediasession")));
-INSTANTIATE_TEST_CASE_P(
- streams, WebPlatformTest,
- ::testing::ValuesIn(EnumerateWebPlatformTests("streams",
- "'ReadableStream' in this")));
+INSTANTIATE_TEST_CASE_P(streams, WebPlatformTest,
+ ::testing::ValuesIn(EnumerateWebPlatformTests(
+ "streams", "'ReadableStream' in this")));
INSTANTIATE_TEST_CASE_P(
cobalt_special, WebPlatformTest,
diff --git a/src/cobalt/loader/decoder.h b/src/cobalt/loader/decoder.h
index 1f51912..6e08643 100644
--- a/src/cobalt/loader/decoder.h
+++ b/src/cobalt/loader/decoder.h
@@ -69,7 +69,7 @@
// Provides textdecoder with last url to prevent security leak if resource is
// cross-origin.
- virtual void SetLastURLOrigin(const loader::Origin&) {}
+ virtual void SetLastURLOrigin(const Origin&) {}
};
} // namespace loader
diff --git a/src/cobalt/loader/fetcher.h b/src/cobalt/loader/fetcher.h
index 6ce28cf..9288081 100644
--- a/src/cobalt/loader/fetcher.h
+++ b/src/cobalt/loader/fetcher.h
@@ -26,6 +26,13 @@
namespace cobalt {
namespace loader {
+// https://fetch.spec.whatwg.org/#concept-request-mode
+// Right now Cobalt only needs two modes.
+enum RequestMode {
+ kNoCORSMode,
+ kCORSMode,
+};
+
class Fetcher {
public:
class Handler {
@@ -64,7 +71,7 @@
// Concrete Fetcher subclass should start fetching immediately in constructor.
explicit Fetcher(Handler* handler) : handler_(handler) {}
- const loader::Origin& last_url_origin() { return last_url_origin_; }
+ const Origin& last_url_origin() { return last_url_origin_; }
// Concrete Fetcher subclass should cancel fetching in destructor.
virtual ~Fetcher() = 0;
@@ -73,7 +80,7 @@
Handler* handler() const { return handler_; }
// used by html elements to check if resource is cross-origin.
- loader::Origin last_url_origin_;
+ Origin last_url_origin_;
private:
Handler* handler_;
diff --git a/src/cobalt/loader/fetcher_factory.cc b/src/cobalt/loader/fetcher_factory.cc
index 9776365..d582d15 100644
--- a/src/cobalt/loader/fetcher_factory.cc
+++ b/src/cobalt/loader/fetcher_factory.cc
@@ -92,12 +92,14 @@
scoped_ptr<Fetcher> FetcherFactory::CreateFetcher(const GURL& url,
Fetcher::Handler* handler) {
- return CreateSecureFetcher(url, csp::SecurityCallback(), handler).Pass();
+ return CreateSecureFetcher(url, csp::SecurityCallback(), kNoCORSMode,
+ Origin(), handler)
+ .Pass();
}
scoped_ptr<Fetcher> FetcherFactory::CreateSecureFetcher(
const GURL& url, const csp::SecurityCallback& url_security_callback,
- Fetcher::Handler* handler) {
+ RequestMode request_mode, const Origin& origin, Fetcher::Handler* handler) {
DLOG(INFO) << "Fetching: " << ClipUrl(url, 60);
if (!url.is_valid()) {
@@ -111,8 +113,8 @@
network_module_) {
NetFetcher::Options options;
return scoped_ptr<Fetcher>(new NetFetcher(url, url_security_callback,
- handler, network_module_,
- options));
+ handler, network_module_, options,
+ request_mode, origin));
}
if (url.SchemeIs("blob") && !blob_resolver_.is_null()) {
diff --git a/src/cobalt/loader/fetcher_factory.h b/src/cobalt/loader/fetcher_factory.h
index a367df7..1278350 100644
--- a/src/cobalt/loader/fetcher_factory.h
+++ b/src/cobalt/loader/fetcher_factory.h
@@ -50,6 +50,7 @@
scoped_ptr<Fetcher> CreateSecureFetcher(
const GURL& url, const csp::SecurityCallback& url_security_callback,
+ RequestMode request_mode, const Origin& origin,
Fetcher::Handler* handler);
network::NetworkModule* network_module() const { return network_module_; }
diff --git a/src/cobalt/loader/loader.cc b/src/cobalt/loader/loader.cc
index 58c1ca9..bc07421 100644
--- a/src/cobalt/loader/loader.cc
+++ b/src/cobalt/loader/loader.cc
@@ -57,7 +57,6 @@
decoder_->DecodeChunkPassed(data.Pass());
}
void OnDone(Fetcher* fetcher) OVERRIDE {
- UNREFERENCED_PARAMETER(fetcher);
DCHECK(fetcher);
decoder_->SetLastURLOrigin(fetcher->last_url_origin());
decoder_->Finish();
diff --git a/src/cobalt/loader/loader_factory.cc b/src/cobalt/loader/loader_factory.cc
index d65a87b..c5c9890 100644
--- a/src/cobalt/loader/loader_factory.cc
+++ b/src/cobalt/loader/loader_factory.cc
@@ -43,11 +43,12 @@
scoped_ptr<Loader> LoaderFactory::CreateImageLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const image::ImageDecoder::SuccessCallback& success_callback,
- const image::ImageDecoder::ErrorCallback& error_callback) {
+ const image::ImageDecoder::ErrorCallback& error_callback,
+ const Origin& origin) {
DCHECK(thread_checker_.CalledOnValidThread());
scoped_ptr<Loader> loader(new Loader(
- MakeFetcherCreator(url, url_security_callback),
+ MakeFetcherCreator(url, url_security_callback, kNoCORSMode, origin),
scoped_ptr<Decoder>(new image::ThreadedImageDecoderProxy(
resource_provider_, success_callback, error_callback,
load_thread_.message_loop())),
@@ -61,11 +62,12 @@
scoped_ptr<Loader> LoaderFactory::CreateTypefaceLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const font::TypefaceDecoder::SuccessCallback& success_callback,
- const font::TypefaceDecoder::ErrorCallback& error_callback) {
+ const font::TypefaceDecoder::ErrorCallback& error_callback,
+ const Origin& origin) {
DCHECK(thread_checker_.CalledOnValidThread());
scoped_ptr<Loader> loader(new Loader(
- MakeFetcherCreator(url, url_security_callback),
+ MakeFetcherCreator(url, url_security_callback, kCORSMode, origin),
scoped_ptr<Decoder>(new font::TypefaceDecoder(
resource_provider_, success_callback, error_callback)),
error_callback,
@@ -79,11 +81,12 @@
scoped_ptr<Loader> LoaderFactory::CreateMeshLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const mesh::MeshDecoder::SuccessCallback& success_callback,
- const mesh::MeshDecoder::ErrorCallback& error_callback) {
+ const mesh::MeshDecoder::ErrorCallback& error_callback,
+ const Origin& origin) {
DCHECK(thread_checker_.CalledOnValidThread());
scoped_ptr<Loader> loader(new Loader(
- MakeFetcherCreator(url, url_security_callback),
+ MakeFetcherCreator(url, url_security_callback, kNoCORSMode, origin),
scoped_ptr<Decoder>(new mesh::MeshDecoder(
resource_provider_, success_callback, error_callback)),
error_callback,
@@ -94,12 +97,13 @@
}
Loader::FetcherCreator LoaderFactory::MakeFetcherCreator(
- const GURL& url, const csp::SecurityCallback& url_security_callback) {
+ const GURL& url, const csp::SecurityCallback& url_security_callback,
+ RequestMode request_mode, const Origin& origin) {
DCHECK(thread_checker_.CalledOnValidThread());
return base::Bind(&FetcherFactory::CreateSecureFetcher,
base::Unretained(fetcher_factory_), url,
- url_security_callback);
+ url_security_callback, request_mode, origin);
}
void LoaderFactory::Suspend() {
diff --git a/src/cobalt/loader/loader_factory.h b/src/cobalt/loader/loader_factory.h
index 4cd8b25..019bc45 100644
--- a/src/cobalt/loader/loader_factory.h
+++ b/src/cobalt/loader/loader_factory.h
@@ -43,19 +43,22 @@
scoped_ptr<Loader> CreateImageLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const image::ImageDecoder::SuccessCallback& success_callback,
- const image::ImageDecoder::ErrorCallback& error_callback);
+ const image::ImageDecoder::ErrorCallback& error_callback,
+ const Origin& origin);
// Creates a loader that fetches and decodes a render_tree::Typeface.
scoped_ptr<Loader> CreateTypefaceLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const font::TypefaceDecoder::SuccessCallback& success_callback,
- const font::TypefaceDecoder::ErrorCallback& error_callback);
+ const font::TypefaceDecoder::ErrorCallback& error_callback,
+ const Origin& orgin);
// Creates a loader that fetches and decodes a Mesh.
scoped_ptr<Loader> CreateMeshLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const mesh::MeshDecoder::SuccessCallback& success_callback,
- const mesh::MeshDecoder::ErrorCallback& error_callback);
+ const mesh::MeshDecoder::ErrorCallback& error_callback,
+ const Origin& origin);
// Clears out the loader factory's resource provider, aborting any in-progress
// loads.
@@ -70,7 +73,8 @@
void OnLoaderDestroyed(Loader* loader);
Loader::FetcherCreator MakeFetcherCreator(
- const GURL& url, const csp::SecurityCallback& url_security_callback);
+ const GURL& url, const csp::SecurityCallback& url_security_callback,
+ RequestMode request_mode, const Origin& origin);
// Ensures that the LoaderFactory methods are only called from the same
// thread.
diff --git a/src/cobalt/loader/loader_test.cc b/src/cobalt/loader/loader_test.cc
index 0c8d736..46cf4fe 100644
--- a/src/cobalt/loader/loader_test.cc
+++ b/src/cobalt/loader/loader_test.cc
@@ -41,7 +41,7 @@
public:
explicit TextDecoderCallback(base::RunLoop* run_loop) : run_loop_(run_loop) {}
- void OnDone(const std::string& text, const loader::Origin&) {
+ void OnDone(const std::string& text, const Origin&) {
text_ = text;
MessageLoop::current()->PostTask(FROM_HERE, run_loop_->QuitClosure());
}
diff --git a/src/cobalt/loader/mock_loader_factory.h b/src/cobalt/loader/mock_loader_factory.h
index c680190..d6fa51b 100644
--- a/src/cobalt/loader/mock_loader_factory.h
+++ b/src/cobalt/loader/mock_loader_factory.h
@@ -51,7 +51,7 @@
scoped_ptr<Loader> CreateImageLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const image::ImageDecoder::SuccessCallback& success_callback,
- const image::ImageDecoder::ErrorCallback& error_callback) {
+ const image::ImageDecoder::ErrorCallback& error_callback, const Origin&) {
return scoped_ptr<Loader>(
CreateImageLoaderMock(url, url_security_callback, success_callback,
error_callback));
@@ -60,7 +60,8 @@
scoped_ptr<Loader> CreateTypefaceLoader(
const GURL& url, const csp::SecurityCallback& url_security_callback,
const font::TypefaceDecoder::SuccessCallback& success_callback,
- const font::TypefaceDecoder::ErrorCallback& error_callback) {
+ const font::TypefaceDecoder::ErrorCallback& error_callback,
+ const Origin&) {
return scoped_ptr<Loader>(
CreateTypefaceLoaderMock(url, url_security_callback, success_callback,
error_callback));
diff --git a/src/cobalt/loader/net_fetcher.cc b/src/cobalt/loader/net_fetcher.cc
index 5c904ed..29a21c5 100644
--- a/src/cobalt/loader/net_fetcher.cc
+++ b/src/cobalt/loader/net_fetcher.cc
@@ -17,6 +17,7 @@
#include <string>
#include "base/stringprintf.h"
+#include "cobalt/loader/cors_preflight.h"
#include "cobalt/network/network_module.h"
#include "net/url_request/url_fetcher.h"
#if defined(OS_STARBOARD)
@@ -72,15 +73,23 @@
const csp::SecurityCallback& security_callback,
Handler* handler,
const network::NetworkModule* network_module,
- const Options& options)
+ const Options& options, RequestMode request_mode,
+ const Origin& origin)
: Fetcher(handler),
security_callback_(security_callback),
ALLOW_THIS_IN_INITIALIZER_LIST(start_callback_(
- base::Bind(&NetFetcher::Start, base::Unretained(this)))) {
+ base::Bind(&NetFetcher::Start, base::Unretained(this)))),
+ request_cross_origin_(false),
+ origin_(origin) {
url_fetcher_.reset(
net::URLFetcher::Create(url, options.request_method, this));
url_fetcher_->SetRequestContext(network_module->url_request_context_getter());
url_fetcher_->DiscardResponse();
+ if (request_mode == kCORSMode && !url.SchemeIs("data") &&
+ origin != Origin(url)) {
+ request_cross_origin_ = true;
+ url_fetcher_->AddExtraRequestHeader("Origin:" + origin.SerializedOrigin());
+ }
// Delay the actual start until this function is complete. Otherwise we might
// call handler's callbacks at an unexpected time- e.g. receiving OnError()
@@ -124,6 +133,19 @@
return HandleError(msg).InvalidateThis();
}
}
+
+ // net::URLFetcher can not guarantee GetResponseHeaders() always return
+ // non-null pointer.
+ if (request_cross_origin_ &&
+ (!source->GetResponseHeaders() ||
+ !CORSPreflight::CORSCheck(*source->GetResponseHeaders(),
+ origin_.SerializedOrigin(), false))) {
+ std::string msg(base::StringPrintf(
+ "Cross origin request to %s was rejected by Same-Origin-Policy",
+ source->GetURL().spec().c_str()));
+ return HandleError(msg).InvalidateThis();
+ }
+
last_url_origin_ = Origin(source->GetURL());
}
diff --git a/src/cobalt/loader/net_fetcher.h b/src/cobalt/loader/net_fetcher.h
index 6f1f5f5..baaae2c 100644
--- a/src/cobalt/loader/net_fetcher.h
+++ b/src/cobalt/loader/net_fetcher.h
@@ -44,7 +44,8 @@
NetFetcher(const GURL& url, const csp::SecurityCallback& security_callback,
Handler* handler, const network::NetworkModule* network_module,
- const Options& options);
+ const Options& options, RequestMode request_mode,
+ const Origin& origin);
~NetFetcher() OVERRIDE;
// net::URLFetcherDelegate interface
@@ -86,6 +87,12 @@
// after being constructed, but before Start() runs.
base::CancelableClosure start_callback_;
+ // True if request mode is CORS and request URL's origin is different from
+ // request's origin.
+ bool request_cross_origin_;
+ // The request's origin.
+ Origin origin_;
+
DISALLOW_COPY_AND_ASSIGN(NetFetcher);
};
diff --git a/src/cobalt/loader/resource_cache.h b/src/cobalt/loader/resource_cache.h
index 024cc55..805a0c5 100644
--- a/src/cobalt/loader/resource_cache.h
+++ b/src/cobalt/loader/resource_cache.h
@@ -68,7 +68,8 @@
typedef base::Callback<scoped_ptr<Loader>(
const GURL&, const csp::SecurityCallback&,
const base::Callback<void(const scoped_refptr<ResourceType>&)>&,
- const base::Callback<void(const std::string&)>&)> CreateLoaderFunction;
+ const base::Callback<void(const std::string&)>&, const Origin&)>
+ CreateLoaderFunction;
// This class can be used to attach success or error callbacks to
// CachedResource objects that are executed when the resource finishes
@@ -100,7 +101,7 @@
CachedResource(const GURL& url,
const csp::SecurityCallback& security_callback,
const CreateLoaderFunction& create_loader_function,
- ResourceCacheType* resource_cache);
+ ResourceCacheType* resource_cache, const Origin& origin);
// Resource is available. CachedResource is a wrapper of the resource
// and there is no need to fetch or load this resource again. |loader_|
@@ -214,7 +215,7 @@
CachedResource<CacheType>::CachedResource(
const GURL& url, const csp::SecurityCallback& security_callback,
const CreateLoaderFunction& create_loader_function,
- ResourceCacheType* resource_cache)
+ ResourceCacheType* resource_cache, const Origin& origin)
: url_(url),
resource_cache_(resource_cache),
completion_callbacks_enabled_(false) {
@@ -223,7 +224,8 @@
loader_ = create_loader_function.Run(
url, security_callback,
base::Bind(&CachedResource::OnLoadingSuccess, base::Unretained(this)),
- base::Bind(&CachedResource::OnLoadingError, base::Unretained(this)));
+ base::Bind(&CachedResource::OnLoadingError, base::Unretained(this)),
+ origin);
}
template <typename CacheType>
@@ -405,7 +407,8 @@
// |unreference_cached_resource_map_|, creates a CachedResource with a loader
// for it. If the CachedResource is in the cache map, return the
// CachedResource or wrap the resource if necessary.
- scoped_refptr<CachedResourceType> CreateCachedResource(const GURL& url);
+ scoped_refptr<CachedResourceType> CreateCachedResource(const GURL& url,
+ const Origin& origin);
// Set a callback that the loader will query to determine if the URL is safe
// according to our document's security policy.
@@ -568,7 +571,8 @@
template <typename CacheType>
scoped_refptr<CachedResource<CacheType> >
-ResourceCache<CacheType>::CreateCachedResource(const GURL& url) {
+ResourceCache<CacheType>::CreateCachedResource(const GURL& url,
+ const Origin& origin) {
DCHECK(resource_cache_thread_checker_.CalledOnValidThread());
DCHECK(url.is_valid());
@@ -609,7 +613,7 @@
// Create the cached resource and fetch its resource based on the url.
scoped_refptr<CachedResourceType> cached_resource(new CachedResourceType(
- url, security_callback_, create_loader_function_, this));
+ url, security_callback_, create_loader_function_, this, origin));
cached_resource_map_.insert(
std::make_pair(url.spec(), cached_resource.get()));
diff --git a/src/cobalt/loader/sync_loader.cc b/src/cobalt/loader/sync_loader.cc
index e8d45f9..e26698e 100644
--- a/src/cobalt/loader/sync_loader.cc
+++ b/src/cobalt/loader/sync_loader.cc
@@ -72,7 +72,8 @@
decoder_->DecodeChunk(data, size);
}
void OnDone(Fetcher* fetcher) OVERRIDE {
- UNREFERENCED_PARAMETER(fetcher);
+ DCHECK(fetcher);
+ decoder_->SetLastURLOrigin(fetcher->last_url_origin());
decoder_->Finish();
loader_on_thread_->Signal();
}
diff --git a/src/cobalt/loader/text_decoder_test.cc b/src/cobalt/loader/text_decoder_test.cc
index 90e8824..b6ddb19 100644
--- a/src/cobalt/loader/text_decoder_test.cc
+++ b/src/cobalt/loader/text_decoder_test.cc
@@ -23,13 +23,12 @@
namespace {
struct TextDecoderCallback {
- void Callback(const std::string& value,
- const loader::Origin& last_url_origin) {
+ void Callback(const std::string& value, const Origin& last_url_origin) {
text = value;
last_url_origin_ = last_url_origin;
}
std::string text;
- loader::Origin last_url_origin_;
+ Origin last_url_origin_;
};
} // namespace
diff --git a/src/cobalt/media/base/audio_block_fifo.cc b/src/cobalt/media/base/audio_block_fifo.cc
deleted file mode 100644
index b2ac5da..0000000
--- a/src/cobalt/media/base/audio_block_fifo.cc
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/audio_block_fifo.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-AudioBlockFifo::AudioBlockFifo(int channels, int frames, int blocks)
- : channels_(channels),
- block_frames_(frames),
- write_block_(0),
- read_block_(0),
- available_blocks_(0),
- write_pos_(0) {
- IncreaseCapacity(blocks);
-}
-
-AudioBlockFifo::~AudioBlockFifo() {}
-
-void AudioBlockFifo::Push(const void* source, int frames,
- int bytes_per_sample) {
- DCHECK(source);
- DCHECK_GT(frames, 0);
- DCHECK_GT(bytes_per_sample, 0);
- DCHECK_LT(available_blocks_, static_cast<int>(audio_blocks_.size()));
- CHECK_LE(frames, GetUnfilledFrames());
-
- const uint8_t* source_ptr = static_cast<const uint8_t*>(source);
- int frames_to_push = frames;
- while (frames_to_push) {
- // Get the current write block.
- AudioBus* current_block = audio_blocks_[write_block_];
-
- // Figure out what segment sizes we need when adding the new content to
- // the FIFO.
- const int push_frames =
- std::min(block_frames_ - write_pos_, frames_to_push);
-
- // Deinterleave the content to the FIFO and update the |write_pos_|.
- current_block->FromInterleavedPartial(source_ptr, write_pos_, push_frames,
- bytes_per_sample);
- write_pos_ = (write_pos_ + push_frames) % block_frames_;
- if (!write_pos_) {
- // The current block is completely filled, increment |write_block_| and
- // |available_blocks_|.
- write_block_ = (write_block_ + 1) % audio_blocks_.size();
- ++available_blocks_;
- }
-
- source_ptr += push_frames * bytes_per_sample * channels_;
- frames_to_push -= push_frames;
- DCHECK_GE(frames_to_push, 0);
- }
-}
-
-const AudioBus* AudioBlockFifo::Consume() {
- DCHECK(available_blocks_);
- AudioBus* audio_bus = audio_blocks_[read_block_];
- read_block_ = (read_block_ + 1) % audio_blocks_.size();
- --available_blocks_;
- return audio_bus;
-}
-
-void AudioBlockFifo::Clear() {
- write_pos_ = 0;
- write_block_ = 0;
- read_block_ = 0;
- available_blocks_ = 0;
-}
-
-int AudioBlockFifo::GetAvailableFrames() const {
- return available_blocks_ * block_frames_ + write_pos_;
-}
-
-int AudioBlockFifo::GetUnfilledFrames() const {
- const int unfilled_frames =
- (audio_blocks_.size() - available_blocks_ * block_frames_ - write_pos_);
- DCHECK_GE(unfilled_frames, 0);
- return unfilled_frames;
-}
-
-void AudioBlockFifo::IncreaseCapacity(int blocks) {
- DCHECK_GT(blocks, 0);
-
- // Create |blocks| of audio buses and insert them to the containers.
- audio_blocks_.reserve(audio_blocks_.size() + blocks);
-
- const int original_size = audio_blocks_.size();
- for (int i = 0; i < blocks; ++i) {
- audio_blocks_.push_back(
- AudioBus::Create(channels_, block_frames_).release());
- }
-
- if (!original_size) return;
-
- std::rotate(audio_blocks_.begin() + read_block_,
- audio_blocks_.begin() + original_size, audio_blocks_.end());
-
- // Update the write pointer if it is on top of the new inserted blocks.
- if (write_block_ >= read_block_) write_block_ += blocks;
-
- // Update the read pointers correspondingly.
- read_block_ += blocks;
-
- DCHECK_LT(read_block_, static_cast<int>(audio_blocks_.size()));
- DCHECK_LT(write_block_, static_cast<int>(audio_blocks_.size()));
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_block_fifo.h b/src/cobalt/media/base/audio_block_fifo.h
deleted file mode 100644
index 5eb2bdf..0000000
--- a/src/cobalt/media/base/audio_block_fifo.h
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_BLOCK_FIFO_H_
-#define COBALT_MEDIA_BASE_AUDIO_BLOCK_FIFO_H_
-
-#include "base/basictypes.h"
-#include "base/memory/scoped_vector.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-// First-in first-out container for AudioBus elements.
-// The FIFO is composed of blocks of AudioBus elements, it accepts interleaved
-// data as input and will deinterleave it into the FIFO, and it only allows
-// consuming a whole block of AudioBus element.
-// This class is thread-unsafe.
-class MEDIA_EXPORT AudioBlockFifo {
- public:
- // Creates a new AudioBlockFifo and allocates |blocks| memory, each block
- // of memory can store |channels| of length |frames| data.
- AudioBlockFifo(int channels, int frames, int blocks);
- virtual ~AudioBlockFifo();
-
- // Pushes interleaved audio data from |source| to the FIFO.
- // The method will deinterleave the data into a audio bus.
- // Push() will crash if the allocated space is insufficient.
- void Push(const void* source, int frames, int bytes_per_sample);
-
- // Consumes a block of audio from the FIFO. Returns an AudioBus which
- // contains the consumed audio data to avoid copying.
- // Consume() will crash if the FIFO does not contain a block of data.
- const AudioBus* Consume();
-
- // Empties the FIFO without deallocating any memory.
- void Clear();
-
- // Number of available block of memory ready to be consumed in the FIFO.
- int available_blocks() const { return available_blocks_; }
-
- // Number of available frames of data in the FIFO.
- int GetAvailableFrames() const;
-
- // Number of unfilled frames in the whole FIFO.
- int GetUnfilledFrames() const;
-
- // Dynamically increase |blocks| of memory to the FIFO.
- void IncreaseCapacity(int blocks);
-
- private:
- // The actual FIFO is a vector of audio buses.
- ScopedVector<AudioBus> audio_blocks_;
-
- // Number of channels in AudioBus.
- const int channels_;
-
- // Maximum number of frames of data one block of memory can contain.
- // This value is set by |frames| in the constructor.
- const int block_frames_;
-
- // Used to keep track which block of memory to be written.
- int write_block_;
-
- // Used to keep track which block of memory to be consumed.
- int read_block_;
-
- // Number of available blocks of memory to be consumed.
- int available_blocks_;
-
- // Current write position in the current written block.
- int write_pos_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioBlockFifo);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_BLOCK_FIFO_H_
diff --git a/src/cobalt/media/base/audio_buffer.cc b/src/cobalt/media/base/audio_buffer.cc
deleted file mode 100644
index dec746f..0000000
--- a/src/cobalt/media/base/audio_buffer.cc
+++ /dev/null
@@ -1,276 +0,0 @@
-// 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 "cobalt/media/base/audio_buffer.h"
-
-#include <cmath>
-#include <limits>
-
-#include "base/logging.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/limits.h"
-#include "cobalt/media/base/timestamp_constants.h"
-#include "starboard/memory.h"
-
-namespace cobalt {
-namespace media {
-
-static base::TimeDelta CalculateDuration(int frames, double sample_rate) {
- DCHECK_GT(sample_rate, 0);
- return base::TimeDelta::FromMicroseconds(
- frames * base::Time::kMicrosecondsPerSecond / sample_rate);
-}
-
-AudioBuffer::AudioBuffer(SampleFormat sample_format,
- ChannelLayout channel_layout, int channel_count,
- int sample_rate, int frame_count, bool create_buffer,
- const uint8_t* const* data,
- const base::TimeDelta timestamp)
- : sample_format_(sample_format),
- channel_layout_(channel_layout),
- channel_count_(channel_count),
- sample_rate_(sample_rate),
- adjusted_frame_count_(frame_count),
- end_of_stream_(!create_buffer && data == NULL && frame_count == 0),
- timestamp_(timestamp),
- duration_(end_of_stream_
- ? base::TimeDelta()
- : CalculateDuration(adjusted_frame_count_, sample_rate_)),
- data_size_(0) {
- CHECK_GE(channel_count_, 0);
- CHECK_LE(channel_count_, limits::kMaxChannels);
- CHECK_GE(frame_count, 0);
- DCHECK(channel_layout == CHANNEL_LAYOUT_DISCRETE ||
- ChannelLayoutToChannelCount(channel_layout) == channel_count);
-
- int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format);
- DCHECK_LE(bytes_per_channel, kChannelAlignment);
-
- // Empty buffer?
- if (!create_buffer) return;
-
- int data_size_per_channel = frame_count * bytes_per_channel;
- if (IsPlanar(sample_format)) {
- // Planar data, so need to allocate buffer for each channel.
- // Determine per channel data size, taking into account alignment.
- int block_size_per_channel =
- (data_size_per_channel + kChannelAlignment - 1) &
- ~(kChannelAlignment - 1);
- DCHECK_GE(block_size_per_channel, data_size_per_channel);
-
- // Allocate a contiguous buffer for all the channel data.
- data_size_ = channel_count_ * block_size_per_channel;
- data_.reset(static_cast<uint8_t*>(
- base::AlignedAlloc(data_size_, kChannelAlignment)));
- channel_data_.reserve(channel_count_);
-
- // Copy each channel's data into the appropriate spot.
- for (int i = 0; i < channel_count_; ++i) {
- channel_data_.push_back(data_.get() + i * block_size_per_channel);
- if (data) SbMemoryCopy(channel_data_[i], data[i], data_size_per_channel);
- }
- return;
- }
-
- // Remaining formats are interleaved data.
- DCHECK(IsInterleaved(sample_format)) << sample_format_;
- // Allocate our own buffer and copy the supplied data into it. Buffer must
- // contain the data for all channels.
- data_size_ = data_size_per_channel * channel_count_;
- data_.reset(
- static_cast<uint8_t*>(base::AlignedAlloc(data_size_, kChannelAlignment)));
- channel_data_.reserve(1);
- channel_data_.push_back(data_.get());
- if (data) SbMemoryCopy(data_.get(), data[0], data_size_);
-}
-
-AudioBuffer::~AudioBuffer() {}
-
-// static
-scoped_refptr<AudioBuffer> AudioBuffer::CopyFrom(
- SampleFormat sample_format, ChannelLayout channel_layout, int channel_count,
- int sample_rate, int frame_count, const uint8_t* const* data,
- const base::TimeDelta timestamp) {
- // If you hit this CHECK you likely have a bug in a demuxer. Go fix it.
- CHECK_GT(frame_count, 0); // Otherwise looks like an EOF buffer.
- CHECK(data[0]);
- return make_scoped_refptr(
- new AudioBuffer(sample_format, channel_layout, channel_count, sample_rate,
- frame_count, true, data, timestamp));
-}
-
-// static
-scoped_refptr<AudioBuffer> AudioBuffer::CreateBuffer(
- SampleFormat sample_format, ChannelLayout channel_layout, int channel_count,
- int sample_rate, int frame_count) {
- CHECK_GT(frame_count, 0); // Otherwise looks like an EOF buffer.
- return make_scoped_refptr(
- new AudioBuffer(sample_format, channel_layout, channel_count, sample_rate,
- frame_count, true, NULL, kNoTimestamp));
-}
-
-// static
-scoped_refptr<AudioBuffer> AudioBuffer::CreateEmptyBuffer(
- ChannelLayout channel_layout, int channel_count, int sample_rate,
- int frame_count, const base::TimeDelta timestamp) {
- CHECK_GT(frame_count, 0); // Otherwise looks like an EOF buffer.
- // Since data == NULL, format doesn't matter.
- return make_scoped_refptr(
- new AudioBuffer(kSampleFormatF32, channel_layout, channel_count,
- sample_rate, frame_count, false, NULL, timestamp));
-}
-
-// static
-scoped_refptr<AudioBuffer> AudioBuffer::CreateEOSBuffer() {
- return make_scoped_refptr(new AudioBuffer(kUnknownSampleFormat,
- CHANNEL_LAYOUT_NONE, 0, 0, 0, false,
- NULL, kNoTimestamp));
-}
-
-// Convert int16_t values in the range [INT16_MIN, INT16_MAX] to [-1.0, 1.0].
-inline float ConvertSample(int16_t value) {
- return value * (value < 0 ? -1.0f / std::numeric_limits<int16_t>::min()
- : 1.0f / std::numeric_limits<int16_t>::max());
-}
-
-void AudioBuffer::AdjustSampleRate(int sample_rate) {
- DCHECK(!end_of_stream_);
- sample_rate_ = sample_rate;
- duration_ = CalculateDuration(adjusted_frame_count_, sample_rate_);
-}
-
-void AudioBuffer::ReadFrames(int frames_to_copy, int source_frame_offset,
- int dest_frame_offset, AudioBus* dest) {
- // Deinterleave each channel (if necessary) and convert to 32bit
- // floating-point with nominal range -1.0 -> +1.0 (if necessary).
-
- // |dest| must have the same number of channels, and the number of frames
- // specified must be in range.
- DCHECK(!end_of_stream());
- DCHECK_EQ(dest->channels(), channel_count_);
- DCHECK_LE(source_frame_offset + frames_to_copy, adjusted_frame_count_);
- DCHECK_LE(dest_frame_offset + frames_to_copy, dest->frames());
-
- if (!data_) {
- // Special case for an empty buffer.
- dest->ZeroFramesPartial(dest_frame_offset, frames_to_copy);
- return;
- }
-
- if (sample_format_ == kSampleFormatPlanarF32) {
- // Format is planar float32. Copy the data from each channel as a block.
- for (int ch = 0; ch < channel_count_; ++ch) {
- const float* source_data =
- reinterpret_cast<const float*>(channel_data_[ch]) +
- source_frame_offset;
- SbMemoryCopy(dest->channel(ch) + dest_frame_offset, source_data,
- sizeof(float) * frames_to_copy);
- }
- return;
- }
-
- if (sample_format_ == kSampleFormatPlanarS16) {
- // Format is planar signed16. Convert each value into float and insert into
- // output channel data.
- for (int ch = 0; ch < channel_count_; ++ch) {
- const int16_t* source_data =
- reinterpret_cast<const int16_t*>(channel_data_[ch]) +
- source_frame_offset;
- float* dest_data = dest->channel(ch) + dest_frame_offset;
- for (int i = 0; i < frames_to_copy; ++i) {
- dest_data[i] = ConvertSample(source_data[i]);
- }
- }
- return;
- }
-
- if (sample_format_ == kSampleFormatF32) {
- // Format is interleaved float32. Copy the data into each channel.
- const float* source_data = reinterpret_cast<const float*>(data_.get()) +
- source_frame_offset * channel_count_;
- for (int ch = 0; ch < channel_count_; ++ch) {
- float* dest_data = dest->channel(ch) + dest_frame_offset;
- for (int i = 0, offset = ch; i < frames_to_copy;
- ++i, offset += channel_count_) {
- dest_data[i] = source_data[offset];
- }
- }
- return;
- }
-
- // Remaining formats are integer interleaved data. Use the deinterleaving code
- // in AudioBus to copy the data.
- DCHECK(
- sample_format_ == kSampleFormatU8 || sample_format_ == kSampleFormatS16 ||
- sample_format_ == kSampleFormatS24 || sample_format_ == kSampleFormatS32);
- int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format_);
- int frame_size = channel_count_ * bytes_per_channel;
- const uint8_t* source_data = data_.get() + source_frame_offset * frame_size;
- dest->FromInterleavedPartial(source_data, dest_frame_offset, frames_to_copy,
- bytes_per_channel);
-}
-
-void AudioBuffer::TrimStart(int frames_to_trim) {
- CHECK_GE(frames_to_trim, 0);
- CHECK_LE(frames_to_trim, adjusted_frame_count_);
-
- TrimRange(0, frames_to_trim);
-}
-
-void AudioBuffer::TrimEnd(int frames_to_trim) {
- CHECK_GE(frames_to_trim, 0);
- CHECK_LE(frames_to_trim, adjusted_frame_count_);
-
- // Adjust the number of frames and duration for this buffer.
- adjusted_frame_count_ -= frames_to_trim;
- duration_ = CalculateDuration(adjusted_frame_count_, sample_rate_);
-}
-
-void AudioBuffer::TrimRange(int start, int end) {
- CHECK_GE(start, 0);
- CHECK_LE(end, adjusted_frame_count_);
-
- const int frames_to_trim = end - start;
- CHECK_GE(frames_to_trim, 0);
- CHECK_LE(frames_to_trim, adjusted_frame_count_);
-
- const int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format_);
- const int frames_to_copy = adjusted_frame_count_ - end;
- if (frames_to_copy > 0) {
- switch (sample_format_) {
- case kSampleFormatPlanarS16:
- case kSampleFormatPlanarF32:
- case kSampleFormatPlanarS32:
- // Planar data must be shifted per channel.
- for (int ch = 0; ch < channel_count_; ++ch) {
- SbMemoryMove(channel_data_[ch] + start * bytes_per_channel,
- channel_data_[ch] + end * bytes_per_channel,
- bytes_per_channel * frames_to_copy);
- }
- break;
- case kSampleFormatU8:
- case kSampleFormatS16:
- case kSampleFormatS24:
- case kSampleFormatS32:
- case kSampleFormatF32: {
- // Interleaved data can be shifted all at once.
- const int frame_size = channel_count_ * bytes_per_channel;
- SbMemoryMove(channel_data_[0] + start * frame_size,
- channel_data_[0] + end * frame_size,
- frame_size * frames_to_copy);
- break;
- }
- case kUnknownSampleFormat:
- NOTREACHED() << "Invalid sample format!";
- }
- } else {
- CHECK_EQ(frames_to_copy, 0);
- }
-
- // Trim the leftover data off the end of the buffer and update duration.
- TrimEnd(frames_to_trim);
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_buffer.h b/src/cobalt/media/base/audio_buffer.h
deleted file mode 100644
index a5e3d03..0000000
--- a/src/cobalt/media/base/audio_buffer.h
+++ /dev/null
@@ -1,175 +0,0 @@
-// 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_BUFFER_H_
-#define COBALT_MEDIA_BASE_AUDIO_BUFFER_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/memory/aligned_memory.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/time.h"
-#include "cobalt/media/base/channel_layout.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/sample_format.h"
-#include "starboard/types.h"
-
-namespace mojo {
-template <typename T, typename U>
-struct TypeConverter;
-template <typename T>
-class StructPtr;
-};
-
-namespace cobalt {
-namespace media {
-class AudioBus;
-
-namespace mojom {
-class AudioBuffer;
-}
-
-// An audio buffer that takes a copy of the data passed to it, holds it, and
-// copies it into an AudioBus when needed. Also supports an end of stream
-// marker.
-class MEDIA_EXPORT AudioBuffer
- : public base::RefCountedThreadSafe<AudioBuffer> {
- public:
- // Alignment of each channel's data; this must match what ffmpeg expects
- // (which may be 0, 16, or 32, depending on the processor). Selecting 32 in
- // order to work on all processors.
- enum { kChannelAlignment = 32 };
-
- // Create an AudioBuffer whose channel data is copied from |data|. For
- // interleaved data, only the first buffer is used. For planar data, the
- // number of buffers must be equal to |channel_count|. |frame_count| is the
- // number of frames in each buffer. |data| must not be null and |frame_count|
- // must be >= 0.
- static scoped_refptr<AudioBuffer> CopyFrom(SampleFormat sample_format,
- ChannelLayout channel_layout,
- int channel_count, int sample_rate,
- int frame_count,
- const uint8_t* const* data,
- const base::TimeDelta timestamp);
-
- // Create an AudioBuffer with |frame_count| frames. Buffer is allocated, but
- // not initialized. Timestamp and duration are set to kNoTimestamp.
- static scoped_refptr<AudioBuffer> CreateBuffer(SampleFormat sample_format,
- ChannelLayout channel_layout,
- int channel_count,
- int sample_rate,
- int frame_count);
-
- // Create an empty AudioBuffer with |frame_count| frames.
- static scoped_refptr<AudioBuffer> CreateEmptyBuffer(
- ChannelLayout channel_layout, int channel_count, int sample_rate,
- int frame_count, const base::TimeDelta timestamp);
-
- // Create a AudioBuffer indicating we've reached end of stream.
- // Calling any method other than end_of_stream() on the resulting buffer
- // is disallowed.
- static scoped_refptr<AudioBuffer> CreateEOSBuffer();
-
- // Update sample rate and computed duration.
- // TODO(chcunningham): Remove this upon patching FFmpeg's AAC decoder to
- // provide the correct sample rate at the boundary of an implicit config
- // change.
- void AdjustSampleRate(int sample_rate);
-
- // Copy frames into |dest|. |frames_to_copy| is the number of frames to copy.
- // |source_frame_offset| specifies how many frames in the buffer to skip
- // first. |dest_frame_offset| is the frame offset in |dest|. The frames are
- // converted from their source format into planar float32 data (which is all
- // that AudioBus handles).
- void ReadFrames(int frames_to_copy, int source_frame_offset,
- int dest_frame_offset, AudioBus* dest);
-
- // Trim an AudioBuffer by removing |frames_to_trim| frames from the start.
- // Timestamp and duration are adjusted to reflect the fewer frames.
- // Note that repeated calls to TrimStart() may result in timestamp() and
- // duration() being off by a few microseconds due to rounding issues.
- void TrimStart(int frames_to_trim);
-
- // Trim an AudioBuffer by removing |frames_to_trim| frames from the end.
- // Duration is adjusted to reflect the fewer frames.
- void TrimEnd(int frames_to_trim);
-
- // Trim an AudioBuffer by removing |end - start| frames from [|start|, |end|).
- // Even if |start| is zero, timestamp() is not adjusted, only duration().
- void TrimRange(int start, int end);
-
- // Return the number of channels.
- int channel_count() const { return channel_count_; }
-
- // Return the number of frames held.
- int frame_count() const { return adjusted_frame_count_; }
-
- // Return the sample rate.
- int sample_rate() const { return sample_rate_; }
-
- // Return the channel layout.
- ChannelLayout channel_layout() const { return channel_layout_; }
-
- base::TimeDelta timestamp() const { return timestamp_; }
- base::TimeDelta duration() const { return duration_; }
- void set_timestamp(base::TimeDelta timestamp) { timestamp_ = timestamp; }
-
- // If there's no data in this buffer, it represents end of stream.
- bool end_of_stream() const { return end_of_stream_; }
-
- // Access to the raw buffer for ffmpeg and Android MediaCodec decoders to
- // write directly to. For planar formats the vector elements correspond to
- // the channels. For interleaved formats the resulting vector has exactly
- // one element which contains the buffer pointer.
- const std::vector<uint8_t*>& channel_data() const { return channel_data_; }
-
- // The size of allocated data memory block. For planar formats channels go
- // sequentially in this block.
- size_t data_size() const { return data_size_; }
-
- private:
- friend class base::RefCountedThreadSafe<AudioBuffer>;
-
- // mojo::TypeConverter added as a friend so that AudioBuffer can be
- // transferred across a mojo connection.
- friend struct mojo::TypeConverter<mojo::StructPtr<mojom::AudioBuffer>,
- scoped_refptr<AudioBuffer> >;
-
- // Allocates aligned contiguous buffer to hold all channel data (1 block for
- // interleaved data, |channel_count| blocks for planar data), copies
- // [data,data+data_size) to the allocated buffer(s). If |data| is null, no
- // data is copied. If |create_buffer| is false, no data buffer is created (or
- // copied to).
- AudioBuffer(SampleFormat sample_format, ChannelLayout channel_layout,
- int channel_count, int sample_rate, int frame_count,
- bool create_buffer, const uint8_t* const* data,
- const base::TimeDelta timestamp);
-
- virtual ~AudioBuffer();
-
- const SampleFormat sample_format_;
- const ChannelLayout channel_layout_;
- const int channel_count_;
- int sample_rate_;
- int adjusted_frame_count_;
- const bool end_of_stream_;
- base::TimeDelta timestamp_;
- base::TimeDelta duration_;
-
- // Contiguous block of channel data.
- scoped_ptr_malloc<uint8_t, base::ScopedPtrAlignedFree> data_;
- size_t data_size_;
-
- // For planar data, points to each channels data.
- std::vector<uint8_t*> channel_data_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(AudioBuffer);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_BUFFER_H_
diff --git a/src/cobalt/media/base/audio_buffer_converter.cc b/src/cobalt/media/base/audio_buffer_converter.cc
deleted file mode 100644
index 2aa57fd..0000000
--- a/src/cobalt/media/base/audio_buffer_converter.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/audio_buffer_converter.h"
-
-#include <algorithm>
-#include <cmath>
-
-#include "base/logging.h"
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_decoder_config.h"
-#include "cobalt/media/base/audio_timestamp_helper.h"
-#include "cobalt/media/base/sinc_resampler.h"
-#include "cobalt/media/base/timestamp_constants.h"
-#include "cobalt/media/base/vector_math.h"
-
-namespace cobalt {
-namespace media {
-
-// Is the config presented by |buffer| a config change from |params|?
-static bool IsConfigChange(const AudioParameters& params,
- const scoped_refptr<AudioBuffer>& buffer) {
- return buffer->sample_rate() != params.sample_rate() ||
- buffer->channel_count() != params.channels() ||
- buffer->channel_layout() != params.channel_layout();
-}
-
-AudioBufferConverter::AudioBufferConverter(const AudioParameters& output_params)
- : output_params_(output_params),
- input_params_(output_params),
- last_input_buffer_offset_(0),
- input_frames_(0),
- buffered_input_frames_(0.0),
- io_sample_rate_ratio_(1.0),
- timestamp_helper_(output_params_.sample_rate()),
- is_flushing_(false) {}
-
-AudioBufferConverter::~AudioBufferConverter() {}
-
-void AudioBufferConverter::AddInput(const scoped_refptr<AudioBuffer>& buffer) {
- // On EOS flush any remaining buffered data.
- if (buffer->end_of_stream()) {
- Flush();
- queued_outputs_.push_back(buffer);
- return;
- }
-
- // We'll need a new |audio_converter_| if there was a config change.
- if (IsConfigChange(input_params_, buffer)) ResetConverter(buffer);
-
- // Pass straight through if there's no work to be done.
- if (!audio_converter_) {
- queued_outputs_.push_back(buffer);
- return;
- }
-
- if (timestamp_helper_.base_timestamp() == kNoTimestamp)
- timestamp_helper_.SetBaseTimestamp(buffer->timestamp());
-
- queued_inputs_.push_back(buffer);
- input_frames_ += buffer->frame_count();
-
- ConvertIfPossible();
-}
-
-bool AudioBufferConverter::HasNextBuffer() { return !queued_outputs_.empty(); }
-
-scoped_refptr<AudioBuffer> AudioBufferConverter::GetNextBuffer() {
- DCHECK(!queued_outputs_.empty());
- scoped_refptr<AudioBuffer> out = queued_outputs_.front();
- queued_outputs_.pop_front();
- return out;
-}
-
-void AudioBufferConverter::Reset() {
- audio_converter_.reset();
- queued_inputs_.clear();
- queued_outputs_.clear();
- timestamp_helper_.SetBaseTimestamp(kNoTimestamp);
- input_params_ = output_params_;
- input_frames_ = 0;
- buffered_input_frames_ = 0.0;
- last_input_buffer_offset_ = 0;
-}
-
-void AudioBufferConverter::ResetTimestampState() {
- Flush();
- timestamp_helper_.SetBaseTimestamp(kNoTimestamp);
-}
-
-double AudioBufferConverter::ProvideInput(AudioBus* audio_bus,
- uint32_t frames_delayed) {
- DCHECK(is_flushing_ || input_frames_ >= audio_bus->frames());
-
- int requested_frames_left = audio_bus->frames();
- int dest_index = 0;
-
- while (requested_frames_left > 0 && !queued_inputs_.empty()) {
- scoped_refptr<AudioBuffer> input_buffer = queued_inputs_.front();
-
- int frames_to_read =
- std::min(requested_frames_left,
- input_buffer->frame_count() - last_input_buffer_offset_);
- input_buffer->ReadFrames(frames_to_read, last_input_buffer_offset_,
- dest_index, audio_bus);
- last_input_buffer_offset_ += frames_to_read;
-
- if (last_input_buffer_offset_ == input_buffer->frame_count()) {
- // We've consumed all the frames in |input_buffer|.
- queued_inputs_.pop_front();
- last_input_buffer_offset_ = 0;
- }
-
- requested_frames_left -= frames_to_read;
- dest_index += frames_to_read;
- }
-
- // If we're flushing, zero any extra space, otherwise we should always have
- // enough data to completely fulfill the request.
- if (is_flushing_ && requested_frames_left > 0) {
- audio_bus->ZeroFramesPartial(audio_bus->frames() - requested_frames_left,
- requested_frames_left);
- } else {
- DCHECK_EQ(requested_frames_left, 0);
- }
-
- input_frames_ -= audio_bus->frames() - requested_frames_left;
- DCHECK_GE(input_frames_, 0);
-
- buffered_input_frames_ += audio_bus->frames() - requested_frames_left;
-
- // Full volume.
- return 1.0;
-}
-
-void AudioBufferConverter::ResetConverter(
- const scoped_refptr<AudioBuffer>& buffer) {
- Flush();
- audio_converter_.reset();
- input_params_.Reset(
- input_params_.format(), buffer->channel_layout(), buffer->sample_rate(),
- input_params_.bits_per_sample(),
- // If resampling is needed and the FIFO disabled, the AudioConverter will
- // always request SincResampler::kDefaultRequestSize frames. Otherwise it
- // will use the output frame size.
- buffer->sample_rate() == output_params_.sample_rate()
- ? output_params_.frames_per_buffer()
- : SincResampler::kDefaultRequestSize);
- input_params_.set_channels_for_discrete(buffer->channel_count());
-
- io_sample_rate_ratio_ = static_cast<double>(input_params_.sample_rate()) /
- output_params_.sample_rate();
-
- // If |buffer| matches |output_params_| we don't need an AudioConverter at
- // all, and can early-out here.
- if (!IsConfigChange(output_params_, buffer)) return;
-
- // Note: The FIFO is disabled to avoid extraneous memcpy().
- audio_converter_.reset(
- new AudioConverter(input_params_, output_params_, true));
- audio_converter_->AddInput(this);
-}
-
-void AudioBufferConverter::ConvertIfPossible() {
- DCHECK(audio_converter_);
-
- int request_frames = 0;
-
- if (is_flushing_) {
- // If we're flushing we want to convert *everything* even if this means
- // we'll have to pad some silence in ProvideInput().
- request_frames =
- ceil((buffered_input_frames_ + input_frames_) / io_sample_rate_ratio_);
- } else {
- // How many calls to ProvideInput() we can satisfy completely.
- int chunks = input_frames_ / input_params_.frames_per_buffer();
-
- // How many output frames that corresponds to:
- request_frames = chunks * audio_converter_->ChunkSize();
- }
-
- if (!request_frames) return;
-
- scoped_refptr<AudioBuffer> output_buffer = AudioBuffer::CreateBuffer(
- kSampleFormatPlanarF32, output_params_.channel_layout(),
- output_params_.channels(), output_params_.sample_rate(), request_frames);
- std::unique_ptr<AudioBus> output_bus =
- AudioBus::CreateWrapper(output_buffer->channel_count());
-
- int frames_remaining = request_frames;
-
- // The AudioConverter wants requests of a fixed size, so we'll slide an
- // AudioBus of that size across the |output_buffer|.
- while (frames_remaining != 0) {
- // It's important that this is a multiple of AudioBus::kChannelAlignment in
- // all requests except for the last, otherwise downstream SIMD optimizations
- // will crash on unaligned data.
- const int frames_this_iteration = std::min(
- static_cast<int>(SincResampler::kDefaultRequestSize), frames_remaining);
- const int offset_into_buffer =
- output_buffer->frame_count() - frames_remaining;
-
- // Wrap the portion of the AudioBuffer in an AudioBus so the AudioConverter
- // can fill it.
- output_bus->set_frames(frames_this_iteration);
- for (int ch = 0; ch < output_buffer->channel_count(); ++ch) {
- output_bus->SetChannelData(
- ch, reinterpret_cast<float*>(output_buffer->channel_data()[ch]) +
- offset_into_buffer);
- }
-
- // Do the actual conversion.
- audio_converter_->Convert(output_bus.get());
- frames_remaining -= frames_this_iteration;
- buffered_input_frames_ -= frames_this_iteration * io_sample_rate_ratio_;
- }
-
- // Compute the timestamp.
- output_buffer->set_timestamp(timestamp_helper_.GetTimestamp());
- timestamp_helper_.AddFrames(request_frames);
-
- queued_outputs_.push_back(output_buffer);
-}
-
-void AudioBufferConverter::Flush() {
- if (!audio_converter_) return;
- is_flushing_ = true;
- ConvertIfPossible();
- is_flushing_ = false;
- audio_converter_->Reset();
- DCHECK_EQ(input_frames_, 0);
- DCHECK_EQ(last_input_buffer_offset_, 0);
- DCHECK_LT(buffered_input_frames_, 1.0);
- DCHECK(queued_inputs_.empty());
- buffered_input_frames_ = 0.0;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_buffer_converter.h b/src/cobalt/media/base/audio_buffer_converter.h
deleted file mode 100644
index ea118c4..0000000
--- a/src/cobalt/media/base/audio_buffer_converter.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_BUFFER_CONVERTER_H_
-#define COBALT_MEDIA_BASE_AUDIO_BUFFER_CONVERTER_H_
-
-#include <deque>
-#include <memory>
-
-#include "base/memory/ref_counted.h"
-#include "base/time.h"
-#include "cobalt/media/base/audio_converter.h"
-#include "cobalt/media/base/audio_parameters.h"
-#include "cobalt/media/base/audio_timestamp_helper.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-class AudioBuffer;
-class AudioBus;
-
-// Takes AudioBuffers in any format and uses an AudioConverter to convert them
-// to a common format (usually the hardware output format).
-class MEDIA_EXPORT AudioBufferConverter : public AudioConverter::InputCallback {
- public:
- explicit AudioBufferConverter(const AudioParameters& output_params);
- ~AudioBufferConverter() OVERRIDE;
-
- void AddInput(const scoped_refptr<AudioBuffer>& buffer);
-
- // Is an output buffer available via GetNextBuffer()?
- bool HasNextBuffer();
-
- // This should only be called this is HasNextBuffer() returns true.
- scoped_refptr<AudioBuffer> GetNextBuffer();
-
- // Reset internal state.
- void Reset();
-
- // Reset internal timestamp state. Upon the next AddInput() call, our base
- // timestamp will be set to match the input buffer.
- void ResetTimestampState();
-
- int input_buffer_size_for_testing() const {
- return input_params_.frames_per_buffer();
- }
- int input_frames_left_for_testing() const { return input_frames_; }
-
- private:
- // Callback to provide data to the AudioConverter
- double ProvideInput(AudioBus* audio_bus, uint32_t frames_delayed) OVERRIDE;
-
- // Reset the converter in response to a configuration change.
- void ResetConverter(const scoped_refptr<AudioBuffer>& input_buffer);
-
- // Perform conversion if we have enough data.
- void ConvertIfPossible();
-
- // Flush remaining output
- void Flush();
-
- // The output parameters.
- AudioParameters output_params_;
-
- // The current input parameters (we cache these to detect configuration
- // changes, so we know when to reset the AudioConverter).
- AudioParameters input_params_;
-
- typedef std::deque<scoped_refptr<AudioBuffer> > BufferQueue;
-
- // Queued up inputs (there will never be all that much data stored here, as
- // soon as there's enough here to produce an output buffer we will do so).
- BufferQueue queued_inputs_;
-
- // Offset into the front element of |queued_inputs_|. A ProvideInput() call
- // doesn't necessarily always consume an entire buffer.
- int last_input_buffer_offset_;
-
- // Buffer of output frames, to be returned by GetNextBuffer().
- BufferQueue queued_outputs_;
-
- // How many frames of input we have in |queued_inputs_|.
- int input_frames_;
-
- // Input frames in the AudioConverter's internal buffers.
- double buffered_input_frames_;
-
- // Ratio of sample rates, in/out.
- double io_sample_rate_ratio_;
-
- // Computes timestamps in terms of the output sample rate.
- AudioTimestampHelper timestamp_helper_;
-
- // Are we flushing everything, without regard for providing AudioConverter
- // full AudioBuses in ProvideInput()?
- bool is_flushing_;
-
- // The AudioConverter which does the real work here.
- std::unique_ptr<AudioConverter> audio_converter_;
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_BUFFER_CONVERTER_H_
diff --git a/src/cobalt/media/base/audio_buffer_converter_unittest.cc b/src/cobalt/media/base/audio_buffer_converter_unittest.cc
deleted file mode 100644
index 408e95a..0000000
--- a/src/cobalt/media/base/audio_buffer_converter_unittest.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/audio_buffer_converter.h"
-
-#include <memory>
-
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/sinc_resampler.h"
-#include "cobalt/media/base/test_helpers.h"
-#include "starboard/types.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-// Important: Use an odd buffer size here so SIMD issues are caught.
-const int kOutFrameSize = 441;
-const int kOutSampleRate = 44100;
-const ChannelLayout kOutChannelLayout = CHANNEL_LAYOUT_STEREO;
-const int kOutChannelCount = 2;
-
-static scoped_refptr<AudioBuffer> MakeTestBuffer(int sample_rate,
- ChannelLayout channel_layout,
- int channel_count,
- int frames) {
- return MakeAudioBuffer<uint8_t>(kSampleFormatU8, channel_layout,
- channel_count, sample_rate, 0, 1, frames,
- base::TimeDelta::FromSeconds(0));
-}
-
-class AudioBufferConverterTest : public ::testing::Test {
- public:
- AudioBufferConverterTest()
- : input_frames_(0),
- expected_output_frames_(0.0),
- output_frames_(0),
- output_params_(AudioParameters::AUDIO_PCM_LOW_LATENCY,
- kOutChannelLayout, kOutSampleRate, 16, kOutFrameSize) {
- audio_buffer_converter_.reset(new AudioBufferConverter(output_params_));
- }
-
- void Reset() {
- audio_buffer_converter_->Reset();
- output_frames_ = expected_output_frames_ = input_frames_ = 0;
- }
-
- void AddInput(const scoped_refptr<AudioBuffer>& in) {
- if (!in->end_of_stream()) {
- input_frames_ += in->frame_count();
- expected_output_frames_ +=
- in->frame_count() *
- (static_cast<double>(output_params_.sample_rate()) /
- in->sample_rate());
- }
- audio_buffer_converter_->AddInput(in);
- }
-
- void ConsumeOutput() {
- ASSERT_TRUE(audio_buffer_converter_->HasNextBuffer());
- scoped_refptr<AudioBuffer> out = audio_buffer_converter_->GetNextBuffer();
- if (!out->end_of_stream()) {
- output_frames_ += out->frame_count();
- EXPECT_EQ(out->sample_rate(), output_params_.sample_rate());
- EXPECT_EQ(out->channel_layout(), output_params_.channel_layout());
- EXPECT_EQ(out->channel_count(), output_params_.channels());
- } else {
- EXPECT_FALSE(audio_buffer_converter_->HasNextBuffer());
- }
- }
-
- void ConsumeAllOutput() {
- AddInput(AudioBuffer::CreateEOSBuffer());
- while (audio_buffer_converter_->HasNextBuffer()) ConsumeOutput();
- EXPECT_EQ(output_frames_, ceil(expected_output_frames_));
- }
-
- protected:
- std::unique_ptr<AudioBufferConverter> audio_buffer_converter_;
-
- int input_frames_;
- double expected_output_frames_;
- int output_frames_;
- int input_buffers_;
- AudioParameters output_params_;
-};
-
-TEST_F(AudioBufferConverterTest, PassThrough) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(kOutSampleRate, kOutChannelLayout, kOutChannelCount, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, Downsample) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(48000, kOutChannelLayout, kOutChannelCount, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, Upsample) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(8000, kOutChannelLayout, kOutChannelCount, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-// Test resampling a buffer smaller than the SincResampler's kernel size.
-TEST_F(AudioBufferConverterTest, Resample_TinyBuffer) {
- AddInput(MakeTestBuffer(48000, CHANNEL_LAYOUT_STEREO, 2,
- SincResampler::kKernelSize - 1));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, Resample_DifferingBufferSizes) {
- const int input_sample_rate = 48000;
- AddInput(MakeTestBuffer(input_sample_rate, kOutChannelLayout,
- kOutChannelCount, 100));
- AddInput(MakeTestBuffer(input_sample_rate, kOutChannelLayout,
- kOutChannelCount, 200));
- AddInput(MakeTestBuffer(input_sample_rate, kOutChannelLayout,
- kOutChannelCount, 300));
- AddInput(MakeTestBuffer(input_sample_rate, kOutChannelLayout,
- kOutChannelCount, 400));
- AddInput(MakeTestBuffer(input_sample_rate, kOutChannelLayout,
- kOutChannelCount, 500));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ChannelDownmix) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(kOutSampleRate, CHANNEL_LAYOUT_MONO, 1, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ChannelUpmix) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(kOutSampleRate, CHANNEL_LAYOUT_5_1, 6, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ResampleAndRemix) {
- scoped_refptr<AudioBuffer> in =
- MakeTestBuffer(48000, CHANNEL_LAYOUT_5_1, 6, 512);
- AddInput(in);
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ConfigChange_SampleRate) {
- AddInput(MakeTestBuffer(48000, kOutChannelLayout, kOutChannelCount, 512));
- AddInput(MakeTestBuffer(44100, kOutChannelLayout, kOutChannelCount, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ConfigChange_ChannelLayout) {
- AddInput(MakeTestBuffer(kOutSampleRate, CHANNEL_LAYOUT_STEREO, 2, 512));
- AddInput(MakeTestBuffer(kOutSampleRate, CHANNEL_LAYOUT_MONO, 1, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ConfigChange_SampleRateAndChannelLayout) {
- AddInput(MakeTestBuffer(44100, CHANNEL_LAYOUT_STEREO, 2, 512));
- AddInput(MakeTestBuffer(48000, CHANNEL_LAYOUT_MONO, 1, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ConfigChange_Multiple) {
- AddInput(MakeTestBuffer(44100, CHANNEL_LAYOUT_STEREO, 2, 512));
- AddInput(MakeTestBuffer(48000, CHANNEL_LAYOUT_MONO, 1, 512));
- AddInput(MakeTestBuffer(44100, CHANNEL_LAYOUT_5_1, 6, 512));
- AddInput(MakeTestBuffer(22050, CHANNEL_LAYOUT_STEREO, 2, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, Reset) {
- AddInput(MakeTestBuffer(44100, CHANNEL_LAYOUT_STEREO, 2, 512));
- Reset();
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ResampleThenReset) {
- // Resampling is likely to leave some data buffered in AudioConverter's
- // fifo or resampler, so make sure Reset() cleans that all up.
- AddInput(MakeTestBuffer(48000, CHANNEL_LAYOUT_STEREO, 2, 512));
- Reset();
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, ResetThenConvert) {
- AddInput(
- MakeTestBuffer(kOutSampleRate, kOutChannelLayout, kOutChannelCount, 512));
- Reset();
- // Make sure we can keep using the AudioBufferConverter after we've Reset().
- AddInput(
- MakeTestBuffer(kOutSampleRate, kOutChannelLayout, kOutChannelCount, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, DiscreteChannelLayout) {
- output_params_ =
- AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY,
- CHANNEL_LAYOUT_DISCRETE, kOutSampleRate, 16, 512);
- output_params_.set_channels_for_discrete(2);
- audio_buffer_converter_.reset(new AudioBufferConverter(output_params_));
- AddInput(MakeTestBuffer(kOutSampleRate, CHANNEL_LAYOUT_STEREO, 2, 512));
- ConsumeAllOutput();
-}
-
-TEST_F(AudioBufferConverterTest, LargeBuffersResampling) {
- output_params_ = AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY,
- kOutChannelLayout, kOutSampleRate, 16, 2048);
-
- audio_buffer_converter_.reset(new AudioBufferConverter(output_params_));
- const int kInputSampleRate = 48000;
- const int kInputFrameSize = 8192;
- ASSERT_NE(kInputSampleRate, kOutSampleRate);
-
- const int kInputBuffers = 3;
- for (int i = 0; i < kInputBuffers; ++i) {
- AddInput(MakeTestBuffer(kInputSampleRate, kOutChannelLayout,
- kOutChannelCount, kInputFrameSize));
- }
-
- // Do not add an EOS packet here, as it will invoke flushing.
- while (audio_buffer_converter_->HasNextBuffer()) ConsumeOutput();
-
- // Since the input buffer size is a multiple of the input request size there
- // should never be any frames remaining at this point.
- ASSERT_EQ(kInputFrameSize %
- audio_buffer_converter_->input_buffer_size_for_testing(),
- 0);
- EXPECT_EQ(0, audio_buffer_converter_->input_frames_left_for_testing());
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_buffer_queue.cc b/src/cobalt/media/base/audio_buffer_queue.cc
deleted file mode 100644
index 69cf82d..0000000
--- a/src/cobalt/media/base/audio_buffer_queue.cc
+++ /dev/null
@@ -1,131 +0,0 @@
-// 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 "cobalt/media/base/audio_buffer_queue.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "cobalt/media/base/audio_bus.h"
-
-namespace cobalt {
-namespace media {
-
-AudioBufferQueue::AudioBufferQueue() { Clear(); }
-AudioBufferQueue::~AudioBufferQueue() {}
-
-void AudioBufferQueue::Clear() {
- buffers_.clear();
- current_buffer_ = buffers_.begin();
- current_buffer_offset_ = 0;
- frames_ = 0;
-}
-
-void AudioBufferQueue::Append(const scoped_refptr<AudioBuffer>& buffer_in) {
- // Add the buffer to the queue. Inserting into deque invalidates all
- // iterators, so point to the first buffer.
- buffers_.push_back(buffer_in);
- current_buffer_ = buffers_.begin();
-
- // Update the |frames_| counter since we have added frames.
- frames_ += buffer_in->frame_count();
- CHECK_GT(frames_, 0); // make sure it doesn't overflow.
-}
-
-int AudioBufferQueue::ReadFrames(int frames, int dest_frame_offset,
- AudioBus* dest) {
- DCHECK_GE(dest->frames(), frames + dest_frame_offset);
- return InternalRead(frames, true, 0, dest_frame_offset, dest);
-}
-
-int AudioBufferQueue::PeekFrames(int frames, int source_frame_offset,
- int dest_frame_offset, AudioBus* dest) {
- DCHECK_GE(dest->frames(), frames);
- return InternalRead(frames, false, source_frame_offset, dest_frame_offset,
- dest);
-}
-
-void AudioBufferQueue::SeekFrames(int frames) {
- // Perform seek only if we have enough bytes in the queue.
- CHECK_LE(frames, frames_);
- int taken = InternalRead(frames, true, 0, 0, NULL);
- DCHECK_EQ(taken, frames);
-}
-
-int AudioBufferQueue::InternalRead(int frames, bool advance_position,
- int source_frame_offset,
- int dest_frame_offset, AudioBus* dest) {
- // Counts how many frames are actually read from the buffer queue.
- int taken = 0;
- BufferQueue::iterator current_buffer = current_buffer_;
- int current_buffer_offset = current_buffer_offset_;
-
- int frames_to_skip = source_frame_offset;
- while (taken < frames) {
- // |current_buffer| is valid since the first time this buffer is appended
- // with data. Make sure there is data to be processed.
- if (current_buffer == buffers_.end()) break;
-
- scoped_refptr<AudioBuffer> buffer = *current_buffer;
-
- int remaining_frames_in_buffer =
- buffer->frame_count() - current_buffer_offset;
-
- if (frames_to_skip > 0) {
- // If there are frames to skip, do it first. May need to skip into
- // subsequent buffers.
- int skipped = std::min(remaining_frames_in_buffer, frames_to_skip);
- current_buffer_offset += skipped;
- frames_to_skip -= skipped;
- } else {
- // Find the right amount to copy from the current buffer. We shall copy no
- // more than |frames| frames in total and each single step copies no more
- // than the current buffer size.
- int copied = std::min(frames - taken, remaining_frames_in_buffer);
-
- // if |dest| is NULL, there's no need to copy.
- if (dest) {
- buffer->ReadFrames(copied, current_buffer_offset,
- dest_frame_offset + taken, dest);
- }
-
- // Increase total number of frames copied, which regulates when to end
- // this loop.
- taken += copied;
-
- // We have read |copied| frames from the current buffer. Advance the
- // offset.
- current_buffer_offset += copied;
- }
-
- // Has the buffer has been consumed?
- if (current_buffer_offset == buffer->frame_count()) {
- // If we are at the last buffer, no more data to be copied, so stop.
- BufferQueue::iterator next = current_buffer + 1;
- if (next == buffers_.end()) break;
-
- // Advances the iterator.
- current_buffer = next;
- current_buffer_offset = 0;
- }
- }
-
- if (advance_position) {
- // Update the appropriate values since |taken| frames have been copied out.
- frames_ -= taken;
- DCHECK_GE(frames_, 0);
- DCHECK(current_buffer_ != buffers_.end() || frames_ == 0);
-
- // Remove any buffers before the current buffer as there is no going
- // backwards.
- buffers_.erase(buffers_.begin(), current_buffer);
- current_buffer_ = buffers_.begin();
- current_buffer_offset_ = current_buffer_offset;
- }
-
- return taken;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_buffer_queue.h b/src/cobalt/media/base/audio_buffer_queue.h
deleted file mode 100644
index 37881bb..0000000
--- a/src/cobalt/media/base/audio_buffer_queue.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_BUFFER_QUEUE_H_
-#define COBALT_MEDIA_BASE_AUDIO_BUFFER_QUEUE_H_
-
-#include <deque>
-
-#include "base/basictypes.h"
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-class AudioBus;
-
-// A queue of AudioBuffers to support reading of arbitrary chunks of a media
-// data source. Audio data can be copied into an AudioBus for output. The
-// current position can be forwarded to anywhere in the buffered data.
-//
-// This class is not inherently thread-safe. Concurrent access must be
-// externally serialized.
-class MEDIA_EXPORT AudioBufferQueue {
- public:
- AudioBufferQueue();
- ~AudioBufferQueue();
-
- // Clears the buffer queue.
- void Clear();
-
- // Appends |buffer_in| to this queue.
- void Append(const scoped_refptr<AudioBuffer>& buffer_in);
-
- // Reads a maximum of |frames| frames into |dest| from the current position.
- // Returns the number of frames read. The current position will advance by the
- // amount of frames read. |dest_frame_offset| specifies a starting offset into
- // |dest|. On each call, the frames are converted from their source format
- // into the destination AudioBus.
- int ReadFrames(int frames, int dest_frame_offset, AudioBus* dest);
-
- // Copies up to |frames| frames from current position to |dest|. Returns
- // number of frames copied. Doesn't advance current position. Starts at
- // |source_frame_offset| from current position. |dest_frame_offset| specifies
- // a starting offset into |dest|. On each call, the frames are converted from
- // their source format into the destination AudioBus.
- int PeekFrames(int frames, int source_frame_offset, int dest_frame_offset,
- AudioBus* dest);
-
- // Moves the current position forward by |frames| frames. If |frames| exceeds
- // frames available, the seek operation will fail.
- void SeekFrames(int frames);
-
- // Returns the number of frames buffered beyond the current position.
- int frames() const { return frames_; }
-
- private:
- // Definition of the buffer queue.
- typedef std::deque<scoped_refptr<AudioBuffer> > BufferQueue;
-
- // An internal method shared by ReadFrames() and SeekFrames() that actually
- // does reading. It reads a maximum of |frames| frames into |dest|. Returns
- // the number of frames read. The current position will be moved forward by
- // the number of frames read if |advance_position| is set. If |dest| is NULL,
- // only the current position will advance but no data will be copied.
- // |source_frame_offset| can be used to skip frames before reading.
- // |dest_frame_offset| specifies a starting offset into |dest|.
- int InternalRead(int frames, bool advance_position, int source_frame_offset,
- int dest_frame_offset, AudioBus* dest);
-
- BufferQueue::iterator current_buffer_;
- BufferQueue buffers_;
- int current_buffer_offset_;
-
- // Number of frames available to be read in the buffer.
- int frames_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioBufferQueue);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_BUFFER_QUEUE_H_
diff --git a/src/cobalt/media/base/audio_buffer_queue_unittest.cc b/src/cobalt/media/base/audio_buffer_queue_unittest.cc
deleted file mode 100644
index 27829ab..0000000
--- a/src/cobalt/media/base/audio_buffer_queue_unittest.cc
+++ /dev/null
@@ -1,348 +0,0 @@
-// 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 "cobalt/media/base/audio_buffer_queue.h"
-
-#include <limits>
-#include <memory>
-
-#include "base/logging.h"
-#include "base/time.h"
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/test_helpers.h"
-#include "cobalt/media/base/timestamp_constants.h"
-#include "starboard/types.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-const int kSampleRate = 44100;
-
-static void VerifyBus(AudioBus* bus, int offset, int frames, int buffer_size,
- float start, float increment) {
- for (int ch = 0; ch < bus->channels(); ++ch) {
- const float v = start + ch * buffer_size * increment;
- for (int i = offset; i < offset + frames; ++i) {
- ASSERT_FLOAT_EQ(v + (i - offset) * increment, bus->channel(ch)[i])
- << "i=" << i << ", ch=" << ch;
- }
- }
-}
-
-template <typename T>
-static scoped_refptr<AudioBuffer> MakeTestBuffer(SampleFormat format,
- ChannelLayout channel_layout,
- T start, T step, int frames) {
- return MakeAudioBuffer<T>(format, channel_layout,
- ChannelLayoutToChannelCount(channel_layout),
- kSampleRate, start, step, frames, kNoTimestamp);
-}
-
-TEST(AudioBufferQueueTest, AppendAndClear) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_MONO;
- AudioBufferQueue buffer;
- EXPECT_EQ(0, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(8, buffer.frames());
- buffer.Clear();
- EXPECT_EQ(0, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 20, 1, 8));
- EXPECT_EQ(8, buffer.frames());
-}
-
-TEST(AudioBufferQueueTest, MultipleAppend) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_MONO;
- AudioBufferQueue buffer;
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(8, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(16, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(24, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(32, buffer.frames());
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 10, 1, 8));
- EXPECT_EQ(40, buffer.frames());
-}
-
-TEST(AudioBufferQueueTest, IteratorCheck) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_MONO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
-
- // Append 40 frames in 5 buffers. Intersperse ReadFrames() to make the
- // iterator is pointing to the correct position.
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 10.0f, 1.0f, 8));
- EXPECT_EQ(8, buffer.frames());
-
- EXPECT_EQ(4, buffer.ReadFrames(4, 0, bus.get()));
- EXPECT_EQ(4, buffer.frames());
- VerifyBus(bus.get(), 0, 4, bus->frames(), 10, 1);
-
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 20.0f, 1.0f, 8));
- EXPECT_EQ(12, buffer.frames());
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 30.0f, 1.0f, 8));
- EXPECT_EQ(20, buffer.frames());
-
- buffer.SeekFrames(16);
- EXPECT_EQ(4, buffer.ReadFrames(4, 0, bus.get()));
- EXPECT_EQ(0, buffer.frames());
- VerifyBus(bus.get(), 0, 4, bus->frames(), 34, 1);
-
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 40.0f, 1.0f, 8));
- EXPECT_EQ(8, buffer.frames());
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 50.0f, 1.0f, 8));
- EXPECT_EQ(16, buffer.frames());
-
- EXPECT_EQ(4, buffer.ReadFrames(4, 0, bus.get()));
- VerifyBus(bus.get(), 0, 4, bus->frames(), 40, 1);
-
- // Read off the end of the buffer.
- EXPECT_EQ(12, buffer.frames());
- buffer.SeekFrames(8);
- EXPECT_EQ(4, buffer.ReadFrames(100, 0, bus.get()));
- VerifyBus(bus.get(), 0, 4, bus->frames(), 54, 1);
-}
-
-TEST(AudioBufferQueueTest, Seek) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- AudioBufferQueue buffer;
-
- // Add 6 frames of data.
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 1.0f, 1.0f, 6));
- EXPECT_EQ(6, buffer.frames());
-
- // Seek past 2 frames.
- buffer.SeekFrames(2);
- EXPECT_EQ(4, buffer.frames());
-
- // Seek to end of data.
- buffer.SeekFrames(4);
- EXPECT_EQ(0, buffer.frames());
-
- // At end, seek now fails unless 0 specified.
- buffer.SeekFrames(0);
-}
-
-TEST(AudioBufferQueueTest, ReadF32) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 76 frames of data.
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 1.0f, 1.0f, 6));
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 13.0f, 1.0f, 10));
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 33.0f, 1.0f, 60));
- EXPECT_EQ(76, buffer.frames());
-
- // Read 3 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- EXPECT_EQ(3, buffer.ReadFrames(3, 0, bus.get()));
- EXPECT_EQ(73, buffer.frames());
- VerifyBus(bus.get(), 0, 3, 6, 1, 1);
-
- // Now read 5 frames, which will span buffers. Append the data into AudioBus.
- EXPECT_EQ(5, buffer.ReadFrames(5, 3, bus.get()));
- EXPECT_EQ(68, buffer.frames());
- VerifyBus(bus.get(), 0, 6, 6, 1, 1);
- VerifyBus(bus.get(), 6, 2, 10, 13, 1);
-
- // Now skip into the third buffer.
- buffer.SeekFrames(20);
- EXPECT_EQ(48, buffer.frames());
-
- // Now read 2 frames, which are in the third buffer.
- EXPECT_EQ(2, buffer.ReadFrames(2, 0, bus.get()));
- VerifyBus(bus.get(), 0, 2, 60, 45, 1);
-}
-
-TEST(AudioBufferQueueTest, ReadU8) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 4;
- AudioBufferQueue buffer;
-
- // Add 4 frames of data.
- buffer.Append(
- MakeTestBuffer<uint8_t>(kSampleFormatU8, channel_layout, 128, 1, frames));
-
- // Read all 4 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- EXPECT_EQ(frames, buffer.ReadFrames(frames, 0, bus.get()));
- EXPECT_EQ(0, buffer.frames());
- VerifyBus(bus.get(), 0, frames, bus->frames(), 0, 1.0f / 127.0f);
-}
-
-TEST(AudioBufferQueueTest, ReadS16) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 24 frames of data.
- buffer.Append(
- MakeTestBuffer<int16_t>(kSampleFormatS16, channel_layout, 1, 1, 4));
- buffer.Append(
- MakeTestBuffer<int16_t>(kSampleFormatS16, channel_layout, 9, 1, 20));
- EXPECT_EQ(24, buffer.frames());
-
- // Read 6 frames from the buffer.
- const int frames = 6;
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, buffer.frames());
- EXPECT_EQ(frames, buffer.ReadFrames(frames, 0, bus.get()));
- EXPECT_EQ(18, buffer.frames());
- VerifyBus(bus.get(), 0, 4, 4, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
- VerifyBus(bus.get(), 4, 2, 20, 9.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-}
-
-TEST(AudioBufferQueueTest, ReadS32) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 24 frames of data.
- buffer.Append(
- MakeTestBuffer<int32_t>(kSampleFormatS32, channel_layout, 1, 1, 4));
- buffer.Append(
- MakeTestBuffer<int32_t>(kSampleFormatS32, channel_layout, 9, 1, 20));
- EXPECT_EQ(24, buffer.frames());
-
- // Read 6 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- EXPECT_EQ(6, buffer.ReadFrames(6, 0, bus.get()));
- EXPECT_EQ(18, buffer.frames());
- VerifyBus(bus.get(), 0, 4, 4, 1.0f / std::numeric_limits<int32_t>::max(),
- 1.0f / std::numeric_limits<int32_t>::max());
- VerifyBus(bus.get(), 4, 2, 20, 9.0f / std::numeric_limits<int32_t>::max(),
- 1.0f / std::numeric_limits<int32_t>::max());
-
- // Read the next 2 frames.
- EXPECT_EQ(2, buffer.ReadFrames(2, 0, bus.get()));
- EXPECT_EQ(16, buffer.frames());
- VerifyBus(bus.get(), 0, 2, 20, 11.0f / std::numeric_limits<int32_t>::max(),
- 1.0f / std::numeric_limits<int32_t>::max());
-}
-
-TEST(AudioBufferQueueTest, ReadF32Planar) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 14 frames of data.
- buffer.Append(MakeTestBuffer<float>(kSampleFormatPlanarF32, channel_layout,
- 1.0f, 1.0f, 4));
- buffer.Append(MakeTestBuffer<float>(kSampleFormatPlanarF32, channel_layout,
- 50.0f, 1.0f, 10));
- EXPECT_EQ(14, buffer.frames());
-
- // Read 6 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- EXPECT_EQ(6, buffer.ReadFrames(6, 0, bus.get()));
- EXPECT_EQ(8, buffer.frames());
- VerifyBus(bus.get(), 0, 4, 4, 1, 1);
- VerifyBus(bus.get(), 4, 2, 10, 50, 1);
-}
-
-TEST(AudioBufferQueueTest, ReadS16Planar) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 24 frames of data.
- buffer.Append(
- MakeTestBuffer<int16_t>(kSampleFormatPlanarS16, channel_layout, 1, 1, 4));
- buffer.Append(MakeTestBuffer<int16_t>(kSampleFormatPlanarS16, channel_layout,
- 5, 1, 20));
- EXPECT_EQ(24, buffer.frames());
-
- // Read 6 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- EXPECT_EQ(6, buffer.ReadFrames(6, 0, bus.get()));
- EXPECT_EQ(18, buffer.frames());
- VerifyBus(bus.get(), 0, 4, 4, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
- VerifyBus(bus.get(), 4, 2, 20, 5.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-}
-
-TEST(AudioBufferQueueTest, ReadManyChannels) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_OCTAGONAL;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 76 frames of data.
- buffer.Append(
- MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 0.0f, 1.0f, 6));
- buffer.Append(MakeTestBuffer<float>(kSampleFormatF32, channel_layout,
- 6.0f * channels, 1.0f, 10));
- buffer.Append(MakeTestBuffer<float>(kSampleFormatF32, channel_layout,
- 16.0f * channels, 1.0f, 60));
- EXPECT_EQ(76, buffer.frames());
-
- // Read 3 frames from the buffer.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- EXPECT_EQ(30, buffer.ReadFrames(30, 0, bus.get()));
- EXPECT_EQ(46, buffer.frames());
- VerifyBus(bus.get(), 0, 6, 6, 0, 1);
- VerifyBus(bus.get(), 6, 10, 10, 6 * channels, 1);
- VerifyBus(bus.get(), 16, 14, 60, 16 * channels, 1);
-}
-
-TEST(AudioBufferQueueTest, Peek) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- AudioBufferQueue buffer;
-
- // Add 60 frames of data.
- const int frames = 60;
- buffer.Append(MakeTestBuffer<float>(kSampleFormatF32, channel_layout, 0.0f,
- 1.0f, frames));
- EXPECT_EQ(frames, buffer.frames());
-
- // Peek at the first 30 frames.
- std::unique_ptr<AudioBus> bus1 = AudioBus::Create(channels, frames);
- EXPECT_EQ(frames, buffer.frames());
- EXPECT_EQ(frames, buffer.PeekFrames(60, 0, 0, bus1.get()));
- EXPECT_EQ(30, buffer.PeekFrames(30, 0, 0, bus1.get()));
- EXPECT_EQ(frames, buffer.frames());
- VerifyBus(bus1.get(), 0, 30, bus1->frames(), 0, 1);
-
- // Now read the next 30 frames (which should be the same as those peeked at).
- std::unique_ptr<AudioBus> bus2 = AudioBus::Create(channels, frames);
- EXPECT_EQ(30, buffer.ReadFrames(30, 0, bus2.get()));
- VerifyBus(bus2.get(), 0, 30, bus2->frames(), 0, 1);
-
- // Peek 10 frames forward
- bus1->Zero();
- EXPECT_EQ(5, buffer.PeekFrames(5, 10, 0, bus1.get()));
- VerifyBus(bus1.get(), 0, 5, bus1->frames(), 40, 1);
-
- // Peek to the end of the buffer.
- EXPECT_EQ(30, buffer.frames());
- EXPECT_EQ(30, buffer.PeekFrames(60, 0, 0, bus1.get()));
- EXPECT_EQ(30, buffer.PeekFrames(30, 0, 0, bus1.get()));
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_buffer_unittest.cc b/src/cobalt/media/base/audio_buffer_unittest.cc
deleted file mode 100644
index 2e3cf5d..0000000
--- a/src/cobalt/media/base/audio_buffer_unittest.cc
+++ /dev/null
@@ -1,376 +0,0 @@
-// 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 <limits>
-#include <memory>
-
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/test_helpers.h"
-#include "starboard/types.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-static const int kSampleRate = 4800;
-
-static void VerifyBusWithOffset(AudioBus* bus, int offset, int frames,
- float start, float start_offset,
- float increment) {
- for (int ch = 0; ch < bus->channels(); ++ch) {
- const float v = start_offset + start + ch * bus->frames() * increment;
- for (int i = offset; i < offset + frames; ++i) {
- ASSERT_FLOAT_EQ(v + i * increment, bus->channel(ch)[i]) << "i=" << i
- << ", ch=" << ch;
- }
- }
-}
-
-static void VerifyBus(AudioBus* bus, int frames, float start, float increment) {
- VerifyBusWithOffset(bus, 0, frames, start, 0, increment);
-}
-
-static void TrimRangeTest(SampleFormat sample_format) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = kSampleRate / 10;
- const base::TimeDelta timestamp = base::TimeDelta();
- const base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<float>(sample_format, channel_layout, channels,
- kSampleRate, 0, 1, frames, timestamp);
- EXPECT_EQ(frames, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration, buffer->duration());
-
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
-
- // Verify all frames before trimming.
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 0, 1);
-
- // Trim 10ms of frames from the middle of the buffer.
- int trim_start = frames / 2;
- const int trim_length = kSampleRate / 100;
- const base::TimeDelta trim_duration = base::TimeDelta::FromMilliseconds(10);
- buffer->TrimRange(trim_start, trim_start + trim_length);
- EXPECT_EQ(frames - trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, 0, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- 0, trim_length, 1);
-
- // Trim 10ms of frames from the start, which just adjusts the buffer's
- // internal start offset.
- buffer->TrimStart(trim_length);
- trim_start -= trim_length;
- EXPECT_EQ(frames - 2 * trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - 2 * trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, trim_length, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- trim_length, trim_length, 1);
-
- // Trim 10ms of frames from the end, which just adjusts the buffer's frame
- // count.
- buffer->TrimEnd(trim_length);
- EXPECT_EQ(frames - 3 * trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - 3 * trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, trim_length, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- trim_length, trim_length, 1);
-
- // Trim another 10ms from the inner portion of the buffer.
- buffer->TrimRange(trim_start, trim_start + trim_length);
- EXPECT_EQ(frames - 4 * trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - 4 * trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, trim_length, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- trim_length, trim_length * 2, 1);
-
- // Trim off the end using TrimRange() to ensure end index is exclusive.
- buffer->TrimRange(buffer->frame_count() - trim_length, buffer->frame_count());
- EXPECT_EQ(frames - 5 * trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - 5 * trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, trim_length, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- trim_length, trim_length * 2, 1);
-
- // Trim off the start using TrimRange() to ensure start index is inclusive.
- buffer->TrimRange(0, trim_length);
- trim_start -= trim_length;
- EXPECT_EQ(frames - 6 * trim_length, buffer->frame_count());
- EXPECT_EQ(timestamp, buffer->timestamp());
- EXPECT_EQ(duration - 6 * trim_duration, buffer->duration());
- bus->Zero();
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), trim_start, 2 * trim_length, 1);
- VerifyBusWithOffset(bus.get(), trim_start, buffer->frame_count() - trim_start,
- trim_length * 2, trim_length * 2, 1);
-}
-
-TEST(AudioBufferTest, CopyFrom) {
- const ChannelLayout kChannelLayout = CHANNEL_LAYOUT_MONO;
- scoped_refptr<AudioBuffer> original_buffer = MakeAudioBuffer<uint8_t>(
- kSampleFormatU8, kChannelLayout,
- ChannelLayoutToChannelCount(kChannelLayout), kSampleRate, 1, 1,
- kSampleRate / 100, base::TimeDelta());
- scoped_refptr<AudioBuffer> new_buffer = AudioBuffer::CopyFrom(
- kSampleFormatU8, original_buffer->channel_layout(),
- original_buffer->channel_count(), original_buffer->sample_rate(),
- original_buffer->frame_count(), &original_buffer->channel_data()[0],
- original_buffer->timestamp());
- EXPECT_EQ(original_buffer->frame_count(), new_buffer->frame_count());
- EXPECT_EQ(original_buffer->timestamp(), new_buffer->timestamp());
- EXPECT_EQ(original_buffer->duration(), new_buffer->duration());
- EXPECT_EQ(original_buffer->sample_rate(), new_buffer->sample_rate());
- EXPECT_EQ(original_buffer->channel_count(), new_buffer->channel_count());
- EXPECT_EQ(original_buffer->channel_layout(), new_buffer->channel_layout());
- EXPECT_FALSE(original_buffer->end_of_stream());
-}
-
-TEST(AudioBufferTest, CreateEOSBuffer) {
- scoped_refptr<AudioBuffer> buffer = AudioBuffer::CreateEOSBuffer();
- EXPECT_TRUE(buffer->end_of_stream());
-}
-
-TEST(AudioBufferTest, FrameSize) {
- const uint8_t kTestData[] = {0, 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};
- const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(1337);
-
- const uint8_t* const data[] = {kTestData};
- scoped_refptr<AudioBuffer> buffer =
- AudioBuffer::CopyFrom(kSampleFormatU8, CHANNEL_LAYOUT_STEREO, 2,
- kSampleRate, 16, data, kTimestamp);
- EXPECT_EQ(16, buffer->frame_count()); // 2 channels of 8-bit data
-
- buffer = AudioBuffer::CopyFrom(kSampleFormatF32, CHANNEL_LAYOUT_4_0, 4,
- kSampleRate, 2, data, kTimestamp);
- EXPECT_EQ(2, buffer->frame_count()); // now 4 channels of 32-bit data
-}
-
-TEST(AudioBufferTest, ReadU8) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 10;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<uint8_t>(kSampleFormatU8, channel_layout, channels,
- kSampleRate, 128, 1, frames, start_time);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 0, 1.0f / 127.0f);
-
- // Now read the same data one frame at a time.
- bus->Zero();
- for (int i = 0; i < frames; ++i) buffer->ReadFrames(1, i, i, bus.get());
- VerifyBus(bus.get(), frames, 0, 1.0f / 127.0f);
-}
-
-TEST(AudioBufferTest, ReadS16) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 10;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<int16_t>(kSampleFormatS16, channel_layout, channels,
- kSampleRate, 1, 1, frames, start_time);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-
- // Now read the same data one frame at a time.
- bus->Zero();
- for (int i = 0; i < frames; ++i) buffer->ReadFrames(1, i, i, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-}
-
-TEST(AudioBufferTest, ReadS32) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 20;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<int32_t>(kSampleFormatS32, channel_layout, channels,
- kSampleRate, 1, 1, frames, start_time);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int32_t>::max(),
- 1.0f / std::numeric_limits<int32_t>::max());
-
- // Read second 10 frames.
- bus->Zero();
- buffer->ReadFrames(10, 10, 0, bus.get());
- VerifyBus(bus.get(), 10, 11.0f / std::numeric_limits<int32_t>::max(),
- 1.0f / std::numeric_limits<int32_t>::max());
-}
-
-TEST(AudioBufferTest, ReadF32) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 20;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<float>(kSampleFormatF32, channel_layout, channels,
- kSampleRate, 1.0f, 1.0f, frames, start_time);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(10, 0, 0, bus.get());
- VerifyBus(bus.get(), 10, 1, 1);
-
- // Read second 10 frames.
- bus->Zero();
- buffer->ReadFrames(10, 10, 0, bus.get());
- VerifyBus(bus.get(), 10, 11, 1);
-}
-
-TEST(AudioBufferTest, ReadS16Planar) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 20;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<int16_t>(kSampleFormatPlanarS16, channel_layout, channels,
- kSampleRate, 1, 1, frames, start_time);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(10, 0, 0, bus.get());
- VerifyBus(bus.get(), 10, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-
- // Read all the frames backwards, one by one. ch[0] should be 20, 19, ...
- bus->Zero();
- for (int i = frames - 1; i >= 0; --i) buffer->ReadFrames(1, i, i, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-
- // Read 0 frames with different offsets. Existing data in AudioBus should be
- // unchanged.
- buffer->ReadFrames(0, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
- buffer->ReadFrames(0, 0, 10, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
- buffer->ReadFrames(0, 10, 0, bus.get());
- VerifyBus(bus.get(), frames, 1.0f / std::numeric_limits<int16_t>::max(),
- 1.0f / std::numeric_limits<int16_t>::max());
-}
-
-TEST(AudioBufferTest, ReadF32Planar) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = 100;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<float>(kSampleFormatPlanarF32, channel_layout, channels,
- kSampleRate, 1.0f, 1.0f, frames, start_time);
-
- // Read all 100 frames from the buffer. F32 is planar, so ch[0] should be 1,
- // 2, 3, 4, ..., ch[1] should be 101, 102, 103, ..., and so on for all 4
- // channels.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, 100);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 1, 1);
-
- // Now read 20 frames from the middle of the buffer.
- bus->Zero();
- buffer->ReadFrames(20, 50, 0, bus.get());
- VerifyBus(bus.get(), 20, 51, 1);
-}
-
-TEST(AudioBufferTest, EmptyBuffer) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = kSampleRate / 100;
- const base::TimeDelta start_time;
- scoped_refptr<AudioBuffer> buffer = AudioBuffer::CreateEmptyBuffer(
- channel_layout, channels, kSampleRate, frames, start_time);
- EXPECT_EQ(frames, buffer->frame_count());
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(base::TimeDelta::FromMilliseconds(10), buffer->duration());
- EXPECT_FALSE(buffer->end_of_stream());
-
- // Read all 100 frames from the buffer. All data should be 0.
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- VerifyBus(bus.get(), frames, 0, 0);
-}
-
-TEST(AudioBufferTest, Trim) {
- const ChannelLayout channel_layout = CHANNEL_LAYOUT_4_0;
- const int channels = ChannelLayoutToChannelCount(channel_layout);
- const int frames = kSampleRate / 10;
- const base::TimeDelta start_time;
- const base::TimeDelta duration = base::TimeDelta::FromMilliseconds(100);
- scoped_refptr<AudioBuffer> buffer =
- MakeAudioBuffer<float>(kSampleFormatPlanarF32, channel_layout, channels,
- kSampleRate, 0.0f, 1.0f, frames, start_time);
- EXPECT_EQ(frames, buffer->frame_count());
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(duration, buffer->duration());
-
- const int ten_ms_of_frames = kSampleRate / 100;
- const base::TimeDelta ten_ms = base::TimeDelta::FromMilliseconds(10);
-
- std::unique_ptr<AudioBus> bus = AudioBus::Create(channels, frames);
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), buffer->frame_count(), 0.0f, 1.0f);
-
- // Trim off 10ms of frames from the start.
- buffer->TrimStart(ten_ms_of_frames);
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(frames - ten_ms_of_frames, buffer->frame_count());
- EXPECT_EQ(duration - ten_ms, buffer->duration());
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), buffer->frame_count(), ten_ms_of_frames, 1.0f);
-
- // Trim off 10ms of frames from the end.
- buffer->TrimEnd(ten_ms_of_frames);
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(frames - 2 * ten_ms_of_frames, buffer->frame_count());
- EXPECT_EQ(duration - 2 * ten_ms, buffer->duration());
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), buffer->frame_count(), ten_ms_of_frames, 1.0f);
-
- // Trim off 40ms more from the start.
- buffer->TrimStart(4 * ten_ms_of_frames);
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(frames - 6 * ten_ms_of_frames, buffer->frame_count());
- EXPECT_EQ(duration - 6 * ten_ms, buffer->duration());
- buffer->ReadFrames(buffer->frame_count(), 0, 0, bus.get());
- VerifyBus(bus.get(), buffer->frame_count(), 5 * ten_ms_of_frames, 1.0f);
-
- // Trim off the final 40ms from the end.
- buffer->TrimEnd(4 * ten_ms_of_frames);
- EXPECT_EQ(0, buffer->frame_count());
- EXPECT_EQ(start_time, buffer->timestamp());
- EXPECT_EQ(base::TimeDelta(), buffer->duration());
-}
-
-TEST(AudioBufferTest, TrimRangePlanar) {
- TrimRangeTest(kSampleFormatPlanarF32);
-}
-
-TEST(AudioBufferTest, TrimRangeInterleaved) { TrimRangeTest(kSampleFormatF32); }
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_bus.cc b/src/cobalt/media/base/audio_bus.cc
deleted file mode 100644
index 65536ef..0000000
--- a/src/cobalt/media/base/audio_bus.cc
+++ /dev/null
@@ -1,336 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_bus.h"
-
-#include <algorithm>
-#include <limits>
-
-#include "base/logging.h"
-#include "base/numerics/safe_conversions.h"
-#include "cobalt/media/base/audio_parameters.h"
-#include "cobalt/media/base/audio_sample_types.h"
-#include "cobalt/media/base/limits.h"
-#include "cobalt/media/base/vector_math.h"
-#include "starboard/memory.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-static bool IsAligned(void* ptr) {
- return (reinterpret_cast<uintptr_t>(ptr) &
- (AudioBus::kChannelAlignment - 1)) == 0U;
-}
-
-// In order to guarantee that the memory block for each channel starts at an
-// aligned address when splitting a contiguous block of memory into one block
-// per channel, we may have to make these blocks larger than otherwise needed.
-// We do this by allocating space for potentially more frames than requested.
-// This method returns the required size for the contiguous memory block
-// in bytes and outputs the adjusted number of frames via |out_aligned_frames|.
-static int CalculateMemorySizeInternal(int channels, int frames,
- int* out_aligned_frames) {
- // Since our internal sample format is float, we can guarantee the alignment
- // by making the number of frames an integer multiple of
- // AudioBus::kChannelAlignment / sizeof(float).
- int aligned_frames =
- ((frames * sizeof(float) + AudioBus::kChannelAlignment - 1) &
- ~(AudioBus::kChannelAlignment - 1)) /
- sizeof(float);
-
- if (out_aligned_frames) *out_aligned_frames = aligned_frames;
-
- return sizeof(float) * channels * aligned_frames;
-}
-
-static void ValidateConfig(int channels, int frames) {
- CHECK_GT(frames, 0);
- CHECK_GT(channels, 0);
- CHECK_LE(channels, static_cast<int>(limits::kMaxChannels));
-}
-
-void AudioBus::CheckOverflow(int start_frame, int frames, int total_frames) {
- CHECK_GE(start_frame, 0);
- CHECK_GE(frames, 0);
- CHECK_GT(total_frames, 0);
- int sum = start_frame + frames;
- CHECK_LE(sum, total_frames);
- CHECK_GE(sum, 0);
-}
-
-AudioBus::AudioBus(int channels, int frames)
- : frames_(frames), can_set_channel_data_(false) {
- ValidateConfig(channels, frames_);
-
- int aligned_frames = 0;
- int size = CalculateMemorySizeInternal(channels, frames, &aligned_frames);
-
- data_.reset(static_cast<float*>(
- base::AlignedAlloc(size, AudioBus::kChannelAlignment)));
-
- BuildChannelData(channels, aligned_frames, data_.get());
-}
-
-AudioBus::AudioBus(int channels, int frames, float* data)
- : frames_(frames), can_set_channel_data_(false) {
- // Since |data| may have come from an external source, ensure it's valid.
- CHECK(data);
- ValidateConfig(channels, frames_);
-
- int aligned_frames = 0;
- CalculateMemorySizeInternal(channels, frames, &aligned_frames);
-
- BuildChannelData(channels, aligned_frames, data);
-}
-
-AudioBus::AudioBus(int frames, const std::vector<float*>& channel_data)
- : channel_data_(channel_data),
- frames_(frames),
- can_set_channel_data_(false) {
- ValidateConfig(base::checked_cast<int>(channel_data_.size()), frames_);
-
- // Sanity check wrapped vector for alignment and channel count.
- for (size_t i = 0; i < channel_data_.size(); ++i)
- DCHECK(IsAligned(channel_data_[i]));
-}
-
-AudioBus::AudioBus(int channels)
- : channel_data_(channels), frames_(0), can_set_channel_data_(true) {
- CHECK_GT(channels, 0);
- for (size_t i = 0; i < channel_data_.size(); ++i) channel_data_[i] = NULL;
-}
-
-AudioBus::~AudioBus() {}
-
-std::unique_ptr<AudioBus> AudioBus::Create(int channels, int frames) {
- return base::WrapUnique(new AudioBus(channels, frames));
-}
-
-std::unique_ptr<AudioBus> AudioBus::Create(const AudioParameters& params) {
- return base::WrapUnique(
- new AudioBus(params.channels(), params.frames_per_buffer()));
-}
-
-std::unique_ptr<AudioBus> AudioBus::CreateWrapper(int channels) {
- return base::WrapUnique(new AudioBus(channels));
-}
-
-std::unique_ptr<AudioBus> AudioBus::WrapVector(
- int frames, const std::vector<float*>& channel_data) {
- return base::WrapUnique(new AudioBus(frames, channel_data));
-}
-
-std::unique_ptr<AudioBus> AudioBus::WrapMemory(int channels, int frames,
- void* data) {
- // |data| must be aligned by AudioBus::kChannelAlignment.
- CHECK(IsAligned(data));
- return base::WrapUnique(
- new AudioBus(channels, frames, static_cast<float*>(data)));
-}
-
-std::unique_ptr<AudioBus> AudioBus::WrapMemory(const AudioParameters& params,
- void* data) {
- // |data| must be aligned by AudioBus::kChannelAlignment.
- CHECK(IsAligned(data));
- return base::WrapUnique(new AudioBus(params.channels(),
- params.frames_per_buffer(),
- static_cast<float*>(data)));
-}
-
-void AudioBus::SetChannelData(int channel, float* data) {
- CHECK(can_set_channel_data_);
- CHECK(data);
- CHECK_GE(channel, 0);
- CHECK_LT(static_cast<size_t>(channel), channel_data_.size());
- DCHECK(IsAligned(data));
- channel_data_[channel] = data;
-}
-
-void AudioBus::set_frames(int frames) {
- CHECK(can_set_channel_data_);
- ValidateConfig(static_cast<int>(channel_data_.size()), frames);
- frames_ = frames;
-}
-
-void AudioBus::ZeroFramesPartial(int start_frame, int frames) {
- CheckOverflow(start_frame, frames, frames_);
-
- if (frames <= 0) return;
-
- for (size_t i = 0; i < channel_data_.size(); ++i) {
- SbMemorySet(channel_data_[i] + start_frame, 0,
- frames * sizeof(*channel_data_[i]));
- }
-}
-
-void AudioBus::ZeroFrames(int frames) { ZeroFramesPartial(0, frames); }
-
-void AudioBus::Zero() { ZeroFrames(frames_); }
-
-bool AudioBus::AreFramesZero() const {
- for (size_t i = 0; i < channel_data_.size(); ++i) {
- for (int j = 0; j < frames_; ++j) {
- if (channel_data_[i][j]) return false;
- }
- }
- return true;
-}
-
-int AudioBus::CalculateMemorySize(const AudioParameters& params) {
- return CalculateMemorySizeInternal(params.channels(),
- params.frames_per_buffer(), NULL);
-}
-
-int AudioBus::CalculateMemorySize(int channels, int frames) {
- return CalculateMemorySizeInternal(channels, frames, NULL);
-}
-
-void AudioBus::BuildChannelData(int channels, int aligned_frames, float* data) {
- DCHECK(IsAligned(data));
- DCHECK_EQ(channel_data_.size(), 0U);
- // Initialize |channel_data_| with pointers into |data|.
- channel_data_.reserve(channels);
- for (int i = 0; i < channels; ++i)
- channel_data_.push_back(data + i * aligned_frames);
-}
-
-// Forwards to non-deprecated version.
-void AudioBus::FromInterleaved(const void* source, int frames,
- int bytes_per_sample) {
- switch (bytes_per_sample) {
- case 1:
- FromInterleaved<UnsignedInt8SampleTypeTraits>(
- reinterpret_cast<const uint8_t*>(source), frames);
- break;
- case 2:
- FromInterleaved<SignedInt16SampleTypeTraits>(
- reinterpret_cast<const int16_t*>(source), frames);
- break;
- case 4:
- FromInterleaved<SignedInt32SampleTypeTraits>(
- reinterpret_cast<const int32_t*>(source), frames);
- break;
- default:
- NOTREACHED() << "Unsupported bytes per sample encountered: "
- << bytes_per_sample;
- ZeroFrames(frames);
- }
-}
-
-// Forwards to non-deprecated version.
-void AudioBus::FromInterleavedPartial(const void* source, int start_frame,
- int frames, int bytes_per_sample) {
- switch (bytes_per_sample) {
- case 1:
- FromInterleavedPartial<UnsignedInt8SampleTypeTraits>(
- reinterpret_cast<const uint8_t*>(source), start_frame, frames);
- break;
- case 2:
- FromInterleavedPartial<SignedInt16SampleTypeTraits>(
- reinterpret_cast<const int16_t*>(source), start_frame, frames);
- break;
- case 4:
- FromInterleavedPartial<SignedInt32SampleTypeTraits>(
- reinterpret_cast<const int32_t*>(source), start_frame, frames);
- break;
- default:
- NOTREACHED() << "Unsupported bytes per sample encountered: "
- << bytes_per_sample;
- ZeroFramesPartial(start_frame, frames);
- }
-}
-
-// Forwards to non-deprecated version.
-void AudioBus::ToInterleaved(int frames, int bytes_per_sample,
- void* dest) const {
- switch (bytes_per_sample) {
- case 1:
- ToInterleaved<UnsignedInt8SampleTypeTraits>(
- frames, reinterpret_cast<uint8_t*>(dest));
- break;
- case 2:
- ToInterleaved<SignedInt16SampleTypeTraits>(
- frames, reinterpret_cast<int16_t*>(dest));
- break;
- case 4:
- ToInterleaved<SignedInt32SampleTypeTraits>(
- frames, reinterpret_cast<int32_t*>(dest));
- break;
- default:
- NOTREACHED() << "Unsupported bytes per sample encountered: "
- << bytes_per_sample;
- }
-}
-
-// Forwards to non-deprecated version.
-void AudioBus::ToInterleavedPartial(int start_frame, int frames,
- int bytes_per_sample, void* dest) const {
- switch (bytes_per_sample) {
- case 1:
- ToInterleavedPartial<UnsignedInt8SampleTypeTraits>(
- start_frame, frames, reinterpret_cast<uint8_t*>(dest));
- break;
- case 2:
- ToInterleavedPartial<SignedInt16SampleTypeTraits>(
- start_frame, frames, reinterpret_cast<int16_t*>(dest));
- break;
- case 4:
- ToInterleavedPartial<SignedInt32SampleTypeTraits>(
- start_frame, frames, reinterpret_cast<int32_t*>(dest));
- break;
- default:
- NOTREACHED() << "Unsupported bytes per sample encountered: "
- << bytes_per_sample;
- }
-}
-
-void AudioBus::CopyTo(AudioBus* dest) const {
- CopyPartialFramesTo(0, frames(), 0, dest);
-}
-
-void AudioBus::CopyPartialFramesTo(int source_start_frame, int frame_count,
- int dest_start_frame, AudioBus* dest) const {
- CHECK_EQ(channels(), dest->channels());
- CHECK_LE(source_start_frame + frame_count, frames());
- CHECK_LE(dest_start_frame + frame_count, dest->frames());
-
- // Since we don't know if the other AudioBus is wrapped or not (and we don't
- // want to care), just copy using the public channel() accessors.
- for (int i = 0; i < channels(); ++i) {
- SbMemoryCopy(dest->channel(i) + dest_start_frame,
- channel(i) + source_start_frame,
- sizeof(*channel(i)) * frame_count);
- }
-}
-
-void AudioBus::Scale(float volume) {
- if (volume > 0 && volume != 1) {
- for (int i = 0; i < channels(); ++i)
- vector_math::FMUL(channel(i), volume, frames(), channel(i));
- } else if (volume == 0) {
- Zero();
- }
-}
-
-void AudioBus::SwapChannels(int a, int b) {
- DCHECK(a < channels() && a >= 0);
- DCHECK(b < channels() && b >= 0);
- DCHECK_NE(a, b);
- std::swap(channel_data_[a], channel_data_[b]);
-}
-
-scoped_refptr<AudioBusRefCounted> AudioBusRefCounted::Create(int channels,
- int frames) {
- return scoped_refptr<AudioBusRefCounted>(
- new AudioBusRefCounted(channels, frames));
-}
-
-AudioBusRefCounted::AudioBusRefCounted(int channels, int frames)
- : AudioBus(channels, frames) {}
-
-AudioBusRefCounted::~AudioBusRefCounted() {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_bus.h b/src/cobalt/media/base/audio_bus.h
deleted file mode 100644
index 5870486..0000000
--- a/src/cobalt/media/base/audio_bus.h
+++ /dev/null
@@ -1,311 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_BUS_H_
-#define COBALT_MEDIA_BASE_AUDIO_BUS_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/memory/aligned_memory.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "cobalt/media/base/media_export.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-class AudioParameters;
-
-// Represents a sequence of audio frames containing frames() audio samples for
-// each of channels() channels. The data is stored as a set of contiguous
-// float arrays with one array per channel. The memory for the arrays is either
-// allocated and owned by the AudioBus or it is provided to one of the factory
-// methods. AudioBus guarantees that it allocates memory such that float array
-// for each channel is aligned by AudioBus::kChannelAlignment bytes and it
-// requires the same for memory passed to its Wrap...() factory methods.
-// TODO(chfremer): There are currently no unit tests involving CreateWrapper and
-// SetChannelData, so we need to add them.
-class MEDIA_EXPORT AudioBus {
- public:
- // Guaranteed alignment of each channel's data; use 16-byte alignment for easy
- // SSE optimizations.
- enum { kChannelAlignment = 16 };
-
- // Creates a new AudioBus and allocates |channels| of length |frames|. Uses
- // channels() and frames_per_buffer() from AudioParameters if given.
- static scoped_ptr<AudioBus> Create(int channels, int frames);
- static scoped_ptr<AudioBus> Create(const AudioParameters& params);
-
- // Creates a new AudioBus with the given number of channels, but zero length.
- // Clients are expected to subsequently call SetChannelData() and set_frames()
- // to wrap externally allocated memory.
- static scoped_ptr<AudioBus> CreateWrapper(int channels);
-
- // Creates a new AudioBus from an existing channel vector. Does not transfer
- // ownership of |channel_data| to AudioBus; i.e., |channel_data| must outlive
- // the returned AudioBus. Each channel must be aligned by kChannelAlignment.
- static scoped_ptr<AudioBus> WrapVector(
- int frames, const std::vector<float*>& channel_data);
-
- // Creates a new AudioBus by wrapping an existing block of memory. Block must
- // be at least CalculateMemorySize() bytes in size. |data| must outlive the
- // returned AudioBus. |data| must be aligned by kChannelAlignment.
- static scoped_ptr<AudioBus> WrapMemory(int channels, int frames, void* data);
- static scoped_ptr<AudioBus> WrapMemory(const AudioParameters& params,
- void* data);
-
- // Based on the given number of channels and frames, calculates the minimum
- // required size in bytes of a contiguous block of memory to be passed to
- // AudioBus for storage of the audio data.
- // Uses channels() and frames_per_buffer() from AudioParameters if given.
- static int CalculateMemorySize(int channels, int frames);
- static int CalculateMemorySize(const AudioParameters& params);
-
- // Methods that are expected to be called after AudioBus::CreateWrapper() in
- // order to wrap externally allocated memory. Note: It is illegal to call
- // these methods when using a factory method other than CreateWrapper().
- void SetChannelData(int channel, float* data);
- void set_frames(int frames);
-
- // Overwrites the sample values stored in this AudioBus instance with values
- // from a given interleaved |source_buffer| with expected layout
- // [ch0, ch1, ..., chN, ch0, ch1, ...] and sample values in the format
- // corresponding to the given SourceSampleTypeTraits.
- // The sample values are converted to float values by means of the method
- // convert_to_float32() provided by the SourceSampleTypeTraits. For a list of
- // ready-to-use SampleTypeTraits, see file audio_sample_types.h.
- // If |num_frames_to_write| is less than frames(), the remaining frames are
- // zeroed out. If |num_frames_to_write| is more than frames(), this results in
- // undefined behavior.
- template <class SourceSampleTypeTraits>
- void FromInterleaved(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int num_frames_to_write);
-
- // DEPRECATED (https://crbug.com/580391)
- // Please use the version templated with SourceSampleTypeTraits instead.
- // TODO(chfremer): Remove (https://crbug.com/619623)
- void FromInterleaved(const void* source, int frames, int bytes_per_sample);
-
- // Similar to FromInterleaved...(), but overwrites the frames starting at a
- // given offset |write_offset_in_frames| and does not zero out frames that are
- // not overwritten.
- template <class SourceSampleTypeTraits>
- void FromInterleavedPartial(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int write_offset_in_frames, int num_frames_to_write);
-
- // DEPRECATED (https://crbug.com/580391)
- // Please use the version templated with SourceSampleTypeTraits instead.
- // TODO(chfremer): Remove (https://crbug.com/619623)
- void FromInterleavedPartial(const void* source, int start_frame, int frames,
- int bytes_per_sample);
-
- // Reads the sample values stored in this AudioBus instance and places them
- // into the given |dest_buffer| in interleaved format using the sample format
- // specified by TargetSampleTypeTraits. For a list of ready-to-use
- // SampleTypeTraits, see file audio_sample_types.h. If |num_frames_to_read| is
- // larger than frames(), this results in undefined behavior.
- template <class TargetSampleTypeTraits>
- void ToInterleaved(
- int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest_buffer) const;
-
- // DEPRECATED (https://crbug.com/580391)
- // Please use the version templated with TargetSampleTypeTraits instead.
- // TODO(chfremer): Remove (https://crbug.com/619623)
- void ToInterleaved(int frames, int bytes_per_sample, void* dest) const;
-
- // Similar to ToInterleaved(), but reads the frames starting at a given
- // offset |read_offset_in_frames|.
- template <class TargetSampleTypeTraits>
- void ToInterleavedPartial(
- int read_offset_in_frames, int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest_buffer) const;
-
- // DEPRECATED (https://crbug.com/580391)
- // Please use the version templated with TargetSampleTypeTraits instead.
- // TODO(chfremer): Remove (https://crbug.com/619623)
- void ToInterleavedPartial(int start_frame, int frames, int bytes_per_sample,
- void* dest) const;
-
- // Helper method for copying channel data from one AudioBus to another. Both
- // AudioBus object must have the same frames() and channels().
- void CopyTo(AudioBus* dest) const;
-
- // Helper method to copy frames from one AudioBus to another. Both AudioBus
- // objects must have the same number of channels(). |source_start_frame| is
- // the starting offset. |dest_start_frame| is the starting offset in |dest|.
- // |frame_count| is the number of frames to copy.
- void CopyPartialFramesTo(int source_start_frame, int frame_count,
- int dest_start_frame, AudioBus* dest) const;
-
- // Returns a raw pointer to the requested channel. Pointer is guaranteed to
- // have a 16-byte alignment. Warning: Do not rely on having sane (i.e. not
- // inf, nan, or between [-1.0, 1.0]) values in the channel data.
- float* channel(int channel) { return channel_data_[channel]; }
- const float* channel(int channel) const { return channel_data_[channel]; }
-
- // Returns the number of channels.
- int channels() const { return static_cast<int>(channel_data_.size()); }
- // Returns the number of frames.
- int frames() const { return frames_; }
-
- // Helper method for zeroing out all channels of audio data.
- void Zero();
- void ZeroFrames(int frames);
- void ZeroFramesPartial(int start_frame, int frames);
-
- // Checks if all frames are zero.
- bool AreFramesZero() const;
-
- // Scale internal channel values by |volume| >= 0. If an invalid value
- // is provided, no adjustment is done.
- void Scale(float volume);
-
- // Swaps channels identified by |a| and |b|. The caller needs to make sure
- // the channels are valid.
- void SwapChannels(int a, int b);
-
- virtual ~AudioBus();
-
- protected:
- AudioBus(int channels, int frames);
- AudioBus(int channels, int frames, float* data);
- AudioBus(int frames, const std::vector<float*>& channel_data);
- explicit AudioBus(int channels);
-
- private:
- // Helper method for building |channel_data_| from a block of memory. |data|
- // must be at least CalculateMemorySize(...) bytes in size.
- void BuildChannelData(int channels, int aligned_frame, float* data);
-
- static void CheckOverflow(int start_frame, int frames, int total_frames);
-
- template <class SourceSampleTypeTraits>
- static void CopyConvertFromInterleavedSourceToAudioBus(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int write_offset_in_frames, int num_frames_to_write, AudioBus* dest);
-
- template <class TargetSampleTypeTraits>
- static void CopyConvertFromAudioBusToInterleavedTarget(
- const AudioBus* source, int read_offset_in_frames, int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest_buffer);
-
- // Contiguous block of channel memory.
- scoped_ptr_malloc<float, base::ScopedPtrAlignedFree> data_;
-
- // One float pointer per channel pointing to a contiguous block of memory for
- // that channel. If the memory is owned by this instance, this will
- // point to the memory in |data_|. Otherwise, it may point to memory provided
- // by the client.
- std::vector<float*> channel_data_;
- int frames_;
-
- // Protect SetChannelData() and set_frames() for use by CreateWrapper().
- bool can_set_channel_data_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioBus);
-};
-
-// Delegates to FromInterleavedPartial()
-template <class SourceSampleTypeTraits>
-void AudioBus::FromInterleaved(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int num_frames_to_write) {
- FromInterleavedPartial<SourceSampleTypeTraits>(source_buffer, 0,
- num_frames_to_write);
- // Zero any remaining frames.
- ZeroFramesPartial(num_frames_to_write, frames_ - num_frames_to_write);
-}
-
-template <class SourceSampleTypeTraits>
-void AudioBus::FromInterleavedPartial(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int write_offset_in_frames, int num_frames_to_write) {
- CheckOverflow(write_offset_in_frames, num_frames_to_write, frames_);
- CopyConvertFromInterleavedSourceToAudioBus<SourceSampleTypeTraits>(
- source_buffer, write_offset_in_frames, num_frames_to_write, this);
-}
-
-// Delegates to ToInterleavedPartial()
-template <class TargetSampleTypeTraits>
-void AudioBus::ToInterleaved(
- int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest_buffer) const {
- ToInterleavedPartial<TargetSampleTypeTraits>(0, num_frames_to_read,
- dest_buffer);
-}
-
-template <class TargetSampleTypeTraits>
-void AudioBus::ToInterleavedPartial(
- int read_offset_in_frames, int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest) const {
- CheckOverflow(read_offset_in_frames, num_frames_to_read, frames_);
- CopyConvertFromAudioBusToInterleavedTarget<TargetSampleTypeTraits>(
- this, read_offset_in_frames, num_frames_to_read, dest);
-}
-
-// TODO(chfremer): Consider using vector instructions to speed this up,
-// https://crbug.com/619628
-template <class SourceSampleTypeTraits>
-void AudioBus::CopyConvertFromInterleavedSourceToAudioBus(
- const typename SourceSampleTypeTraits::ValueType* source_buffer,
- int write_offset_in_frames, int num_frames_to_write, AudioBus* dest) {
- const int channels = dest->channels();
- for (int ch = 0; ch < channels; ++ch) {
- float* channel_data = dest->channel(ch);
- for (int target_frame_index = write_offset_in_frames,
- read_pos_in_source = ch;
- target_frame_index < write_offset_in_frames + num_frames_to_write;
- ++target_frame_index, read_pos_in_source += channels) {
- auto source_value = source_buffer[read_pos_in_source];
- channel_data[target_frame_index] =
- SourceSampleTypeTraits::ToFloat(source_value);
- }
- }
-}
-
-// TODO(chfremer): Consider using vector instructions to speed this up,
-// https://crbug.com/619628
-template <class TargetSampleTypeTraits>
-void AudioBus::CopyConvertFromAudioBusToInterleavedTarget(
- const AudioBus* source, int read_offset_in_frames, int num_frames_to_read,
- typename TargetSampleTypeTraits::ValueType* dest_buffer) {
- const int channels = source->channels();
- for (int ch = 0; ch < channels; ++ch) {
- const float* channel_data = source->channel(ch);
- for (int source_frame_index = read_offset_in_frames, write_pos_in_dest = ch;
- source_frame_index < read_offset_in_frames + num_frames_to_read;
- ++source_frame_index, write_pos_in_dest += channels) {
- float sourceSampleValue = channel_data[source_frame_index];
- dest_buffer[write_pos_in_dest] =
- TargetSampleTypeTraits::FromFloat(sourceSampleValue);
- }
- }
-}
-
-// RefCounted version of AudioBus. This is not meant for general use. Only use
-// this when your lifetime requirements make it impossible to use an
-// AudioBus scoped_ptr.
-class MEDIA_EXPORT AudioBusRefCounted
- : public media::AudioBus,
- public base::RefCountedThreadSafe<AudioBusRefCounted> {
- public:
- static scoped_refptr<AudioBusRefCounted> Create(int channels, int frames);
-
- private:
- friend class base::RefCountedThreadSafe<AudioBusRefCounted>;
-
- AudioBusRefCounted(int channels, int frames);
- ~AudioBusRefCounted() OVERRIDE;
-
- DISALLOW_COPY_AND_ASSIGN(AudioBusRefCounted);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_BUS_H_
diff --git a/src/cobalt/media/base/audio_capturer_source.h b/src/cobalt/media/base/audio_capturer_source.h
deleted file mode 100644
index 9f7f3fa..0000000
--- a/src/cobalt/media/base/audio_capturer_source.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
-#define COBALT_MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
-
-#include <string>
-#include <vector>
-
-#include "base/memory/ref_counted.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_parameters.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-// AudioCapturerSource is an interface representing the source for
-// captured audio. An implementation will periodically call Capture() on a
-// callback object.
-class AudioCapturerSource
- : public base::RefCountedThreadSafe<media::AudioCapturerSource> {
- public:
- class CaptureCallback {
- public:
- // Callback to deliver the captured data from the OS.
- // TODO(chcunningham): Update delay argument to use frames instead of
- // milliseconds to prevent loss of precision. See http://crbug.com/587291.
- virtual void Capture(const AudioBus* audio_source,
- int audio_delay_milliseconds, double volume,
- bool key_pressed) = 0;
-
- // Signals an error has occurred.
- virtual void OnCaptureError(const std::string& message) = 0;
-
- protected:
- virtual ~CaptureCallback() {}
- };
-
- // Sets information about the audio stream format and the device
- // to be used. It must be called before any of the other methods.
- // The |session_id| is used by the browser to identify which input device to
- // be used. For clients who do not care about device permission and device
- // selection, pass |session_id| using
- // AudioInputDeviceManager::kFakeOpenSessionId.
- virtual void Initialize(const AudioParameters& params,
- CaptureCallback* callback, int session_id) = 0;
-
- // Starts the audio recording.
- virtual void Start() = 0;
-
- // Stops the audio recording. This API is synchronous, and no more data
- // callback will be passed to the client after it is being called.
- virtual void Stop() = 0;
-
- // Sets the capture volume, with range [0.0, 1.0] inclusive.
- virtual void SetVolume(double volume) = 0;
-
- // Enables or disables the WebRtc AGC control.
- virtual void SetAutomaticGainControl(bool enable) = 0;
-
- protected:
- friend class base::RefCountedThreadSafe<AudioCapturerSource>;
- virtual ~AudioCapturerSource() {}
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_CAPTURER_SOURCE_H_
diff --git a/src/cobalt/media/base/audio_decoder.cc b/src/cobalt/media/base/audio_decoder.cc
deleted file mode 100644
index ea41120..0000000
--- a/src/cobalt/media/base/audio_decoder.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_decoder.h"
-
-#include "cobalt/media/base/audio_buffer.h"
-
-namespace cobalt {
-namespace media {
-
-AudioDecoder::AudioDecoder() {}
-
-AudioDecoder::~AudioDecoder() {}
-
-bool AudioDecoder::NeedsBitstreamConversion() const { return false; }
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_fifo.cc b/src/cobalt/media/base/audio_fifo.cc
deleted file mode 100644
index 87a3156..0000000
--- a/src/cobalt/media/base/audio_fifo.cc
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_fifo.h"
-
-#include "base/logging.h"
-#include "starboard/memory.h"
-
-namespace cobalt {
-namespace media {
-
-// Given current position in the FIFO, the maximum number of elements in the
-// FIFO and the size of the input; this method provides two output results:
-// |size| and |wrap_size|. These two results can then be utilized for memcopy
-// operations to and from the FIFO.
-// Under "normal" circumstances, |size| will be equal to |in_size| and
-// |wrap_size| will be zero. This case corresponding to the non-wrapping case
-// where we have not yet reached the "edge" of the FIFO. If |pos| + |in_size|
-// exceeds the total size of the FIFO, we must wrap around and start reusing
-// a part the allocated memory. The size of this part is given by |wrap_size|.
-static void GetSizes(int pos, int max_size, int in_size, int* size,
- int* wrap_size) {
- if (pos + in_size > max_size) {
- // Wrapping is required => derive size of each segment.
- *size = max_size - pos;
- *wrap_size = in_size - *size;
- } else {
- // Wrapping is not required.
- *size = in_size;
- *wrap_size = 0;
- }
-}
-
-// Updates the read/write position with |step| modulo the maximum number of
-// elements in the FIFO to ensure that the position counters wraps around at
-// the endpoint.
-static int UpdatePos(int pos, int step, int max_size) {
- return ((pos + step) % max_size);
-}
-
-AudioFifo::AudioFifo(int channels, int frames)
- : audio_bus_(AudioBus::Create(channels, frames)),
- max_frames_(frames),
- frames_pushed_(0),
- frames_consumed_(0),
- read_pos_(0),
- write_pos_(0) {}
-
-AudioFifo::~AudioFifo() {}
-
-int AudioFifo::frames() const {
- int delta = frames_pushed_ - frames_consumed_;
- return delta;
-}
-
-void AudioFifo::Push(const AudioBus* source) {
- DCHECK(source);
- DCHECK_EQ(source->channels(), audio_bus_->channels());
-
- // Ensure that there is space for the new data in the FIFO.
- const int source_size = source->frames();
- CHECK_LE(source_size + frames(), max_frames_);
-
- // Figure out if wrapping is needed and if so what segment sizes we need
- // when adding the new audio bus content to the FIFO.
- int append_size = 0;
- int wrap_size = 0;
- GetSizes(write_pos_, max_frames(), source_size, &append_size, &wrap_size);
-
- // Copy all channels from the source to the FIFO. Wrap around if needed.
- for (int ch = 0; ch < source->channels(); ++ch) {
- float* dest = audio_bus_->channel(ch);
- const float* src = source->channel(ch);
-
- // Append part of (or the complete) source to the FIFO.
- SbMemoryCopy(&dest[write_pos_], &src[0], append_size * sizeof(src[0]));
- if (wrap_size > 0) {
- // Wrapping is needed: copy remaining part from the source to the FIFO.
- SbMemoryCopy(&dest[0], &src[append_size], wrap_size * sizeof(src[0]));
- }
- }
-
- frames_pushed_ += source_size;
- DCHECK_LE(frames(), max_frames());
- write_pos_ = UpdatePos(write_pos_, source_size, max_frames());
-}
-
-void AudioFifo::Consume(AudioBus* destination, int start_frame,
- int frames_to_consume) {
- DCHECK(destination);
- DCHECK_EQ(destination->channels(), audio_bus_->channels());
-
- // It is not possible to ask for more data than what is available in the FIFO.
- CHECK_LE(frames_to_consume, frames());
-
- // A copy from the FIFO to |destination| will only be performed if the
- // allocated memory in |destination| is sufficient.
- CHECK_LE(frames_to_consume + start_frame, destination->frames());
-
- // Figure out if wrapping is needed and if so what segment sizes we need
- // when removing audio bus content from the FIFO.
- int consume_size = 0;
- int wrap_size = 0;
- GetSizes(read_pos_, max_frames(), frames_to_consume, &consume_size,
- &wrap_size);
-
- // For all channels, remove the requested amount of data from the FIFO
- // and copy the content to the destination. Wrap around if needed.
- for (int ch = 0; ch < destination->channels(); ++ch) {
- float* dest = destination->channel(ch);
- const float* src = audio_bus_->channel(ch);
-
- // Copy a selected part of the FIFO to the destination.
- SbMemoryCopy(&dest[start_frame], &src[read_pos_],
- consume_size * sizeof(src[0]));
- if (wrap_size > 0) {
- // Wrapping is needed: copy remaining part to the destination.
- SbMemoryCopy(&dest[consume_size + start_frame], &src[0],
- wrap_size * sizeof(src[0]));
- }
- }
-
- frames_consumed_ += frames_to_consume;
- read_pos_ = UpdatePos(read_pos_, frames_to_consume, max_frames());
-}
-
-void AudioFifo::Clear() {
- frames_pushed_ = 0;
- frames_consumed_ = 0;
- read_pos_ = 0;
- write_pos_ = 0;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_fifo.h b/src/cobalt/media/base/audio_fifo.h
deleted file mode 100644
index 007aa14..0000000
--- a/src/cobalt/media/base/audio_fifo.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_FIFO_H_
-#define COBALT_MEDIA_BASE_AUDIO_FIFO_H_
-
-#include <memory>
-
-#include "base/basictypes.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-// First-in first-out container for AudioBus elements.
-// The maximum number of audio frames in the FIFO is set at construction and
-// can not be extended dynamically. The allocated memory is utilized as a
-// ring buffer.
-// This class is thread-unsafe.
-class MEDIA_EXPORT AudioFifo {
- public:
- // Creates a new AudioFifo and allocates |channels| of length |frames|.
- AudioFifo(int channels, int frames);
- virtual ~AudioFifo();
-
- // Pushes all audio channel data from |source| to the FIFO.
- // Push() will crash if the allocated space is insufficient.
- void Push(const AudioBus* source);
-
- // Consumes |frames_to_consume| audio frames from the FIFO and copies
- // them to |destination| starting at position |start_frame|.
- // Consume() will crash if the FIFO does not contain |frames_to_consume|
- // frames or if there is insufficient space in |destination| to store the
- // frames.
- void Consume(AudioBus* destination, int start_frame, int frames_to_consume);
-
- // Empties the FIFO without deallocating any memory.
- void Clear();
-
- // Number of actual audio frames in the FIFO.
- int frames() const;
-
- int max_frames() const { return max_frames_; }
-
- private:
- // The actual FIFO is an audio bus implemented as a ring buffer.
- std::unique_ptr<AudioBus> audio_bus_;
-
- // Maximum number of elements the FIFO can contain.
- // This value is set by |frames| in the constructor.
- const int max_frames_;
-
- // Number of actual elements in the FIFO.
- int frames_pushed_;
- int frames_consumed_;
-
- // Current read position.
- int read_pos_;
-
- // Current write position.
- int write_pos_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioFifo);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_FIFO_H_
diff --git a/src/cobalt/media/base/audio_hash.cc b/src/cobalt/media/base/audio_hash.cc
deleted file mode 100644
index f88da39..0000000
--- a/src/cobalt/media/base/audio_hash.cc
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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 "cobalt/media/base/audio_hash.h"
-
-// MSVC++ requires this to be set before any other includes to get M_PI.
-#define _USE_MATH_DEFINES
-#include <cmath>
-#include <sstream>
-
-#include "base/basictypes.h"
-#include "base/stringprintf.h"
-#include "cobalt/media/base/audio_bus.h"
-
-namespace cobalt {
-namespace media {
-
-AudioHash::AudioHash() : audio_hash_(), sample_count_(0) {}
-
-AudioHash::~AudioHash() {}
-
-void AudioHash::Update(const AudioBus* audio_bus, int frames) {
- // Use uint32_t to ensure overflow is a defined operation.
- for (uint32_t ch = 0; ch < static_cast<uint32_t>(audio_bus->channels());
- ++ch) {
- const float* channel = audio_bus->channel(ch);
- for (uint32_t i = 0; i < static_cast<uint32_t>(frames); ++i) {
- const uint32_t kSampleIndex = sample_count_ + i;
- const uint32_t kHashIndex =
- (kSampleIndex * (ch + 1)) % arraysize(audio_hash_);
-
- // Mix in a sine wave with the result so we ensure that sequences of empty
- // buffers don't result in an empty hash.
- if (ch == 0) {
- audio_hash_[kHashIndex] +=
- channel[i] + sin(2.0 * M_PI * M_PI * kSampleIndex);
- } else {
- audio_hash_[kHashIndex] += channel[i];
- }
- }
- }
-
- sample_count_ += static_cast<uint32_t>(frames);
-}
-
-std::string AudioHash::ToString() const {
- std::string result;
- for (size_t i = 0; i < arraysize(audio_hash_); ++i)
- result += base::StringPrintf("%.2f,", audio_hash_[i]);
- return result;
-}
-
-bool AudioHash::IsEquivalent(const std::string& other, double tolerance) const {
- float other_hash;
- char comma;
-
- std::stringstream is(other);
- for (size_t i = 0; i < arraysize(audio_hash_); ++i) {
- is >> other_hash >> comma;
- if (fabs(audio_hash_[i] - other_hash) > tolerance) return false;
- }
- return true;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_hash.h b/src/cobalt/media/base/audio_hash.h
deleted file mode 100644
index 66594b4..0000000
--- a/src/cobalt/media/base/audio_hash.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_HASH_H_
-#define COBALT_MEDIA_BASE_AUDIO_HASH_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/string_piece.h"
-#include "cobalt/media/base/media_export.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-class AudioBus;
-
-// Computes a running hash for a series of AudioBus objects. The hash is the
-// sum of each sample bucketed based on the frame index, channel number, and
-// current hash count. The hash was designed with two properties in mind:
-//
-// 1. Uniform error distribution across the input sample.
-// 2. Resilience to error below a certain threshold.
-//
-// The first is achieved by using a simple summing approach and moving position
-// weighting into the bucket choice. The second is handled during conversion to
-// string by rounding out values to only two decimal places.
-//
-// Using only two decimal places allows for roughly -40 dBFS of error. For
-// reference, SincResampler produces an RMS error of around -15 dBFS. See
-// http://en.wikipedia.org/wiki/DBFS and http://crbug.com/168204 for more info.
-class MEDIA_EXPORT AudioHash {
- public:
- AudioHash();
- ~AudioHash();
-
- // Update current hash with the contents of the provided AudioBus.
- void Update(const AudioBus* audio_bus, int frames);
-
- // Return a string representation of the current hash.
- std::string ToString() const;
-
- // Compare with another hash value given as string representation.
- // Returns true if for every bucket the difference between this and
- // other is less than tolerance.
- bool IsEquivalent(const std::string& other, double tolerance) const;
-
- private:
- // Storage for the audio hash. The number of buckets controls the importance
- // of position in the hash. A higher number reduces the chance of false
- // positives related to incorrect sample position. Value chosen by dice roll.
- float audio_hash_[6];
-
- // The total number of samples processed per channel. Uses a uint32_t instead
- // of size_t so overflows on 64-bit and 32-bit machines are equivalent.
- uint32_t sample_count_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioHash);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_HASH_H_
diff --git a/src/cobalt/media/base/audio_hash_unittest.cc b/src/cobalt/media/base/audio_hash_unittest.cc
deleted file mode 100644
index 4f1ebbc..0000000
--- a/src/cobalt/media/base/audio_hash_unittest.cc
+++ /dev/null
@@ -1,172 +0,0 @@
-// 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 <algorithm>
-#include <memory>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_hash.h"
-#include "cobalt/media/base/fake_audio_render_callback.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-static const int kChannelCount = 2;
-static const int kFrameCount = 1024;
-
-class AudioHashTest : public testing::Test {
- public:
- AudioHashTest()
- : bus_one_(AudioBus::Create(kChannelCount, kFrameCount)),
- bus_two_(AudioBus::Create(kChannelCount, kFrameCount)),
- fake_callback_(0.01) {
- // Fill each channel in each bus with unique data.
- GenerateUniqueChannels(bus_one_.get());
- GenerateUniqueChannels(bus_two_.get());
- }
-
- void GenerateUniqueChannels(AudioBus* audio_bus) {
- // Use an AudioBus wrapper to avoid an extra memcpy when filling channels.
- std::unique_ptr<AudioBus> wrapped_bus = AudioBus::CreateWrapper(1);
- wrapped_bus->set_frames(audio_bus->frames());
-
- // Since FakeAudioRenderCallback generates only a single channel of unique
- // audio data, we need to fill each channel manually.
- for (int ch = 0; ch < audio_bus->channels(); ++ch) {
- wrapped_bus->SetChannelData(0, audio_bus->channel(ch));
- fake_callback_.Render(wrapped_bus.get(), 0, 0);
- }
- }
-
- ~AudioHashTest() override {}
-
- protected:
- std::unique_ptr<AudioBus> bus_one_;
- std::unique_ptr<AudioBus> bus_two_;
- FakeAudioRenderCallback fake_callback_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AudioHashTest);
-};
-
-// Ensure the same data hashes the same.
-TEST_F(AudioHashTest, Equivalence) {
- AudioHash hash_one;
- hash_one.Update(bus_one_.get(), bus_one_->frames());
-
- AudioHash hash_two;
- hash_two.Update(bus_one_.get(), bus_one_->frames());
-
- EXPECT_EQ(hash_one.ToString(), hash_two.ToString());
-}
-
-// Ensure sample order matters to the hash.
-TEST_F(AudioHashTest, SampleOrder) {
- AudioHash original_hash;
- original_hash.Update(bus_one_.get(), bus_one_->frames());
-
- // Swap a sample in the bus.
- std::swap(bus_one_->channel(0)[0], bus_one_->channel(0)[1]);
-
- AudioHash swapped_hash;
- swapped_hash.Update(bus_one_.get(), bus_one_->frames());
-
- EXPECT_NE(original_hash.ToString(), swapped_hash.ToString());
-}
-
-// Ensure channel order matters to the hash.
-TEST_F(AudioHashTest, ChannelOrder) {
- AudioHash original_hash;
- original_hash.Update(bus_one_.get(), bus_one_->frames());
-
- // Reverse channel order for the same sample data.
- const int channels = bus_one_->channels();
- std::unique_ptr<AudioBus> swapped_ch_bus = AudioBus::CreateWrapper(channels);
- swapped_ch_bus->set_frames(bus_one_->frames());
- for (int i = channels - 1; i >= 0; --i)
- swapped_ch_bus->SetChannelData(channels - (i + 1), bus_one_->channel(i));
-
- AudioHash swapped_hash;
- swapped_hash.Update(swapped_ch_bus.get(), swapped_ch_bus->frames());
-
- EXPECT_NE(original_hash.ToString(), swapped_hash.ToString());
-}
-
-// Ensure bus order matters to the hash.
-TEST_F(AudioHashTest, BusOrder) {
- AudioHash original_hash;
- original_hash.Update(bus_one_.get(), bus_one_->frames());
- original_hash.Update(bus_two_.get(), bus_two_->frames());
-
- AudioHash reordered_hash;
- reordered_hash.Update(bus_two_.get(), bus_two_->frames());
- reordered_hash.Update(bus_one_.get(), bus_one_->frames());
-
- EXPECT_NE(original_hash.ToString(), reordered_hash.ToString());
-}
-
-// Ensure bus order matters to the hash even with empty buses.
-TEST_F(AudioHashTest, EmptyBusOrder) {
- bus_one_->Zero();
- bus_two_->Zero();
-
- AudioHash one_bus_hash;
- one_bus_hash.Update(bus_one_.get(), bus_one_->frames());
-
- AudioHash two_bus_hash;
- two_bus_hash.Update(bus_one_.get(), bus_one_->frames());
- two_bus_hash.Update(bus_two_.get(), bus_two_->frames());
-
- EXPECT_NE(one_bus_hash.ToString(), two_bus_hash.ToString());
-}
-
-// Where A = [0, n], ensure hash(A[0:n/2]), hash(A[n/2:n]) and hash(A) result
-// in the same value.
-TEST_F(AudioHashTest, HashIgnoresUpdateOrder) {
- AudioHash full_hash;
- full_hash.Update(bus_one_.get(), bus_one_->frames());
-
- AudioHash half_hash;
- half_hash.Update(bus_one_.get(), bus_one_->frames() / 2);
-
- // Create a new bus representing the second half of |bus_one_|.
- const int half_frames = bus_one_->frames() / 2;
- const int channels = bus_one_->channels();
- std::unique_ptr<AudioBus> half_bus = AudioBus::CreateWrapper(channels);
- half_bus->set_frames(half_frames);
- for (int i = 0; i < channels; ++i)
- half_bus->SetChannelData(i, bus_one_->channel(i) + half_frames);
-
- half_hash.Update(half_bus.get(), half_bus->frames());
- EXPECT_EQ(full_hash.ToString(), half_hash.ToString());
-}
-
-// Ensure approximate hashes pass verification.
-TEST_F(AudioHashTest, VerifySimilarHash) {
- AudioHash hash_one;
- hash_one.Update(bus_one_.get(), bus_one_->frames());
-
- // Twiddle the values inside the first bus.
- float* channel = bus_one_->channel(0);
- for (int i = 0; i < bus_one_->frames(); i += bus_one_->frames() / 64)
- channel[i] += 0.0001f;
-
- AudioHash hash_two;
- hash_two.Update(bus_one_.get(), bus_one_->frames());
-
- EXPECT_EQ(hash_one.ToString(), hash_two.ToString());
-
- // Twiddle the values too much...
- for (int i = 0; i < bus_one_->frames(); ++i) channel[i] += 0.0001f;
-
- AudioHash hash_three;
- hash_three.Update(bus_one_.get(), bus_one_->frames());
- EXPECT_NE(hash_one.ToString(), hash_three.ToString());
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_latency.cc b/src/cobalt/media/base/audio_latency.cc
deleted file mode 100644
index 9379217..0000000
--- a/src/cobalt/media/base/audio_latency.cc
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2016 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 "cobalt/media/base/audio_latency.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "build/build_config.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-namespace {
-#if !defined(OS_WIN)
-// Taken from "Bit Twiddling Hacks"
-// http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
-uint32_t RoundUpToPowerOfTwo(uint32_t v) {
- v--;
- v |= v >> 1;
- v |= v >> 2;
- v |= v >> 4;
- v |= v >> 8;
- v |= v >> 16;
- v++;
- return v;
-}
-#endif
-} // namespace
-
-// static
-int AudioLatency::GetHighLatencyBufferSize(int sample_rate,
- int preferred_buffer_size) {
- // Empirically, we consider 20ms of samples to be high latency.
- const double twenty_ms_size = 2.0 * sample_rate / 100;
-
-#if defined(OS_WIN)
- preferred_buffer_size = std::max(preferred_buffer_size, 1);
-
- // Windows doesn't use power of two buffer sizes, so we should always round up
- // to the nearest multiple of the output buffer size.
- const int high_latency_buffer_size =
- std::ceil(twenty_ms_size / preferred_buffer_size) * preferred_buffer_size;
-#else
- // On other platforms use the nearest higher power of two buffer size. For a
- // given sample rate, this works out to:
- //
- // <= 3200 : 64
- // <= 6400 : 128
- // <= 12800 : 256
- // <= 25600 : 512
- // <= 51200 : 1024
- // <= 102400 : 2048
- // <= 204800 : 4096
- //
- // On Linux, the minimum hardware buffer size is 512, so the lower calculated
- // values are unused. OSX may have a value as low as 128.
- const int high_latency_buffer_size = RoundUpToPowerOfTwo(twenty_ms_size);
-#endif // defined(OS_WIN)
-
-#if defined(OS_CHROMEOS)
- return high_latency_buffer_size; // No preference.
-#else
- return std::max(preferred_buffer_size, high_latency_buffer_size);
-#endif // defined(OS_CHROMEOS)
-}
-
-// static
-int AudioLatency::GetRtcBufferSize(int sample_rate, int hardware_buffer_size) {
- // Use native hardware buffer size as default. On Windows, we strive to open
- // up using this native hardware buffer size to achieve best
- // possible performance and to ensure that no FIFO is needed on the browser
- // side to match the client request. That is why there is no #if case for
- // Windows below.
- int frames_per_buffer = hardware_buffer_size;
-
- // No |hardware_buffer_size| is specified, fall back to 10 ms buffer size.
- if (!frames_per_buffer) {
- frames_per_buffer = sample_rate / 100;
- DVLOG(1) << "Using 10 ms sink output buffer size: " << frames_per_buffer;
- return frames_per_buffer;
- }
-
-#if defined(OS_LINUX) || defined(OS_MACOSX)
- // On Linux and MacOS, the low level IO implementations on the browser side
- // supports all buffer size the clients want. We use the native peer
- // connection buffer size (10ms) to achieve best possible performance.
- frames_per_buffer = sample_rate / 100;
-#elif defined(OS_ANDROID)
- // TODO(olka/henrika): This settings are very old, need to be revisited.
- int frames_per_10ms = sample_rate / 100;
- if (frames_per_buffer < 2 * frames_per_10ms) {
- // Examples of low-latency frame sizes and the resulting |buffer_size|:
- // Nexus 7 : 240 audio frames => 2*480 = 960
- // Nexus 10 : 256 => 2*441 = 882
- // Galaxy Nexus: 144 => 2*441 = 882
- frames_per_buffer = 2 * frames_per_10ms;
- DVLOG(1) << "Low-latency output detected on Android";
- }
-#endif
-
- DVLOG(1) << "Using sink output buffer size: " << frames_per_buffer;
- return frames_per_buffer;
-}
-
-// static
-int AudioLatency::GetInteractiveBufferSize(int hardware_buffer_size) {
-#if defined(OS_ANDROID)
- // The optimum low-latency hardware buffer size is usually too small on
- // Android for WebAudio to render without glitching. So, if it is small, use
- // a larger size.
- //
- // Since WebAudio renders in 128-frame blocks, the small buffer sizes (144 for
- // a Galaxy Nexus), cause significant processing jitter. Sometimes multiple
- // blocks will processed, but other times will not be since the WebAudio can't
- // satisfy the request. By using a larger render buffer size, we smooth out
- // the jitter.
- const int kSmallBufferSize = 1024;
- const int kDefaultCallbackBufferSize = 2048;
- if (hardware_buffer_size <= kSmallBufferSize)
- return kDefaultCallbackBufferSize;
-#endif
-
- return hardware_buffer_size;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_latency.h b/src/cobalt/media/base/audio_latency.h
deleted file mode 100644
index bc6681f..0000000
--- a/src/cobalt/media/base/audio_latency.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2016 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_LATENCY_H_
-#define COBALT_MEDIA_BASE_AUDIO_LATENCY_H_
-
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-class MEDIA_EXPORT AudioLatency {
- public:
- // Categories of expected latencies for input/output audio. Do not change
- // existing values, they are used for UMA histogram reporting.
- enum LatencyType {
- // Specific latency in milliseconds.
- LATENCY_EXACT_MS = 0,
- // Lowest possible latency which does not cause glitches.
- LATENCY_INTERACTIVE = 1,
- // Latency optimized for real time communication.
- LATENCY_RTC = 2,
- // Latency optimized for continuous playback and power saving.
- LATENCY_PLAYBACK = 3,
- // For validation only.
- LATENCY_LAST = LATENCY_PLAYBACK,
- LATENCY_COUNT = LATENCY_LAST + 1
- };
-
- // |preferred_buffer_size| should be set to 0 if a client has no preference.
- static int GetHighLatencyBufferSize(int sample_rate,
- int preferred_buffer_size);
-
- // |hardware_buffer_size| should be set to 0 if unknown/invalid/not preferred.
- static int GetRtcBufferSize(int sample_rate, int hardware_buffer_size);
-
- static int GetInteractiveBufferSize(int hardware_buffer_size);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_LATENCY_H_
diff --git a/src/cobalt/media/base/audio_latency_unittest.cc b/src/cobalt/media/base/audio_latency_unittest.cc
deleted file mode 100644
index 542fba9..0000000
--- a/src/cobalt/media/base/audio_latency_unittest.cc
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2016 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 "cobalt/media/base/audio_latency.h"
-
-#include "base/logging.h"
-#include "build/build_config.h"
-#include "starboard/types.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-// TODO(olka): extend unit tests, use real-world sample rates.
-
-TEST(AudioLatency, HighLatencyBufferSizes) {
-#if defined(OS_WIN)
- for (int i = 6400; i <= 204800; i *= 2) {
- EXPECT_EQ(2 * (i / 100),
- AudioLatency::GetHighLatencyBufferSize(i, i / 100));
- }
-#else
- for (int i = 6400; i <= 204800; i *= 2)
- EXPECT_EQ(2 * (i / 100), AudioLatency::GetHighLatencyBufferSize(i, 32));
-#endif // defined(OS_WIN)
-}
-
-TEST(AudioLatency, InteractiveBufferSizes) {
-#if defined(OS_ANDROID)
- int i = 6400;
- for (; i <= 102400; i *= 2)
- EXPECT_EQ(2048, AudioLatency::GetInteractiveBufferSize(i / 100));
- for (; i <= 204800; i *= 2)
- EXPECT_EQ(i / 100, AudioLatency::GetInteractiveBufferSize(i / 100));
-#else
- for (int i = 6400; i <= 204800; i *= 2)
- EXPECT_EQ(i / 100, AudioLatency::GetInteractiveBufferSize(i / 100));
-#endif // defined(OS_ANDROID)
-}
-
-TEST(AudioLatency, RtcBufferSizes) {
- for (int i = 6400; i < 204800; i *= 2) {
- EXPECT_EQ(i / 100, AudioLatency::GetRtcBufferSize(i, 0));
-#if defined(OS_WIN)
- EXPECT_EQ(500, AudioLatency::GetRtcBufferSize(i, 500));
-#elif defined(OS_ANDROID)
- EXPECT_EQ(i / 50, AudioLatency::GetRtcBufferSize(i, i / 50 - 1));
- EXPECT_EQ(i / 50 + 1, AudioLatency::GetRtcBufferSize(i, i / 50 + 1));
-#else
- EXPECT_EQ(i / 100, AudioLatency::GetRtcBufferSize(i, 500));
-#endif // defined(OS_WIN)
- }
-}
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_point.cc b/src/cobalt/media/base/audio_point.cc
deleted file mode 100644
index 9d86f87..0000000
--- a/src/cobalt/media/base/audio_point.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2015 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 "cobalt/media/base/audio_point.h"
-
-#include "base/logging.h"
-#include "base/string_number_conversions.h"
-#include "base/string_split.h"
-#include "base/string_util.h"
-#include "base/stringprintf.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-std::string PointsToString(const std::vector<Point>& points) {
- std::string points_string;
- if (!points.empty()) {
- for (size_t i = 0; i < points.size() - 1; ++i) {
- points_string.append(points[i].ToString());
- points_string.append(", ");
- }
- points_string.append(points.back().ToString());
- }
- return points_string;
-}
-
-std::vector<Point> ParsePointsFromString(const std::string& points_string) {
- std::vector<Point> points;
- if (points_string.empty()) return points;
-
- const auto& tokens =
- base::SplitString(points_string, base::kWhitespaceASCII,
- base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
- if (tokens.size() < 3 || tokens.size() % 3 != 0) {
- LOG(ERROR) << "Malformed points string: " << points_string;
- return points;
- }
-
- std::vector<float> float_tokens;
- float_tokens.reserve(tokens.size());
- for (const auto& token : tokens) {
- double float_token;
- if (!base::StringToDouble(token, &float_token)) {
- LOG(ERROR) << "Unable to convert token=" << token
- << " to double from points string: " << points_string;
- return points;
- }
- float_tokens.push_back(float_token);
- }
-
- points.reserve(float_tokens.size() / 3);
- for (size_t i = 0; i < float_tokens.size(); i += 3) {
- points.push_back(
- Point(float_tokens[i + 0], float_tokens[i + 1], float_tokens[i + 2]));
- }
-
- return points;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_point.h b/src/cobalt/media/base/audio_point.h
deleted file mode 100644
index 4f6f989..0000000
--- a/src/cobalt/media/base/audio_point.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2015 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_POINT_H_
-#define COBALT_MEDIA_BASE_AUDIO_POINT_H_
-
-#include <string>
-#include <vector>
-
-#include "cobalt/media/base/media_export.h"
-#include "ui/gfx/geometry/point3_f.h"
-
-namespace cobalt {
-namespace media {
-
-using Point = gfx::Point3F;
-
-// Returns a vector of points parsed from a whitespace-separated string
-// formatted as: "x1 y1 z1 ... zn yn zn" for n points.
-//
-// Returns an empty vector if |points_string| is empty or isn't parseable.
-MEDIA_EXPORT std::vector<Point> ParsePointsFromString(
- const std::string& points_string);
-
-// Returns |points| as a human-readable string. (Not necessarily in the format
-// required by ParsePointsFromString).
-MEDIA_EXPORT std::string PointsToString(const std::vector<Point>& points);
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_POINT_H_
diff --git a/src/cobalt/media/base/audio_point_unittest.cc b/src/cobalt/media/base/audio_point_unittest.cc
deleted file mode 100644
index a9d82b3..0000000
--- a/src/cobalt/media/base/audio_point_unittest.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2015 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 <cmath>
-
-#include "cobalt/media/base/audio_point.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-namespace {
-
-TEST(PointTest, PointsToString) {
- std::vector<Point> points(1, Point(1, 0, 0.01f));
- points.push_back(Point(0, 2, 0.02f));
- EXPECT_EQ("1.000000,0.000000,0.010000, 0.000000,2.000000,0.020000",
- PointsToString(points));
-
- EXPECT_EQ("", PointsToString(std::vector<Point>()));
-}
-
-TEST(PointTest, ParsePointString) {
- const std::vector<Point> expected_empty;
- EXPECT_EQ(expected_empty, ParsePointsFromString(""));
- EXPECT_EQ(expected_empty, ParsePointsFromString("0 0 a"));
- EXPECT_EQ(expected_empty, ParsePointsFromString("1 2"));
- EXPECT_EQ(expected_empty, ParsePointsFromString("1 2 3 4"));
-
- {
- std::vector<Point> expected(1, Point(-0.02f, 0, 0));
- expected.push_back(Point(0.02f, 0, 0));
- EXPECT_EQ(expected, ParsePointsFromString("-0.02 0 0 0.02 0 0"));
- }
- {
- std::vector<Point> expected(1, Point(1, 2, 3));
- EXPECT_EQ(expected, ParsePointsFromString("1 2 3"));
- }
-}
-
-} // namespace
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_pull_fifo.cc b/src/cobalt/media/base/audio_pull_fifo.cc
deleted file mode 100644
index 758d94c..0000000
--- a/src/cobalt/media/base/audio_pull_fifo.cc
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_pull_fifo.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "starboard/memory.h"
-
-namespace cobalt {
-namespace media {
-
-AudioPullFifo::AudioPullFifo(int channels, int frames, const ReadCB& read_cb)
- : read_cb_(read_cb),
- fifo_(AudioBus::Create(channels, frames)),
- fifo_index_(frames) {}
-
-AudioPullFifo::~AudioPullFifo() {}
-
-void AudioPullFifo::Consume(AudioBus* destination, int frames_to_consume) {
- DCHECK_LE(frames_to_consume, destination->frames());
-
- int remaining_frames_to_provide = frames_to_consume;
-
- // Try to fulfill the request using what's available in the FIFO.
- int frames_read = ReadFromFifo(destination, remaining_frames_to_provide, 0);
- int write_pos = frames_read;
- remaining_frames_to_provide -= frames_read;
-
- // Get the remaining audio frames from the producer using the callback.
- while (remaining_frames_to_provide > 0) {
- DCHECK_EQ(fifo_index_, fifo_->frames());
- fifo_index_ = 0;
-
- // Fill up the FIFO by acquiring audio data from the producer.
- read_cb_.Run(write_pos, fifo_.get());
-
- // Try to fulfill the request using what's available in the FIFO.
- frames_read =
- ReadFromFifo(destination, remaining_frames_to_provide, write_pos);
- write_pos += frames_read;
- remaining_frames_to_provide -= frames_read;
- }
-}
-
-void AudioPullFifo::Clear() { fifo_index_ = fifo_->frames(); }
-
-int AudioPullFifo::SizeInFrames() const { return fifo_->frames(); }
-
-int AudioPullFifo::ReadFromFifo(AudioBus* destination, int frames_to_provide,
- int write_pos) {
- int frames = std::min(frames_to_provide, fifo_->frames() - fifo_index_);
- if (frames <= 0) return 0;
-
- for (int ch = 0; ch < fifo_->channels(); ++ch) {
- const float* src = fifo_->channel(ch) + fifo_index_;
- float* dest = destination->channel(ch) + write_pos;
- SbMemoryCopy(dest, src, frames * sizeof(*src));
- }
-
- fifo_index_ += frames;
- return frames;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_pull_fifo.h b/src/cobalt/media/base/audio_pull_fifo.h
deleted file mode 100644
index 4c1271f..0000000
--- a/src/cobalt/media/base/audio_pull_fifo.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_PULL_FIFO_H_
-#define COBALT_MEDIA_BASE_AUDIO_PULL_FIFO_H_
-
-#include <memory>
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-class AudioBus;
-
-// A FIFO (First In First Out) buffer to handle mismatches in buffer sizes
-// between a producer and consumer. The consumer will pull data from this FIFO.
-// If data is already available in the FIFO, it is provided to the consumer.
-// If insufficient data is available to satisfy the request, the FIFO will ask
-// the producer for more data to fulfill a request.
-class MEDIA_EXPORT AudioPullFifo {
- public:
- // Callback type for providing more data into the FIFO. Expects AudioBus
- // to be completely filled with data upon return; zero padded if not enough
- // frames are available to satisfy the request. |frame_delay| is the number
- // of output frames already processed and can be used to estimate delay.
- typedef base::Callback<void(int frame_delay, AudioBus* audio_bus)> ReadCB;
-
- // Constructs an AudioPullFifo with the specified |read_cb|, which is used to
- // read audio data to the FIFO if data is not already available. The internal
- // FIFO can contain |channel| number of channels, where each channel is of
- // length |frames| audio frames.
- AudioPullFifo(int channels, int frames, const ReadCB& read_cb);
- virtual ~AudioPullFifo();
-
- // Consumes |frames_to_consume| audio frames from the FIFO and copies
- // them to |destination|. If the FIFO does not have enough data, we ask
- // the producer to give us more data to fulfill the request using the
- // ReadCB implementation.
- void Consume(AudioBus* destination, int frames_to_consume);
-
- // Empties the FIFO without deallocating any memory.
- void Clear();
-
- // Returns the size of the fifo in number of frames.
- int SizeInFrames() const;
-
- private:
- // Attempt to fulfill the request using what is available in the FIFO.
- // Append new data to the |destination| starting at |write_pos|.
- int ReadFromFifo(AudioBus* destination, int frames_to_provide, int write_pos);
-
- // Source of data to the FIFO.
- const ReadCB read_cb_;
-
- // Temporary audio bus to hold the data from the producer.
- std::unique_ptr<AudioBus> fifo_;
- int fifo_index_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioPullFifo);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_PULL_FIFO_H_
diff --git a/src/cobalt/media/base/audio_pull_fifo_unittest.cc b/src/cobalt/media/base/audio_pull_fifo_unittest.cc
deleted file mode 100644
index d2ded4c..0000000
--- a/src/cobalt/media/base/audio_pull_fifo_unittest.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright (c) 2012 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 <memory>
-
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/stringprintf.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_pull_fifo.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-// Block diagram of a possible real-world usage:
-//
-// | Producer | ----> | AudioPullFifo | ----> | Consumer |
-// push pull
-// 2048 ----> (2048) ----> ~512
-
-// Number of channels in each audio bus.
-static int kChannels = 2;
-
-// Max number of audio framed the FIFO can contain.
-static const int kMaxFramesInFifo = 2048;
-
-class AudioPullFifoTest : public testing::TestWithParam<int> {
- public:
- AudioPullFifoTest()
- : pull_fifo_(kChannels, kMaxFramesInFifo,
- base::Bind(&AudioPullFifoTest::ProvideInput,
- base::Unretained(this))),
- audio_bus_(AudioBus::Create(kChannels, kMaxFramesInFifo)),
- fill_value_(0),
- last_frame_delay_(-1) {
- EXPECT_EQ(kMaxFramesInFifo, pull_fifo_.SizeInFrames());
- }
- virtual ~AudioPullFifoTest() {}
-
- void VerifyValue(const float data[], int size, float start_value) {
- float value = start_value;
- for (int i = 0; i < size; ++i) {
- ASSERT_FLOAT_EQ(value++, data[i]) << "i=" << i;
- }
- }
-
- // Consume data using different sizes, acquire audio frames from the FIFO
- // and verify that the retrieved values matches the values written by the
- // producer.
- void ConsumeTest(int frames_to_consume) {
- int start_value = 0;
- SCOPED_TRACE(
- base::StringPrintf("Checking frames_to_consume %d", frames_to_consume));
- pull_fifo_.Consume(audio_bus_.get(), frames_to_consume);
- for (int j = 0; j < kChannels; ++j) {
- VerifyValue(audio_bus_->channel(j), frames_to_consume, start_value);
- }
- start_value += frames_to_consume;
- EXPECT_LT(last_frame_delay_, audio_bus_->frames());
- }
-
- // AudioPullFifo::ReadCB implementation where we increase a value for each
- // audio frame that we provide. Note that all channels are given the same
- // value to simplify the verification.
- virtual void ProvideInput(int frame_delay, AudioBus* audio_bus) {
- ASSERT_GT(frame_delay, last_frame_delay_);
- last_frame_delay_ = frame_delay;
-
- EXPECT_EQ(audio_bus->channels(), audio_bus_->channels());
- EXPECT_EQ(audio_bus->frames(), kMaxFramesInFifo);
- for (int i = 0; i < audio_bus->frames(); ++i) {
- for (int j = 0; j < audio_bus->channels(); ++j) {
- // Store same value in all channels.
- audio_bus->channel(j)[i] = fill_value_;
- }
- fill_value_++;
- }
- }
-
- protected:
- AudioPullFifo pull_fifo_;
- std::unique_ptr<AudioBus> audio_bus_;
- int fill_value_;
- int last_frame_delay_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AudioPullFifoTest);
-};
-
-TEST_P(AudioPullFifoTest, Consume) { ConsumeTest(GetParam()); }
-
-// Test common |frames_to_consume| values which will be used as input
-// parameter to AudioPullFifo::Consume() when the consumer asks for data.
-INSTANTIATE_TEST_CASE_P(AudioPullFifoTest, AudioPullFifoTest,
- testing::Values(544, 512, 512, 512, 512, 2048, 544, 441,
- 440, 433, 500));
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_push_fifo.cc b/src/cobalt/media/base/audio_push_fifo.cc
deleted file mode 100644
index 8bea7dfe..0000000
--- a/src/cobalt/media/base/audio_push_fifo.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2016 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 "cobalt/media/base/audio_push_fifo.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-
-namespace cobalt {
-namespace media {
-
-AudioPushFifo::AudioPushFifo(const OutputCallback& callback)
- : callback_(callback), frames_per_buffer_(0) {
- DCHECK(!callback_.is_null());
-}
-
-AudioPushFifo::~AudioPushFifo() {}
-
-void AudioPushFifo::Reset(int frames_per_buffer) {
- DCHECK_GT(frames_per_buffer, 0);
-
- audio_queue_.reset();
- queued_frames_ = 0;
-
- frames_per_buffer_ = frames_per_buffer;
-}
-
-void AudioPushFifo::Push(const AudioBus& input_bus) {
- DCHECK_GT(frames_per_buffer_, 0);
-
- // Fast path: No buffering required.
- if ((queued_frames_ == 0) && (input_bus.frames() == frames_per_buffer_)) {
- callback_.Run(input_bus, 0);
- return;
- }
-
- // Lazy-create the |audio_queue_| if needed.
- if (!audio_queue_ || audio_queue_->channels() != input_bus.channels())
- audio_queue_ = AudioBus::Create(input_bus.channels(), frames_per_buffer_);
-
- // Start with a frame offset that refers to the position of the first sample
- // in |audio_queue_| relative to the first sample in |input_bus|.
- int frame_delay = -queued_frames_;
-
- // Repeatedly fill up |audio_queue_| with more sample frames from |input_bus|
- // and deliver batches until all sample frames in |input_bus| have been
- // consumed.
- int input_offset = 0;
- do {
- // Attempt to fill |audio_queue_| completely.
- const int frames_to_enqueue =
- std::min(static_cast<int>(input_bus.frames() - input_offset),
- frames_per_buffer_ - queued_frames_);
- if (frames_to_enqueue > 0) {
- DVLOG(2) << "Enqueuing " << frames_to_enqueue << " frames.";
- input_bus.CopyPartialFramesTo(input_offset, frames_to_enqueue,
- queued_frames_, audio_queue_.get());
- queued_frames_ += frames_to_enqueue;
- input_offset += frames_to_enqueue;
- }
-
- // If |audio_queue_| has been filled completely, deliver the re-buffered
- // audio to the consumer.
- if (queued_frames_ == frames_per_buffer_) {
- DVLOG(2) << "Delivering another " << queued_frames_ << " frames.";
- callback_.Run(*audio_queue_, frame_delay);
- frame_delay += frames_per_buffer_;
- queued_frames_ = 0;
- } else {
- // Not enough frames queued-up yet to deliver more frames.
- }
- } while (input_offset < input_bus.frames());
-}
-
-void AudioPushFifo::Flush() {
- if (queued_frames_ == 0) return;
-
- audio_queue_->ZeroFramesPartial(queued_frames_,
- audio_queue_->frames() - queued_frames_);
- callback_.Run(*audio_queue_, -queued_frames_);
- queued_frames_ = 0;
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_push_fifo.h b/src/cobalt/media/base/audio_push_fifo.h
deleted file mode 100644
index 846eff9..0000000
--- a/src/cobalt/media/base/audio_push_fifo.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2016 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_PUSH_FIFO_H_
-#define COBALT_MEDIA_BASE_AUDIO_PUSH_FIFO_H_
-
-#include <memory>
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-// Yet another FIFO for audio data that re-buffers audio to a desired buffer
-// size. Unlike AudioFifo and AudioBlockFifo, this FIFO cannot overflow: The
-// client is required to provide a callback that is called synchronously during
-// a push whenever enough data becomes available. This implementation
-// eliminates redundant memory copies when the input buffer size always matches
-// the desired buffer size.
-class MEDIA_EXPORT AudioPushFifo final {
- public:
- // Called synchronously zero, one, or multiple times during a call to Push()
- // to deliver re-buffered audio. |frame_delay| refers to the position of the
- // first frame in |output| relative to the first frame in the Push() call. If
- // negative, this indicates the output contains some data from a prior call to
- // Push(). If zero or positive, the output contains data from the current
- // call to Push(). Clients can use this to adjust timestamps.
- using OutputCallback =
- base::Callback<void(const AudioBus& output_bus, int frame_delay)>;
-
- // Creates a new AudioPushFifo which delivers re-buffered audio by running
- // |callback|.
- explicit AudioPushFifo(const OutputCallback& callback);
-
- ~AudioPushFifo();
-
- // Returns the number of frames in each AudioBus delivered to the
- // OutputCallback.
- int frames_per_buffer() const { return frames_per_buffer_; }
-
- // Must be called at least once before the first call to Push(). May be
- // called later (e.g., to support an audio format change).
- void Reset(int frames_per_buffer);
-
- // Pushes all audio channel data from |input_bus| through the FIFO. This will
- // result in zero, one, or multiple synchronous calls to the OutputCallback
- // provided in the constructor. If the |input_bus| has a different number of
- // channels than the prior Push() call, any currently-queued frames will be
- // dropped.
- void Push(const AudioBus& input_bus);
-
- // Flushes any enqueued frames by invoking the OutputCallback with those
- // frames plus padded zero samples. If there are no frames currently
- // enqueued, OutputCallback is not run.
- void Flush();
-
- private:
- const OutputCallback callback_;
-
- int frames_per_buffer_;
-
- // Queue of frames pending for delivery.
- std::unique_ptr<AudioBus> audio_queue_;
- int queued_frames_;
-
- DISALLOW_COPY_AND_ASSIGN(AudioPushFifo);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_PUSH_FIFO_H_
diff --git a/src/cobalt/media/base/audio_push_fifo_unittest.cc b/src/cobalt/media/base/audio_push_fifo_unittest.cc
deleted file mode 100644
index 3c3ebf4..0000000
--- a/src/cobalt/media/base/audio_push_fifo_unittest.cc
+++ /dev/null
@@ -1,249 +0,0 @@
-// Copyright 2016 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 <algorithm>
-#include <limits>
-#include <memory>
-#include <vector>
-
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_push_fifo.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-namespace {
-
-class AudioPushFifoTest : public testing::TestWithParam<int> {
- public:
- AudioPushFifoTest() {}
- ~AudioPushFifoTest() override {}
-
- int output_chunk_size() const { return GetParam(); }
-
- void SetUp() final {
- fifo_.reset(new AudioPushFifo(base::Bind(
- &AudioPushFifoTest::ReceiveAndCheckNextChunk, base::Unretained(this))));
- fifo_->Reset(output_chunk_size());
- ASSERT_EQ(output_chunk_size(), fifo_->frames_per_buffer());
- }
-
- protected:
- struct OutputChunkResult {
- int num_frames;
- float first_sample_value;
- float last_sample_value;
- int frame_delay;
- };
-
- // Returns the number of output chunks that should have been emitted given the
- // number of input frames pushed so far.
- size_t GetExpectedOutputChunks(int frames_pushed) const {
- return static_cast<size_t>(frames_pushed / output_chunk_size());
- }
-
- // Returns the number of Push() calls to make in order to get at least 3
- // output chunks.
- int GetNumPushTestIterations(int input_chunk_size) const {
- return 3 * std::max(1, output_chunk_size() / input_chunk_size);
- }
-
- // Repeatedly pushes constant-sized batches of input samples and checks that
- // the input data is re-chunked correctly.
- void RunSimpleRechunkTest(int input_chunk_size) {
- const int num_iterations = GetNumPushTestIterations(input_chunk_size);
-
- int sample_value = 0;
- const std::unique_ptr<AudioBus> audio_bus =
- AudioBus::Create(1, input_chunk_size);
-
- for (int i = 0; i < num_iterations; ++i) {
- EXPECT_EQ(GetExpectedOutputChunks(i * input_chunk_size), results_.size());
-
- // Fill audio data with predictable values.
- for (int j = 0; j < audio_bus->frames(); ++j)
- audio_bus->channel(0)[j] = static_cast<float>(sample_value++);
-
- fifo_->Push(*audio_bus);
- // Note: AudioPushFifo has just called ReceiveAndCheckNextChunk() zero or
- // more times.
- }
- EXPECT_EQ(GetExpectedOutputChunks(num_iterations * input_chunk_size),
- results_.size());
-
- // Confirm first and last sample values that have been output are the
- // expected ones.
- ASSERT_FALSE(results_.empty());
- EXPECT_EQ(0.0f, results_.front().first_sample_value);
- const float last_value_in_last_chunk = static_cast<float>(
- GetExpectedOutputChunks(num_iterations * input_chunk_size) *
- output_chunk_size() -
- 1);
- EXPECT_EQ(last_value_in_last_chunk, results_.back().last_sample_value);
-
- // Confirm the expected frame delays for the first output chunk (or two).
- if (input_chunk_size < output_chunk_size()) {
- const int num_queued_before_first_output =
- ((output_chunk_size() - 1) / input_chunk_size) * input_chunk_size;
- EXPECT_EQ(-num_queued_before_first_output, results_.front().frame_delay);
- } else if (input_chunk_size >= output_chunk_size()) {
- EXPECT_EQ(0, results_[0].frame_delay);
- if (input_chunk_size >= 2 * output_chunk_size()) {
- EXPECT_EQ(output_chunk_size(), results_[1].frame_delay);
- } else {
- const int num_remaining_after_first_output =
- input_chunk_size - output_chunk_size();
- EXPECT_EQ(-num_remaining_after_first_output, results_[1].frame_delay);
- }
- }
-
- const size_t num_results_before_flush = results_.size();
- fifo_->Flush();
- const size_t num_results_after_flush = results_.size();
- if (num_results_after_flush > num_results_before_flush) {
- EXPECT_NE(0, results_.back().frame_delay);
- EXPECT_LT(-output_chunk_size(), results_.back().frame_delay);
- }
- }
-
- // Returns a "random" integer in the range [begin,end).
- int GetRandomInRange(int begin, int end) {
- const int len = end - begin;
- const int rand_offset = (len == 0) ? 0 : (NextRandomInt() % (end - begin));
- return begin + rand_offset;
- }
-
- std::unique_ptr<AudioPushFifo> fifo_;
- std::vector<OutputChunkResult> results_;
-
- private:
- // Called by |fifo_| to deliver another chunk of audio. Sanity checks
- // the sample values are as expected, and without any dropped/duplicated, and
- // adds a result to |results_|.
- void ReceiveAndCheckNextChunk(const AudioBus& audio_bus, int frame_delay) {
- OutputChunkResult result;
- result.num_frames = audio_bus.frames();
- result.first_sample_value = audio_bus.channel(0)[0];
- result.last_sample_value = audio_bus.channel(0)[audio_bus.frames() - 1];
- result.frame_delay = frame_delay;
-
- // Check that each sample value is the previous sample value plus one.
- for (int i = 1; i < audio_bus.frames(); ++i) {
- const float expected_value = result.first_sample_value + i;
- const float actual_value = audio_bus.channel(0)[i];
- if (actual_value != expected_value) {
- if (actual_value == 0.0f) {
- // This chunk is probably being emitted by a Flush(). If that's true
- // then the frame_delay will be negative and the rest of the
- // |audio_bus| should be all zeroes.
- ASSERT_GT(0, frame_delay);
- for (int j = i + 1; j < audio_bus.frames(); ++j)
- ASSERT_EQ(0.0f, audio_bus.channel(0)[j]);
- break;
- } else {
- ASSERT_EQ(expected_value, actual_value) << "Sample at offset " << i
- << " is incorrect.";
- }
- }
- }
-
- results_.push_back(result);
- }
-
- // Note: Not using base::RandInt() because it is horribly slow on debug
- // builds. The following is a very simple, deterministic LCG:
- int NextRandomInt() {
- rand_seed_ = (1103515245 * rand_seed_ + 12345) % (1 << 31);
- return static_cast<int>(rand_seed_);
- }
-
- uint32_t rand_seed_ = 0x7e110;
-
- DISALLOW_COPY_AND_ASSIGN(AudioPushFifoTest);
-};
-
-// Tests an atypical edge case: Push()ing one frame at a time.
-TEST_P(AudioPushFifoTest, PushOneFrameAtATime) { RunSimpleRechunkTest(1); }
-
-// Tests that re-chunking the audio from common platform input chunk sizes
-// works.
-TEST_P(AudioPushFifoTest, Push128FramesAtATime) { RunSimpleRechunkTest(128); }
-TEST_P(AudioPushFifoTest, Push512FramesAtATime) { RunSimpleRechunkTest(512); }
-
-// Tests that re-chunking the audio from common "10 ms" input chunk sizes
-// works (44100 Hz * 10 ms = 441, and 48000 Hz * 10 ms = 480).
-TEST_P(AudioPushFifoTest, Push441FramesAtATime) { RunSimpleRechunkTest(441); }
-TEST_P(AudioPushFifoTest, Push480FramesAtATime) { RunSimpleRechunkTest(480); }
-
-// Tests that re-chunking when input audio is provided in varying chunk sizes
-// works.
-TEST_P(AudioPushFifoTest, PushArbitraryNumbersOfFramesAtATime) {
- // The loop below will run until both: 1) kMinNumIterations loops have
- // occurred; and 2) there are at least 3 entries in |results_|.
- const int kMinNumIterations = 30;
-
- int sample_value = 0;
- int frames_pushed_so_far = 0;
- for (int i = 0; i < kMinNumIterations || results_.size() < 3; ++i) {
- EXPECT_EQ(GetExpectedOutputChunks(frames_pushed_so_far), results_.size());
-
- // Create an AudioBus of a random length, populated with sample values.
- const int input_chunk_size = GetRandomInRange(1, 1920);
- const std::unique_ptr<AudioBus> audio_bus =
- AudioBus::Create(1, input_chunk_size);
- for (int j = 0; j < audio_bus->frames(); ++j)
- audio_bus->channel(0)[j] = static_cast<float>(sample_value++);
-
- fifo_->Push(*audio_bus);
- // Note: AudioPushFifo has just called ReceiveAndCheckNextChunk() zero or
- // more times.
-
- frames_pushed_so_far += input_chunk_size;
- }
- EXPECT_EQ(GetExpectedOutputChunks(frames_pushed_so_far), results_.size());
-
- ASSERT_FALSE(results_.empty());
- EXPECT_EQ(0.0f, results_.front().first_sample_value);
- const float last_value_in_last_chunk = static_cast<float>(
- GetExpectedOutputChunks(frames_pushed_so_far) * output_chunk_size() - 1);
- EXPECT_EQ(last_value_in_last_chunk, results_.back().last_sample_value);
-
- const size_t num_results_before_flush = results_.size();
- fifo_->Flush();
- const size_t num_results_after_flush = results_.size();
- if (num_results_after_flush > num_results_before_flush) {
- EXPECT_NE(0, results_.back().frame_delay);
- EXPECT_LT(-output_chunk_size(), results_.back().frame_delay);
- }
-}
-
-INSTANTIATE_TEST_CASE_P(, AudioPushFifoTest,
- ::testing::Values(
- // 1 ms output chunks at common sample rates.
- 16, // 16000 Hz
- 22, // 22050 Hz
- 44, // 44100 Hz
- 48, // 48000 Hz
-
- // 10 ms output chunks at common sample rates.
- 160, // 16000 Hz
- 220, // 22050 Hz
- 441, // 44100 Hz
- 480, // 48000 Hz
-
- // 60 ms output chunks at common sample rates.
- 960, // 16000 Hz
- 1323, // 22050 Hz
- 2646, // 44100 Hz
- 2880 // 48000 Hz
- ));
-
-} // namespace
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_renderer.cc b/src/cobalt/media/base/audio_renderer.cc
deleted file mode 100644
index 1dae249..0000000
--- a/src/cobalt/media/base/audio_renderer.cc
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_renderer.h"
-
-namespace cobalt {
-namespace media {
-
-AudioRenderer::AudioRenderer() {}
-AudioRenderer::~AudioRenderer() {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_renderer.h b/src/cobalt/media/base/audio_renderer.h
deleted file mode 100644
index f6a9628..0000000
--- a/src/cobalt/media/base/audio_renderer.h
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_RENDERER_H_
-#define COBALT_MEDIA_BASE_AUDIO_RENDERER_H_
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "base/time.h"
-#include "cobalt/media/base/buffering_state.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/pipeline_status.h"
-
-namespace cobalt {
-namespace media {
-
-class CdmContext;
-class DemuxerStream;
-class RendererClient;
-class TimeSource;
-
-class MEDIA_EXPORT AudioRenderer {
- public:
- AudioRenderer();
-
- // Stop all operations and fire all pending callbacks.
- virtual ~AudioRenderer();
-
- // Initialize an AudioRenderer with |stream|, executing |init_cb| upon
- // completion. If initialization fails, only |init_cb|
- // (not RendererClient::OnError) will be called.
- //
- // |cdm_context| can be used to handle encrypted streams. May be null if the
- // stream is not encrypted.
- virtual void Initialize(DemuxerStream* stream, CdmContext* cdm_context,
- RendererClient* client,
- const PipelineStatusCB& init_cb) = 0;
-
- // Returns the TimeSource associated with audio rendering.
- virtual TimeSource* GetTimeSource() = 0;
-
- // Discard any audio data, executing |callback| when completed.
- //
- // Clients should expect |buffering_state_cb| to be called with
- // BUFFERING_HAVE_NOTHING while flushing is in progress.
- virtual void Flush(const base::Closure& callback) = 0;
-
- // Starts playback by reading from |stream| and decoding and rendering audio.
- //
- // Only valid to call after a successful Initialize() or Flush().
- virtual void StartPlaying() = 0;
-
- // Sets the output volume.
- virtual void SetVolume(float volume) = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AudioRenderer);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_RENDERER_H_
diff --git a/src/cobalt/media/base/audio_renderer_sink.h b/src/cobalt/media/base/audio_renderer_sink.h
deleted file mode 100644
index 2795952..0000000
--- a/src/cobalt/media/base/audio_renderer_sink.h
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_RENDERER_SINK_H_
-#define COBALT_MEDIA_BASE_AUDIO_RENDERER_SINK_H_
-
-#include <string>
-
-#include "base/callback.h"
-#include "base/memory/ref_counted.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_parameters.h"
-#include "cobalt/media/base/output_device_info.h"
-#include "starboard/types.h"
-#include "url/origin.h"
-
-namespace cobalt {
-namespace media {
-
-// AudioRendererSink is an interface representing the end-point for
-// rendered audio. An implementation is expected to
-// periodically call Render() on a callback object.
-
-class AudioRendererSink
- : public base::RefCountedThreadSafe<media::AudioRendererSink> {
- public:
- class RenderCallback {
- public:
- // Attempts to completely fill all channels of |dest|, returns actual
- // number of frames filled. |frames_skipped| contains the number of frames
- // the consumer has skipped, if any.
- // TODO(jameswest): Change to use the same signature as
- // AudioOutputStream::AudioSourceCallback::OnMoreData.
- virtual int Render(AudioBus* dest, uint32_t frames_delayed,
- uint32_t frames_skipped) = 0;
-
- // Signals an error has occurred.
- virtual void OnRenderError() = 0;
-
- protected:
- virtual ~RenderCallback() {}
- };
-
- // Sets important information about the audio stream format.
- // It must be called before any of the other methods.
- virtual void Initialize(const AudioParameters& params,
- RenderCallback* callback) = 0;
-
- // Starts audio playback.
- virtual void Start() = 0;
-
- // Stops audio playback and performs cleanup. It must be called before
- // destruction.
- virtual void Stop() = 0;
-
- // Pauses playback.
- virtual void Pause() = 0;
-
- // Resumes playback after calling Pause().
- virtual void Play() = 0;
-
- // Sets the playback volume, with range [0.0, 1.0] inclusive.
- // Returns |true| on success.
- virtual bool SetVolume(double volume) = 0;
-
- // Returns current output device information. If the information is not
- // available yet, this method may block until it becomes available.
- // If the sink is not associated with any output device, |device_status| of
- // OutputDeviceInfo should be set to OUTPUT_DEVICE_STATUS_ERROR_INTERNAL.
- // Must never be called on the IO thread.
- virtual OutputDeviceInfo GetOutputDeviceInfo() = 0;
-
- // If DCHECKs are enabled, this function returns true if called on rendering
- // thread, otherwise false. With DCHECKs disabled, it returns true. Thus, it
- // is intended to be used for DCHECKing.
- virtual bool CurrentThreadIsRenderingThread() = 0;
-
- protected:
- friend class base::RefCountedThreadSafe<AudioRendererSink>;
- virtual ~AudioRendererSink() {}
-};
-
-// Same as AudioRendererSink except that Initialize() and Start() can be called
-// again after Stop().
-// TODO(sandersd): Fold back into AudioRendererSink once all subclasses support
-// this.
-
-class RestartableAudioRendererSink : public AudioRendererSink {
- protected:
- ~RestartableAudioRendererSink() override {}
-};
-
-class SwitchableAudioRendererSink : public RestartableAudioRendererSink {
- public:
- // Attempts to switch the audio output device associated with a sink.
- // Once the attempt is finished, |callback| is invoked with the
- // result of the operation passed as a parameter. The result is a value from
- // the media::OutputDeviceStatus enum.
- // There is no guarantee about the thread where |callback| will be invoked.
- virtual void SwitchOutputDevice(const std::string& device_id,
- const url::Origin& security_origin,
- const OutputDeviceStatusCB& callback) = 0;
-
- protected:
- ~SwitchableAudioRendererSink() override {}
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_RENDERER_SINK_H_
diff --git a/src/cobalt/media/base/audio_splicer.cc b/src/cobalt/media/base/audio_splicer.cc
deleted file mode 100644
index 9414daf..0000000
--- a/src/cobalt/media/base/audio_splicer.cc
+++ /dev/null
@@ -1,551 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_splicer.h"
-
-#include <algorithm>
-#include <cstdlib>
-#include <deque>
-#include <utility>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_decoder_config.h"
-#include "cobalt/media/base/audio_timestamp_helper.h"
-#include "cobalt/media/base/media_log.h"
-#include "cobalt/media/base/vector_math.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-namespace {
-
-enum {
- // Minimum gap size needed before the splicer will take action to
- // fill a gap. This avoids periodically inserting and then dropping samples
- // when the buffer timestamps are slightly off because of timestamp rounding
- // in the source content. Unit is frames.
- kMinGapSize = 2,
-
- // Limits the number of MEDIA_LOG() per sanitizer instance warning the user
- // about splicer overlaps within |kMaxTimeDeltaInMilliseconds| or gaps larger
- // than |kMinGapSize| and less than |kMaxTimeDeltaInMilliseconds|. These
- // warnings may be frequent for some streams, and number of sanitizer
- // instances may be high, so keep this limit low to help reduce log spam.
- kMaxSanitizerWarningLogs = 5,
-};
-
-// AudioBuffer::TrimStart() is not as accurate as the timestamp helper, so
-// manually adjust the duration and timestamp after trimming.
-void AccurateTrimStart(int frames_to_trim,
- const scoped_refptr<AudioBuffer> buffer,
- const AudioTimestampHelper& timestamp_helper) {
- buffer->TrimStart(frames_to_trim);
- buffer->set_timestamp(timestamp_helper.GetTimestamp());
-}
-
-// Returns an AudioBus whose frame buffer is backed by the provided AudioBuffer.
-std::unique_ptr<AudioBus> CreateAudioBufferWrapper(
- const scoped_refptr<AudioBuffer>& buffer) {
- std::unique_ptr<AudioBus> wrapper =
- AudioBus::CreateWrapper(buffer->channel_count());
- wrapper->set_frames(buffer->frame_count());
- for (int ch = 0; ch < buffer->channel_count(); ++ch) {
- wrapper->SetChannelData(
- ch, reinterpret_cast<float*>(buffer->channel_data()[ch]));
- }
- return wrapper;
-}
-
-} // namespace
-
-class AudioStreamSanitizer {
- public:
- AudioStreamSanitizer(int samples_per_second,
- const scoped_refptr<MediaLog>& media_log);
- ~AudioStreamSanitizer();
-
- // Resets the sanitizer state by clearing the output buffers queue, and
- // resetting the timestamp helper.
- void Reset();
-
- // Similar to Reset(), but initializes the timestamp helper with the given
- // parameters.
- void ResetTimestampState(int64_t frame_count, base::TimeDelta base_timestamp);
-
- // Adds a new buffer full of samples or end of stream buffer to the splicer.
- // Returns true if the buffer was accepted. False is returned if an error
- // occurred.
- bool AddInput(const scoped_refptr<AudioBuffer>& input);
-
- // Returns true if the sanitizer has a buffer to return.
- bool HasNextBuffer() const;
-
- // Removes the next buffer from the output buffer queue and returns it; should
- // only be called if HasNextBuffer() returns true.
- scoped_refptr<AudioBuffer> GetNextBuffer();
-
- // Returns the total frame count of all buffers available for output.
- int GetFrameCount() const;
-
- const AudioTimestampHelper& timestamp_helper() {
- return output_timestamp_helper_;
- }
-
- // Transfer all buffers into |output|. Returns false if AddInput() on the
- // |output| sanitizer fails for any buffer removed from |this|.
- bool DrainInto(AudioStreamSanitizer* output);
-
- private:
- void AddOutputBuffer(const scoped_refptr<AudioBuffer>& buffer);
-
- AudioTimestampHelper output_timestamp_helper_;
- bool received_end_of_stream_ = false;
-
- typedef std::deque<scoped_refptr<AudioBuffer> > BufferQueue;
- BufferQueue output_buffers_;
-
- scoped_refptr<MediaLog> media_log_;
-
- // To prevent log spam, counts the number of audio gap or overlaps warned in
- // logs.
- int num_warning_logs_ = 0;
-
- DISALLOW_ASSIGN(AudioStreamSanitizer);
-};
-
-AudioStreamSanitizer::AudioStreamSanitizer(
- int samples_per_second, const scoped_refptr<MediaLog>& media_log)
- : output_timestamp_helper_(samples_per_second), media_log_(media_log) {}
-
-AudioStreamSanitizer::~AudioStreamSanitizer() {}
-
-void AudioStreamSanitizer::Reset() { ResetTimestampState(0, kNoTimestamp); }
-
-void AudioStreamSanitizer::ResetTimestampState(int64_t frame_count,
- base::TimeDelta base_timestamp) {
- output_buffers_.clear();
- received_end_of_stream_ = false;
- output_timestamp_helper_.SetBaseTimestamp(base_timestamp);
- if (frame_count > 0) output_timestamp_helper_.AddFrames(frame_count);
-}
-
-bool AudioStreamSanitizer::AddInput(const scoped_refptr<AudioBuffer>& input) {
- DCHECK(!received_end_of_stream_ || input->end_of_stream());
-
- if (input->end_of_stream()) {
- output_buffers_.push_back(input);
- received_end_of_stream_ = true;
- return true;
- }
-
- DCHECK(input->timestamp() != kNoTimestamp);
- DCHECK(input->duration() > base::TimeDelta());
- DCHECK_GT(input->frame_count(), 0);
-
- if (output_timestamp_helper_.base_timestamp() == kNoTimestamp)
- output_timestamp_helper_.SetBaseTimestamp(input->timestamp());
-
- if (output_timestamp_helper_.base_timestamp() > input->timestamp()) {
- MEDIA_LOG(ERROR, media_log_)
- << "Audio splicing failed: unexpected timestamp sequence. base "
- "timestamp="
- << output_timestamp_helper_.base_timestamp().InMicroseconds()
- << "us, input timestamp=" << input->timestamp().InMicroseconds()
- << "us";
- return false;
- }
-
- const base::TimeDelta timestamp = input->timestamp();
- const base::TimeDelta expected_timestamp =
- output_timestamp_helper_.GetTimestamp();
- const base::TimeDelta delta = timestamp - expected_timestamp;
-
- if (std::abs(delta.InMilliseconds()) >
- AudioSplicer::kMaxTimeDeltaInMilliseconds) {
- MEDIA_LOG(ERROR, media_log_)
- << "Audio splicing failed: coded frame timestamp differs from "
- "expected timestamp "
- << expected_timestamp.InMicroseconds() << "us by "
- << delta.InMicroseconds() << "us, more than threshold of +/-"
- << AudioSplicer::kMaxTimeDeltaInMilliseconds
- << "ms. Expected timestamp is based on decoded frames and frame rate.";
- return false;
- }
-
- int frames_to_fill = 0;
- if (!delta.is_zero())
- frames_to_fill = output_timestamp_helper_.GetFramesToTarget(timestamp);
-
- if (frames_to_fill == 0 || std::abs(frames_to_fill) < kMinGapSize) {
- AddOutputBuffer(input);
- return true;
- }
-
- if (frames_to_fill > 0) {
- LIMITED_MEDIA_LOG(DEBUG, media_log_, num_warning_logs_,
- kMaxSanitizerWarningLogs)
- << "Audio splicer inserting silence for small gap of "
- << delta.InMicroseconds() << "us at time "
- << expected_timestamp.InMicroseconds() << "us.";
- DVLOG(1) << "Gap detected @ " << expected_timestamp.InMicroseconds()
- << " us: " << delta.InMicroseconds() << " us";
-
- // Create a buffer with enough silence samples to fill the gap and
- // add it to the output buffer.
- scoped_refptr<AudioBuffer> gap = AudioBuffer::CreateEmptyBuffer(
- input->channel_layout(), input->channel_count(), input->sample_rate(),
- frames_to_fill, expected_timestamp);
- AddOutputBuffer(gap);
-
- // Add the input buffer now that the gap has been filled.
- AddOutputBuffer(input);
- return true;
- }
-
- // Overlapping buffers marked as splice frames are handled by AudioSplicer,
- // but decoder and demuxer quirks may sometimes produce overlapping samples
- // which need to be sanitized.
- //
- // A crossfade can't be done here because only the current buffer is available
- // at this point, not previous buffers.
- LIMITED_MEDIA_LOG(DEBUG, media_log_, num_warning_logs_,
- kMaxSanitizerWarningLogs)
- << "Audio splicer skipping frames for small overlap of "
- << -delta.InMicroseconds() << "us at time "
- << expected_timestamp.InMicroseconds() << "us.";
- DVLOG(1) << "Overlap detected @ " << expected_timestamp.InMicroseconds()
- << " us: " << -delta.InMicroseconds() << " us";
-
- const int frames_to_skip = -frames_to_fill;
- if (input->frame_count() <= frames_to_skip) {
- DVLOG(1) << "Dropping whole buffer";
- return true;
- }
-
- // Copy the trailing samples that do not overlap samples already output
- // into a new buffer. Add this new buffer to the output queue.
- //
- // TODO(acolwell): Implement a cross-fade here so the transition is less
- // jarring.
- AccurateTrimStart(frames_to_skip, input, output_timestamp_helper_);
- AddOutputBuffer(input);
- return true;
-}
-
-bool AudioStreamSanitizer::HasNextBuffer() const {
- return !output_buffers_.empty();
-}
-
-scoped_refptr<AudioBuffer> AudioStreamSanitizer::GetNextBuffer() {
- scoped_refptr<AudioBuffer> ret = output_buffers_.front();
- output_buffers_.pop_front();
- return ret;
-}
-
-void AudioStreamSanitizer::AddOutputBuffer(
- const scoped_refptr<AudioBuffer>& buffer) {
- output_timestamp_helper_.AddFrames(buffer->frame_count());
- output_buffers_.push_back(buffer);
-}
-
-int AudioStreamSanitizer::GetFrameCount() const {
- int frame_count = 0;
- for (const auto& buffer : output_buffers_)
- frame_count += buffer->frame_count();
- return frame_count;
-}
-
-bool AudioStreamSanitizer::DrainInto(AudioStreamSanitizer* output) {
- while (HasNextBuffer()) {
- if (!output->AddInput(GetNextBuffer())) return false;
- }
- return true;
-}
-
-AudioSplicer::AudioSplicer(int samples_per_second,
- const scoped_refptr<MediaLog>& media_log)
- : max_crossfade_duration_(
- base::TimeDelta::FromMilliseconds(kCrossfadeDurationInMilliseconds)),
- splice_timestamp_(kNoTimestamp),
- max_splice_end_timestamp_(kNoTimestamp),
- output_sanitizer_(
- new AudioStreamSanitizer(samples_per_second, media_log)),
- pre_splice_sanitizer_(
- new AudioStreamSanitizer(samples_per_second, media_log)),
- post_splice_sanitizer_(
- new AudioStreamSanitizer(samples_per_second, media_log)),
- have_all_pre_splice_buffers_(false) {}
-
-AudioSplicer::~AudioSplicer() {}
-
-void AudioSplicer::Reset() {
- output_sanitizer_->Reset();
- pre_splice_sanitizer_->Reset();
- post_splice_sanitizer_->Reset();
- have_all_pre_splice_buffers_ = false;
- reset_splice_timestamps();
-}
-
-bool AudioSplicer::AddInput(const scoped_refptr<AudioBuffer>& input) {
- // If we're not processing a splice, add the input to the output queue.
- if (splice_timestamp_ == kNoTimestamp) {
- DCHECK(!pre_splice_sanitizer_->HasNextBuffer());
- DCHECK(!post_splice_sanitizer_->HasNextBuffer());
- return output_sanitizer_->AddInput(input);
- }
-
- const AudioTimestampHelper& output_ts_helper =
- output_sanitizer_->timestamp_helper();
-
- if (!have_all_pre_splice_buffers_) {
- DCHECK(!input->end_of_stream());
-
- // If the provided buffer is entirely before the splice point it can also be
- // added to the output queue.
- if (input->timestamp() + input->duration() < splice_timestamp_) {
- DCHECK(!pre_splice_sanitizer_->HasNextBuffer());
- return output_sanitizer_->AddInput(input);
- }
-
- // If we've encountered the first pre splice buffer, reset the pre splice
- // sanitizer based on |output_sanitizer_|. This is done so that gaps and
- // overlaps between buffers across the sanitizers are accounted for prior
- // to calculating crossfade.
- if (!pre_splice_sanitizer_->HasNextBuffer()) {
- pre_splice_sanitizer_->ResetTimestampState(
- output_ts_helper.frame_count(), output_ts_helper.base_timestamp());
- }
-
- return pre_splice_sanitizer_->AddInput(input);
- }
-
- // The first post splice buffer is expected to match |splice_timestamp_|.
- if (!post_splice_sanitizer_->HasNextBuffer())
- CHECK(splice_timestamp_ == input->timestamp());
-
- // At this point we have all the fade out preroll buffers from the decoder.
- // We now need to wait until we have enough data to perform the crossfade (or
- // we receive an end of stream).
- if (!post_splice_sanitizer_->AddInput(input)) return false;
-
- // Ensure |output_sanitizer_| has a valid base timestamp so we can use it for
- // timestamp calculations.
- if (output_ts_helper.base_timestamp() == kNoTimestamp) {
- output_sanitizer_->ResetTimestampState(
- 0, pre_splice_sanitizer_->timestamp_helper().base_timestamp());
- }
-
- // If a splice frame was incorrectly marked due to poor demuxed timestamps, we
- // may not actually have a splice. Here we check if any frames exist before
- // the splice. In this case, just transfer all data to the output sanitizer.
- const int frames_before_splice =
- output_ts_helper.base_timestamp() == kNoTimestamp
- ? 0
- : output_ts_helper.GetFramesToTarget(splice_timestamp_);
- if (frames_before_splice < 0 ||
- pre_splice_sanitizer_->GetFrameCount() <= frames_before_splice) {
- CHECK(pre_splice_sanitizer_->DrainInto(output_sanitizer_.get()));
-
- // If the file contains incorrectly muxed timestamps, there may be huge gaps
- // between the demuxed and decoded timestamps.
- if (!post_splice_sanitizer_->DrainInto(output_sanitizer_.get()))
- return false;
-
- reset_splice_timestamps();
- return true;
- }
-
- // Wait until we have enough data to crossfade or end of stream.
- if (!input->end_of_stream() &&
- input->timestamp() + input->duration() < max_splice_end_timestamp_) {
- return true;
- }
-
- scoped_refptr<AudioBuffer> crossfade_buffer;
- std::unique_ptr<AudioBus> pre_splice =
- ExtractCrossfadeFromPreSplice(&crossfade_buffer);
-
- // Crossfade the pre splice and post splice sections and transfer all relevant
- // buffers into |output_sanitizer_|.
- CrossfadePostSplice(std::move(pre_splice), crossfade_buffer);
-
- // Clear the splice timestamp so new splices can be accepted.
- reset_splice_timestamps();
- return true;
-}
-
-bool AudioSplicer::HasNextBuffer() const {
- return output_sanitizer_->HasNextBuffer();
-}
-
-scoped_refptr<AudioBuffer> AudioSplicer::GetNextBuffer() {
- return output_sanitizer_->GetNextBuffer();
-}
-
-void AudioSplicer::SetSpliceTimestamp(base::TimeDelta splice_timestamp) {
- if (splice_timestamp == kNoTimestamp) {
- DCHECK(splice_timestamp_ != kNoTimestamp);
- DCHECK(!have_all_pre_splice_buffers_);
- have_all_pre_splice_buffers_ = true;
- return;
- }
-
- if (splice_timestamp_ == splice_timestamp) return;
-
- // TODO(dalecurtis): We may need the concept of a future_splice_timestamp_ to
- // handle cases where another splice comes in before we've received 5ms of
- // data from the last one. Leave this as a CHECK for now to figure out if
- // this case is possible.
- CHECK(splice_timestamp_ == kNoTimestamp);
- splice_timestamp_ = splice_timestamp;
- max_splice_end_timestamp_ = splice_timestamp_ + max_crossfade_duration_;
- pre_splice_sanitizer_->Reset();
- post_splice_sanitizer_->Reset();
- have_all_pre_splice_buffers_ = false;
-}
-
-std::unique_ptr<AudioBus> AudioSplicer::ExtractCrossfadeFromPreSplice(
- scoped_refptr<AudioBuffer>* crossfade_buffer) {
- DCHECK(crossfade_buffer);
- const AudioTimestampHelper& output_ts_helper =
- output_sanitizer_->timestamp_helper();
-
- int frames_before_splice =
- output_ts_helper.GetFramesToTarget(splice_timestamp_);
-
- // Determine crossfade frame count based on available frames in each splicer
- // and capping to the maximum crossfade duration.
- const int max_crossfade_frame_count =
- output_ts_helper.GetFramesToTarget(max_splice_end_timestamp_) -
- frames_before_splice;
- const int frames_to_crossfade = std::min(
- max_crossfade_frame_count,
- std::min(pre_splice_sanitizer_->GetFrameCount() - frames_before_splice,
- post_splice_sanitizer_->GetFrameCount()));
- // There must always be frames to crossfade, otherwise the splice should not
- // have been generated.
- DCHECK_GT(frames_to_crossfade, 0);
-
- int frames_read = 0;
- std::unique_ptr<AudioBus> output_bus;
- while (pre_splice_sanitizer_->HasNextBuffer() &&
- frames_read < frames_to_crossfade) {
- scoped_refptr<AudioBuffer> preroll = pre_splice_sanitizer_->GetNextBuffer();
-
- // We don't know the channel count until we see the first buffer, so wait
- // until the first buffer to allocate the output AudioBus.
- if (!output_bus) {
- output_bus =
- AudioBus::Create(preroll->channel_count(), frames_to_crossfade);
- // Allocate output buffer for crossfade.
- *crossfade_buffer = AudioBuffer::CreateBuffer(
- kSampleFormatPlanarF32, preroll->channel_layout(),
- preroll->channel_count(), preroll->sample_rate(),
- frames_to_crossfade);
- }
-
- // There may be enough of a gap introduced during decoding such that an
- // entire buffer exists before the splice point.
- if (frames_before_splice >= preroll->frame_count()) {
- // Adjust the number of frames remaining before the splice. NOTE: This is
- // safe since |pre_splice_sanitizer_| is a continuation of the timeline in
- // |output_sanitizer_|. As such we're guaranteed there are no gaps or
- // overlaps in the timeline between the two sanitizers.
- frames_before_splice -= preroll->frame_count();
- CHECK(output_sanitizer_->AddInput(preroll));
- continue;
- }
-
- const int frames_to_read =
- std::min(preroll->frame_count() - frames_before_splice,
- output_bus->frames() - frames_read);
- preroll->ReadFrames(frames_to_read, frames_before_splice, frames_read,
- output_bus.get());
- frames_read += frames_to_read;
-
- // If only part of the buffer was consumed, trim it appropriately and stick
- // it into the output queue.
- if (frames_before_splice) {
- preroll->TrimEnd(preroll->frame_count() - frames_before_splice);
- CHECK(output_sanitizer_->AddInput(preroll));
- frames_before_splice = 0;
- }
- }
-
- // Ensure outputs were properly allocated. The method should not have been
- // called if there is not enough data to crossfade.
- // TODO(dalecurtis): Convert to DCHECK() once http://crbug.com/356073 fixed.
- CHECK(output_bus);
- CHECK(crossfade_buffer->get());
-
- // All necessary buffers have been processed, it's safe to reset.
- pre_splice_sanitizer_->Reset();
- DCHECK_EQ(output_bus->frames(), frames_read);
- DCHECK_EQ(output_ts_helper.GetFramesToTarget(splice_timestamp_), 0);
- return output_bus;
-}
-
-void AudioSplicer::CrossfadePostSplice(
- std::unique_ptr<AudioBus> pre_splice_bus,
- const scoped_refptr<AudioBuffer>& crossfade_buffer) {
- // Use the calculated timestamp and duration to ensure there's no extra gaps
- // or overlaps to process when adding the buffer to |output_sanitizer_|.
- const AudioTimestampHelper& output_ts_helper =
- output_sanitizer_->timestamp_helper();
- crossfade_buffer->set_timestamp(output_ts_helper.GetTimestamp());
-
- // AudioBuffer::ReadFrames() only allows output into an AudioBus, so wrap
- // our AudioBuffer in one so we can avoid extra data copies.
- std::unique_ptr<AudioBus> output_bus =
- CreateAudioBufferWrapper(crossfade_buffer);
-
- // Extract crossfade section from the |post_splice_sanitizer_|.
- int frames_read = 0, frames_to_trim = 0;
- scoped_refptr<AudioBuffer> remainder;
- while (post_splice_sanitizer_->HasNextBuffer() &&
- frames_read < output_bus->frames()) {
- scoped_refptr<AudioBuffer> postroll =
- post_splice_sanitizer_->GetNextBuffer();
- const int frames_to_read =
- std::min(postroll->frame_count(), output_bus->frames() - frames_read);
- postroll->ReadFrames(frames_to_read, 0, frames_read, output_bus.get());
- frames_read += frames_to_read;
-
- // If only part of the buffer was consumed, save it for after we've added
- // the crossfade buffer
- if (frames_to_read < postroll->frame_count()) {
- DCHECK(!remainder.get());
- remainder.swap(postroll);
- frames_to_trim = frames_to_read;
- }
- }
-
- DCHECK_EQ(output_bus->frames(), frames_read);
-
- // Crossfade the audio into |crossfade_buffer|.
- for (int ch = 0; ch < output_bus->channels(); ++ch) {
- vector_math::Crossfade(pre_splice_bus->channel(ch),
- pre_splice_bus->frames(), output_bus->channel(ch));
- }
-
- CHECK(output_sanitizer_->AddInput(crossfade_buffer));
- DCHECK_EQ(crossfade_buffer->frame_count(), output_bus->frames());
-
- if (remainder.get()) {
- // Trim off consumed frames.
- AccurateTrimStart(frames_to_trim, remainder, output_ts_helper);
- CHECK(output_sanitizer_->AddInput(remainder));
- }
-
- // Transfer all remaining buffers out and reset once empty.
- CHECK(post_splice_sanitizer_->DrainInto(output_sanitizer_.get()));
- post_splice_sanitizer_->Reset();
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/audio_splicer.h b/src/cobalt/media/base/audio_splicer.h
deleted file mode 100644
index 550fa70..0000000
--- a/src/cobalt/media/base/audio_splicer.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef COBALT_MEDIA_BASE_AUDIO_SPLICER_H_
-#define COBALT_MEDIA_BASE_AUDIO_SPLICER_H_
-
-#include <memory>
-
-#include "base/basictypes.h"
-#include "base/memory/ref_counted.h"
-#include "base/time.h"
-#include "cobalt/media/base/audio_parameters.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/timestamp_constants.h"
-
-namespace cobalt {
-namespace media {
-
-class AudioBuffer;
-class AudioBus;
-class AudioStreamSanitizer;
-class MediaLog;
-
-// Helper class that handles filling gaps and resolving overlaps.
-class MEDIA_EXPORT AudioSplicer {
- public:
- AudioSplicer(int samples_per_second,
- const scoped_refptr<MediaLog>& media_log);
- ~AudioSplicer();
-
- enum {
- // The number of ms to crossfade before trimming when buffers overlap.
- kCrossfadeDurationInMilliseconds = 5,
-
- // Largest gap or overlap allowed between buffers. Anything larger than
- // this will trigger an error. This is an arbitrary value, but the initial
- // selection of 50ms roughly represents the duration of 2 compressed AAC or
- // MP3 frames.
- kMaxTimeDeltaInMilliseconds = 50,
- };
-
- // Resets the splicer state by clearing the output buffers queue and resetting
- // the timestamp helper.
- void Reset();
-
- // Adds a new buffer full of samples or end of stream buffer to the splicer.
- // Returns true if the buffer was accepted. False is returned if an error
- // occurred.
- bool AddInput(const scoped_refptr<AudioBuffer>& input);
-
- // Returns true if the splicer has a buffer to return.
- bool HasNextBuffer() const;
-
- // Removes the next buffer from the output buffer queue and returns it; this
- // should only be called if HasNextBuffer() returns true.
- scoped_refptr<AudioBuffer> GetNextBuffer();
-
- // Indicates an upcoming splice point. All buffers overlapping or after the
- // |splice_timestamp| will be considered as "before the splice." Clients must
- // then call SetSpliceTimestamp(kNoTimestamp) to signal that future buffers
- // should be considered as "after the splice."
- //
- // Once |kCrossfadeDurationInMilliseconds| of buffers "after the splice" or
- // end of stream has been received, the "after" buffers will be crossfaded
- // with all "before" buffers which overlap them. "before" buffers outside
- // of the overlap range will be discarded.
- void SetSpliceTimestamp(base::TimeDelta splice_timestamp);
-
- private:
- friend class AudioSplicerTest;
-
- // Extracts frames to be crossfaded from |pre_splice_sanitizer_|. Transfers
- // all frames before |splice_timestamp_| into |output_sanitizer_| and drops
- // frames outside of the crossfade duration.
- //
- // The size of the returned AudioBus is the crossfade duration in frames.
- // Crossfade duration is calculated based on the number of frames available
- // after |splice_timestamp_| in each sanitizer and capped by
- // |max_crossfade_duration_|.
- //
- // |pre_splice_sanitizer_| will be empty after this operation.
- std::unique_ptr<AudioBus> ExtractCrossfadeFromPreSplice(
- scoped_refptr<AudioBuffer>* crossfade_buffer);
-
- // Crossfades |pre_splice_bus->frames()| frames from
- // |post_splice_sanitizer_|
- // with those from |pre_splice_bus|. Adds the crossfaded buffer to
- // |output_sanitizer_| along with all buffers in |post_splice_sanitizer_|.
- //
- // |post_splice_sanitizer_| will be empty after this operation.
- void CrossfadePostSplice(std::unique_ptr<AudioBus> pre_splice_bus,
- const scoped_refptr<AudioBuffer>& crossfade_buffer);
-
- // Reset the splice and splice end timestamps.
- void reset_splice_timestamps() {
- splice_timestamp_ = max_splice_end_timestamp_ = kNoTimestamp;
- }
-
- const base::TimeDelta max_crossfade_duration_;
- base::TimeDelta splice_timestamp_;
- base::TimeDelta max_splice_end_timestamp_;
-
- // The various sanitizers for each stage of the crossfade process. Buffers in
- // |output_sanitizer_| are immediately available for consumption by external
- // callers.
- //
- // Overlapped buffers go into the |pre_splice_sanitizer_| while overlapping
- // buffers go into the |post_splice_sanitizer_|. Once enough buffers for
- // crossfading are received the pre and post sanitizers are drained into
- // |output_sanitizer_| by the two ExtractCrossfadeFromXXX methods above.
- //
- // |pre_splice_sanitizer_| is not constructed until the first splice frame is
- // encountered. At which point it is constructed based on the timestamp state
- // of |output_sanitizer_|. It is destructed once the splice is finished.
- std::unique_ptr<AudioStreamSanitizer> output_sanitizer_;
- std::unique_ptr<AudioStreamSanitizer> pre_splice_sanitizer_;
- std::unique_ptr<AudioStreamSanitizer> post_splice_sanitizer_;
-
- // Whether all buffers which should go into |pre_splice_sanitizer_| have been
- // received. If true, buffers should now be put in |post_splice_sanitizer_|.
- bool have_all_pre_splice_buffers_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(AudioSplicer);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_AUDIO_SPLICER_H_
diff --git a/src/cobalt/media/base/audio_splicer_unittest.cc b/src/cobalt/media/base/audio_splicer_unittest.cc
deleted file mode 100644
index 29220c6..0000000
--- a/src/cobalt/media/base/audio_splicer_unittest.cc
+++ /dev/null
@@ -1,743 +0,0 @@
-// Copyright (c) 2012 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 "cobalt/media/base/audio_splicer.h"
-
-#include <memory>
-
-#include "base/basictypes.h"
-#include "cobalt/media/base/audio_buffer.h"
-#include "cobalt/media/base/audio_bus.h"
-#include "cobalt/media/base/audio_timestamp_helper.h"
-#include "cobalt/media/base/test_helpers.h"
-#include "cobalt/media/base/timestamp_constants.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace cobalt {
-namespace media {
-
-// Do not change this format. AddInput() and GetValue() only work with float.
-static const SampleFormat kSampleFormat = kSampleFormatF32;
-static_assert(kSampleFormat == kSampleFormatF32, "invalid splice format");
-
-static const int kChannels = 1;
-static const ChannelLayout kChannelLayout = CHANNEL_LAYOUT_MONO;
-static const int kDefaultSampleRate = 44100;
-static const int kDefaultBufferSize = 100;
-
-class AudioSplicerTest : public ::testing::Test {
- public:
- AudioSplicerTest()
- : splicer_(kDefaultSampleRate, new MediaLog()),
- input_timestamp_helper_(kDefaultSampleRate) {
- input_timestamp_helper_.SetBaseTimestamp(base::TimeDelta());
- }
-
- scoped_refptr<AudioBuffer> GetNextInputBuffer(float value) {
- return GetNextInputBuffer(value, kDefaultBufferSize);
- }
-
- scoped_refptr<AudioBuffer> GetNextInputBuffer(float value, int frame_size) {
- scoped_refptr<AudioBuffer> buffer = MakeAudioBuffer<float>(
- kSampleFormat, kChannelLayout, kChannels, kDefaultSampleRate, value,
- 0.0f, frame_size, input_timestamp_helper_.GetTimestamp());
- input_timestamp_helper_.AddFrames(frame_size);
- return buffer;
- }
-
- float GetValue(const scoped_refptr<AudioBuffer>& buffer) {
- return reinterpret_cast<const float*>(buffer->channel_data()[0])[0];
- }
-
- bool VerifyData(const scoped_refptr<AudioBuffer>& buffer, float value) {
- int frames = buffer->frame_count();
- std::unique_ptr<AudioBus> bus = AudioBus::Create(kChannels, frames);
- buffer->ReadFrames(frames, 0, 0, bus.get());
- for (int ch = 0; ch < buffer->channel_count(); ++ch) {
- for (int i = 0; i < frames; ++i) {
- if (bus->channel(ch)[i] != value) return false;
- }
- }
- return true;
- }
-
- void VerifyNextBuffer(const scoped_refptr<AudioBuffer>& input) {
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> output = splicer_.GetNextBuffer();
- EXPECT_EQ(input->timestamp(), output->timestamp());
- EXPECT_EQ(input->duration(), output->duration());
- EXPECT_EQ(input->frame_count(), output->frame_count());
- EXPECT_TRUE(VerifyData(output, GetValue(input)));
- }
-
- void VerifyPreSpliceOutput(
- const scoped_refptr<AudioBuffer>& overlapped_buffer,
- const scoped_refptr<AudioBuffer>& overlapping_buffer,
- int expected_pre_splice_size,
- base::TimeDelta expected_pre_splice_duration) {
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> pre_splice_output = splicer_.GetNextBuffer();
- EXPECT_EQ(overlapped_buffer->timestamp(), pre_splice_output->timestamp());
- EXPECT_EQ(expected_pre_splice_size, pre_splice_output->frame_count());
- EXPECT_EQ(expected_pre_splice_duration, pre_splice_output->duration());
- EXPECT_TRUE(VerifyData(pre_splice_output, GetValue(overlapped_buffer)));
- }
-
- void VerifyCrossfadeOutput(
- const scoped_refptr<AudioBuffer>& overlapped_buffer_1,
- const scoped_refptr<AudioBuffer>& overlapped_buffer_2,
- const scoped_refptr<AudioBuffer>& overlapping_buffer,
- int second_overlap_index, int expected_crossfade_size,
- base::TimeDelta expected_crossfade_duration) {
- ASSERT_TRUE(splicer_.HasNextBuffer());
-
- scoped_refptr<AudioBuffer> crossfade_output = splicer_.GetNextBuffer();
- EXPECT_EQ(expected_crossfade_size, crossfade_output->frame_count());
- EXPECT_EQ(expected_crossfade_duration, crossfade_output->duration());
-
- // The splice timestamp may be adjusted by a microsecond.
- EXPECT_NEAR(overlapping_buffer->timestamp().InMicroseconds(),
- crossfade_output->timestamp().InMicroseconds(), 1);
-
- // Verify the actual crossfade.
- const int frames = crossfade_output->frame_count();
- float overlapped_value = GetValue(overlapped_buffer_1);
- const float overlapping_value = GetValue(overlapping_buffer);
- std::unique_ptr<AudioBus> bus = AudioBus::Create(kChannels, frames);
- crossfade_output->ReadFrames(frames, 0, 0, bus.get());
- for (int ch = 0; ch < crossfade_output->channel_count(); ++ch) {
- float cf_ratio = 0;
- const float cf_increment = 1.0f / frames;
- for (int i = 0; i < frames; ++i, cf_ratio += cf_increment) {
- if (overlapped_buffer_2.get() && i >= second_overlap_index)
- overlapped_value = GetValue(overlapped_buffer_2);
- const float actual = bus->channel(ch)[i];
- const float expected =
- (1.0f - cf_ratio) * overlapped_value + cf_ratio * overlapping_value;
- ASSERT_FLOAT_EQ(expected, actual) << "i=" << i;
- }
- }
- }
-
- bool AddInput(const scoped_refptr<AudioBuffer>& input) {
- // Since the splicer doesn't make copies it's working directly on the input
- // buffers. We must make a copy before adding to ensure the original buffer
- // is not modified in unexpected ways.
- scoped_refptr<AudioBuffer> buffer_copy =
- input->end_of_stream()
- ? AudioBuffer::CreateEOSBuffer()
- : AudioBuffer::CopyFrom(kSampleFormat, input->channel_layout(),
- input->channel_count(),
- input->sample_rate(), input->frame_count(),
- &input->channel_data()[0],
- input->timestamp());
- return splicer_.AddInput(buffer_copy);
- }
-
- base::TimeDelta max_crossfade_duration() {
- return splicer_.max_crossfade_duration_;
- }
-
- protected:
- AudioSplicer splicer_;
- AudioTimestampHelper input_timestamp_helper_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AudioSplicerTest);
-};
-
-TEST_F(AudioSplicerTest, PassThru) {
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Test single buffer pass-thru behavior.
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
- EXPECT_TRUE(AddInput(input_1));
- VerifyNextBuffer(input_1);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Test that multiple buffers can be queued in the splicer.
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f);
- scoped_refptr<AudioBuffer> input_3 = GetNextInputBuffer(0.3f);
- EXPECT_TRUE(AddInput(input_2));
- EXPECT_TRUE(AddInput(input_3));
- VerifyNextBuffer(input_2);
- VerifyNextBuffer(input_3);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-TEST_F(AudioSplicerTest, Reset) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
- EXPECT_TRUE(AddInput(input_1));
- ASSERT_TRUE(splicer_.HasNextBuffer());
-
- splicer_.Reset();
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Add some bytes to the timestamp helper so that the
- // next buffer starts many frames beyond the end of
- // |input_1|. This is to make sure that Reset() actually
- // clears its state and doesn't try to insert a gap.
- input_timestamp_helper_.AddFrames(100);
-
- // Verify that a new input buffer passes through as expected.
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f);
- EXPECT_TRUE(AddInput(input_2));
- VerifyNextBuffer(input_2);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-TEST_F(AudioSplicerTest, EndOfStream) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
- scoped_refptr<AudioBuffer> input_2 = AudioBuffer::CreateEOSBuffer();
- scoped_refptr<AudioBuffer> input_3 = GetNextInputBuffer(0.2f);
- EXPECT_TRUE(input_2->end_of_stream());
-
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_TRUE(AddInput(input_2));
-
- VerifyNextBuffer(input_1);
-
- scoped_refptr<AudioBuffer> output_2 = splicer_.GetNextBuffer();
- EXPECT_FALSE(splicer_.HasNextBuffer());
- EXPECT_TRUE(output_2->end_of_stream());
-
- // Verify that buffers can be added again after Reset().
- splicer_.Reset();
- EXPECT_TRUE(AddInput(input_3));
- VerifyNextBuffer(input_3);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test the gap insertion code.
-// +--------------+ +--------------+
-// |11111111111111| |22222222222222|
-// +--------------+ +--------------+
-// Results in:
-// +--------------+----+--------------+
-// |11111111111111|0000|22222222222222|
-// +--------------+----+--------------+
-TEST_F(AudioSplicerTest, GapInsertion) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
-
- // Add bytes to the timestamp helper so that the next buffer
- // will have a starting timestamp that indicates a gap is
- // present.
- const int kGapSize = 7;
- input_timestamp_helper_.AddFrames(kGapSize);
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f);
-
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_TRUE(AddInput(input_2));
-
- // Verify that the first input buffer passed through unmodified.
- VerifyNextBuffer(input_1);
-
- // Verify the contents of the gap buffer.
- scoped_refptr<AudioBuffer> output_2 = splicer_.GetNextBuffer();
- base::TimeDelta gap_timestamp = input_1->timestamp() + input_1->duration();
- base::TimeDelta gap_duration = input_2->timestamp() - gap_timestamp;
- EXPECT_GT(gap_duration, base::TimeDelta());
- EXPECT_EQ(gap_timestamp, output_2->timestamp());
- EXPECT_NEAR(gap_duration.InMicroseconds(),
- output_2->duration().InMicroseconds(), 1);
- EXPECT_EQ(kGapSize, output_2->frame_count());
- EXPECT_TRUE(VerifyData(output_2, 0.0f));
-
- // Verify that the second input buffer passed through unmodified.
- VerifyNextBuffer(input_2);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test that an error is signalled when the gap between input buffers is
-// too large.
-TEST_F(AudioSplicerTest, GapTooLarge) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
-
- // Add a seconds worth of bytes so that an unacceptably large
- // gap exists between |input_1| and |input_2|.
- const int kGapSize = kDefaultSampleRate;
- input_timestamp_helper_.AddFrames(kGapSize);
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f);
-
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_FALSE(AddInput(input_2));
-
- VerifyNextBuffer(input_1);
-
- // Verify that the second buffer is not available.
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Reset the timestamp helper so it can generate a buffer that is
- // right after |input_1|.
- input_timestamp_helper_.SetBaseTimestamp(input_1->timestamp() +
- input_1->duration());
-
- // Verify that valid buffers are still accepted.
- scoped_refptr<AudioBuffer> input_3 = GetNextInputBuffer(0.3f);
- EXPECT_TRUE(AddInput(input_3));
- VerifyNextBuffer(input_3);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Verifies that an error is signalled if AddInput() is called
-// with a timestamp that is earlier than the first buffer added.
-TEST_F(AudioSplicerTest, BufferAddedBeforeBase) {
- input_timestamp_helper_.SetBaseTimestamp(
- base::TimeDelta::FromMicroseconds(10));
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
-
- // Reset the timestamp helper so the next buffer will have a timestamp earlier
- // than |input_1|.
- input_timestamp_helper_.SetBaseTimestamp(base::TimeDelta::FromSeconds(0));
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.1f);
-
- EXPECT_GT(input_1->timestamp(), input_2->timestamp());
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_FALSE(AddInput(input_2));
-}
-
-// Test when one buffer partially overlaps another.
-// +--------------+
-// |11111111111111|
-// +--------------+
-// +--------------+
-// |22222222222222|
-// +--------------+
-// Results in:
-// +--------------+----------+
-// |11111111111111|2222222222|
-// +--------------+----------+
-TEST_F(AudioSplicerTest, PartialOverlap) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
-
- // Reset timestamp helper so that the next buffer will have a
- // timestamp that starts in the middle of |input_1|.
- const int kOverlapSize = input_1->frame_count() / 4;
- input_timestamp_helper_.SetBaseTimestamp(input_1->timestamp());
- input_timestamp_helper_.AddFrames(input_1->frame_count() - kOverlapSize);
-
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f);
-
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_TRUE(AddInput(input_2));
-
- // Verify that the first input buffer passed through unmodified.
- VerifyNextBuffer(input_1);
-
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> output_2 = splicer_.GetNextBuffer();
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Verify that the second input buffer was truncated to only contain
- // the samples that are after the end of |input_1|.
- base::TimeDelta expected_timestamp =
- input_1->timestamp() + input_1->duration();
- base::TimeDelta expected_duration =
- (input_2->timestamp() + input_2->duration()) - expected_timestamp;
- EXPECT_EQ(expected_timestamp, output_2->timestamp());
- EXPECT_EQ(expected_duration, output_2->duration());
- EXPECT_TRUE(VerifyData(output_2, GetValue(input_2)));
-}
-
-// Test that an input buffer that is completely overlapped by a buffer
-// that was already added is dropped.
-// +--------------+
-// |11111111111111|
-// +--------------+
-// +-----+
-// |22222|
-// +-----+
-// +-------------+
-// |3333333333333|
-// +-------------+
-// Results in:
-// +--------------+-------------+
-// |11111111111111|3333333333333|
-// +--------------+-------------+
-TEST_F(AudioSplicerTest, DropBuffer) {
- scoped_refptr<AudioBuffer> input_1 = GetNextInputBuffer(0.1f);
-
- // Reset timestamp helper so that the next buffer will have a
- // timestamp that starts in the middle of |input_1|.
- const int kOverlapOffset = input_1->frame_count() / 2;
- const int kOverlapSize = input_1->frame_count() / 4;
- input_timestamp_helper_.SetBaseTimestamp(input_1->timestamp());
- input_timestamp_helper_.AddFrames(kOverlapOffset);
-
- scoped_refptr<AudioBuffer> input_2 = GetNextInputBuffer(0.2f, kOverlapSize);
-
- // Reset the timestamp helper so the next buffer will be right after
- // |input_1|.
- input_timestamp_helper_.SetBaseTimestamp(input_1->timestamp());
- input_timestamp_helper_.AddFrames(input_1->frame_count());
- scoped_refptr<AudioBuffer> input_3 = GetNextInputBuffer(0.3f);
-
- EXPECT_TRUE(AddInput(input_1));
- EXPECT_TRUE(AddInput(input_2));
- EXPECT_TRUE(AddInput(input_3));
-
- VerifyNextBuffer(input_1);
- VerifyNextBuffer(input_3);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test crossfade when one buffer partially overlaps another.
-// +--------------+
-// |11111111111111|
-// +--------------+
-// +--------------+
-// |22222222222222|
-// +--------------+
-// Results in:
-// +----------+----+----------+
-// |1111111111|xxxx|2222222222|
-// +----------+----+----------+
-// Where "xxxx" represents the crossfaded portion of the signal.
-TEST_F(AudioSplicerTest, PartialOverlapCrossfade) {
- const int kCrossfadeSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration());
- const int kBufferSize = kCrossfadeSize * 2;
-
- scoped_refptr<AudioBuffer> extra_pre_splice_buffer =
- GetNextInputBuffer(0.2f, kBufferSize);
- scoped_refptr<AudioBuffer> overlapped_buffer =
- GetNextInputBuffer(1.0f, kBufferSize);
-
- // Reset timestamp helper so that the next buffer will have a timestamp that
- // starts in the middle of |overlapped_buffer|.
- input_timestamp_helper_.SetBaseTimestamp(overlapped_buffer->timestamp());
- input_timestamp_helper_.AddFrames(overlapped_buffer->frame_count() -
- kCrossfadeSize);
- splicer_.SetSpliceTimestamp(input_timestamp_helper_.GetTimestamp());
- scoped_refptr<AudioBuffer> overlapping_buffer =
- GetNextInputBuffer(0.0f, kBufferSize);
-
- // |extra_pre_splice_buffer| is entirely before the splice and should be ready
- // for output.
- EXPECT_TRUE(AddInput(extra_pre_splice_buffer));
- VerifyNextBuffer(extra_pre_splice_buffer);
-
- // The splicer should be internally queuing input since |overlapped_buffer| is
- // part of the splice.
- EXPECT_TRUE(AddInput(overlapped_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // |overlapping_buffer| completes the splice.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_TRUE(AddInput(overlapping_buffer));
- ASSERT_TRUE(splicer_.HasNextBuffer());
-
- // Add one more buffer to make sure it's passed through untouched.
- scoped_refptr<AudioBuffer> extra_post_splice_buffer =
- GetNextInputBuffer(0.5f, kBufferSize);
- EXPECT_TRUE(AddInput(extra_post_splice_buffer));
-
- VerifyPreSpliceOutput(overlapped_buffer, overlapping_buffer, 221,
- base::TimeDelta::FromMicroseconds(5011));
-
- // Due to rounding the crossfade size may vary by up to a frame.
- const int kExpectedCrossfadeSize = 220;
- EXPECT_NEAR(kExpectedCrossfadeSize, kCrossfadeSize, 1);
-
- VerifyCrossfadeOutput(overlapped_buffer, NULL, overlapping_buffer, 0,
- kExpectedCrossfadeSize,
- base::TimeDelta::FromMicroseconds(4988));
-
- // Retrieve the remaining portion after crossfade.
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> post_splice_output = splicer_.GetNextBuffer();
- EXPECT_EQ(base::TimeDelta::FromMicroseconds(20022),
- post_splice_output->timestamp());
- EXPECT_EQ(overlapping_buffer->frame_count() - kExpectedCrossfadeSize,
- post_splice_output->frame_count());
- EXPECT_EQ(base::TimeDelta::FromMicroseconds(5034),
- post_splice_output->duration());
-
- EXPECT_TRUE(VerifyData(post_splice_output, GetValue(overlapping_buffer)));
-
- VerifyNextBuffer(extra_post_splice_buffer);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test crossfade when one buffer partially overlaps another, but an end of
-// stream buffer is received before the crossfade duration is reached.
-// +--------------+
-// |11111111111111|
-// +--------------+
-// +---------++---+
-// |222222222||EOS|
-// +---------++---+
-// Results in:
-// +----------+----+----++---+
-// |1111111111|xxxx|2222||EOS|
-// +----------+----+----++---+
-// Where "x" represents the crossfaded portion of the signal.
-TEST_F(AudioSplicerTest, PartialOverlapCrossfadeEndOfStream) {
- const int kCrossfadeSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration());
-
- scoped_refptr<AudioBuffer> overlapped_buffer =
- GetNextInputBuffer(1.0f, kCrossfadeSize * 2);
-
- // Reset timestamp helper so that the next buffer will have a timestamp that
- // starts 3/4 of the way into |overlapped_buffer|.
- input_timestamp_helper_.SetBaseTimestamp(overlapped_buffer->timestamp());
- input_timestamp_helper_.AddFrames(3 * overlapped_buffer->frame_count() / 4);
- splicer_.SetSpliceTimestamp(input_timestamp_helper_.GetTimestamp());
- scoped_refptr<AudioBuffer> overlapping_buffer =
- GetNextInputBuffer(0.0f, kCrossfadeSize / 3);
-
- // The splicer should be internally queuing input since |overlapped_buffer| is
- // part of the splice.
- EXPECT_TRUE(AddInput(overlapped_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // |overlapping_buffer| should not have enough data to complete the splice, so
- // ensure output is not available.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_TRUE(AddInput(overlapping_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // Now add an EOS buffer which should complete the splice.
- EXPECT_TRUE(AddInput(AudioBuffer::CreateEOSBuffer()));
-
- VerifyPreSpliceOutput(overlapped_buffer, overlapping_buffer, 331,
- base::TimeDelta::FromMicroseconds(7505));
- VerifyCrossfadeOutput(overlapped_buffer, NULL, overlapping_buffer, 0,
- overlapping_buffer->frame_count(),
- overlapping_buffer->duration());
-
- // Ensure the last buffer is an EOS buffer.
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> post_splice_output = splicer_.GetNextBuffer();
- EXPECT_TRUE(post_splice_output->end_of_stream());
-
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test crossfade when one buffer partially overlaps another, but the amount of
-// overlapped data is less than the crossfade duration.
-// +------------+
-// |111111111111|
-// +------------+
-// +--------------+
-// |22222222222222|
-// +--------------+
-// Results in:
-// +----------+-+------------+
-// |1111111111|x|222222222222|
-// +----------+-+------------+
-// Where "x" represents the crossfaded portion of the signal.
-TEST_F(AudioSplicerTest, PartialOverlapCrossfadeShortPreSplice) {
- const int kCrossfadeSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration());
-
- scoped_refptr<AudioBuffer> overlapped_buffer =
- GetNextInputBuffer(1.0f, kCrossfadeSize / 2);
-
- // Reset timestamp helper so that the next buffer will have a timestamp that
- // starts in the middle of |overlapped_buffer|.
- input_timestamp_helper_.SetBaseTimestamp(overlapped_buffer->timestamp());
- input_timestamp_helper_.AddFrames(overlapped_buffer->frame_count() / 2);
- splicer_.SetSpliceTimestamp(input_timestamp_helper_.GetTimestamp());
- scoped_refptr<AudioBuffer> overlapping_buffer =
- GetNextInputBuffer(0.0f, kCrossfadeSize * 2);
-
- // The splicer should be internally queuing input since |overlapped_buffer| is
- // part of the splice.
- EXPECT_TRUE(AddInput(overlapped_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // |overlapping_buffer| completes the splice.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_TRUE(AddInput(overlapping_buffer));
-
- const int kExpectedPreSpliceSize = 55;
- const base::TimeDelta kExpectedPreSpliceDuration =
- base::TimeDelta::FromMicroseconds(1247);
- VerifyPreSpliceOutput(overlapped_buffer, overlapping_buffer,
- kExpectedPreSpliceSize, kExpectedPreSpliceDuration);
- VerifyCrossfadeOutput(overlapped_buffer, NULL, overlapping_buffer, 0,
- kExpectedPreSpliceSize, kExpectedPreSpliceDuration);
-
- // Retrieve the remaining portion after crossfade.
- ASSERT_TRUE(splicer_.HasNextBuffer());
- scoped_refptr<AudioBuffer> post_splice_output = splicer_.GetNextBuffer();
- EXPECT_EQ(overlapping_buffer->timestamp() + kExpectedPreSpliceDuration,
- post_splice_output->timestamp());
- EXPECT_EQ(overlapping_buffer->frame_count() - kExpectedPreSpliceSize,
- post_splice_output->frame_count());
- EXPECT_EQ(overlapping_buffer->duration() - kExpectedPreSpliceDuration,
- post_splice_output->duration());
-
- EXPECT_TRUE(VerifyData(post_splice_output, GetValue(overlapping_buffer)));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test behavior when a splice frame is incorrectly marked and does not actually
-// overlap.
-// +----------+
-// |1111111111|
-// +----------+
-// +--------------+
-// |22222222222222|
-// +--------------+
-// Results in:
-// +----------+--------------+
-// |1111111111|22222222222222|
-// +----------+--------------+
-TEST_F(AudioSplicerTest, IncorrectlyMarkedSplice) {
- const int kBufferSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration()) * 2;
-
- scoped_refptr<AudioBuffer> first_buffer =
- GetNextInputBuffer(1.0f, kBufferSize);
- // Fuzz the duration slightly so that the buffer overlaps the splice timestamp
- // by a microsecond, which is not enough to crossfade.
- const base::TimeDelta kSpliceTimestamp =
- input_timestamp_helper_.GetTimestamp() -
- base::TimeDelta::FromMicroseconds(1);
- splicer_.SetSpliceTimestamp(kSpliceTimestamp);
- scoped_refptr<AudioBuffer> second_buffer =
- GetNextInputBuffer(0.0f, kBufferSize);
- second_buffer->set_timestamp(kSpliceTimestamp);
-
- // The splicer should be internally queuing input since |first_buffer| is part
- // of the supposed splice.
- EXPECT_TRUE(AddInput(first_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // |second_buffer| should complete the supposed splice, so ensure output is
- // now available.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_TRUE(AddInput(second_buffer));
-
- VerifyNextBuffer(first_buffer);
- VerifyNextBuffer(second_buffer);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test behavior when a splice frame is incorrectly marked and there is a gap
-// between whats in the pre splice and post splice.
-// +--------+
-// |11111111|
-// +--------+
-// +--------------+
-// |22222222222222|
-// +--------------+
-// Results in:
-// +--------+-+--------------+
-// |11111111|0|22222222222222|
-// +--------+-+--------------+
-TEST_F(AudioSplicerTest, IncorrectlyMarkedSpliceWithGap) {
- const int kBufferSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration()) * 2;
- const int kGapSize = 2;
-
- scoped_refptr<AudioBuffer> first_buffer =
- GetNextInputBuffer(1.0f, kBufferSize - kGapSize);
- scoped_refptr<AudioBuffer> gap_buffer = GetNextInputBuffer(0.0f, kGapSize);
- splicer_.SetSpliceTimestamp(input_timestamp_helper_.GetTimestamp());
- scoped_refptr<AudioBuffer> second_buffer =
- GetNextInputBuffer(0.0f, kBufferSize);
-
- // The splicer should pass through the first buffer since it's not part of the
- // splice.
- EXPECT_TRUE(AddInput(first_buffer));
- VerifyNextBuffer(first_buffer);
-
- // Do not add |gap_buffer|.
-
- // |second_buffer| will complete the supposed splice.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_TRUE(AddInput(second_buffer));
-
- VerifyNextBuffer(gap_buffer);
- VerifyNextBuffer(second_buffer);
- EXPECT_FALSE(splicer_.HasNextBuffer());
-}
-
-// Test behavior when a splice frame is incorrectly marked and there is a gap
-// between what's in the pre splice and post splice that is too large to recover
-// from.
-// +--------+
-// |11111111|
-// +--------+
-// +------+
-// |222222|
-// +------+
-// Results in an error and not a crash.
-TEST_F(AudioSplicerTest, IncorrectlyMarkedSpliceWithBadGap) {
- const int kBufferSize =
- input_timestamp_helper_.GetFramesToTarget(max_crossfade_duration()) * 2;
- const int kGapSize = kBufferSize +
- input_timestamp_helper_.GetFramesToTarget(
- base::TimeDelta::FromMilliseconds(
- AudioSplicer::kMaxTimeDeltaInMilliseconds + 1));
-
- scoped_refptr<AudioBuffer> first_buffer =
- GetNextInputBuffer(1.0f, kBufferSize);
- scoped_refptr<AudioBuffer> gap_buffer = GetNextInputBuffer(0.0f, kGapSize);
- splicer_.SetSpliceTimestamp(input_timestamp_helper_.GetTimestamp());
- scoped_refptr<AudioBuffer> second_buffer =
- GetNextInputBuffer(0.0f, kBufferSize);
-
- // The splicer should pass through the first buffer since it's not part of the
- // splice.
- EXPECT_TRUE(AddInput(first_buffer));
- VerifyNextBuffer(first_buffer);
-
- // Do not add |gap_buffer|.
-
- // |second_buffer| will complete the supposed splice.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- EXPECT_FALSE(AddInput(second_buffer));
-}
-
-// Ensure we don't crash when a splice frame is incorrectly marked such that the
-// splice timestamp has already passed when SetSpliceTimestamp() is called.
-// This can happen if the encoded timestamps are too far behind the decoded
-// timestamps.
-TEST_F(AudioSplicerTest, IncorrectlyMarkedPastSplice) {
- const int kBufferSize = 200;
-
- scoped_refptr<AudioBuffer> first_buffer =
- GetNextInputBuffer(1.0f, kBufferSize);
- EXPECT_TRUE(AddInput(first_buffer));
- VerifyNextBuffer(first_buffer);
-
- // Start the splice at a timestamp which has already occurred.
- splicer_.SetSpliceTimestamp(base::TimeDelta());
-
- scoped_refptr<AudioBuffer> second_buffer =
- GetNextInputBuffer(0.5f, kBufferSize);
- EXPECT_TRUE(AddInput(second_buffer));
- EXPECT_FALSE(splicer_.HasNextBuffer());
-
- // |third_buffer| will complete the supposed splice. The buffer size is set
- // such that unchecked the splicer would try to trim off a negative number of
- // frames.
- splicer_.SetSpliceTimestamp(kNoTimestamp);
- scoped_refptr<AudioBuffer> third_buffer =
- GetNextInputBuffer(0.0f, kBufferSize * 10);
- third_buffer->set_timestamp(base::TimeDelta());
- EXPECT_TRUE(AddInput(third_buffer));
-
- // The second buffer should come through unmodified.
- VerifyNextBuffer(second_buffer);
-
- // The third buffer should be partially dropped since it overlaps the second.
- ASSERT_TRUE(splicer_.HasNextBuffer());
- const base::TimeDelta second_buffer_end_ts =
- second_buffer->timestamp() + second_buffer->duration();
- scoped_refptr<AudioBuffer> output = splicer_.GetNextBuffer();
- EXPECT_EQ(second_buffer_end_ts, output->timestamp());
- EXPECT_EQ(third_buffer->duration() -
- (second_buffer_end_ts - third_buffer->timestamp()),
- output->duration());
- EXPECT_TRUE(VerifyData(output, GetValue(third_buffer)));
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_callback_promise.cc b/src/cobalt/media/base/cdm_callback_promise.cc
deleted file mode 100644
index 28dbbee..0000000
--- a/src/cobalt/media/base/cdm_callback_promise.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/cdm_callback_promise.h"
-
-#include "base/callback_helpers.h"
-#include "base/logging.h"
-
-namespace cobalt {
-namespace media {
-
-template <typename... T>
-CdmCallbackPromise<T...>::CdmCallbackPromise(
- const base::Callback<void(const T&...)>& resolve_cb,
- const PromiseRejectedCB& reject_cb)
- : resolve_cb_(resolve_cb), reject_cb_(reject_cb) {
- DCHECK(!resolve_cb_.is_null());
- DCHECK(!reject_cb_.is_null());
-}
-
-template <typename... T>
-CdmCallbackPromise<T...>::~CdmCallbackPromise() {
- if (IsPromiseSettled()) return;
-
- DCHECK(!resolve_cb_.is_null() && !reject_cb_.is_null());
- RejectPromiseOnDestruction();
-}
-
-template <typename... T>
-void CdmCallbackPromise<T...>::resolve(const T&... result) {
- MarkPromiseSettled();
- base::ResetAndReturn(&resolve_cb_).Run(result...);
-}
-
-template <typename... T>
-void CdmCallbackPromise<T...>::reject(MediaKeys::Exception exception_code,
- uint32_t system_code,
- const std::string& error_message) {
- MarkPromiseSettled();
- base::ResetAndReturn(&reject_cb_)
- .Run(exception_code, system_code, error_message);
-}
-
-// Explicit template instantiation for the Promises needed.
-template class MEDIA_EXPORT CdmCallbackPromise<>;
-template class MEDIA_EXPORT CdmCallbackPromise<std::string>;
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_callback_promise.h b/src/cobalt/media/base/cdm_callback_promise.h
deleted file mode 100644
index a721f56..0000000
--- a/src/cobalt/media/base/cdm_callback_promise.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_CALLBACK_PROMISE_H_
-#define COBALT_MEDIA_BASE_CDM_CALLBACK_PROMISE_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "cobalt/media/base/cdm_promise.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/media_keys.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-typedef base::Callback<void(
- MediaKeys::Exception exception_code, uint32_t system_code,
- const std::string& error_message)> PromiseRejectedCB;
-
-template <typename... T>
-class MEDIA_EXPORT CdmCallbackPromise : public CdmPromiseTemplate<T...> {
- public:
- CdmCallbackPromise(const base::Callback<void(const T&...)>& resolve_cb,
- const PromiseRejectedCB& reject_cb);
- virtual ~CdmCallbackPromise();
-
- // CdmPromiseTemplate<T> implementation.
- virtual void resolve(const T&... result) OVERRIDE;
- virtual void reject(MediaKeys::Exception exception_code, uint32_t system_code,
- const std::string& error_message) OVERRIDE;
-
- private:
- using CdmPromiseTemplate<T...>::IsPromiseSettled;
- using CdmPromiseTemplate<T...>::MarkPromiseSettled;
- using CdmPromiseTemplate<T...>::RejectPromiseOnDestruction;
-
- base::Callback<void(const T&...)> resolve_cb_;
- PromiseRejectedCB reject_cb_;
-
- DISALLOW_COPY_AND_ASSIGN(CdmCallbackPromise);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_CALLBACK_PROMISE_H_
diff --git a/src/cobalt/media/base/cdm_config.h b/src/cobalt/media/base/cdm_config.h
deleted file mode 100644
index f197fb8..0000000
--- a/src/cobalt/media/base/cdm_config.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2015 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_CONFIG_H_
-#define COBALT_MEDIA_BASE_CDM_CONFIG_H_
-
-namespace cobalt {
-namespace media {
-
-// The runtime configuration for new CDM instances as computed by
-// |requestMediaKeySystemAccess|. This is in some sense the Chromium-side
-// counterpart of Blink's WebMediaKeySystemConfiguration.
-struct CdmConfig {
- // Allow access to a distinctive identifier.
- bool allow_distinctive_identifier = false;
-
- // Allow access to persistent state.
- bool allow_persistent_state = false;
-
- // Use hardware-secure codecs. This flag is only used on Android, it should
- // always be false on other platforms.
- bool use_hw_secure_codecs = false;
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_CONFIG_H_
diff --git a/src/cobalt/media/base/cdm_context.cc b/src/cobalt/media/base/cdm_context.cc
deleted file mode 100644
index d6af837..0000000
--- a/src/cobalt/media/base/cdm_context.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/cdm_context.h"
-
-namespace cobalt {
-namespace media {
-
-const int CdmContext::kInvalidCdmId = 0;
-
-CdmContext::CdmContext() {}
-
-CdmContext::~CdmContext() {}
-
-void IgnoreCdmAttached(bool /* success */) {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_context.h b/src/cobalt/media/base/cdm_context.h
deleted file mode 100644
index 8a27b8a..0000000
--- a/src/cobalt/media/base/cdm_context.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_CONTEXT_H_
-#define COBALT_MEDIA_BASE_CDM_CONTEXT_H_
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "cobalt/media/base/media_export.h"
-
-namespace cobalt {
-namespace media {
-
-class Decryptor;
-
-// An interface representing the context that a media player needs from a
-// content decryption module (CDM) to decrypt (and decode) encrypted buffers.
-// This is used to pass the CDM to the media player (e.g. SetCdm()).
-class MEDIA_EXPORT CdmContext {
- public:
- // Indicates an invalid CDM ID. See GetCdmId() for details.
- static const int kInvalidCdmId;
-
- virtual ~CdmContext();
-
- // Gets the Decryptor object associated with the CDM. Returns NULL if the
- // CDM does not support a Decryptor (i.e. platform-based CDMs where decryption
- // occurs implicitly along with decoding). The returned object is only
- // guaranteed to be valid during the CDM's lifetime.
- virtual Decryptor* GetDecryptor() = 0;
-
- // Returns an ID that can be used to find a remote CDM, in which case this CDM
- // serves as a proxy to the remote one. Returns kInvalidCdmId when remote CDM
- // is not supported (e.g. this CDM is a local CDM).
- virtual int GetCdmId() const = 0;
-
- protected:
- CdmContext();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(CdmContext);
-};
-
-// Callback to notify that the CdmContext has been completely attached to
-// the media pipeline. Parameter indicates whether the operation succeeded.
-typedef base::Callback<void(bool)> CdmAttachedCB;
-
-// A dummy implementation of CdmAttachedCB.
-MEDIA_EXPORT void IgnoreCdmAttached(bool success);
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_CONTEXT_H_
diff --git a/src/cobalt/media/base/cdm_factory.cc b/src/cobalt/media/base/cdm_factory.cc
deleted file mode 100644
index b227ab0..0000000
--- a/src/cobalt/media/base/cdm_factory.cc
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/cdm_factory.h"
-
-namespace cobalt {
-namespace media {
-
-CdmFactory::CdmFactory() {}
-
-CdmFactory::~CdmFactory() {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_factory.h b/src/cobalt/media/base/cdm_factory.h
deleted file mode 100644
index 77925a4..0000000
--- a/src/cobalt/media/base/cdm_factory.h
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_FACTORY_H_
-#define COBALT_MEDIA_BASE_CDM_FACTORY_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/media_keys.h"
-
-class GURL;
-
-namespace cobalt {
-namespace media {
-
-// Callback used when CDM is created. |error_message| only used if
-// MediaKeys is null (i.e. CDM can't be created).
-using CdmCreatedCB = base::Callback<void(const scoped_refptr<MediaKeys>&,
- const std::string& error_message)>;
-
-struct CdmConfig;
-
-class MEDIA_EXPORT CdmFactory {
- public:
- CdmFactory();
- virtual ~CdmFactory();
-
- // Creates a CDM for |key_system| and returns it through |cdm_created_cb|
- // asynchronously.
- virtual void Create(
- const std::string& key_system, const GURL& security_origin,
- const CdmConfig& cdm_config, const SessionMessageCB& session_message_cb,
- const SessionClosedCB& session_closed_cb,
- const SessionKeysChangeCB& session_keys_change_cb,
- const SessionExpirationUpdateCB& session_expiration_update_cb,
- const CdmCreatedCB& cdm_created_cb) = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(CdmFactory);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_FACTORY_H_
diff --git a/src/cobalt/media/base/cdm_initialized_promise.cc b/src/cobalt/media/base/cdm_initialized_promise.cc
deleted file mode 100644
index bb1775f..0000000
--- a/src/cobalt/media/base/cdm_initialized_promise.cc
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2015 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 "cobalt/media/base/cdm_initialized_promise.h"
-
-namespace cobalt {
-namespace media {
-
-CdmInitializedPromise::CdmInitializedPromise(
- const CdmCreatedCB& cdm_created_cb, const scoped_refptr<MediaKeys>& cdm)
- : cdm_created_cb_(cdm_created_cb), cdm_(cdm) {}
-
-CdmInitializedPromise::~CdmInitializedPromise() {}
-
-void CdmInitializedPromise::resolve() {
- MarkPromiseSettled();
- cdm_created_cb_.Run(cdm_, "");
-}
-
-void CdmInitializedPromise::reject(MediaKeys::Exception exception_code,
- uint32_t system_code,
- const std::string& error_message) {
- MarkPromiseSettled();
- cdm_created_cb_.Run(NULL, error_message);
- // Usually after this |this| (and the |cdm_| within it) will be destroyed.
-}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_initialized_promise.h b/src/cobalt/media/base/cdm_initialized_promise.h
deleted file mode 100644
index 360c2f2..0000000
--- a/src/cobalt/media/base/cdm_initialized_promise.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2015 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_INITIALIZED_PROMISE_H_
-#define COBALT_MEDIA_BASE_CDM_INITIALIZED_PROMISE_H_
-
-#include <string>
-
-#include "base/memory/ref_counted.h"
-#include "cobalt/media/base/cdm_factory.h"
-#include "cobalt/media/base/cdm_promise.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/media_keys.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-// Promise to be resolved when the CDM is initialized. It owns the MediaKeys
-// object until the initialization completes, which it then passes to
-// |cdm_created_cb|.
-class MEDIA_EXPORT CdmInitializedPromise : public SimpleCdmPromise {
- public:
- CdmInitializedPromise(const CdmCreatedCB& cdm_created_cb,
- const scoped_refptr<MediaKeys>& cdm);
- ~CdmInitializedPromise() OVERRIDE;
-
- // SimpleCdmPromise implementation.
- void resolve() OVERRIDE;
- void reject(MediaKeys::Exception exception_code, uint32_t system_code,
- const std::string& error_message) OVERRIDE;
-
- private:
- CdmCreatedCB cdm_created_cb_;
-
- // Holds a ref-count of the CDM.
- scoped_refptr<MediaKeys> cdm_;
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_INITIALIZED_PROMISE_H_
diff --git a/src/cobalt/media/base/cdm_key_information.cc b/src/cobalt/media/base/cdm_key_information.cc
deleted file mode 100644
index f4ecd5b..0000000
--- a/src/cobalt/media/base/cdm_key_information.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2015 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 "base/stl_util.h"
-#include "cobalt/media/base/cdm_key_information.h"
-
-namespace cobalt {
-namespace media {
-
-CdmKeyInformation::CdmKeyInformation()
- : status(INTERNAL_ERROR), system_code(0) {}
-
-CdmKeyInformation::CdmKeyInformation(const std::vector<uint8_t>& key_id,
- KeyStatus status, uint32_t system_code)
- : key_id(key_id), status(status), system_code(system_code) {}
-
-CdmKeyInformation::CdmKeyInformation(const std::string& key_id,
- KeyStatus status, uint32_t system_code)
- : CdmKeyInformation(reinterpret_cast<const uint8_t*>(key_id.data()),
- key_id.size(), status, system_code) {}
-
-CdmKeyInformation::CdmKeyInformation(const uint8_t* key_id_data,
- size_t key_id_length, KeyStatus status,
- uint32_t system_code)
- : key_id(key_id_data, key_id_data + key_id_length),
- status(status),
- system_code(system_code) {}
-
-CdmKeyInformation::CdmKeyInformation(const CdmKeyInformation& other) = default;
-
-CdmKeyInformation::~CdmKeyInformation() {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_key_information.h b/src/cobalt/media/base/cdm_key_information.h
deleted file mode 100644
index f150549..0000000
--- a/src/cobalt/media/base/cdm_key_information.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2015 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_KEY_INFORMATION_H_
-#define COBALT_MEDIA_BASE_CDM_KEY_INFORMATION_H_
-
-#include <string>
-#include <vector>
-
-#include "cobalt/media/base/media_export.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-struct MEDIA_EXPORT CdmKeyInformation {
- enum KeyStatus {
- USABLE = 0,
- INTERNAL_ERROR = 1,
- EXPIRED = 2,
- OUTPUT_RESTRICTED = 3,
- OUTPUT_DOWNSCALED = 4,
- KEY_STATUS_PENDING = 5,
- RELEASED = 6,
- KEY_STATUS_MAX = RELEASED
- };
-
- // Default constructor needed for passing this type through IPC. Regular
- // code should use one of the other constructors.
- CdmKeyInformation();
- CdmKeyInformation(const std::vector<uint8_t>& key_id, KeyStatus status,
- uint32_t system_code);
- CdmKeyInformation(const std::string& key_id, KeyStatus status,
- uint32_t system_code);
- CdmKeyInformation(const uint8_t* key_id_data, size_t key_id_length,
- KeyStatus status, uint32_t system_code);
- CdmKeyInformation(const CdmKeyInformation& other);
- ~CdmKeyInformation();
-
- std::vector<uint8_t> key_id;
- KeyStatus status;
- uint32_t system_code;
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_KEY_INFORMATION_H_
diff --git a/src/cobalt/media/base/cdm_promise.cc b/src/cobalt/media/base/cdm_promise.cc
deleted file mode 100644
index 1048e63..0000000
--- a/src/cobalt/media/base/cdm_promise.cc
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/cdm_promise.h"
-
-namespace cobalt {
-namespace media {
-
-CdmPromise::CdmPromise() {}
-
-CdmPromise::~CdmPromise() {}
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_promise.h b/src/cobalt/media/base/cdm_promise.h
deleted file mode 100644
index 9ab3ff4..0000000
--- a/src/cobalt/media/base/cdm_promise.h
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_PROMISE_H_
-#define COBALT_MEDIA_BASE_CDM_PROMISE_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/media_keys.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-// Interface for promises being resolved/rejected in response to various
-// session actions. These may be called synchronously or asynchronously.
-// The promise must be resolved or rejected exactly once. It is expected that
-// the caller free the promise once it is resolved/rejected.
-
-// These classes are almost generic, except for the parameters to reject(). If
-// a generic class for promises is available, this could be changed to use the
-// generic class as long as the parameters to reject() can be set appropriately.
-
-// The base class only has a reject() method and GetResolveParameterType() that
-// indicates the type of CdmPromiseTemplate. CdmPromiseTemplate<T> adds the
-// resolve(T) method that is dependent on the type of promise. This base class
-// is specified so that the promises can be easily saved before passing across
-// the pepper interface.
-class MEDIA_EXPORT CdmPromise {
- public:
- enum ResolveParameterType {
- VOID_TYPE,
- INT_TYPE,
- STRING_TYPE,
- KEY_IDS_VECTOR_TYPE
- };
-
- CdmPromise();
- virtual ~CdmPromise();
-
- // Used to indicate that the operation failed. |exception_code| must be
- // specified. |system_code| is a Key System-specific value for the error
- // that occurred, or 0 if there is no associated status code or such status
- // codes are not supported by the Key System. |error_message| is optional.
- virtual void reject(MediaKeys::Exception exception_code, uint32_t system_code,
- const std::string& error_message) = 0;
-
- // Used to determine the template type of CdmPromiseTemplate<T> so that
- // saved CdmPromise objects can be cast to the correct templated version.
- virtual ResolveParameterType GetResolveParameterType() const = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(CdmPromise);
-};
-
-// For some reason the Windows compiler is not happy with the implementation
-// of CdmPromiseTemplate being in the .cc file, so moving it here.
-template <typename... T>
-struct CdmPromiseTraits {};
-
-template <>
-struct CdmPromiseTraits<> {
- static const CdmPromise::ResolveParameterType kType = CdmPromise::VOID_TYPE;
-};
-
-template <>
-struct CdmPromiseTraits<int> {
- static const CdmPromise::ResolveParameterType kType = CdmPromise::INT_TYPE;
-};
-
-template <>
-struct CdmPromiseTraits<std::string> {
- static const CdmPromise::ResolveParameterType kType = CdmPromise::STRING_TYPE;
-};
-
-// This class adds the resolve(T) method. This class is still an interface, and
-// is used as the type of promise that gets passed around.
-template <typename... T>
-class MEDIA_EXPORT CdmPromiseTemplate : public CdmPromise {
- public:
- CdmPromiseTemplate() : is_settled_(false) {}
-
- virtual ~CdmPromiseTemplate() { DCHECK(is_settled_); }
-
- virtual void resolve(const T&... result) = 0;
-
- // CdmPromise implementation.
- virtual void reject(MediaKeys::Exception exception_code, uint32_t system_code,
- const std::string& error_message) = 0;
-
- ResolveParameterType GetResolveParameterType() const override {
- return CdmPromiseTraits<T...>::kType;
- }
-
- protected:
- bool IsPromiseSettled() const { return is_settled_; }
-
- // All implementations must call this method in resolve() and reject() methods
- // to indicate that the promise has been settled.
- void MarkPromiseSettled() {
- // Promise can only be settled once.
- DCHECK(!is_settled_);
- is_settled_ = true;
- }
-
- // Must be called by the concrete destructor if !IsPromiseSettled().
- // Note: We can't call reject() in ~CdmPromise() because reject() is virtual.
- void RejectPromiseOnDestruction() {
- DCHECK(!is_settled_);
- std::string message =
- "Unfulfilled promise rejected automatically during destruction.";
- DVLOG(1) << message;
- reject(MediaKeys::INVALID_STATE_ERROR, 0, message);
- DCHECK(is_settled_);
- }
-
- private:
- // Keep track of whether the promise has been resolved or rejected yet.
- bool is_settled_;
-
- DISALLOW_COPY_AND_ASSIGN(CdmPromiseTemplate);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_PROMISE_H_
diff --git a/src/cobalt/media/base/cdm_promise_adapter.cc b/src/cobalt/media/base/cdm_promise_adapter.cc
deleted file mode 100644
index 88db68e..0000000
--- a/src/cobalt/media/base/cdm_promise_adapter.cc
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2014 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 "cobalt/media/base/cdm_promise_adapter.h"
-
-#include <utility>
-
-#include "cobalt/media/base/media_keys.h"
-
-namespace cobalt {
-namespace media {
-
-CdmPromiseAdapter::CdmPromiseAdapter() : next_promise_id_(1) {}
-
-CdmPromiseAdapter::~CdmPromiseAdapter() {
- DCHECK(promises_.empty());
- DCHECK(thread_checker_.CalledOnValidThread());
- Clear();
-}
-
-uint32_t CdmPromiseAdapter::SavePromise(std::unique_ptr<CdmPromise> promise) {
- DCHECK(thread_checker_.CalledOnValidThread());
- uint32_t promise_id = next_promise_id_++;
- promises_.add(promise_id, std::move(promise));
- return promise_id;
-}
-
-template <typename... T>
-void CdmPromiseAdapter::ResolvePromise(uint32_t promise_id,
- const T&... result) {
- std::unique_ptr<CdmPromise> promise = TakePromise(promise_id);
- if (!promise) {
- NOTREACHED() << "Promise not found for " << promise_id;
- return;
- }
-
- // Sanity check the type before we do static_cast.
- CdmPromise::ResolveParameterType type = promise->GetResolveParameterType();
- CdmPromise::ResolveParameterType expected = CdmPromiseTraits<T...>::kType;
- if (type != expected) {
- NOTREACHED() << "Promise type mismatch: " << type << " vs " << expected;
- return;
- }
-
- static_cast<CdmPromiseTemplate<T...>*>(promise.get())->resolve(result...);
-}
-
-void CdmPromiseAdapter::RejectPromise(uint32_t promise_id,
- MediaKeys::Exception exception_code,
- uint32_t system_code,
- const std::string& error_message) {
- std::unique_ptr<CdmPromise> promise = TakePromise(promise_id);
- if (!promise) {
- NOTREACHED() << "No promise found for promise_id " << promise_id;
- return;
- }
-
- promise->reject(exception_code, system_code, error_message);
-}
-
-void CdmPromiseAdapter::Clear() {
- // Reject all outstanding promises.
- DCHECK(thread_checker_.CalledOnValidThread());
- for (auto& promise : promises_)
- promise.second->reject(MediaKeys::UNKNOWN_ERROR, 0, "Operation aborted.");
- promises_.clear();
-}
-
-std::unique_ptr<CdmPromise> CdmPromiseAdapter::TakePromise(
- uint32_t promise_id) {
- DCHECK(thread_checker_.CalledOnValidThread());
- PromiseMap::iterator it = promises_.find(promise_id);
- if (it == promises_.end()) return NULL;
- return promises_.take_and_erase(it);
-}
-
-// Explicit instantiation of function templates.
-template MEDIA_EXPORT void CdmPromiseAdapter::ResolvePromise(uint32_t);
-template MEDIA_EXPORT void CdmPromiseAdapter::ResolvePromise(
- uint32_t, const std::string&);
-
-} // namespace media
-} // namespace cobalt
diff --git a/src/cobalt/media/base/cdm_promise_adapter.h b/src/cobalt/media/base/cdm_promise_adapter.h
deleted file mode 100644
index a7247e2..0000000
--- a/src/cobalt/media/base/cdm_promise_adapter.h
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef COBALT_MEDIA_BASE_CDM_PROMISE_ADAPTER_H_
-#define COBALT_MEDIA_BASE_CDM_PROMISE_ADAPTER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/scoped_ptr_hash_map.h"
-#include "base/threading/thread_checker.h"
-#include "cobalt/media/base/cdm_promise.h"
-#include "cobalt/media/base/media_export.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-// Helps convert CdmPromises to an integer identifier and vice versa. The
-// integer identifier is needed where we cannot pass CdmPromises through, such
-// as PPAPI, IPC and JNI.
-class MEDIA_EXPORT CdmPromiseAdapter {
- public:
- CdmPromiseAdapter();
- ~CdmPromiseAdapter();
-
- // Takes ownership of |promise| and returns an integer promise ID.
- uint32_t SavePromise(std::unique_ptr<media::CdmPromise> promise);
-
- // Takes the promise for |promise_id|, sanity checks its |type|, and resolves
- // it with |result|.
- template <typename... T>
- void ResolvePromise(uint32_t promise_id, const T&... result);
-
- // Takes the promise for |promise_id| and rejects it with |exception_code|,
- // |system_code| and |error_message|.
- void RejectPromise(uint32_t promise_id, MediaKeys::Exception exception_code,
- uint32_t system_code, const std::string& error_message);
-
- // Rejects and clears all |promises_|.
- void Clear();
-
- private:
- // A map between promise IDs and CdmPromises. It owns the CdmPromises.
- typedef base::ScopedPtrHashMap<uint32_t, std::unique_ptr<CdmPromise>>
- PromiseMap;
-
- // Finds, takes the ownership of and returns the promise for |promise_id|.
- // Returns null if no promise can be found.
- std::unique_ptr<CdmPromise> TakePromise(uint32_t promise_id);
-
- uint32_t next_promise_id_;
- PromiseMap promises_;
-
- base::ThreadChecker thread_checker_;
- DISALLOW_COPY_AND_ASSIGN(CdmPromiseAdapter);
-};
-
-} // namespace media
-} // namespace cobalt
-
-#endif // COBALT_MEDIA_BASE_CDM_PROMISE_ADAPTER_H_
diff --git a/src/cobalt/media/base/channel_mixing_matrix.cc b/src/cobalt/media/base/channel_mixing_matrix.cc
deleted file mode 100644
index fb07184..0000000
--- a/src/cobalt/media/base/channel_mixing_matrix.cc
+++ /dev/null
@@ -1,301 +0,0 @@
-// Copyright (c) 2012 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.
-
-// MSVC++ requires this to be set before any other includes to get M_SQRT1_2.
-#define _USE_MATH_DEFINES
-
-#include "cobalt/media/base/channel_mixing_matrix.h"
-
-#include <algorithm>
-#include <cmath>
-
-#include "base/logging.h"
-#include "starboard/types.h"
-
-namespace cobalt {
-namespace media {
-
-// Default scale factor for mixing two channels together. We use a different
-// value for stereo -> mono and mono -> stereo mixes.
-static const float kEqualPowerScale = static_cast<float>(M_SQRT1_2);
-
-static void ValidateLayout(ChannelLayout layout) {
- CHECK_NE(layout, CHANNEL_LAYOUT_NONE);
- CHECK_LE(layout, CHANNEL_LAYOUT_MAX);
- CHECK_NE(layout, CHANNEL_LAYOUT_UNSUPPORTED);
- CHECK_NE(layout, CHANNEL_LAYOUT_DISCRETE);
- CHECK_NE(layout, CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC);
-
- // Verify there's at least one channel. Should always be true here by virtue
- // of not being one of the invalid layouts, but lets double check to be sure.
- int channel_count = ChannelLayoutToChannelCount(layout);
- DCHECK_GT(channel_count, 0);
-
- // If we have more than one channel, verify a symmetric layout for sanity.
- // The unit test will verify all possible layouts, so this can be a DCHECK.
- // Symmetry allows simplifying the matrix building code by allowing us to
- // assume that if one channel of a pair exists, the other will too.
- if (channel_count > 1) {
- // Assert that LEFT exists if and only if RIGHT exists, and so on.
- DCHECK_EQ(ChannelOrder(layout, LEFT) >= 0,
- ChannelOrder(layout, RIGHT) >= 0);
- DCHECK_EQ(ChannelOrder(layout, SIDE_LEFT) >= 0,
- ChannelOrder(layout, SIDE_RIGHT) >= 0);
- DCHECK_EQ(ChannelOrder(layout, BACK_LEFT) >= 0,
- ChannelOrder(layout, BACK_RIGHT) >= 0);
- DCHECK_EQ(ChannelOrder(layout, LEFT_OF_CENTER) >= 0,
- ChannelOrder(layout, RIGHT_OF_CENTER) >= 0);
- } else {
- DCHECK_EQ(layout, CHANNEL_LAYOUT_MONO);
- }
-}
-
-ChannelMixingMatrix::ChannelMixingMatrix(ChannelLayout input_layout,
- int input_channels,
- ChannelLayout output_layout,
- int output_channels)
- : input_layout_(input_layout),
- input_channels_(input_channels),
- output_layout_(output_layout),
- output_channels_(output_channels) {
- // Stereo down mix should never be the output layout.
- CHECK_NE(output_layout, CHANNEL_LAYOUT_STEREO_DOWNMIX);
-
- // Verify that the layouts are supported
- if (input_layout != CHANNEL_LAYOUT_DISCRETE) ValidateLayout(input_layout);
- if (output_layout != CHANNEL_LAYOUT_DISCRETE) ValidateLayout(output_layout);
-
- // Special case for 5.0, 5.1 with back channels when upmixed to 7.0, 7.1,
- // which should map the back LR to side LR.
- if (input_layout_ == CHANNEL_LAYOUT_5_0_BACK &&
- output_layout_ == CHANNEL_LAYOUT_7_0) {
- input_layout_ = CHANNEL_LAYOUT_5_0;
- } else if (input_layout_ == CHANNEL_LAYOUT_5_1_BACK &&
- output_layout_ == CHANNEL_LAYOUT_7_1) {
- input_layout_ = CHANNEL_LAYOUT_5_1;
- }
-}
-
-ChannelMixingMatrix::~ChannelMixingMatrix() {}
-
-bool ChannelMixingMatrix::CreateTransformationMatrix(