From 2e8c30cba4a9c83ffb24bb5459e49e6e7e416599 Mon Sep 17 00:00:00 2001 From: Brian Ting Date: Thu, 16 Nov 2023 15:34:11 -0800 Subject: [PATCH 01/17] Add GetPersistentSetting() to h5vcc_settings. (#1969) Add a persistent settings getter to validate set persistent h5vcc settings. The getter is a string getter that maps to the various types that allows for empty string returns when the getter fails. b/305057554 --- cobalt/h5vcc/h5vcc_settings.cc | 17 +++++++++++++++++ cobalt/h5vcc/h5vcc_settings.h | 5 +++++ cobalt/h5vcc/h5vcc_settings.idl | 2 ++ 3 files changed, 24 insertions(+) diff --git a/cobalt/h5vcc/h5vcc_settings.cc b/cobalt/h5vcc/h5vcc_settings.cc index 4c47039c28d5..59d76c863024 100644 --- a/cobalt/h5vcc/h5vcc_settings.cc +++ b/cobalt/h5vcc/h5vcc_settings.cc @@ -104,5 +104,22 @@ bool H5vccSettings::Set(const std::string& name, SetValueType value) const { return false; } +void H5vccSettings::SetPersistentSettingAsInt(const std::string& key, + int value) const { + if (persistent_settings_) { + persistent_settings_->SetPersistentSetting( + key, std::make_unique(value)); + } +} + +int H5vccSettings::GetPersistentSettingAsInt(const std::string& key, + int default_setting) const { + if (persistent_settings_) { + return persistent_settings_->GetPersistentSettingAsInt(key, + default_setting); + } + return default_setting; +} + } // namespace h5vcc } // namespace cobalt diff --git a/cobalt/h5vcc/h5vcc_settings.h b/cobalt/h5vcc/h5vcc_settings.h index f7e10cf56de4..d958c724e800 100644 --- a/cobalt/h5vcc/h5vcc_settings.h +++ b/cobalt/h5vcc/h5vcc_settings.h @@ -58,6 +58,11 @@ class H5vccSettings : public script::Wrappable { // invalid or not set to the expected value. bool Set(const std::string& name, SetValueType value) const; + void SetPersistentSettingAsInt(const std::string& key, int value) const; + + int GetPersistentSettingAsInt(const std::string& key, + int default_setting) const; + DEFINE_WRAPPABLE_TYPE(H5vccSettings); private: diff --git a/cobalt/h5vcc/h5vcc_settings.idl b/cobalt/h5vcc/h5vcc_settings.idl index 34650a9d1f63..703e483897c4 100644 --- a/cobalt/h5vcc/h5vcc_settings.idl +++ b/cobalt/h5vcc/h5vcc_settings.idl @@ -14,4 +14,6 @@ interface H5vccSettings { boolean set(DOMString name, (long or DOMString) value); + void setPersistentSettingAsInt(DOMString name, long value); + long getPersistentSettingAsInt(DOMString name, long default_setting); }; From b7dd62fdc9057eaa8b03635e49aa7f4ede822c99 Mon Sep 17 00:00:00 2001 From: Oscar Vestlie Date: Thu, 16 Nov 2023 16:46:07 -0800 Subject: [PATCH 02/17] Fix branch name in comment (#1993) b/309858350 --- .github/workflows/label-cherry-pick.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/label-cherry-pick.yaml b/.github/workflows/label-cherry-pick.yaml index 3b9c03d5d779..f58d0a458944 100644 --- a/.github/workflows/label-cherry-pick.yaml +++ b/.github/workflows/label-cherry-pick.yaml @@ -58,6 +58,7 @@ jobs: REPOSITORY: ${{ github.repository }} GITHUB_REF: ${{ github.ref }} MERGE_COMMIT_SHA: ${{ github.event.pull_request.merge_commit_sha }} + CHERRY_PICK_BRANCH: cherry-pick-${{ matrix.target_branch }}-${{ github.event.pull_request.number }} steps: - name: Checkout repository uses: kaidokert/checkout@v3.5.999 @@ -101,7 +102,7 @@ jobs: token: ${{ secrets.CHERRY_PICK_TOKEN }} draft: ${{ steps.cherry-pick.outcome == 'failure' }} base: ${{ matrix.target_branch }} - branch: "cherry-pick-${{ matrix.target_branch }}-${{ github.event.pull_request.number }}" + branch: ${{ env.CHERRY_PICK_BRANCH }} committer: GitHub Release Automation reviewers: ${{ github.event.pull_request.user.login }} title: "Cherry pick PR #${{ github.event.pull_request.number }}: ${{ github.event.pull_request.title }}" @@ -129,6 +130,6 @@ jobs: issue_number: '${{ steps.create-pr.outputs.pull-request-number }}', owner: context.repo.owner, repo: context.repo.repo, - body: '> [!IMPORTANT]\n> There were merge conflicts while cherry picking! Check out the PR branch (${{ matrix.target_branch }}-${{ github.event.pull_request.number }}) and fix the conflicts before proceeding. Check the log at ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} for details.' + body: '> [!IMPORTANT]\n> There were merge conflicts while cherry picking! Check out [${{ env.CHERRY_PICK_BRANCH }}](${{ github.repository }}/tree/${{ env.CHERRY_PICK_BRANCH }}) and fix the conflicts before proceeding. Check the log at ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} for details.' }); } From fbe1ba5011809f30dfa21c88c368f9c0320ee6f1 Mon Sep 17 00:00:00 2001 From: Jelle Foks Date: Thu, 16 Nov 2023 17:42:10 -0800 Subject: [PATCH 03/17] Implement unshipped messages in message port. (#1965) Implement storage of unshipped message in message port, to allow a message port to receive and hold messages before the destination is ready to receive them. Use the above functionality to unblock worker.postMessage calls to no longer wait until the worker script completes loading and executing. b/310240306 b/226640425 --- cobalt/web/BUILD.gn | 1 + cobalt/web/event_target.cc | 27 ++++++++ cobalt/web/event_target.h | 16 ++++- cobalt/web/message_port.cc | 104 +++++++++++++++++++++--------- cobalt/web/message_port.h | 37 ++++++++--- cobalt/web/message_port_test.cc | 45 +++++++++++++ cobalt/worker/client.cc | 10 +-- cobalt/worker/dedicated_worker.cc | 3 +- cobalt/worker/worker.cc | 30 +++------ cobalt/worker/worker.h | 15 ++--- 10 files changed, 205 insertions(+), 83 deletions(-) create mode 100644 cobalt/web/message_port_test.cc diff --git a/cobalt/web/BUILD.gn b/cobalt/web/BUILD.gn index 042f25581fe5..bbdac0de617f 100644 --- a/cobalt/web/BUILD.gn +++ b/cobalt/web/BUILD.gn @@ -185,6 +185,7 @@ target(gtest_target_type, "web_test") { "event_target_test.cc", "event_test.cc", "message_event_test.cc", + "message_port_test.cc", "url_test.cc", "url_utils_test.cc", "window_timers_test.cc", diff --git a/cobalt/web/event_target.cc b/cobalt/web/event_target.cc index 2622b4b402fb..4d2fc0a61da2 100644 --- a/cobalt/web/event_target.cc +++ b/cobalt/web/event_target.cc @@ -282,9 +282,22 @@ void EventTarget::TraceMembers(script::Tracer* tracer) { // instead. } +void EventTarget::AddEventListenerRegistrationCallback( + void* object, base::Token token, base::OnceClosure callback) { + base::AutoLock lock(event_listener_registration_mutex_); + event_listener_registration_callbacks_[token][object] = std::move(callback); +} + +void EventTarget::RemoveEventListenerRegistrationCallbacks(void* object) { + base::AutoLock lock(event_listener_registration_mutex_); + for (auto& token : event_listener_registration_callbacks_) + token.second.erase(object); +} + void EventTarget::AddEventListenerInternal( std::unique_ptr listener_info) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + DCHECK(listener_info); // Remove existing attribute listener of the same type. if (listener_info->is_attribute()) { @@ -314,7 +327,21 @@ void EventTarget::AddEventListenerInternal( debugger_hooks().AsyncTaskScheduled( listener_info->task(), listener_info->type().c_str(), base::DebuggerHooks::AsyncTaskFrequency::kRecurring); + + base::Token type = listener_info->type(); event_listener_infos_.push_back(std::move(listener_info)); + + { + // Call the event listener registration callback. + base::AutoLock lock(event_listener_registration_mutex_); + auto callbacks = event_listener_registration_callbacks_.find(type); + if (callbacks != event_listener_registration_callbacks_.end()) { + for (auto& object : callbacks->second) { + std::move(object.second).Run(); + } + event_listener_registration_callbacks_.erase(type); + } + } } bool EventTarget::HasEventListener(base::Token type) { diff --git a/cobalt/web/event_target.h b/cobalt/web/event_target.h index 1663f80f0422..f61ae4191b98 100644 --- a/cobalt/web/event_target.h +++ b/cobalt/web/event_target.h @@ -15,6 +15,7 @@ #ifndef COBALT_WEB_EVENT_TARGET_H_ #define COBALT_WEB_EVENT_TARGET_H_ +#include #include #include #include @@ -536,7 +537,6 @@ class EventTarget : public script::Wrappable, web::EnvironmentSettings* environment_settings() const { return environment_settings_; } - std::set& event_listener_event_types() const { static std::set event_listener_event_types; for (auto& event_listener_info : event_listener_infos_) { @@ -545,6 +545,12 @@ class EventTarget : public script::Wrappable, return event_listener_event_types; } + // Register a callback to be called when an event listener is added for the + // given type. + void AddEventListenerRegistrationCallback(void* object, base::Token type, + base::OnceClosure callback); + void RemoveEventListenerRegistrationCallbacks(void* object); + protected: virtual ~EventTarget() { environment_settings_ = nullptr; } @@ -569,8 +575,12 @@ class EventTarget : public script::Wrappable, // the special case of window.onerror handling. bool unpack_onerror_events_; - // Thread checker ensures all calls to the EventTarget are made from the same - // thread that it is created in. + base::Lock event_listener_registration_mutex_; + std::map> + event_listener_registration_callbacks_; + + // Thread checker ensures all calls to the EventTarget are made from the + // same thread that it is created in. THREAD_CHECKER(thread_checker_); }; diff --git a/cobalt/web/message_port.cc b/cobalt/web/message_port.cc index 871874b208d7..f6de8e2c998c 100644 --- a/cobalt/web/message_port.cc +++ b/cobalt/web/message_port.cc @@ -23,7 +23,6 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/task_runner.h" #include "cobalt/script/environment_settings.h" #include "cobalt/web/context.h" @@ -34,31 +33,68 @@ namespace cobalt { namespace web { -MessagePort::MessagePort(web::EventTarget* event_target) - : event_target_(event_target) { - if (!event_target_) { - return; +void MessagePort::EntangleWithEventTarget(web::EventTarget* event_target) { + DCHECK(!event_target_); + { + base::AutoLock lock(mutex_); + event_target_ = event_target; + if (!event_target_) { + enabled_ = false; + return; + } } - Context* context = event_target_->environment_settings()->context(); - base::MessageLoop* message_loop = context->message_loop(); - if (!message_loop) { - return; - } - message_loop->task_runner()->PostTask( + target_task_runner()->PostTask( FROM_HERE, base::BindOnce(&Context::AddEnvironmentSettingsChangeObserver, - base::Unretained(context), base::Unretained(this))); + base::Unretained(context()), base::Unretained(this))); remove_environment_settings_change_observer_ = base::BindOnce(&Context::RemoveEnvironmentSettingsChangeObserver, - base::Unretained(context), base::Unretained(this)); + base::Unretained(context()), base::Unretained(this)); + + target_task_runner()->PostTask( + FROM_HERE, + base::Bind( + [](MessagePort* message_port, + web::EventTarget* + event_target) { // The first time a MessagePort object's + // onmessage IDL attribute is set, the + // port's port message queue must be enabled, as if the start() + // method had been called. + // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#messageport + if (event_target->HasEventListener(base::Tokens::message())) { + message_port->Start(); + } else { + event_target->AddEventListenerRegistrationCallback( + message_port, base::Tokens::message(), + base::BindOnce(&MessagePort::Start, + base::Unretained(message_port))); + } + }, + base::Unretained(this), base::Unretained(event_target))); } -MessagePort::~MessagePort() { Close(); } +void MessagePort::Start() { + // The start() method steps are to enable this's port message queue, if it is + // not already enabled. + // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#dom-messageport-start + base::AutoLock lock(mutex_); + if (!event_target_) { + return; + } + enabled_ = true; + for (auto& message : unshipped_messages_) { + PostMessageSerializedLocked(std::move(message)); + } + unshipped_messages_.clear(); +} void MessagePort::Close() { + base::AutoLock lock(mutex_); + unshipped_messages_.clear(); if (!event_target_) { return; } + event_target_->RemoveEventListenerRegistrationCallbacks(this); if (remove_environment_settings_change_observer_) { std::move(remove_environment_settings_change_observer_).Run(); } @@ -66,32 +102,36 @@ void MessagePort::Close() { } void MessagePort::PostMessage(const script::ValueHandleHolder& message) { - PostMessageSerialized(std::make_unique(message)); + auto structured_clone = std::make_unique(message); + { + base::AutoLock lock(mutex_); + if (!(event_target_ && enabled_)) { + unshipped_messages_.push_back(std::move(structured_clone)); + return; + } + PostMessageSerializedLocked(std::move(structured_clone)); + } } -void MessagePort::PostMessageSerialized( +void MessagePort::PostMessageSerializedLocked( std::unique_ptr structured_clone) { - if (!event_target_ || !structured_clone) { - return; - } - // TODO: Forward the location of the origating API call to the PostTask call. - base::MessageLoop* message_loop = - event_target_->environment_settings()->context()->message_loop(); - if (!message_loop) { + if (!structured_clone || !event_target_ || !enabled_) { return; } + // TODO: Forward the location of the origating API call to the PostTask + // call. // https://html.spec.whatwg.org/multipage/workers.html#handler-worker-onmessage // TODO: Update MessageEvent to support more types. (b/227665847) // TODO: Remove dependency of MessageEvent on net iobuffer (b/227665847) - message_loop->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&MessagePort::DispatchMessage, AsWeakPtr(), - std::move(structured_clone))); -} - -void MessagePort::DispatchMessage( - std::unique_ptr structured_clone) { - event_target_->DispatchEvent(new web::MessageEvent( - base::Tokens::message(), std::move(structured_clone))); + target_task_runner()->PostTask( + FROM_HERE, + base::BindOnce( + [](base::WeakPtr event_target, + std::unique_ptr structured_clone) { + event_target->DispatchEvent(new web::MessageEvent( + base::Tokens::message(), std::move(structured_clone))); + }, + event_target_->AsWeakPtr(), std::move(structured_clone))); } } // namespace web diff --git a/cobalt/web/message_port.h b/cobalt/web/message_port.h index cee51093e722..71ef61556a22 100644 --- a/cobalt/web/message_port.h +++ b/cobalt/web/message_port.h @@ -17,6 +17,8 @@ #include #include +#include +#include #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" @@ -34,14 +36,16 @@ namespace cobalt { namespace web { class MessagePort : public script::Wrappable, - public base::SupportsWeakPtr, public Context::EnvironmentSettingsChangeObserver { public: - explicit MessagePort(web::EventTarget* event_target); - ~MessagePort(); + MessagePort() = default; + ~MessagePort() { Close(); } + MessagePort(const MessagePort&) = delete; MessagePort& operator=(const MessagePort&) = delete; + void EntangleWithEventTarget(web::EventTarget* event_target); + void OnEnvironmentSettingsChanged(bool context_valid) override { if (!context_valid) { Close(); @@ -53,10 +57,8 @@ class MessagePort : public script::Wrappable, // -> void PostMessage(const script::ValueHandleHolder& message, // script::Sequence transfer) {} void PostMessage(const script::ValueHandleHolder& message); - void PostMessageSerialized( - std::unique_ptr structured_clone); - void Start() {} + void Start(); void Close(); const web::EventTargetListenerInfo::EventListenerScriptValue* onmessage() @@ -91,15 +93,32 @@ class MessagePort : public script::Wrappable, event_listener); } - web::EventTarget* event_target() { return event_target_; } + EventTarget* event_target() const { return event_target_; } + Context* context() const { + return event_target_ ? event_target_->environment_settings()->context() + : nullptr; + } + base::TaskRunner* target_task_runner() const { + return event_target_ ? event_target_->environment_settings() + ->context() + ->message_loop() + ->task_runner() + : nullptr; + } DEFINE_WRAPPABLE_TYPE(MessagePort); private: - void DispatchMessage( + void PostMessageSerializedLocked( std::unique_ptr structured_clone); - // The event target to dispatch events to. + base::Lock mutex_; + std::vector> unshipped_messages_; + + // A port message queue can be enabled or disabled, and is initially disabled. + // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#message-ports + bool enabled_ = false; + web::EventTarget* event_target_ = nullptr; base::OnceClosure remove_environment_settings_change_observer_; }; diff --git a/cobalt/web/message_port_test.cc b/cobalt/web/message_port_test.cc new file mode 100644 index 000000000000..140c2919d053 --- /dev/null +++ b/cobalt/web/message_port_test.cc @@ -0,0 +1,45 @@ +// Copyright 2023 The Cobalt Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "cobalt/web/message_port.h" + +#include "base/strings/string_util.h" +#include "cobalt/web/testing/test_with_javascript.h" + + +#define EXPECT_SUBSTRING(needle, haystack) \ + EXPECT_PRED_FORMAT2(::testing::IsSubstring, (needle), (haystack)) + +namespace cobalt { +namespace web { + +namespace { +class MessagePortTestWithJavaScript : public testing::TestWebWithJavaScript {}; +} // namespace + +TEST_P(MessagePortTestWithJavaScript, MessagePortIsNotConstructible) { + std::string result; + EXPECT_FALSE(EvaluateScript("var event = new MessagePort();", &result)) + << "Failed to evaluate script."; + EXPECT_SUBSTRING("TypeError: MessagePort is not constructible", result) + << result; +} + +INSTANTIATE_TEST_CASE_P( + MessagePortTestsWithJavaScript, MessagePortTestWithJavaScript, + ::testing::ValuesIn(testing::TestWebWithJavaScript::GetWebTypes()), + testing::TestWebWithJavaScript::GetTypeName); + +} // namespace web +} // namespace cobalt diff --git a/cobalt/worker/client.cc b/cobalt/worker/client.cc index 7ca45bec2711..707958867994 100644 --- a/cobalt/worker/client.cc +++ b/cobalt/worker/client.cc @@ -22,12 +22,12 @@ namespace cobalt { namespace worker { -Client::Client(web::EnvironmentSettings* client) - : MessagePort(client->context() - ->GetWindowOrWorkerGlobalScope() - ->navigator_base() - ->service_worker()) { +Client::Client(web::EnvironmentSettings* client) { DCHECK(client); + EntangleWithEventTarget(client->context() + ->GetWindowOrWorkerGlobalScope() + ->navigator_base() + ->service_worker()); // Algorithm for Create Client: // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#create-client // 1. Let clientObject be a new Client object. diff --git a/cobalt/worker/dedicated_worker.cc b/cobalt/worker/dedicated_worker.cc index 783cead9bef5..af3e62b5614c 100644 --- a/cobalt/worker/dedicated_worker.cc +++ b/cobalt/worker/dedicated_worker.cc @@ -85,7 +85,8 @@ void DedicatedWorker::Initialize(script::ExceptionState* exception_state) { // 6. Let worker be a new Worker object. // 7. Let outside port be a new MessagePort in outside settings's Realm. // 8. Associate the outside port with worker. - outside_port_ = new web::MessagePort(this); + outside_port_ = new web::MessagePort(); + outside_port_->EntangleWithEventTarget(this); // 9. Run this step in parallel: // 1. Run a worker given worker, worker URL, outside settings, outside // port, and options. diff --git a/cobalt/worker/worker.cc b/cobalt/worker/worker.cc index 28ee68eefaba..a126d864abac 100644 --- a/cobalt/worker/worker.cc +++ b/cobalt/worker/worker.cc @@ -19,7 +19,6 @@ #include "base/location.h" #include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/task_runner.h" #include "base/threading/thread.h" #include "cobalt/browser/user_agent_platform_info.h" @@ -40,6 +39,7 @@ namespace cobalt { namespace worker { Worker::Worker(const char* name, const Options& options) : options_(options) { + message_port_ = new web::MessagePort(); // Algorithm for 'run a worker' // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#run-a-worker // 1. Let is shared be true if worker is a SharedWorker object, and false @@ -71,7 +71,6 @@ void Worker::WillDestroyCurrentMessageLoop() { // Destroy members that were constructed in the worker thread. loader_.reset(); worker_global_scope_ = nullptr; - message_port_ = nullptr; content_.reset(); } @@ -265,7 +264,7 @@ void Worker::Execute(const std::string& content, // Done at step 8. // 16. Let inside port be a new MessagePort object in inside settings's Realm. // 17. Associate inside port with worker global scope. - message_port_ = new web::MessagePort(worker_global_scope_); + message_port_->EntangleWithEventTarget(worker_global_scope_); // 18. Entangle outside port and inside port. // TODO(b/226640425): Implement this when Message Ports can be entangled. // 19. Create a new WorkerLocation object and associate it with worker global @@ -280,7 +279,6 @@ void Worker::Execute(const std::string& content, // worker until such time as either the closing flag switches to true or // the worker stops being a suspendable worker. // 22. Set inside settings's execution ready flag. - execution_ready_.Signal(); // 23. If script is a classic script, then run the classic script script. // Otherwise, it is a module script; run the module script script. @@ -314,11 +312,11 @@ void Worker::Abort() { // Algorithm for 'run a worker' // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#run-a-worker // 29. Clear the worker global scope's map of active timers. - if (worker_global_scope_ && message_loop()) { - message_loop()->task_runner()->PostBlockingTask( + if (worker_global_scope_ && task_runner()) { + task_runner()->PostTask( FROM_HERE, base::Bind( - [](WorkerGlobalScope* worker_global_scope) { - worker_global_scope->DestroyTimers(); + [](web::WindowOrWorkerGlobalScope* global_scope) { + global_scope->DestroyTimers(); }, base::Unretained(worker_global_scope_.get()))); } @@ -357,20 +355,8 @@ void Worker::Terminate() { } void Worker::PostMessage(const script::ValueHandleHolder& message) { - DCHECK(message_loop()); - auto structured_clone = std::make_unique(message); - if (base::MessageLoop::current() != message_loop()) { - // Block until the worker thread is ready to execute code to handle the - // event. - execution_ready_.Wait(); - message_loop()->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&web::MessagePort::PostMessageSerialized, - message_port()->AsWeakPtr(), - std::move(structured_clone))); - } else { - DCHECK(execution_ready_.IsSignaled()); - message_port()->PostMessageSerialized(std::move(structured_clone)); - } + DCHECK(message_port_); + message_port_->PostMessage(message); } } // namespace worker diff --git a/cobalt/worker/worker.h b/cobalt/worker/worker.h index 364837a2fd01..5cce8cb6514e 100644 --- a/cobalt/worker/worker.h +++ b/cobalt/worker/worker.h @@ -24,6 +24,7 @@ #include "base/memory/scoped_refptr.h" #include "base/message_loop/message_loop_current.h" #include "base/synchronization/waitable_event.h" +#include "base/task_runner.h" #include "base/threading/thread.h" #include "cobalt/base/source_location.h" #include "cobalt/csp/content_security_policy.h" @@ -81,11 +82,9 @@ class Worker : public base::MessageLoop::DestructionObserver { void Terminate(); - web::MessagePort* message_port() const { return message_port_.get(); } - - // The message loop this object is running on. - base::MessageLoop* message_loop() const { - return web_agent_ ? web_agent_->message_loop() : nullptr; + // The task runner for this object. + base::TaskRunner* task_runner() const { + return web_agent_ ? web_agent_->message_loop()->task_runner() : nullptr; } void PostMessage(const script::ValueHandleHolder& message); @@ -138,12 +137,6 @@ class Worker : public base::MessageLoop::DestructionObserver { // Content of the script. Released after Execute is called. std::unique_ptr content_; - - // The execution ready flag. - // https://html.spec.whatwg.org/commit-snapshots/465a6b672c703054de278b0f8133eb3ad33d93f4/#concept-environment-execution-ready-flag - base::WaitableEvent execution_ready_ = { - base::WaitableEvent::ResetPolicy::MANUAL, - base::WaitableEvent::InitialState::NOT_SIGNALED}; }; } // namespace worker From 05c0e05ce32b5181c4a655bbe32911a31ebfe3f9 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Tue, 14 Nov 2023 12:12:55 -0800 Subject: [PATCH 04/17] Deprecate SbStringCompareNoCase b/305768669 --- cobalt/debug/console/command_manager.cc | 6 ++++ cobalt/dom/on_screen_keyboard.cc | 8 +++-- cobalt/loader/cors_preflight.cc | 31 +++++++++++++++++++ cobalt/loader/cors_preflight_cache.cc | 7 +++++ cobalt/loader/cors_preflight_cache.h | 4 +++ .../skia/skia/src/ports/SkFontMgr_cobalt.cc | 12 +++++++ .../skia/src/ports/SkFontStyleSet_cobalt.cc | 22 +++++++++++++ starboard/client_porting/poem/strings_poem.h | 2 ++ starboard/elf_loader/exported_symbols.cc | 6 ++-- .../shared/posix/string_compare_no_case.cc | 2 ++ .../shared/posix/string_compare_no_case_n.cc | 2 ++ starboard/shared/starboard/media/mime_type.cc | 6 ++++ .../shared/stub/string_compare_no_case.cc | 2 ++ .../shared/stub/string_compare_no_case_n.cc | 2 ++ .../shared/win32/string_compare_no_case.cc | 2 ++ .../shared/win32/string_compare_no_case_n.cc | 2 ++ third_party/musl/BUILD.gn | 2 ++ 17 files changed, 112 insertions(+), 6 deletions(-) diff --git a/cobalt/debug/console/command_manager.cc b/cobalt/debug/console/command_manager.cc index 3c30ae38912e..f87ea66e2c35 100644 --- a/cobalt/debug/console/command_manager.cc +++ b/cobalt/debug/console/command_manager.cc @@ -50,9 +50,15 @@ ConsoleCommandManager::CommandHandler::~CommandHandler() { // static bool ConsoleCommandManager::CommandHandler::IsOnEnableOrTrue( const std::string& message) { + #if SB_API_VERSION < 16 return (SbStringCompareNoCase("on", message.c_str()) == 0) || (SbStringCompareNoCase("enable", message.c_str()) == 0) || (SbStringCompareNoCase("true", message.c_str()) == 0); + #else + return (strcasecmp("on", message.c_str()) == 0) || + (strcasecmp("enable", message.c_str()) == 0) || + (strcasecmp("true", message.c_str()) == 0); + #endif // SB_API_VERSION < 16 } diff --git a/cobalt/dom/on_screen_keyboard.cc b/cobalt/dom/on_screen_keyboard.cc index ec41ff409b62..07a3c9704262 100644 --- a/cobalt/dom/on_screen_keyboard.cc +++ b/cobalt/dom/on_screen_keyboard.cc @@ -51,8 +51,12 @@ bool ParseColor(const char* color_str, int& r, int& g, int& b) { } // Handle rgb color notation rgb(R, G, B) - if (!is_hex && len >= 10 && - SbStringCompareNoCaseN("rgb(", color_str, 4) == 0) { + #if SB_API_VERSION < 16 + bool strcmp = SbStringCompareNoCaseN("rgb(", color_str, 4) == 0; + #else + bool strcmp = strncasecmp("rgb(", color_str, 4) == 0; + #endif //SB_API_VERSION < 16 + if (!is_hex && len >= 10 && strcmp) { int rgb_tmp[3] = {-1, -1, -1}; const char* ptr = color_str + 4; int i = 0; diff --git a/cobalt/loader/cors_preflight.cc b/cobalt/loader/cors_preflight.cc index 980f4d971f1b..718a2cc438aa 100644 --- a/cobalt/loader/cors_preflight.cc +++ b/cobalt/loader/cors_preflight.cc @@ -117,9 +117,15 @@ bool IsInArray(const char* input_str, const char* array[], size_t size) { return false; } for (size_t i = 0; i < size; ++i) { + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(input_str, array[i]) == 0) { return true; } + #else + if (strcasecmp(input_str, array[i]) == 0) { + return true; + } + #endif // SB_API_VERSION < 16 } return false; } @@ -132,10 +138,18 @@ bool HasFieldValue(const std::vector& field_values, if (field_values[i].empty()) { continue; } + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(field_values[i].c_str(), find_value_name.c_str()) == 0) { return true; } + #else + if (strcasecmp(field_values[i].c_str(), + find_value_name.c_str()) == 0) { + return true; + } + #endif // SB_API_VERSION < 16 + } return false; } @@ -220,10 +234,17 @@ bool CORSPreflight::IsSafeResponseHeader( } for (size_t i = 0; i < CORS_exposed_header_name_list.size(); i++) { + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(CORS_exposed_header_name_list.at(i).c_str(), name.c_str()) == 0) { return true; } + #else + if (strcasecmp(CORS_exposed_header_name_list.at(i).c_str(), + name.c_str()) == 0) { + return true; + } + #endif //SB_API_VERSION < 16 } return false; } @@ -381,12 +402,22 @@ void CORSPreflight::OnURLFetchComplete(const net::URLFetcher* source) { if (HasFieldValue(headernames_vec, it.name())) { continue; } + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(it.name().c_str(), kAuthorization) == 0 || (!HasFieldValue(headernames_vec, "*") && !IsSafeRequestHeader(it.name(), it.value()))) { error_callback_.Run(); return; } + #else + if (strcasecmp(it.name().c_str(), kAuthorization) == 0 || + (!HasFieldValue(headernames_vec, "*") && + !IsSafeRequestHeader(it.name(), it.value()))) { + error_callback_.Run(); + return; + } + #endif //SB_API_VERSION < 16 + } // step 10-18 for adding entry to preflight cache. std::string max_age_str; diff --git a/cobalt/loader/cors_preflight_cache.cc b/cobalt/loader/cors_preflight_cache.cc index c16d31339679..6d09a4127ab1 100644 --- a/cobalt/loader/cors_preflight_cache.cc +++ b/cobalt/loader/cors_preflight_cache.cc @@ -127,10 +127,17 @@ bool CORSPreflightCache::HaveEntry( if (entry_ptr->allow_all_headers_except_non_wildcard) { bool has_auth_header = false; for (const auto& header : unsafe_headernames) { + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(header.c_str(), kAuthorization)) { has_auth_header = true; break; } + #else + if (strcasecmp(header.c_str(), kAuthorization)) { + has_auth_header = true; + break; + } + #endif //SB_API_VERSION < 16 } // wildcard header is allowed if entry's allowed headers include it. return !has_auth_header || diff --git a/cobalt/loader/cors_preflight_cache.h b/cobalt/loader/cors_preflight_cache.h index 6e063d5b18a2..48cdb7aeb9fe 100644 --- a/cobalt/loader/cors_preflight_cache.h +++ b/cobalt/loader/cors_preflight_cache.h @@ -54,7 +54,11 @@ class CORSPreflightCache : public base::RefCounted { // Case-insensitive comparator. struct CaseInsensitiveCompare { bool operator()(const std::string& lhs, const std::string& rhs) const { + #if SB_API_VERSION < 16 return SbStringCompareNoCase(lhs.c_str(), rhs.c_str()) < 0; + #else + return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; + #endif //SB_API_VERSION < 16 } }; diff --git a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc index b64037dd062d..b4e3197d18fa 100644 --- a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc +++ b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc @@ -307,9 +307,15 @@ void SkFontMgr_Cobalt::LoadLocaleDefault() { std::string script = icu::Locale::createCanonical(base::GetSystemLanguageScript().c_str()) .getScript(); + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(script.c_str(), ROBOTO_SCRIPT) == 0) { return; } + #else + if (strcasecmp(script.c_str(), ROBOTO_SCRIPT) == 0) { + return; + } + #endif // SB_API_VERSION < 16 default_fonts_loaded_event_.Reset(); for (int i = 0; i < families_.count(); i++) { @@ -515,9 +521,15 @@ bool SkFontMgr_Cobalt::CheckIfFamilyMatchesLocaleScript( } std::string family_script = icu::Locale::createCanonical(family_tag.c_str()).getScript(); + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(script, family_script.c_str()) != 0) { return false; } + #else + if (strcasecmp(script, family_script.c_str()) != 0) { + return false; + } + #endif //SB_API_VERSION < 16 sk_sp check_typeface( new_family->MatchStyleWithoutLocking(SkFontStyle())); diff --git a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc index 136b2e31bce3..c3d5b34e0367 100644 --- a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc +++ b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc @@ -232,6 +232,7 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( ++extension; // Only add font formats that match the format setting. + #if SB_API_VERSION < 16 if (font_format_setting == kTtf) { if (SbStringCompareNoCase("ttf", extension) != 0 && SbStringCompareNoCase(extension, "ttc") != 0) { @@ -241,6 +242,17 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( SbStringCompareNoCase("woff2", extension) != 0) { continue; } + #else + if (font_format_setting == kTtf) { + if (strcasecmp("ttf", extension) != 0 && + strcasecmp(extension, "ttc") != 0) { + continue; + } + } else if (font_format_setting == kWoff2 && + strcasecmp("woff2", extension) != 0) { + continue; + } + #endif //SB_API_VERSION < 16 SkFontStyle style(font_file.weight, SkFontStyle::kNormal_Width, font_file.style == FontFileInfo::kItalic_FontStyle @@ -272,6 +284,7 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( int* index = styles_index_map.find(font_name); if (index != nullptr) { // If style with name already exists in family, replace it. + #if SB_API_VERSION < 16 if (font_format_setting == kTtfPreferred && SbStringCompareNoCase("ttf", extension) == 0) { styles_[*index].reset(font); @@ -279,6 +292,15 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( SbStringCompareNoCase("woff2", extension) == 0) { styles_[*index].reset(font); } + #else + if (font_format_setting == kTtfPreferred && + strcasecmp("ttf", extension) == 0) { + styles_[*index].reset(font); + } else if (font_format_setting == kWoff2Preferred && + strcasecmp("woff2", extension) == 0) { + styles_[*index].reset(font); + } + #endif //SB_API_VERSION < 16 } else { int count = styles_.count(); styles_index_map.set(font_name, count); diff --git a/starboard/client_porting/poem/strings_poem.h b/starboard/client_porting/poem/strings_poem.h index 7cab608fb3b2..7d7be2884962 100644 --- a/starboard/client_porting/poem/strings_poem.h +++ b/starboard/client_porting/poem/strings_poem.h @@ -23,10 +23,12 @@ #include "starboard/string.h" +#if SB_API_VERSION < 16 #undef strcasecmp #define strcasecmp(s1, s2) SbStringCompareNoCase(s1, s2) #undef strncasecmp #define strncasecmp(s1, s2) SbStringCompareNoCaseN(s1, s2) +#endif // SB_API_VERSION < 16 #endif // POEM_NO_EMULATION diff --git a/starboard/elf_loader/exported_symbols.cc b/starboard/elf_loader/exported_symbols.cc index d3bb80696d95..c0134d22a875 100644 --- a/starboard/elf_loader/exported_symbols.cc +++ b/starboard/elf_loader/exported_symbols.cc @@ -303,13 +303,11 @@ ExportedSymbols::ExportedSymbols() { REGISTER_SYMBOL(SbStorageOpenRecord); REGISTER_SYMBOL(SbStorageReadRecord); REGISTER_SYMBOL(SbStorageWriteRecord); +#if SB_API_VERSION < 16 REGISTER_SYMBOL(SbStringCompareNoCase); REGISTER_SYMBOL(SbStringCompareNoCaseN); - -#if SB_API_VERSION < 16 REGISTER_SYMBOL(SbStringDuplicate); -#endif // #if SB_API_VERSION < 16 - +#endif // SB_API_VERSION < 16 REGISTER_SYMBOL(SbStringFormat); REGISTER_SYMBOL(SbStringFormatWide); REGISTER_SYMBOL(SbStringScan); diff --git a/starboard/shared/posix/string_compare_no_case.cc b/starboard/shared/posix/string_compare_no_case.cc index 4837d888b2a9..79479e7eebe1 100644 --- a/starboard/shared/posix/string_compare_no_case.cc +++ b/starboard/shared/posix/string_compare_no_case.cc @@ -17,6 +17,8 @@ #include // Non-standard, required for some platforms. #include +#if SB_API_VERSION < 16 int SbStringCompareNoCase(const char* string1, const char* string2) { return strcasecmp(string1, string2); } +#endif diff --git a/starboard/shared/posix/string_compare_no_case_n.cc b/starboard/shared/posix/string_compare_no_case_n.cc index 75c9141a1afb..e56c4fb7ebce 100644 --- a/starboard/shared/posix/string_compare_no_case_n.cc +++ b/starboard/shared/posix/string_compare_no_case_n.cc @@ -17,8 +17,10 @@ #include // Non-standard, required for some platforms. #include +#if SB_API_VERSION < 16 int SbStringCompareNoCaseN(const char* string1, const char* string2, size_t count) { return ::strncasecmp(string1, string2, count); } +#endif diff --git a/starboard/shared/starboard/media/mime_type.cc b/starboard/shared/starboard/media/mime_type.cc index 4954ceeb318e..80b25f78f834 100644 --- a/starboard/shared/starboard/media/mime_type.cc +++ b/starboard/shared/starboard/media/mime_type.cc @@ -196,9 +196,15 @@ const std::string& MimeType::GetParamName(int index) const { int MimeType::GetParamIndexByName(const char* name) const { for (size_t i = 0; i < params_.size(); ++i) { + #if SB_API_VERSION < 16 if (SbStringCompareNoCase(params_[i].name.c_str(), name) == 0) { return static_cast(i); } + #else + if (strcasecmp(params_[i].name.c_str(), name) == 0) { + return static_cast(i); + } + #endif // SB_API_VERSION < 16 } return kInvalidParamIndex; } diff --git a/starboard/shared/stub/string_compare_no_case.cc b/starboard/shared/stub/string_compare_no_case.cc index 3434800b2d63..aa767bdb86be 100644 --- a/starboard/shared/stub/string_compare_no_case.cc +++ b/starboard/shared/stub/string_compare_no_case.cc @@ -14,6 +14,8 @@ #include "starboard/common/string.h" +#if SB_API_VERSION < 16 int SbStringCompareNoCase(const char* string1, const char* string2) { return 0; } +#endif diff --git a/starboard/shared/stub/string_compare_no_case_n.cc b/starboard/shared/stub/string_compare_no_case_n.cc index e04639e26939..aa7ae6323c75 100644 --- a/starboard/shared/stub/string_compare_no_case_n.cc +++ b/starboard/shared/stub/string_compare_no_case_n.cc @@ -14,8 +14,10 @@ #include "starboard/common/string.h" +#if SB_API_VERSION < 16 int SbStringCompareNoCaseN(const char* string1, const char* string2, size_t count) { return 0; } +#endif diff --git a/starboard/shared/win32/string_compare_no_case.cc b/starboard/shared/win32/string_compare_no_case.cc index 6021bf7d0ae1..85862f19f9ab 100644 --- a/starboard/shared/win32/string_compare_no_case.cc +++ b/starboard/shared/win32/string_compare_no_case.cc @@ -16,6 +16,8 @@ #include +#if SB_API_VERSION < 16 int SbStringCompareNoCase(const char* string1, const char* string2) { return _stricmp(string1, string2); } +#endif diff --git a/starboard/shared/win32/string_compare_no_case_n.cc b/starboard/shared/win32/string_compare_no_case_n.cc index 7490d3d9c7ce..3ac38d73a953 100644 --- a/starboard/shared/win32/string_compare_no_case_n.cc +++ b/starboard/shared/win32/string_compare_no_case_n.cc @@ -16,8 +16,10 @@ #include +#if SB_API_VERSION < 16 int SbStringCompareNoCaseN(const char* string1, const char* string2, size_t count) { return _strnicmp(string1, string2, count); } +#endif diff --git a/third_party/musl/BUILD.gn b/third_party/musl/BUILD.gn index 0c7d0578f439..3886d776441c 100644 --- a/third_party/musl/BUILD.gn +++ b/third_party/musl/BUILD.gn @@ -433,6 +433,7 @@ static_library("c_internal") { "src/string/rindex.c", "src/string/stpcpy.c", "src/string/stpncpy.c", + "src/string/strcasecmp.c", "src/string/strcat.c", "src/string/strchr.c", "src/string/strchrnul.c", @@ -444,6 +445,7 @@ static_library("c_internal") { "src/string/strlcat.c", "src/string/strlcpy.c", "src/string/strlen.c", + "src/string/strncasecmp.c", "src/string/strncat.c", "src/string/strncmp.c", "src/string/strncpy.c", From feed2ccdfaac329575426032f294d28dc98c6fd6 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Thu, 16 Nov 2023 09:52:12 -0800 Subject: [PATCH 05/17] change --- base/strings/string_util_starboard.h | 8 ----- cobalt/browser/application.cc | 2 +- cobalt/csp/source_list.cc | 6 ++-- cobalt/debug/console/command_manager.cc | 6 ---- cobalt/dom/document.cc | 24 +++++++------- cobalt/dom/on_screen_keyboard.cc | 8 ++--- cobalt/loader/cors_preflight.cc | 31 +------------------ cobalt/loader/cors_preflight_cache.cc | 7 ----- cobalt/loader/cors_preflight_cache.h | 4 --- cobalt/media/sandbox/format_guesstimator.cc | 2 +- .../skia/skia/src/ports/SkFontMgr_cobalt.cc | 12 ------- .../skia/src/ports/SkFontStyleSet_cobalt.cc | 22 ------------- .../nplb/string_compare_no_case_n_test.cc | 2 ++ starboard/nplb/string_compare_no_case_test.cc | 3 +- starboard/nplb/string_duplicate_test.cc | 2 ++ starboard/shared/starboard/media/mime_type.cc | 6 ---- starboard/string.h | 2 +- .../chromium/media/base/starboard_utils.cc | 2 +- .../chromium/media/filters/chunk_demuxer.cc | 2 +- .../include/gtest/internal/gtest-port.h | 2 ++ 20 files changed, 31 insertions(+), 122 deletions(-) diff --git a/base/strings/string_util_starboard.h b/base/strings/string_util_starboard.h index 6bb3f65b7e29..c16239526066 100644 --- a/base/strings/string_util_starboard.h +++ b/base/strings/string_util_starboard.h @@ -25,14 +25,6 @@ namespace base { -inline int strcasecmp(const char* string1, const char* string2) { - return SbStringCompareNoCase(string1, string2); -} - -inline int strncasecmp(const char* string1, const char* string2, size_t count) { - return SbStringCompareNoCaseN(string1, string2, count); -} - #if defined(vsnprintf) #undef vsnprintf #endif diff --git a/cobalt/browser/application.cc b/cobalt/browser/application.cc index 7c33e71a19c5..1f73882376c2 100644 --- a/cobalt/browser/application.cc +++ b/cobalt/browser/application.cc @@ -116,7 +116,7 @@ const int64_t kWatchdogTimeInterval = 10000000; const int64_t kWatchdogTimeWait = 2000000; bool IsStringNone(const std::string& str) { - return !base::strcasecmp(str.c_str(), "none"); + return !strcasecmp(str.c_str(), "none"); } #if defined(ENABLE_WEBDRIVER) || defined(ENABLE_DEBUGGER) diff --git a/cobalt/csp/source_list.cc b/cobalt/csp/source_list.cc index 902ba39e2d72..6133e12f0373 100644 --- a/cobalt/csp/source_list.cc +++ b/cobalt/csp/source_list.cc @@ -35,7 +35,7 @@ bool IsSourceListNone(const char* begin, const char* end) { const char* position = begin; SkipWhile(&position, end); size_t len = static_cast(position - begin); - if (base::strncasecmp("'none'", begin, len) != 0) { + if (strncasecmp("'none'", begin, len) != 0) { return false; } @@ -400,7 +400,7 @@ bool SourceList::ParseNonce(const char* begin, const char* end, const char* prefix = "'nonce-"; if (nonce_length <= strlen(prefix) || - base::strncasecmp(prefix, begin, strlen(prefix)) != 0) { + strncasecmp(prefix, begin, strlen(prefix)) != 0) { return true; } @@ -433,7 +433,7 @@ bool SourceList::ParseHash(const char* begin, const char* end, for (size_t i = 0; i < arraysize(kSupportedPrefixes); ++i) { const HashPrefix& algorithm = kSupportedPrefixes[i]; if (hash_length > strlen(algorithm.prefix) && - base::strncasecmp(algorithm.prefix, begin, strlen(algorithm.prefix)) == + strncasecmp(algorithm.prefix, begin, strlen(algorithm.prefix)) == 0) { prefix = algorithm.prefix; *hash_algorithm = algorithm.type; diff --git a/cobalt/debug/console/command_manager.cc b/cobalt/debug/console/command_manager.cc index f87ea66e2c35..99a9420c5990 100644 --- a/cobalt/debug/console/command_manager.cc +++ b/cobalt/debug/console/command_manager.cc @@ -50,15 +50,9 @@ ConsoleCommandManager::CommandHandler::~CommandHandler() { // static bool ConsoleCommandManager::CommandHandler::IsOnEnableOrTrue( const std::string& message) { - #if SB_API_VERSION < 16 - return (SbStringCompareNoCase("on", message.c_str()) == 0) || - (SbStringCompareNoCase("enable", message.c_str()) == 0) || - (SbStringCompareNoCase("true", message.c_str()) == 0); - #else return (strcasecmp("on", message.c_str()) == 0) || (strcasecmp("enable", message.c_str()) == 0) || (strcasecmp("true", message.c_str()) == 0); - #endif // SB_API_VERSION < 16 } diff --git a/cobalt/dom/document.cc b/cobalt/dom/document.cc index e405cd9de197..6fb63cdc46cf 100644 --- a/cobalt/dom/document.cc +++ b/cobalt/dom/document.cc @@ -235,26 +235,26 @@ scoped_refptr Document::CreateEvent( script::ExceptionState* exception_state) { // https://www.w3.org/TR/dom/#dom-document-createevent // The match of interface name is case-insensitive. - if (base::strcasecmp(interface_name.c_str(), "event") == 0 || - base::strcasecmp(interface_name.c_str(), "events") == 0 || - base::strcasecmp(interface_name.c_str(), "htmlevents") == 0) { + if (strcasecmp(interface_name.c_str(), "event") == 0 || + strcasecmp(interface_name.c_str(), "events") == 0 || + strcasecmp(interface_name.c_str(), "htmlevents") == 0) { return new web::Event(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "keyboardevent") == 0 || - base::strcasecmp(interface_name.c_str(), "keyevents") == 0) { + } else if (strcasecmp(interface_name.c_str(), "keyboardevent") == 0 || + strcasecmp(interface_name.c_str(), "keyevents") == 0) { return new KeyboardEvent(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "messageevent") == 0) { + } else if (strcasecmp(interface_name.c_str(), "messageevent") == 0) { return new web::MessageEvent(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "mouseevent") == 0 || - base::strcasecmp(interface_name.c_str(), "mouseevents") == 0) { + } else if (strcasecmp(interface_name.c_str(), "mouseevent") == 0 || + strcasecmp(interface_name.c_str(), "mouseevents") == 0) { return new MouseEvent(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "uievent") == 0 || - base::strcasecmp(interface_name.c_str(), "uievents") == 0) { + } else if (strcasecmp(interface_name.c_str(), "uievent") == 0 || + strcasecmp(interface_name.c_str(), "uievents") == 0) { return new UIEvent(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "wheelevent") == 0) { + } else if (strcasecmp(interface_name.c_str(), "wheelevent") == 0) { // This not in the spec, but commonly implemented to create a WheelEvent. // https://www.w3.org/TR/2016/WD-uievents-20160804/#interface-wheelevent return new WheelEvent(web::Event::Uninitialized); - } else if (base::strcasecmp(interface_name.c_str(), "customevent") == 0) { + } else if (strcasecmp(interface_name.c_str(), "customevent") == 0) { return new web::CustomEvent(web::Event::Uninitialized); } diff --git a/cobalt/dom/on_screen_keyboard.cc b/cobalt/dom/on_screen_keyboard.cc index 07a3c9704262..0b90098312c4 100644 --- a/cobalt/dom/on_screen_keyboard.cc +++ b/cobalt/dom/on_screen_keyboard.cc @@ -51,12 +51,8 @@ bool ParseColor(const char* color_str, int& r, int& g, int& b) { } // Handle rgb color notation rgb(R, G, B) - #if SB_API_VERSION < 16 - bool strcmp = SbStringCompareNoCaseN("rgb(", color_str, 4) == 0; - #else - bool strcmp = strncasecmp("rgb(", color_str, 4) == 0; - #endif //SB_API_VERSION < 16 - if (!is_hex && len >= 10 && strcmp) { + if (!is_hex && len >= 10 && + strncasecmp("rgb(", color_str, 4) == 0) { int rgb_tmp[3] = {-1, -1, -1}; const char* ptr = color_str + 4; int i = 0; diff --git a/cobalt/loader/cors_preflight.cc b/cobalt/loader/cors_preflight.cc index 718a2cc438aa..d2af211981b9 100644 --- a/cobalt/loader/cors_preflight.cc +++ b/cobalt/loader/cors_preflight.cc @@ -117,15 +117,9 @@ bool IsInArray(const char* input_str, const char* array[], size_t size) { return false; } for (size_t i = 0; i < size; ++i) { - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(input_str, array[i]) == 0) { - return true; - } - #else if (strcasecmp(input_str, array[i]) == 0) { return true; } - #endif // SB_API_VERSION < 16 } return false; } @@ -138,17 +132,10 @@ bool HasFieldValue(const std::vector& field_values, if (field_values[i].empty()) { continue; } - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(field_values[i].c_str(), - find_value_name.c_str()) == 0) { - return true; - } - #else if (strcasecmp(field_values[i].c_str(), find_value_name.c_str()) == 0) { return true; } - #endif // SB_API_VERSION < 16 } return false; @@ -185,7 +172,7 @@ bool CORSPreflight::IsSafeRequestHeader(const std::string& name, // Safe if header name is 'Content-Type' and value is a match of // kAllowedMIMEType. - if (SbStringCompareNoCase(name.c_str(), kContentType) == 0) { + if (strcasecmp(name.c_str(), kContentType) == 0) { std::vector content_type_split = base::SplitString( value, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); auto begin_iter = content_type_split[0].cbegin(); @@ -234,17 +221,10 @@ bool CORSPreflight::IsSafeResponseHeader( } for (size_t i = 0; i < CORS_exposed_header_name_list.size(); i++) { - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(CORS_exposed_header_name_list.at(i).c_str(), - name.c_str()) == 0) { - return true; - } - #else if (strcasecmp(CORS_exposed_header_name_list.at(i).c_str(), name.c_str()) == 0) { return true; } - #endif //SB_API_VERSION < 16 } return false; } @@ -402,21 +382,12 @@ void CORSPreflight::OnURLFetchComplete(const net::URLFetcher* source) { if (HasFieldValue(headernames_vec, it.name())) { continue; } - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(it.name().c_str(), kAuthorization) == 0 || - (!HasFieldValue(headernames_vec, "*") && - !IsSafeRequestHeader(it.name(), it.value()))) { - error_callback_.Run(); - return; - } - #else if (strcasecmp(it.name().c_str(), kAuthorization) == 0 || (!HasFieldValue(headernames_vec, "*") && !IsSafeRequestHeader(it.name(), it.value()))) { error_callback_.Run(); return; } - #endif //SB_API_VERSION < 16 } // step 10-18 for adding entry to preflight cache. diff --git a/cobalt/loader/cors_preflight_cache.cc b/cobalt/loader/cors_preflight_cache.cc index 6d09a4127ab1..cd5302d58e0d 100644 --- a/cobalt/loader/cors_preflight_cache.cc +++ b/cobalt/loader/cors_preflight_cache.cc @@ -127,17 +127,10 @@ bool CORSPreflightCache::HaveEntry( if (entry_ptr->allow_all_headers_except_non_wildcard) { bool has_auth_header = false; for (const auto& header : unsafe_headernames) { - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(header.c_str(), kAuthorization)) { - has_auth_header = true; - break; - } - #else if (strcasecmp(header.c_str(), kAuthorization)) { has_auth_header = true; break; } - #endif //SB_API_VERSION < 16 } // wildcard header is allowed if entry's allowed headers include it. return !has_auth_header || diff --git a/cobalt/loader/cors_preflight_cache.h b/cobalt/loader/cors_preflight_cache.h index 48cdb7aeb9fe..e1a72bfcc80f 100644 --- a/cobalt/loader/cors_preflight_cache.h +++ b/cobalt/loader/cors_preflight_cache.h @@ -54,11 +54,7 @@ class CORSPreflightCache : public base::RefCounted { // Case-insensitive comparator. struct CaseInsensitiveCompare { bool operator()(const std::string& lhs, const std::string& rhs) const { - #if SB_API_VERSION < 16 - return SbStringCompareNoCase(lhs.c_str(), rhs.c_str()) < 0; - #else return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; - #endif //SB_API_VERSION < 16 } }; diff --git a/cobalt/media/sandbox/format_guesstimator.cc b/cobalt/media/sandbox/format_guesstimator.cc index 1225b5aec70d..1a571106caeb 100644 --- a/cobalt/media/sandbox/format_guesstimator.cc +++ b/cobalt/media/sandbox/format_guesstimator.cc @@ -118,7 +118,7 @@ std::string ExtractCodecs(const std::string& content_type) { std::vector tokens = ::base::SplitString( content_type, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); for (size_t i = 1; i < tokens.size(); ++i) { - if (base::strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { + if (strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { continue; } auto codec = tokens[i].substr(strlen("codecs=")); diff --git a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc index b4e3197d18fa..918d040d83e0 100644 --- a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc +++ b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontMgr_cobalt.cc @@ -307,15 +307,9 @@ void SkFontMgr_Cobalt::LoadLocaleDefault() { std::string script = icu::Locale::createCanonical(base::GetSystemLanguageScript().c_str()) .getScript(); - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(script.c_str(), ROBOTO_SCRIPT) == 0) { - return; - } - #else if (strcasecmp(script.c_str(), ROBOTO_SCRIPT) == 0) { return; } - #endif // SB_API_VERSION < 16 default_fonts_loaded_event_.Reset(); for (int i = 0; i < families_.count(); i++) { @@ -521,15 +515,9 @@ bool SkFontMgr_Cobalt::CheckIfFamilyMatchesLocaleScript( } std::string family_script = icu::Locale::createCanonical(family_tag.c_str()).getScript(); - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(script, family_script.c_str()) != 0) { - return false; - } - #else if (strcasecmp(script, family_script.c_str()) != 0) { return false; } - #endif //SB_API_VERSION < 16 sk_sp check_typeface( new_family->MatchStyleWithoutLocking(SkFontStyle())); diff --git a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc index c3d5b34e0367..660b96385e80 100644 --- a/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc +++ b/cobalt/renderer/rasterizer/skia/skia/src/ports/SkFontStyleSet_cobalt.cc @@ -232,17 +232,6 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( ++extension; // Only add font formats that match the format setting. - #if SB_API_VERSION < 16 - if (font_format_setting == kTtf) { - if (SbStringCompareNoCase("ttf", extension) != 0 && - SbStringCompareNoCase(extension, "ttc") != 0) { - continue; - } - } else if (font_format_setting == kWoff2 && - SbStringCompareNoCase("woff2", extension) != 0) { - continue; - } - #else if (font_format_setting == kTtf) { if (strcasecmp("ttf", extension) != 0 && strcasecmp(extension, "ttc") != 0) { @@ -252,7 +241,6 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( strcasecmp("woff2", extension) != 0) { continue; } - #endif //SB_API_VERSION < 16 SkFontStyle style(font_file.weight, SkFontStyle::kNormal_Width, font_file.style == FontFileInfo::kItalic_FontStyle @@ -284,15 +272,6 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( int* index = styles_index_map.find(font_name); if (index != nullptr) { // If style with name already exists in family, replace it. - #if SB_API_VERSION < 16 - if (font_format_setting == kTtfPreferred && - SbStringCompareNoCase("ttf", extension) == 0) { - styles_[*index].reset(font); - } else if (font_format_setting == kWoff2Preferred && - SbStringCompareNoCase("woff2", extension) == 0) { - styles_[*index].reset(font); - } - #else if (font_format_setting == kTtfPreferred && strcasecmp("ttf", extension) == 0) { styles_[*index].reset(font); @@ -300,7 +279,6 @@ SkFontStyleSet_Cobalt::SkFontStyleSet_Cobalt( strcasecmp("woff2", extension) == 0) { styles_[*index].reset(font); } - #endif //SB_API_VERSION < 16 } else { int count = styles_.count(); styles_index_map.set(font_name, count); diff --git a/starboard/nplb/string_compare_no_case_n_test.cc b/starboard/nplb/string_compare_no_case_n_test.cc index 84e422808be4..761693faebe0 100644 --- a/starboard/nplb/string_compare_no_case_n_test.cc +++ b/starboard/nplb/string_compare_no_case_n_test.cc @@ -19,6 +19,7 @@ namespace starboard { namespace nplb { namespace { +#if SB_API_VERSION < 16 TEST(SbStringCompareNoCaseNTest, SunnyDaySelf) { const char kString[] = "0123456789"; EXPECT_EQ(0, SbStringCompareNoCaseN(kString, kString, strlen(kString))); @@ -55,6 +56,7 @@ TEST(SbStringCompareNoCaseNTest, SunnyDayCase) { EXPECT_EQ(0, SbStringCompareNoCaseN(kString4, kString3, strlen(kString4) / 2)); } +#endif // SB_API_VERSION < 16 } // namespace } // namespace nplb diff --git a/starboard/nplb/string_compare_no_case_test.cc b/starboard/nplb/string_compare_no_case_test.cc index 9d3748092601..f173db3e7e10 100644 --- a/starboard/nplb/string_compare_no_case_test.cc +++ b/starboard/nplb/string_compare_no_case_test.cc @@ -19,6 +19,7 @@ namespace starboard { namespace nplb { namespace { +#if SB_API_VERSION < 16 TEST(SbStringCompareNoCaseTest, SunnyDaySelf) { const char kString[] = "0123456789"; EXPECT_EQ(0, SbStringCompareNoCase(kString, kString)); @@ -36,7 +37,7 @@ TEST(SbStringCompareNoCaseTest, SunnyDayCase) { EXPECT_EQ(0, SbStringCompareNoCase(kString1, kString2)); EXPECT_EQ(0, SbStringCompareNoCase(kString2, kString1)); } - +#endif // SB_API_VERSION < 16 } // namespace } // namespace nplb } // namespace starboard diff --git a/starboard/nplb/string_duplicate_test.cc b/starboard/nplb/string_duplicate_test.cc index 27f7fc2f48f2..ddf5f19c5ad9 100644 --- a/starboard/nplb/string_duplicate_test.cc +++ b/starboard/nplb/string_duplicate_test.cc @@ -25,7 +25,9 @@ void RunTest(const char* input) { char* dupe = SbStringDuplicate(input); const char* kNull = NULL; EXPECT_NE(kNull, dupe); + #if SB_API_VERSION < 16 EXPECT_EQ(0, SbStringCompareNoCase(input, dupe)); + #endif //SB_API_VERSION < 16 EXPECT_EQ(strlen(input), strlen(dupe)); SbMemoryDeallocate(dupe); } diff --git a/starboard/shared/starboard/media/mime_type.cc b/starboard/shared/starboard/media/mime_type.cc index 80b25f78f834..66d8e4cffa0d 100644 --- a/starboard/shared/starboard/media/mime_type.cc +++ b/starboard/shared/starboard/media/mime_type.cc @@ -196,15 +196,9 @@ const std::string& MimeType::GetParamName(int index) const { int MimeType::GetParamIndexByName(const char* name) const { for (size_t i = 0; i < params_.size(); ++i) { - #if SB_API_VERSION < 16 - if (SbStringCompareNoCase(params_[i].name.c_str(), name) == 0) { - return static_cast(i); - } - #else if (strcasecmp(params_[i].name.c_str(), name) == 0) { return static_cast(i); } - #endif // SB_API_VERSION < 16 } return kInvalidParamIndex; } diff --git a/starboard/string.h b/starboard/string.h index be8e29d8dfe6..945d6f1ee861 100644 --- a/starboard/string.h +++ b/starboard/string.h @@ -36,7 +36,6 @@ extern "C" { // // |source|: The string to be copied. SB_EXPORT char* SbStringDuplicate(const char* source); -#endif // SB_API_VERSION < 16 // Compares two strings, ignoring differences in case. The return value is: // - |< 0| if |string1| is ASCII-betically lower than |string2|. @@ -63,6 +62,7 @@ SB_EXPORT int SbStringCompareNoCase(const char* string1, const char* string2); SB_EXPORT int SbStringCompareNoCaseN(const char* string1, const char* string2, size_t count); +#endif // SB_API_VERSION < 16 // Produces a string formatted with |format| and |arguments|, placing as much // of the result that will fit into |out_buffer|. The return value specifies diff --git a/third_party/chromium/media/base/starboard_utils.cc b/third_party/chromium/media/base/starboard_utils.cc index 1518fb9abdf9..e7e9e56ec04f 100644 --- a/third_party/chromium/media/base/starboard_utils.cc +++ b/third_party/chromium/media/base/starboard_utils.cc @@ -418,7 +418,7 @@ std::string ExtractCodecs(const std::string& mime_type) { std::vector tokens = ::base::SplitString( mime_type, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); for (size_t i = 1; i < tokens.size(); ++i) { - if (base::strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { + if (strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { continue; } auto codec = tokens[i].substr(strlen(kCodecs)); diff --git a/third_party/chromium/media/filters/chunk_demuxer.cc b/third_party/chromium/media/filters/chunk_demuxer.cc index e24189d7fb41..0bb01f4cd5a6 100644 --- a/third_party/chromium/media/filters/chunk_demuxer.cc +++ b/third_party/chromium/media/filters/chunk_demuxer.cc @@ -84,7 +84,7 @@ bool ParseMimeType(const std::string& mime_type, std::string* type, *type = tokens[0]; codecs->clear(); for (size_t i = 1; i < tokens.size(); ++i) { - if (base::strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { + if (strncasecmp(tokens[i].c_str(), kCodecs, strlen(kCodecs))) { continue; } *codecs = tokens[i].substr(strlen(kCodecs)); diff --git a/third_party/googletest/src/googletest/include/gtest/internal/gtest-port.h b/third_party/googletest/src/googletest/include/gtest/internal/gtest-port.h index b6fa7c6137df..a833aaf79d92 100644 --- a/third_party/googletest/src/googletest/include/gtest/internal/gtest-port.h +++ b/third_party/googletest/src/googletest/include/gtest/internal/gtest-port.h @@ -2084,9 +2084,11 @@ inline int IsATTY(FILE* /*file*/) { return SbLogIsTty() ? 1 : 0; } inline int Stat(const char* path, StatStruct* buf) { return SbFileGetPathInfo(path, buf) ? 0 : -1; } +#if SB_API_VERSION < 16 inline int StrCaseCmp(const char* s1, const char* s2) { return SbStringCompareNoCase(s1, s2); } +#endif //SB_API_VERSION < 16 inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return SbFileDelete(dir); } From fc62842e891a393ce070408a9dfb06cfc7e8856e Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Thu, 16 Nov 2023 10:49:37 -0800 Subject: [PATCH 06/17] Change --- third_party/googletest/src/googletest/src/gtest.cc | 2 +- .../source/libvpx/third_party/googletest/src/src/gtest.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/third_party/googletest/src/googletest/src/gtest.cc b/third_party/googletest/src/googletest/src/gtest.cc index 2465a488de53..9ab8d8f04016 100644 --- a/third_party/googletest/src/googletest/src/gtest.cc +++ b/third_party/googletest/src/googletest/src/gtest.cc @@ -2133,7 +2133,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; - return posix::StrCaseCmp(lhs, rhs) == 0; + return strcasecmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true if and only if they diff --git a/third_party/libvpx/source/libvpx/third_party/googletest/src/src/gtest.cc b/third_party/libvpx/source/libvpx/third_party/googletest/src/src/gtest.cc index b8f6a5c31cc8..f23a9534f3bc 100644 --- a/third_party/libvpx/source/libvpx/third_party/googletest/src/src/gtest.cc +++ b/third_party/libvpx/source/libvpx/third_party/googletest/src/src/gtest.cc @@ -2073,7 +2073,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; - return posix::StrCaseCmp(lhs, rhs) == 0; + return strcasecmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true if and only if they From 33336f948ad210a994d23a088848fb2b9cdde074 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Thu, 16 Nov 2023 14:19:32 -0800 Subject: [PATCH 07/17] Change --- cobalt/csp/source_list.cc | 3 +-- cobalt/dom/on_screen_keyboard.cc | 3 +-- cobalt/loader/cors_preflight.cc | 9 +++------ starboard/client_porting/poem/strings_poem.h | 7 ------- starboard/shared/win32/posix_emu/include/stdlib.h | 2 ++ starboard/tools/api_leak_detector/api_leak_detector.py | 2 ++ 6 files changed, 9 insertions(+), 17 deletions(-) diff --git a/cobalt/csp/source_list.cc b/cobalt/csp/source_list.cc index 6133e12f0373..a4268fb9dc24 100644 --- a/cobalt/csp/source_list.cc +++ b/cobalt/csp/source_list.cc @@ -433,8 +433,7 @@ bool SourceList::ParseHash(const char* begin, const char* end, for (size_t i = 0; i < arraysize(kSupportedPrefixes); ++i) { const HashPrefix& algorithm = kSupportedPrefixes[i]; if (hash_length > strlen(algorithm.prefix) && - strncasecmp(algorithm.prefix, begin, strlen(algorithm.prefix)) == - 0) { + strncasecmp(algorithm.prefix, begin, strlen(algorithm.prefix)) == 0) { prefix = algorithm.prefix; *hash_algorithm = algorithm.type; break; diff --git a/cobalt/dom/on_screen_keyboard.cc b/cobalt/dom/on_screen_keyboard.cc index 0b90098312c4..74fbe8315e16 100644 --- a/cobalt/dom/on_screen_keyboard.cc +++ b/cobalt/dom/on_screen_keyboard.cc @@ -51,8 +51,7 @@ bool ParseColor(const char* color_str, int& r, int& g, int& b) { } // Handle rgb color notation rgb(R, G, B) - if (!is_hex && len >= 10 && - strncasecmp("rgb(", color_str, 4) == 0) { + if (!is_hex && len >= 10 && strncasecmp("rgb(", color_str, 4) == 0) { int rgb_tmp[3] = {-1, -1, -1}; const char* ptr = color_str + 4; int i = 0; diff --git a/cobalt/loader/cors_preflight.cc b/cobalt/loader/cors_preflight.cc index d2af211981b9..d0750b166d2c 100644 --- a/cobalt/loader/cors_preflight.cc +++ b/cobalt/loader/cors_preflight.cc @@ -132,11 +132,9 @@ bool HasFieldValue(const std::vector& field_values, if (field_values[i].empty()) { continue; } - if (strcasecmp(field_values[i].c_str(), - find_value_name.c_str()) == 0) { + if (strcasecmp(field_values[i].c_str(), find_value_name.c_str()) == 0) { return true; } - } return false; } @@ -221,8 +219,8 @@ bool CORSPreflight::IsSafeResponseHeader( } for (size_t i = 0; i < CORS_exposed_header_name_list.size(); i++) { - if (strcasecmp(CORS_exposed_header_name_list.at(i).c_str(), - name.c_str()) == 0) { + if (strcasecmp(CORS_exposed_header_name_list.at(i).c_str(), name.c_str()) == + 0) { return true; } } @@ -388,7 +386,6 @@ void CORSPreflight::OnURLFetchComplete(const net::URLFetcher* source) { error_callback_.Run(); return; } - } // step 10-18 for adding entry to preflight cache. std::string max_age_str; diff --git a/starboard/client_porting/poem/strings_poem.h b/starboard/client_porting/poem/strings_poem.h index 7d7be2884962..8cfac86905c7 100644 --- a/starboard/client_porting/poem/strings_poem.h +++ b/starboard/client_porting/poem/strings_poem.h @@ -23,13 +23,6 @@ #include "starboard/string.h" -#if SB_API_VERSION < 16 -#undef strcasecmp -#define strcasecmp(s1, s2) SbStringCompareNoCase(s1, s2) -#undef strncasecmp -#define strncasecmp(s1, s2) SbStringCompareNoCaseN(s1, s2) -#endif // SB_API_VERSION < 16 - #endif // POEM_NO_EMULATION #endif // STARBOARD diff --git a/starboard/shared/win32/posix_emu/include/stdlib.h b/starboard/shared/win32/posix_emu/include/stdlib.h index 7fa9e76d2c8f..f6c8aba3a63f 100644 --- a/starboard/shared/win32/posix_emu/include/stdlib.h +++ b/starboard/shared/win32/posix_emu/include/stdlib.h @@ -17,6 +17,8 @@ // MSVC deprecated strdup() in favor of _strdup() #define strdup _strdup +#define strcasecmp _strcasecmp +#define strncasecmp _strncasecmp #if defined(STARBOARD) #define free sb_free diff --git a/starboard/tools/api_leak_detector/api_leak_detector.py b/starboard/tools/api_leak_detector/api_leak_detector.py index aeee6cc3457f..5a9f3cece51d 100755 --- a/starboard/tools/api_leak_detector/api_leak_detector.py +++ b/starboard/tools/api_leak_detector/api_leak_detector.py @@ -92,6 +92,8 @@ 'malloc', 'posix_memalign', 'realloc', + 'strcasecmp', + 'strncasecmp', ] From c5ca9073af9727090ac3e2ea4757e3f522416a51 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Thu, 16 Nov 2023 15:58:00 -0800 Subject: [PATCH 08/17] change --- starboard/nplb/string_compare_no_case_n_test.cc | 2 +- starboard/nplb/string_compare_no_case_test.cc | 2 +- starboard/nplb/string_duplicate_test.cc | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/starboard/nplb/string_compare_no_case_n_test.cc b/starboard/nplb/string_compare_no_case_n_test.cc index 761693faebe0..5cd234978c80 100644 --- a/starboard/nplb/string_compare_no_case_n_test.cc +++ b/starboard/nplb/string_compare_no_case_n_test.cc @@ -56,7 +56,7 @@ TEST(SbStringCompareNoCaseNTest, SunnyDayCase) { EXPECT_EQ(0, SbStringCompareNoCaseN(kString4, kString3, strlen(kString4) / 2)); } -#endif // SB_API_VERSION < 16 +#endif // SB_API_VERSION < 16 } // namespace } // namespace nplb diff --git a/starboard/nplb/string_compare_no_case_test.cc b/starboard/nplb/string_compare_no_case_test.cc index f173db3e7e10..73544d0295ca 100644 --- a/starboard/nplb/string_compare_no_case_test.cc +++ b/starboard/nplb/string_compare_no_case_test.cc @@ -37,7 +37,7 @@ TEST(SbStringCompareNoCaseTest, SunnyDayCase) { EXPECT_EQ(0, SbStringCompareNoCase(kString1, kString2)); EXPECT_EQ(0, SbStringCompareNoCase(kString2, kString1)); } -#endif // SB_API_VERSION < 16 +#endif // SB_API_VERSION < 16 } // namespace } // namespace nplb } // namespace starboard diff --git a/starboard/nplb/string_duplicate_test.cc b/starboard/nplb/string_duplicate_test.cc index ddf5f19c5ad9..a0afb7b04ad3 100644 --- a/starboard/nplb/string_duplicate_test.cc +++ b/starboard/nplb/string_duplicate_test.cc @@ -25,9 +25,9 @@ void RunTest(const char* input) { char* dupe = SbStringDuplicate(input); const char* kNull = NULL; EXPECT_NE(kNull, dupe); - #if SB_API_VERSION < 16 +#if SB_API_VERSION < 16 EXPECT_EQ(0, SbStringCompareNoCase(input, dupe)); - #endif //SB_API_VERSION < 16 +#endif // SB_API_VERSION < 16 EXPECT_EQ(strlen(input), strlen(dupe)); SbMemoryDeallocate(dupe); } From 75bf163b5747195da0ea36f40c6ff3225227e2e1 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Fri, 17 Nov 2023 07:23:35 -0800 Subject: [PATCH 09/17] use right windows api Change-Id: Ied13d42b84a9c81b73c5d8046a802c5054d6e8a2 --- starboard/shared/win32/posix_emu/include/stdlib.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/starboard/shared/win32/posix_emu/include/stdlib.h b/starboard/shared/win32/posix_emu/include/stdlib.h index f6c8aba3a63f..8d7c27d98011 100644 --- a/starboard/shared/win32/posix_emu/include/stdlib.h +++ b/starboard/shared/win32/posix_emu/include/stdlib.h @@ -17,8 +17,8 @@ // MSVC deprecated strdup() in favor of _strdup() #define strdup _strdup -#define strcasecmp _strcasecmp -#define strncasecmp _strncasecmp +#define strcasecmp _stricmp +#define strncasecmp _strnicmp #if defined(STARBOARD) #define free sb_free From 9fd3a9c1ae2720b7641cb09b60abbc49d3d68c82 Mon Sep 17 00:00:00 2001 From: Antonio Rivera <141369695+antoniori-eng@users.noreply.github.com> Date: Fri, 17 Nov 2023 09:04:19 -0800 Subject: [PATCH 10/17] Ensure that MP3, FLAC, and PCM are not supported for MediaSource. (#1359) This change makes the logic of CanPlayAdaptive more like CanPlayProgressive, wherein unsupported containers are immediately filtered out. Bug: b/297060983 Test: Added unit tests. Also manually ran Cobalt and verified that MediaSource.isTypeSupported returns false for these MIME strings: 'audio/mpeg; codecs="mp3"' 'audio/mpeg' 'audio/ogg; codecs="flac"' 'audio/flac; codecs="flac"' 'audio/wav; codecs="1"' --- cobalt/media/BUILD.gn | 1 + cobalt/media/media_module.cc | 14 ++++-- cobalt/media/media_module_test.cc | 81 +++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 cobalt/media/media_module_test.cc diff --git a/cobalt/media/BUILD.gn b/cobalt/media/BUILD.gn index 0b509f96e34a..7779989a1341 100644 --- a/cobalt/media/BUILD.gn +++ b/cobalt/media/BUILD.gn @@ -124,6 +124,7 @@ target(gtest_target_type, "media_test") { "base/decoder_buffer_cache_test.cc", "bidirectional_fit_reuse_allocator_test.cc", "file_data_source_test.cc", + "media_module_test.cc", "progressive/demuxer_extension_wrapper_test.cc", "progressive/mock_data_source_reader.h", "progressive/mp4_map_unittest.cc", diff --git a/cobalt/media/media_module.cc b/cobalt/media/media_module.cc index 06e7e260bd09..26fa10f4f7bf 100644 --- a/cobalt/media/media_module.cc +++ b/cobalt/media/media_module.cc @@ -121,8 +121,8 @@ class CanPlayTypeHandlerStarboard : public CanPlayTypeHandler { // progressive. SbMediaSupportType support_type; media::FormatSupportQueryMetrics metrics; - if (strstr(mime_type.c_str(), "video/mp4") == 0 && - strstr(mime_type.c_str(), "application/x-mpegURL") == 0) { + if (strstr(mime_type.c_str(), "video/mp4") == NULL && + strstr(mime_type.c_str(), "application/x-mpegURL") == NULL) { support_type = kSbMediaSupportTypeNotSupported; } else { support_type = CanPlayType(mime_type, ""); @@ -135,8 +135,16 @@ class CanPlayTypeHandlerStarboard : public CanPlayTypeHandler { SbMediaSupportType CanPlayAdaptive( const std::string& mime_type, const std::string& key_system) const override { + SbMediaSupportType support_type; media::FormatSupportQueryMetrics metrics; - SbMediaSupportType support_type = CanPlayType(mime_type, key_system); + // Only mp4 and webm videos are supported for adaptive playback in Cobalt; + // any other containers can be immediately rejected. + if (strstr(mime_type.c_str(), "video/mp4") == NULL && + strstr(mime_type.c_str(), "video/webm") == NULL) { + support_type = kSbMediaSupportTypeNotSupported; + } else { + support_type = CanPlayType(mime_type, key_system); + } metrics.RecordAndLogQuery("MediaSource::IsTypeSupported", mime_type, key_system, support_type); return support_type; diff --git a/cobalt/media/media_module_test.cc b/cobalt/media/media_module_test.cc new file mode 100644 index 000000000000..3d975527f1b5 --- /dev/null +++ b/cobalt/media/media_module_test.cc @@ -0,0 +1,81 @@ +// Copyright 2023 The Cobalt Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "cobalt/media/media_module.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace cobalt { +namespace media { +namespace { + +using ::testing::NotNull; + +#if SB_API_VERSION >= 14 +TEST(MediaModuleTest, DoesNotSupportMp3Adaptive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayAdaptive("audio/mpeg; codecs=\"mp3\"", + /*key_system=*/"")); + EXPECT_FALSE(handler->CanPlayAdaptive("audio/mpeg", /*key_system=*/"")); +} + +TEST(MediaModuleTest, DoesNotSupportMp3Progressive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayProgressive("audio/mpeg; codecs=\"mp3\"")); + EXPECT_FALSE(handler->CanPlayProgressive("audio/mpeg")); +} + +TEST(MediaModuleTest, DoesNotSupportFlacAdaptive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayAdaptive("audio/ogg; codecs=\"flac\"", + /*key_system=*/"")); + EXPECT_FALSE(handler->CanPlayAdaptive("audio/flac; codecs=\"flac\"", + /*key_system=*/"")); +} + +TEST(MediaModuleTest, DoesNotSupportFlacProgressive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayProgressive("audio/ogg; codecs=\"flac\"")); + EXPECT_FALSE(handler->CanPlayProgressive("audio/flac; codecs=\"flac\"")); +} + +TEST(MediaModuleTest, DoesNotSupportPcmAdaptive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayAdaptive("audio/wav; codecs=\"1\"", + /*key_system=*/"")); +} + +TEST(MediaModuleTest, DoesNotSupportPcmProgressive) { + std::unique_ptr handler = + MediaModule::CreateCanPlayTypeHandler(); + ASSERT_THAT(handler, NotNull()); + EXPECT_FALSE(handler->CanPlayProgressive("audio/wav; codecs=\"1\"")); +} + +#endif // SB_API_VERSION >= 14 + +} // namespace +} // namespace media +} // namespace cobalt From d2f2d81812d385ee459513345c6a1ab89db2cd13 Mon Sep 17 00:00:00 2001 From: Madhura Jayaraman Date: Fri, 17 Nov 2023 09:15:40 -0800 Subject: [PATCH 11/17] Remove gate for test Change-Id: I4576891a0f6b2036f879c97d6026d666ad273030 --- starboard/nplb/string_duplicate_test.cc | 2 -- 1 file changed, 2 deletions(-) diff --git a/starboard/nplb/string_duplicate_test.cc b/starboard/nplb/string_duplicate_test.cc index a0afb7b04ad3..27f7fc2f48f2 100644 --- a/starboard/nplb/string_duplicate_test.cc +++ b/starboard/nplb/string_duplicate_test.cc @@ -25,9 +25,7 @@ void RunTest(const char* input) { char* dupe = SbStringDuplicate(input); const char* kNull = NULL; EXPECT_NE(kNull, dupe); -#if SB_API_VERSION < 16 EXPECT_EQ(0, SbStringCompareNoCase(input, dupe)); -#endif // SB_API_VERSION < 16 EXPECT_EQ(strlen(input), strlen(dupe)); SbMemoryDeallocate(dupe); } From eebae19178b1568224067459f5fde622a2154f52 Mon Sep 17 00:00:00 2001 From: y4vor Date: Fri, 17 Nov 2023 12:13:17 -0800 Subject: [PATCH 12/17] Revert "Disable evergreen_tests to pickup SbMemory changes." (#1997) Reverts youtube/cobalt#1976 b/302332972 --- starboard/evergreen/testing/run_all_tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/starboard/evergreen/testing/run_all_tests.sh b/starboard/evergreen/testing/run_all_tests.sh index bb9dbb1e8a8d..0894d292654e 100755 --- a/starboard/evergreen/testing/run_all_tests.sh +++ b/starboard/evergreen/testing/run_all_tests.sh @@ -24,7 +24,7 @@ AUTH_METHOD="public-key" USE_COMPRESSED_SYSTEM_IMAGE="false" SYSTEM_IMAGE_EXTENSION=".so" -DISABLE_TESTS="true" +DISABLE_TESTS="false" while getopts "d:a:c" o; do case "${o}" in From 125f4717b16a703b4e0a0bc389473d1affc781fc Mon Sep 17 00:00:00 2001 From: Jason Date: Mon, 20 Nov 2023 11:35:29 -0800 Subject: [PATCH 13/17] [android] Refine audio sink dead object handling (#1813) Cobalt now listens to audio device change and would throw out kSbPlayerErrorCapabilityChanged error if there's any change, so it doesn't need to rely on dead object error to detect audio device change. b/175885408 --- .../shared/audio_track_audio_sink_type.cc | 28 ++++++++----------- .../android/shared/audio_track_bridge.cc | 9 ++---- starboard/android/shared/audio_track_bridge.h | 5 +++- 3 files changed, 17 insertions(+), 25 deletions(-) diff --git a/starboard/android/shared/audio_track_audio_sink_type.cc b/starboard/android/shared/audio_track_audio_sink_type.cc index 438e7d7c7711..dfdf7433f8af 100644 --- a/starboard/android/shared/audio_track_audio_sink_type.cc +++ b/starboard/android/shared/audio_track_audio_sink_type.cc @@ -212,8 +212,7 @@ void AudioTrackAudioSink::AudioThreadFunc() { if (bridge_.GetAndResetHasAudioDeviceChanged(env)) { SB_LOG(INFO) << "Audio device changed, raising a capability changed " "error to restart playback."; - ReportError(kSbPlayerErrorCapabilityChanged, - "Audio device capability changed"); + ReportError(true, "Audio device capability changed"); break; } @@ -317,11 +316,8 @@ void AudioTrackAudioSink::AudioThreadFunc() { auto sync_time = start_time_ + accumulated_written_frames * kSbTimeSecond / sampling_frequency_hz_; - // Not necessary to handle error of WriteData(), even for - // kAudioTrackErrorDeadObject, as the audio has reached the end of - // stream. - // TODO: Ensure that the audio stream can still reach the end when an - // error occurs. + // Not necessary to handle error of WriteData(), as the audio has + // reached the end of stream. WriteData(env, silence_buffer.data(), silence_frames_per_append, sync_time); } @@ -350,16 +346,14 @@ void AudioTrackAudioSink::AudioThreadFunc() { SbTime now = SbTimeGetMonotonicNow(); if (written_frames < 0) { - // Take all |frames_in_audio_track| as consumed since audio track could be - // dead. - consume_frames_func_(frames_in_audio_track, now, context_); - - bool capabilities_changed = - written_frames == AudioTrackBridge::kAudioTrackErrorDeadObject; - ReportError( - capabilities_changed, - FormatString("Error while writing frames: %d", written_frames)); - SB_LOG(INFO) << "Restarting playback."; + if (written_frames == AudioTrackBridge::kAudioTrackErrorDeadObject) { + // There might be an audio device change, try to recreate the player. + ReportError(true, + "Failed to write data and received dead object error."); + } else { + ReportError(false, FormatString("Failed to write data and received %d.", + written_frames)); + } break; } else if (written_frames > 0) { last_written_succeeded_at = now; diff --git a/starboard/android/shared/audio_track_bridge.cc b/starboard/android/shared/audio_track_bridge.cc index 88494994c1a9..e518f745d83d 100644 --- a/starboard/android/shared/audio_track_bridge.cc +++ b/starboard/android/shared/audio_track_bridge.cc @@ -183,13 +183,10 @@ int AudioTrackBridge::WriteSample(const float* samples, SB_DCHECK(num_of_samples <= max_samples_per_write_); num_of_samples = std::min(num_of_samples, max_samples_per_write_); - - // TODO: Test this code path env->SetFloatArrayRegion(static_cast(j_audio_data_), kNoOffset, num_of_samples, samples); - int samples_written = env->CallIntMethodOrAbort( - j_audio_track_bridge_, "write", "([FI)I", j_audio_data_, num_of_samples); - return samples_written; + return env->CallIntMethodOrAbort(j_audio_track_bridge_, "write", "([FI)I", + j_audio_data_, num_of_samples); } int AudioTrackBridge::WriteSample(const uint16_t* samples, @@ -201,8 +198,6 @@ int AudioTrackBridge::WriteSample(const uint16_t* samples, SB_DCHECK(num_of_samples <= max_samples_per_write_); num_of_samples = std::min(num_of_samples, max_samples_per_write_); - - // TODO: Test this code path env->SetByteArrayRegion(static_cast(j_audio_data_), kNoOffset, num_of_samples * sizeof(uint16_t), reinterpret_cast(samples)); diff --git a/starboard/android/shared/audio_track_bridge.h b/starboard/android/shared/audio_track_bridge.h index a5b269684a0a..5d7aeeb8fcd8 100644 --- a/starboard/android/shared/audio_track_bridge.h +++ b/starboard/android/shared/audio_track_bridge.h @@ -59,15 +59,18 @@ class AudioTrackBridge { void Stop(JniEnvExt* env = JniEnvExt::Get()); void PauseAndFlush(JniEnvExt* env = JniEnvExt::Get()); + // Returns zero or the positive number of samples written, or a negative error + // code. int WriteSample(const float* samples, int num_of_samples, JniEnvExt* env = JniEnvExt::Get()); - // Returns samples written. int WriteSample(const uint16_t* samples, int num_of_samples, SbTime sync_time, JniEnvExt* env = JniEnvExt::Get()); // This is used by passthrough, it treats samples as if they are in bytes. + // Returns zero or the positive number of samples written, or a negative error + // code. int WriteSample(const uint8_t* buffer, int num_of_samples, SbTime sync_time, From a11bdbed8a015be7912d240c669549d2169ecc28 Mon Sep 17 00:00:00 2001 From: Jelle Foks Date: Mon, 20 Nov 2023 11:54:23 -0800 Subject: [PATCH 14/17] Add assert for stub platform on windows host. (#1906) The stub platform currently can not be compiled on windows and instead shows cryptic gn errors. To avoid this confusion, assert when trying to configure stub platform on a windows host. --- starboard/stub/platform_configuration/configuration.gni | 1 + 1 file changed, 1 insertion(+) diff --git a/starboard/stub/platform_configuration/configuration.gni b/starboard/stub/platform_configuration/configuration.gni index e13b8d3d617b..0283df241a29 100644 --- a/starboard/stub/platform_configuration/configuration.gni +++ b/starboard/stub/platform_configuration/configuration.gni @@ -30,5 +30,6 @@ no_pedantic_warnings_config_path = "//starboard/stub/platform_configuration:no_pedantic_warnings" is_clang_16 = true +assert(!is_host_win, "Stub build is not (yet) supported on windows host") v8_enable_webassembly = true From fbfbaa7396343084171327d1229e8a1368d8a8f9 Mon Sep 17 00:00:00 2001 From: Igor Sarkisov Date: Mon, 20 Nov 2023 15:12:49 -0800 Subject: [PATCH 15/17] Remove NXSwitch from Docker Compose. (#2002) b/311029556 --- docker-compose-windows-internal.yml | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/docker-compose-windows-internal.yml b/docker-compose-windows-internal.yml index 92482e39ffad..4cea203ad308 100644 --- a/docker-compose-windows-internal.yml +++ b/docker-compose-windows-internal.yml @@ -129,28 +129,3 @@ services: image: cobalt-kokoro-xb1 depends_on: - xb1 - - nxswitch: - <<: *common-definitions - build: - context: ./internal/docker/windows/ - dockerfile: nxswitch/Dockerfile - args: - - encoded_keyfile=${ENCODED_GS_SERVICE_KEY_FILE} - - FROM_IMAGE=cobalt-build-win-internal - environment: - <<: *shared-build-env - PLATFORM: nxswitch - image: cobalt-build-nxswitch - depends_on: - - cobalt-build-win-internal - - nxswitch-kokoro: - build: - context: ./internal/docker/windows/kokoro/ - dockerfile: Dockerfile - args: - - FROM_IMAGE=${FROM_IMAGE:-cobalt-build-nxswitch} - image: cobalt-kokoro-nxswitch - depends_on: - - nxswitch From 85e1b18836672d46a2ccf82a9825d315a48aee7b Mon Sep 17 00:00:00 2001 From: Jason Date: Wed, 22 Nov 2023 10:11:17 -0800 Subject: [PATCH 16/17] Revert "Ensure that MP3, FLAC, and PCM are not supported for MediaSource." (#2005) Reverts youtube/cobalt#1359 b/297060983 --- cobalt/media/BUILD.gn | 1 - cobalt/media/media_module.cc | 14 ++---- cobalt/media/media_module_test.cc | 81 ------------------------------- 3 files changed, 3 insertions(+), 93 deletions(-) delete mode 100644 cobalt/media/media_module_test.cc diff --git a/cobalt/media/BUILD.gn b/cobalt/media/BUILD.gn index 7779989a1341..0b509f96e34a 100644 --- a/cobalt/media/BUILD.gn +++ b/cobalt/media/BUILD.gn @@ -124,7 +124,6 @@ target(gtest_target_type, "media_test") { "base/decoder_buffer_cache_test.cc", "bidirectional_fit_reuse_allocator_test.cc", "file_data_source_test.cc", - "media_module_test.cc", "progressive/demuxer_extension_wrapper_test.cc", "progressive/mock_data_source_reader.h", "progressive/mp4_map_unittest.cc", diff --git a/cobalt/media/media_module.cc b/cobalt/media/media_module.cc index 26fa10f4f7bf..06e7e260bd09 100644 --- a/cobalt/media/media_module.cc +++ b/cobalt/media/media_module.cc @@ -121,8 +121,8 @@ class CanPlayTypeHandlerStarboard : public CanPlayTypeHandler { // progressive. SbMediaSupportType support_type; media::FormatSupportQueryMetrics metrics; - if (strstr(mime_type.c_str(), "video/mp4") == NULL && - strstr(mime_type.c_str(), "application/x-mpegURL") == NULL) { + if (strstr(mime_type.c_str(), "video/mp4") == 0 && + strstr(mime_type.c_str(), "application/x-mpegURL") == 0) { support_type = kSbMediaSupportTypeNotSupported; } else { support_type = CanPlayType(mime_type, ""); @@ -135,16 +135,8 @@ class CanPlayTypeHandlerStarboard : public CanPlayTypeHandler { SbMediaSupportType CanPlayAdaptive( const std::string& mime_type, const std::string& key_system) const override { - SbMediaSupportType support_type; media::FormatSupportQueryMetrics metrics; - // Only mp4 and webm videos are supported for adaptive playback in Cobalt; - // any other containers can be immediately rejected. - if (strstr(mime_type.c_str(), "video/mp4") == NULL && - strstr(mime_type.c_str(), "video/webm") == NULL) { - support_type = kSbMediaSupportTypeNotSupported; - } else { - support_type = CanPlayType(mime_type, key_system); - } + SbMediaSupportType support_type = CanPlayType(mime_type, key_system); metrics.RecordAndLogQuery("MediaSource::IsTypeSupported", mime_type, key_system, support_type); return support_type; diff --git a/cobalt/media/media_module_test.cc b/cobalt/media/media_module_test.cc deleted file mode 100644 index 3d975527f1b5..000000000000 --- a/cobalt/media/media_module_test.cc +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2023 The Cobalt Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cobalt/media/media_module.h" - -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace cobalt { -namespace media { -namespace { - -using ::testing::NotNull; - -#if SB_API_VERSION >= 14 -TEST(MediaModuleTest, DoesNotSupportMp3Adaptive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayAdaptive("audio/mpeg; codecs=\"mp3\"", - /*key_system=*/"")); - EXPECT_FALSE(handler->CanPlayAdaptive("audio/mpeg", /*key_system=*/"")); -} - -TEST(MediaModuleTest, DoesNotSupportMp3Progressive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayProgressive("audio/mpeg; codecs=\"mp3\"")); - EXPECT_FALSE(handler->CanPlayProgressive("audio/mpeg")); -} - -TEST(MediaModuleTest, DoesNotSupportFlacAdaptive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayAdaptive("audio/ogg; codecs=\"flac\"", - /*key_system=*/"")); - EXPECT_FALSE(handler->CanPlayAdaptive("audio/flac; codecs=\"flac\"", - /*key_system=*/"")); -} - -TEST(MediaModuleTest, DoesNotSupportFlacProgressive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayProgressive("audio/ogg; codecs=\"flac\"")); - EXPECT_FALSE(handler->CanPlayProgressive("audio/flac; codecs=\"flac\"")); -} - -TEST(MediaModuleTest, DoesNotSupportPcmAdaptive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayAdaptive("audio/wav; codecs=\"1\"", - /*key_system=*/"")); -} - -TEST(MediaModuleTest, DoesNotSupportPcmProgressive) { - std::unique_ptr handler = - MediaModule::CreateCanPlayTypeHandler(); - ASSERT_THAT(handler, NotNull()); - EXPECT_FALSE(handler->CanPlayProgressive("audio/wav; codecs=\"1\"")); -} - -#endif // SB_API_VERSION >= 14 - -} // namespace -} // namespace media -} // namespace cobalt From ee2f99f0ea80a1ffda2b382daa479d0fe14f7d61 Mon Sep 17 00:00:00 2001 From: MichaelSweden Date: Wed, 22 Nov 2023 19:51:06 +0100 Subject: [PATCH 17/17] Support live streams (ie big timestamps), replace float with double (#1910) b/309222250 Live video streams with epoch timestamps was not possible to play. Huge timestamps values was truncated because use of data type float with limited resolution. Change-Id: I7bed973b56e58bea5cd4740ce1778f32dfe617e2 **BACKGROUND** It is problem to play some live video streams in Cobalt with a javascript player. It turned out to be related to timestamp values. Normally at play of a video the timestamp starts at zero and grow. For live streams they don't. As such a video is continuously created. Then the timestamp can be the current clock, i.e. UTC time. In seconds these values will be quite big and in microseconds huge. Cobalt cannot handle these huge values and therefor cannot play such video streams. **DEVELOPMENT** I started to investigate the call path for the Seek function. The Seek value that comes to a starboard integration is not the same as higher up in function call path. I found out that the function ConvertSecondsToTimestamp will disturb the value. It uses a float type for micro seconds. The float type is only 24 bits. I rewrite it. In javascript "mediaElement.currentTime = 0.0;" will create a call to currentTimeAttributeSetter in v8c_html_media_element.cc (file created during build) and that calls set_current_time in the HTMLMediaElement class. Call flow for seek: In javascript assign currentTime a value. currentTimeAttributeSetter // v8c_html_media_element.cc at build time HTMLMediaElement::set_current_time() HTMLMediaElement::Seek() WebMediaPlayerImpl::Seek() WebMediaPlayerImpl::OnPipelineSeek() WebMediaPlayerImpl::Seek() SbPlayerPipeline::Seek() SbPlayerBridge::PrepareForSeek() SbPlayerBridge::Seek() SbPlayerPrivate::Seek() PlayerWorker::Seek() PlayerWorker::DoSeek() PlayerWorkerHandler::Seek() // third_party/starboard integration I discover that timestamp is saved in different data types. In some places as seconds in a float. The floating-point data type "float" doesn't have enough resolution to handle timestamps. For example date of today will be approx. 1,695,316,864. A float mantissa is only 24 bits. In javascript all numbers are 64 bit float (52 bits mantissa, 11 bits exponent, one sign bit), max 9007199254740991 and min -9007199254740991. Let look at a today time in microseconds: 1,695,392,081,110,344 and compare with 9,007,199,254,740,991. It will fit. In C/C++ data type "double" is 64 bit floating-point. Fortunately, I didn't have to change the glue file between javascript and C++ (v8c_html_media_element.cc). It is already for double. One problem was that the called function in cobalt had a float argument. I ended up with changing float to double in a lot of places. While convert from floating-point value to an integer value (e.g. double to int64_t). The value needs to be rounded, not truncated. This is done in function ConvertSecondsToTimestamp. It might be nicer to use the TimeDelta::FromDouble function. However this function will truncate the value and it is a unittest for it. I don't see the use of such function. Well, I didn't change it. It would have effects a lot. **TEST** I have built (debug/devel/gold linux-x64x11) and run unittest (devel). Got 3 failed unittest, nplb about ipv6. I assume this is not caused by me. Executed Cobalt (devel and debug) in Ubuntu before and after change. With a html page running a javascript DASH player. Unfortunately, I have not found any open test streams on internet with huge timestamps. I have used streams from two different sources (with huge timestamps) to validate this change. **RESULT** Now it is possible to play live streams that have timestamps as current time expressed in epoch. --- cobalt/dom/html_media_element.cc | 72 +++++++++---------- cobalt/dom/html_media_element.h | 12 ++-- cobalt/media/player/web_media_player.h | 12 ++-- cobalt/media/player/web_media_player_impl.cc | 45 +++++------- cobalt/media/player/web_media_player_impl.h | 14 ++-- .../media/sandbox/web_media_player_helper.cc | 2 +- .../media/sandbox/web_media_player_sandbox.cc | 8 +-- cobalt/media_session/media_session_client.cc | 2 +- 8 files changed, 78 insertions(+), 89 deletions(-) diff --git a/cobalt/dom/html_media_element.cc b/cobalt/dom/html_media_element.cc index da10b2e91781..dfbfa2a9de66 100644 --- a/cobalt/dom/html_media_element.cc +++ b/cobalt/dom/html_media_element.cc @@ -138,7 +138,7 @@ HTMLMediaElement::HTMLMediaElement(Document* document, base::Token tag_name) ready_state_(WebMediaPlayer::kReadyStateHaveNothing), ready_state_maximum_(WebMediaPlayer::kReadyStateHaveNothing), volume_(1.0f), - last_seek_time_(0), + last_seek_time_(0.0), previous_progress_time_(std::numeric_limits::max()), duration_(std::numeric_limits::quiet_NaN()), playing_(false), @@ -149,7 +149,7 @@ HTMLMediaElement::HTMLMediaElement(Document* document, base::Token tag_name) resume_frozen_flag_(false), seeking_(false), controls_(false), - last_time_update_event_movie_time_(std::numeric_limits::max()), + last_time_update_event_movie_time_(std::numeric_limits::max()), processing_media_player_callback_(0), media_source_url_(std::string(kMediaSourceUrlProtocol) + ':' + base::GenerateGUID()), @@ -222,7 +222,7 @@ scoped_refptr HTMLMediaElement::buffered() const { } player_->UpdateBufferedTimeRanges( - [&](float start, float end) { buffered->Add(start, end); }); + [&](double start, double end) { buffered->Add(start, end); }); return buffered; } @@ -344,11 +344,11 @@ bool HTMLMediaElement::seeking() const { return seeking_; } -float HTMLMediaElement::current_time( +double HTMLMediaElement::current_time( script::ExceptionState* exception_state) const { if (!player_) { LOG(INFO) << 0 << " (because player is NULL)"; - return 0; + return 0.0; } if (seeking_) { @@ -356,15 +356,14 @@ float HTMLMediaElement::current_time( return last_seek_time_; } - float time = player_->GetCurrentTime(); + const double time = player_->GetCurrentTime(); MLOG() << time << " (from player)"; return time; } void HTMLMediaElement::set_current_time( - float time, script::ExceptionState* exception_state) { + double time, script::ExceptionState* exception_state) { // 4.8.9.9 Seeking - // 1 - If the media element's readyState is // WebMediaPlayer::kReadyStateHaveNothing, then raise an INVALID_STATE_ERR // exception. @@ -377,10 +376,9 @@ void HTMLMediaElement::set_current_time( Seek(time); } -float HTMLMediaElement::duration() const { +double HTMLMediaElement::duration() const { MLOG() << duration_; - // TODO: Turn duration into double. - return static_cast(duration_); + return duration_; } base::Time HTMLMediaElement::GetStartDate() const { @@ -433,7 +431,7 @@ void HTMLMediaElement::set_playback_rate(float rate) { const scoped_refptr& HTMLMediaElement::played() { MLOG(); if (playing_) { - float time = current_time(NULL); + const double time = current_time(NULL); if (time > last_seek_time_) { AddPlayedRange(last_seek_time_, time); } @@ -447,8 +445,8 @@ const scoped_refptr& HTMLMediaElement::played() { } scoped_refptr HTMLMediaElement::seekable() const { - if (player_ && player_->GetMaxTimeSeekable() != 0) { - double max_time_seekable = player_->GetMaxTimeSeekable(); + if (player_ && player_->GetMaxTimeSeekable() != 0.0) { + const double max_time_seekable = player_->GetMaxTimeSeekable(); MLOG() << "(0, " << max_time_seekable << ")"; return new TimeRanges(0, max_time_seekable); } @@ -632,7 +630,7 @@ void HTMLMediaElement::DurationChanged(double duration, bool request_seek) { ScheduleOwnEvent(base::Tokens::durationchange()); if (request_seek) { - Seek(static_cast(duration)); + Seek(duration); } } @@ -775,7 +773,7 @@ void HTMLMediaElement::PrepareForLoad() { // 2 - Asynchronously await a stable state. played_time_ranges_ = new TimeRanges; - last_seek_time_ = 0; + last_seek_time_ = 0.0; ConfigureMediaControls(); } @@ -1019,8 +1017,8 @@ void HTMLMediaElement::OnProgressEventTimer() { return; } - double time = base::Time::Now().ToDoubleT(); - double time_delta = time - previous_progress_time_; + const double time = base::Time::Now().ToDoubleT(); + const double time_delta = time - previous_progress_time_; if (player_->DidLoadingProgress()) { ScheduleOwnEvent(base::Tokens::progress()); @@ -1082,7 +1080,7 @@ void HTMLMediaElement::StopPeriodicTimers() { void HTMLMediaElement::ScheduleTimeupdateEvent(bool periodic_event) { // Some media engines make multiple "time changed" callbacks at the same time, // but we only want one event at a given time so filter here - float movie_time = current_time(NULL); + const double movie_time = current_time(NULL); if (movie_time != last_time_update_event_movie_time_) { if (!periodic_event && playback_progress_timer_.IsRunning()) { playback_progress_timer_.Reset(); @@ -1268,7 +1266,7 @@ void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() { network_state_ = kNetworkIdle; } -void HTMLMediaElement::Seek(float time) { +void HTMLMediaElement::Seek(double time) { LOG(INFO) << "Seek to " << time << "."; // 4.8.9.9 Seeking - continued from set_current_time(). @@ -1279,7 +1277,7 @@ void HTMLMediaElement::Seek(float time) { // Get the current time before setting seeking_, last_seek_time_ is returned // once it is set. - float now = current_time(NULL); + const double now = current_time(NULL); // 2 - If the element's seeking IDL attribute is true, then another instance // of this algorithm is already running. Abort that other instance of the @@ -1297,7 +1295,7 @@ void HTMLMediaElement::Seek(float time) { // 6 - If the new playback position is less than the earliest possible // position, let it be that position instead. - time = std::max(time, 0.f); + time = std::max(time, 0.0); // 7 - If the (possibly now changed) new playback position is not in one of // the ranges given in the seekable attribute, then let it be the position in @@ -1329,7 +1327,7 @@ void HTMLMediaElement::Seek(float time) { seeking_ = false; return; } - time = static_cast(seekable_ranges->Nearest(time)); + time = seekable_ranges->Nearest(time); if (playing_) { if (last_seek_time_ < now) { @@ -1361,7 +1359,7 @@ void HTMLMediaElement::FinishSeek() { ScheduleOwnEvent(base::Tokens::seeked()); } -void HTMLMediaElement::AddPlayedRange(float start, float end) { +void HTMLMediaElement::AddPlayedRange(double start, double end) { if (!played_time_ranges_) { played_time_ranges_ = new TimeRanges; } @@ -1411,7 +1409,7 @@ void HTMLMediaElement::UpdatePlayState() { playback_progress_timer_.Stop(); playing_ = false; - float time = current_time(NULL); + const double time = current_time(NULL); if (time > last_seek_time_) { AddPlayedRange(last_seek_time_, time); } @@ -1431,7 +1429,7 @@ bool HTMLMediaElement::PotentiallyPlaying() const { } bool HTMLMediaElement::EndedPlayback() const { - float dur = duration(); + const double dur = duration(); if (!player_ || std::isnan(dur)) { return false; } @@ -1448,15 +1446,15 @@ bool HTMLMediaElement::EndedPlayback() const { // direction of playback is forwards, Either the media element does not have a // loop attribute specified, or the media element has a current media // controller. - float now = current_time(NULL); - if (playback_rate_ > 0) { - return dur > 0 && now >= dur && !loop(); + const double now = current_time(NULL); + if (playback_rate_ > 0.f) { + return dur > 0.0 && now >= dur && !loop(); } // or the current playback position is the earliest possible position and the // direction of playback is backwards - if (playback_rate_ < 0) { - return now <= 0; + if (playback_rate_ < 0.f) { + return now <= 0.0; } return false; @@ -1557,14 +1555,14 @@ void HTMLMediaElement::TimeChanged(bool eos_played) { // already posted one at the current movie time. ScheduleTimeupdateEvent(false); - float now = current_time(NULL); - float dur = duration(); + const double now = current_time(NULL); + const double dur = duration(); // 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: eos_played |= - !std::isnan(dur) && (0.0f != dur) && now >= dur && playback_rate_ > 0; + !std::isnan(dur) && (0.0 != dur) && now >= dur && playback_rate_ > 0.f; if (eos_played) { LOG(INFO) << "End of stream is played."; // If the media element has a loop attribute specified and does not have a @@ -1573,7 +1571,7 @@ void HTMLMediaElement::TimeChanged(bool eos_played) { sent_end_event_ = false; // then seek to the earliest possible position of the media resource and // abort these steps. - Seek(0); + Seek(0.0); } else { // If the media element does not have a current media controller, and the // media element has still ended playback, and the direction of playback @@ -1603,7 +1601,7 @@ void HTMLMediaElement::DurationChanged() { ScheduleOwnEvent(base::Tokens::durationchange()); - double now = current_time(NULL); + const double now = current_time(NULL); // Reset and update |duration_|. duration_ = std::numeric_limits::quiet_NaN(); if (player_ && ready_state_ >= WebMediaPlayer::kReadyStateHaveMetadata) { @@ -1611,7 +1609,7 @@ void HTMLMediaElement::DurationChanged() { } if (now > duration_) { - Seek(static_cast(duration_)); + Seek(duration_); } EndProcessingMediaPlayerCallback(); diff --git a/cobalt/dom/html_media_element.h b/cobalt/dom/html_media_element.h index 612e21cf20bc..db05a0cd7356 100644 --- a/cobalt/dom/html_media_element.h +++ b/cobalt/dom/html_media_element.h @@ -105,9 +105,9 @@ class HTMLMediaElement : public HTMLElement, bool seeking() const; // Playback state - float current_time(script::ExceptionState* exception_state) const; - void set_current_time(float time, script::ExceptionState* exception_state); - float duration() const; + double current_time(script::ExceptionState* exception_state) const; + void set_current_time(double time, script::ExceptionState* exception_state); + double duration() const; base::Time GetStartDate() const; bool paused() const; bool resume_frozen_flag() const; @@ -210,10 +210,10 @@ class HTMLMediaElement : public HTMLElement, void ChangeNetworkStateFromLoadingToIdle(); // Playback - void Seek(float time); + void Seek(double time); void FinishSeek(); - void AddPlayedRange(float start, float end); + void AddPlayedRange(double start, double end); void UpdateVolume(); void UpdatePlayState(); @@ -269,7 +269,7 @@ class HTMLMediaElement : public HTMLElement, WebMediaPlayer::ReadyState ready_state_maximum_; float volume_; - float last_seek_time_; + double last_seek_time_; double previous_progress_time_; double duration_; diff --git a/cobalt/media/player/web_media_player.h b/cobalt/media/player/web_media_player.h index 459ec6ed0b86..1f8f2646733e 100644 --- a/cobalt/media/player/web_media_player.h +++ b/cobalt/media/player/web_media_player.h @@ -41,7 +41,7 @@ class WebMediaPlayer { // Return true if the punch through box should be rendered. Return false if // no punch through box should be rendered. typedef base::Callback SetBoundsCB; - typedef std::function AddRangeCB; + typedef std::function AddRangeCB; enum NetworkState { kNetworkStateEmpty, @@ -109,12 +109,12 @@ class WebMediaPlayer { // Playback controls. virtual void Play() = 0; virtual void Pause() = 0; - virtual void Seek(float seconds) = 0; + virtual void Seek(double seconds) = 0; virtual void SetRate(float rate) = 0; virtual void SetVolume(float volume) = 0; virtual void SetVisible(bool visible) = 0; virtual void UpdateBufferedTimeRanges(const AddRangeCB& add_range_cb) = 0; - virtual float GetMaxTimeSeekable() const = 0; + virtual double GetMaxTimeSeekable() const = 0; // Suspend/Resume virtual void Suspend() = 0; @@ -136,11 +136,11 @@ class WebMediaPlayer { // Getters of playback state. virtual bool IsPaused() const = 0; virtual bool IsSeeking() const = 0; - virtual float GetDuration() const = 0; + virtual double GetDuration() const = 0; #if SB_HAS(PLAYER_WITH_URL) virtual base::Time GetStartDate() const = 0; #endif // SB_HAS(PLAYER_WITH_URL) - virtual float GetCurrentTime() const = 0; + virtual double GetCurrentTime() const = 0; virtual float GetPlaybackRate() const = 0; // Get rate of loading the resource. @@ -152,7 +152,7 @@ class WebMediaPlayer { virtual bool DidLoadingProgress() const = 0; - virtual float MediaTimeForTimeValue(float timeValue) const = 0; + virtual double MediaTimeForTimeValue(double timeValue) const = 0; virtual PlayerStatistics GetStatistics() const = 0; diff --git a/cobalt/media/player/web_media_player_impl.cc b/cobalt/media/player/web_media_player_impl.cc index 6941c04d3d83..48218c90d160 100644 --- a/cobalt/media/player/web_media_player_impl.cc +++ b/cobalt/media/player/web_media_player_impl.cc @@ -69,12 +69,12 @@ const char* kMediaEme = "Media.EME."; // end of stream position when the current playback position is also near the // end of the stream. In this case, "near the end of stream" means "position // greater than or equal to duration() - kEndOfStreamEpsilonInSeconds". -const double kEndOfStreamEpsilonInSeconds = 2.; +const double kEndOfStreamEpsilonInSeconds = 2.0; DECLARE_INSTANCE_COUNTER(WebMediaPlayerImpl); bool IsNearTheEndOfStream(const WebMediaPlayerImpl* wmpi, double position) { - float duration = wmpi->GetDuration(); + const double duration = wmpi->GetDuration(); if (std::isfinite(duration)) { // If video is very short, we always treat a position as near the end. if (duration <= kEndOfStreamEpsilonInSeconds) return true; @@ -84,19 +84,9 @@ bool IsNearTheEndOfStream(const WebMediaPlayerImpl* wmpi, double position) { } #endif // defined(COBALT_SKIP_SEEK_REQUEST_NEAR_END) -base::TimeDelta ConvertSecondsToTimestamp(float seconds) { - float microseconds = seconds * base::Time::kMicrosecondsPerSecond; - float integer = ceilf(microseconds); - float difference = integer - microseconds; - - // Round down if difference is large enough. - if ((microseconds > 0 && difference > 0.5f) || - (microseconds <= 0 && difference >= 0.5f)) { - integer -= 1.0f; - } - - // Now we can safely cast to int64 microseconds. - return base::TimeDelta::FromMicroseconds(static_cast(integer)); +base::TimeDelta ConvertSecondsToTimestamp(double seconds) { + return base::TimeDelta::FromMicrosecondsD(std::round( + seconds * static_cast(base::Time::kMicrosecondsPerSecond))); } } // namespace @@ -340,7 +330,7 @@ void WebMediaPlayerImpl::Pause() { media_log_->AddEvent<::media::MediaLogEvent::kPause>(); } -void WebMediaPlayerImpl::Seek(float seconds) { +void WebMediaPlayerImpl::Seek(double seconds) { DCHECK_EQ(main_loop_, base::MessageLoop::current()); #if defined(COBALT_SKIP_SEEK_REQUEST_NEAR_END) @@ -461,20 +451,20 @@ bool WebMediaPlayerImpl::IsSeeking() const { return state_.seeking; } -float WebMediaPlayerImpl::GetDuration() const { +double WebMediaPlayerImpl::GetDuration() const { DCHECK_EQ(main_loop_, base::MessageLoop::current()); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) - return std::numeric_limits::quiet_NaN(); + return std::numeric_limits::quiet_NaN(); base::TimeDelta duration = pipeline_->GetMediaDuration(); // Return positive infinity if the resource is unbounded. // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration if (duration == ::media::kInfiniteDuration) - return std::numeric_limits::infinity(); + return std::numeric_limits::infinity(); - return static_cast(duration.InSecondsF()); + return duration.InSecondsF(); } #if SB_HAS(PLAYER_WITH_URL) @@ -490,10 +480,12 @@ base::Time WebMediaPlayerImpl::GetStartDate() const { } #endif // SB_HAS(PLAYER_WITH_URL) -float WebMediaPlayerImpl::GetCurrentTime() const { +double WebMediaPlayerImpl::GetCurrentTime() const { DCHECK_EQ(main_loop_, base::MessageLoop::current()); - if (state_.paused) return static_cast(state_.paused_time.InSecondsF()); - return static_cast(pipeline_->GetMediaTime().InSecondsF()); + if (state_.paused) { + return state_.paused_time.InSecondsF(); + } + return pipeline_->GetMediaTime().InSecondsF(); } float WebMediaPlayerImpl::GetPlaybackRate() const { @@ -533,10 +525,9 @@ void WebMediaPlayerImpl::UpdateBufferedTimeRanges( } } -float WebMediaPlayerImpl::GetMaxTimeSeekable() const { +double WebMediaPlayerImpl::GetMaxTimeSeekable() const { DCHECK_EQ(main_loop_, base::MessageLoop::current()); - - return static_cast(pipeline_->GetMediaDuration().InSecondsF()); + return pipeline_->GetMediaDuration().InSecondsF(); } void WebMediaPlayerImpl::Suspend() { pipeline_->Suspend(); } @@ -554,7 +545,7 @@ bool WebMediaPlayerImpl::DidLoadingProgress() const { return pipeline_->DidLoadingProgress(); } -float WebMediaPlayerImpl::MediaTimeForTimeValue(float timeValue) const { +double WebMediaPlayerImpl::MediaTimeForTimeValue(double timeValue) const { return ConvertSecondsToTimestamp(timeValue).InSecondsF(); } diff --git a/cobalt/media/player/web_media_player_impl.h b/cobalt/media/player/web_media_player_impl.h index adb7ed2a577b..ca85f8120a1a 100644 --- a/cobalt/media/player/web_media_player_impl.h +++ b/cobalt/media/player/web_media_player_impl.h @@ -131,12 +131,12 @@ class WebMediaPlayerImpl : public WebMediaPlayer, // Playback controls. void Play() override; void Pause() override; - void Seek(float seconds) override; + void Seek(double seconds) override; void SetRate(float rate) override; void SetVolume(float volume) override; void SetVisible(bool visible) override; void UpdateBufferedTimeRanges(const AddRangeCB& add_range_cb) override; - float GetMaxTimeSeekable() const override; + double GetMaxTimeSeekable() const override; // Suspend/Resume void Suspend() override; @@ -158,11 +158,11 @@ class WebMediaPlayerImpl : public WebMediaPlayer, // Getters of playback state. bool IsPaused() const override; bool IsSeeking() const override; - float GetDuration() const override; + double GetDuration() const override; #if SB_HAS(PLAYER_WITH_URL) base::Time GetStartDate() const override; #endif // SB_HAS(PLAYER_WITH_URL) - float GetCurrentTime() const override; + double GetCurrentTime() const override; float GetPlaybackRate() const override; // Get rate of loading the resource. @@ -176,7 +176,7 @@ class WebMediaPlayerImpl : public WebMediaPlayer, bool DidLoadingProgress() const override; - float MediaTimeForTimeValue(float timeValue) const override; + double MediaTimeForTimeValue(double timeValue) const override; PlayerStatistics GetStatistics() const override; @@ -264,7 +264,7 @@ class WebMediaPlayerImpl : public WebMediaPlayer, seeking(false), playback_rate(0.0f), pending_seek(false), - pending_seek_seconds(0.0f), + pending_seek_seconds(0.0), starting(false), is_progressive(false), is_media_source(false) {} @@ -288,7 +288,7 @@ class WebMediaPlayerImpl : public WebMediaPlayer, // Seek gets pending if another seek is in progress. Only last pending seek // will have effect. bool pending_seek; - float pending_seek_seconds; + double pending_seek_seconds; bool starting; diff --git a/cobalt/media/sandbox/web_media_player_helper.cc b/cobalt/media/sandbox/web_media_player_helper.cc index c2364a574518..945c1aa4dfa1 100644 --- a/cobalt/media/sandbox/web_media_player_helper.cc +++ b/cobalt/media/sandbox/web_media_player_helper.cc @@ -116,7 +116,7 @@ bool WebMediaPlayerHelper::IsPlaybackFinished() const { // Use a small epsilon to ensure that the video can finish properly even when // the audio and video streams are shorter than the duration specified in the // container. - return player_->GetCurrentTime() >= player_->GetDuration() - 0.1f; + return player_->GetCurrentTime() >= player_->GetDuration() - 0.1; } } // namespace sandbox diff --git a/cobalt/media/sandbox/web_media_player_sandbox.cc b/cobalt/media/sandbox/web_media_player_sandbox.cc index cfa4a2827475..016444d62a1f 100644 --- a/cobalt/media/sandbox/web_media_player_sandbox.cc +++ b/cobalt/media/sandbox/web_media_player_sandbox.cc @@ -329,21 +329,21 @@ class Application { } void AppendData(const std::string& id, ScopedFile* file, int64* offset) { - const float kLowWaterMarkInSeconds = 5.f; + const double kLowWaterMarkInSeconds = 5.0; const int64 kMaxBytesToAppend = 1024 * 1024; std::vector buffer(kMaxBytesToAppend); while (*offset < file->GetSize()) { ::media::Ranges ranges = chunk_demuxer_->GetBufferedRanges(id); - float end_of_buffer = - ranges.size() == 0 ? 0.f : ranges.end(ranges.size() - 1).InSecondsF(); + const double end_of_buffer = + ranges.size() == 0 ? 0.0 : ranges.end(ranges.size() - 1).InSecondsF(); if (end_of_buffer - player_->GetCurrentTime() > kLowWaterMarkInSeconds) { break; } int64 bytes_to_append = std::min(kMaxBytesToAppend, file->GetSize() - *offset); - auto current_time = player_ ? player_->GetCurrentTime() : 0; + const double current_time = player_ ? player_->GetCurrentTime() : 0.0; auto evicted = chunk_demuxer_->EvictCodedFrames( id, base::TimeDelta::FromSecondsD(current_time), bytes_to_append); SB_DCHECK(evicted); diff --git a/cobalt/media_session/media_session_client.cc b/cobalt/media_session/media_session_client.cc index ab740dead22d..d0640670d866 100644 --- a/cobalt/media_session/media_session_client.cc +++ b/cobalt/media_session/media_session_client.cc @@ -58,7 +58,7 @@ void GuessMediaPositionState(MediaSessionState* session_state, *guess_player = current_player; MediaPositionState position_state; - float duration = (*guess_player)->GetDuration(); + const double duration = (*guess_player)->GetDuration(); if (std::isfinite(duration)) { position_state.set_duration(duration); } else if (std::isinf(duration)) {