diff --git a/base/metrics/persistent_histogram_allocator.cc b/base/metrics/persistent_histogram_allocator.cc index 51a3d6c..cad46422 100644 --- a/base/metrics/persistent_histogram_allocator.cc +++ b/base/metrics/persistent_histogram_allocator.cc
@@ -22,10 +22,6 @@ #include "base/pickle.h" #include "base/synchronization/lock.h" -// TODO(bcwhite): Order these methods to match the header file. The current -// order is only temporary in order to aid review of the transition from -// a non-class implementation. - namespace base { namespace { @@ -267,6 +263,188 @@ PersistentHistogramAllocator::~PersistentHistogramAllocator() {} +std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( + Reference ref) { + // Unfortunately, the histogram "pickle" methods cannot be used as part of + // the persistance because the deserialization methods always create local + // count data (while these must reference the persistent counts) and always + // add it to the local list of known histograms (while these may be simple + // references to histograms in other processes). + PersistentHistogramData* histogram_data = + memory_allocator_->GetAsObject<PersistentHistogramData>( + ref, kTypeIdHistogram); + size_t length = memory_allocator_->GetAllocSize(ref); + if (!histogram_data || + reinterpret_cast<char*>(histogram_data)[length - 1] != '\0') { + RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA); + NOTREACHED(); + return nullptr; + } + return CreateHistogram(histogram_data); +} + +std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram( + HistogramType histogram_type, + const std::string& name, + int minimum, + int maximum, + const BucketRanges* bucket_ranges, + int32_t flags, + Reference* ref_ptr) { + // If the allocator is corrupt, don't waste time trying anything else. + // This also allows differentiating on the dashboard between allocations + // failed due to a corrupt allocator and the number of process instances + // with one, the latter being idicated by "newly corrupt", below. + if (memory_allocator_->IsCorrupt()) { + RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT); + return nullptr; + } + + // Create the metadata necessary for a persistent sparse histogram. This + // is done first because it is a small subset of what is required for + // other histograms. + PersistentMemoryAllocator::Reference histogram_ref = + memory_allocator_->Allocate( + offsetof(PersistentHistogramData, name) + name.length() + 1, + kTypeIdHistogram); + PersistentHistogramData* histogram_data = + memory_allocator_->GetAsObject<PersistentHistogramData>(histogram_ref, + kTypeIdHistogram); + if (histogram_data) { + memcpy(histogram_data->name, name.c_str(), name.size() + 1); + histogram_data->histogram_type = histogram_type; + histogram_data->flags = flags | HistogramBase::kIsPersistent; + } + + // Create the remaining metadata necessary for regular histograms. + if (histogram_type != SPARSE_HISTOGRAM) { + size_t bucket_count = bucket_ranges->bucket_count(); + size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count); + if (counts_bytes == 0) { + // |bucket_count| was out-of-range. + NOTREACHED(); + return nullptr; + } + + size_t ranges_bytes = (bucket_count + 1) * sizeof(HistogramBase::Sample); + PersistentMemoryAllocator::Reference counts_ref = + memory_allocator_->Allocate(counts_bytes, kTypeIdCountsArray); + PersistentMemoryAllocator::Reference ranges_ref = + memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray); + HistogramBase::Sample* ranges_data = + memory_allocator_->GetAsObject<HistogramBase::Sample>( + ranges_ref, kTypeIdRangesArray); + + // Only continue here if all allocations were successful. If they weren't, + // there is no way to free the space but that's not really a problem since + // the allocations only fail because the space is full or corrupt and so + // any future attempts will also fail. + if (counts_ref && ranges_data && histogram_data) { + for (size_t i = 0; i < bucket_ranges->size(); ++i) + ranges_data[i] = bucket_ranges->range(i); + + histogram_data->minimum = minimum; + histogram_data->maximum = maximum; + // |bucket_count| must fit within 32-bits or the allocation of the counts + // array would have failed for being too large; the allocator supports + // less than 4GB total size. + histogram_data->bucket_count = static_cast<uint32_t>(bucket_count); + histogram_data->ranges_ref = ranges_ref; + histogram_data->ranges_checksum = bucket_ranges->checksum(); + histogram_data->counts_ref = counts_ref; + } else { + histogram_data = nullptr; // Clear this for proper handling below. + } + } + + if (histogram_data) { + // Create the histogram using resources in persistent memory. This ends up + // resolving the "ref" values stored in histogram_data instad of just + // using what is already known above but avoids duplicating the switch + // statement here and serves as a double-check that everything is + // correct before commiting the new histogram to persistent space. + std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data); + DCHECK(histogram); + if (ref_ptr != nullptr) + *ref_ptr = histogram_ref; + + // By storing the reference within the allocator to this histogram, the + // next import (which will happen before the next histogram creation) + // will know to skip it. + // See also the comment in ImportHistogramsToStatisticsRecorder(). + subtle::NoBarrier_Store(&last_created_, histogram_ref); + return histogram; + } + + CreateHistogramResultType result; + if (memory_allocator_->IsCorrupt()) { + RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT); + result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT; + } else if (memory_allocator_->IsFull()) { + result = CREATE_HISTOGRAM_ALLOCATOR_FULL; + } else { + result = CREATE_HISTOGRAM_ALLOCATOR_ERROR; + } + RecordCreateHistogramResult(result); + NOTREACHED() << "error=" << result; + + return nullptr; +} + +void PersistentHistogramAllocator::FinalizeHistogram(Reference ref, + bool registered) { + // If the created persistent histogram was registered then it needs to + // be marked as "iterable" in order to be found by other processes. + if (registered) + memory_allocator_->MakeIterable(ref); + // If it wasn't registered then a race condition must have caused + // two to be created. The allocator does not support releasing the + // acquired memory so just change the type to be empty. + else + memory_allocator_->ChangeType(ref, 0, kTypeIdHistogram); +} + +void PersistentHistogramAllocator::MergeHistogramDeltaToStatisticsRecorder( + HistogramBase* histogram) { + DCHECK(histogram); + + HistogramBase* existing = GetOrCreateStatisticsRecorderHistogram(histogram); + if (!existing) { + // The above should never fail but if it does, no real harm is done. + // The data won't be merged but it also won't be recorded as merged + // so a future try, if successful, will get what was missed. If it + // continues to fail, some metric data will be lost but that is better + // than crashing. + NOTREACHED(); + return; + } + + // Merge the delta from the passed object to the one in the SR. + existing->AddSamples(*histogram->SnapshotDelta()); +} + +void PersistentHistogramAllocator::MergeHistogramFinalDeltaToStatisticsRecorder( + const HistogramBase* histogram) { + DCHECK(histogram); + + HistogramBase* existing = GetOrCreateStatisticsRecorderHistogram(histogram); + if (!existing) { + // The above should never fail but if it does, no real harm is done. + // Some metric data will be lost but that is better than crashing. + NOTREACHED(); + return; + } + + // Merge the delta from the passed object to the one in the SR. + existing->AddSamples(*histogram->SnapshotFinalDelta()); +} + +PersistentSampleMapRecords* PersistentHistogramAllocator::UseSampleMapRecords( + uint64_t id, + const void* user) { + return sparse_histogram_data_manager_.UseSampleMapRecords(id, user); +} + void PersistentHistogramAllocator::CreateTrackingHistograms(StringPiece name) { memory_allocator_->CreateTrackingHistograms(name); } @@ -321,14 +499,6 @@ return histogram_pointer; } -// static -void PersistentHistogramAllocator::RecordCreateHistogramResult( - CreateHistogramResultType result) { - HistogramBase* result_histogram = GetCreateHistogramResultHistogram(); - if (result_histogram) - result_histogram->Add(result); -} - std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram( PersistentHistogramData* histogram_data_ptr) { if (!histogram_data_ptr) { @@ -483,186 +653,12 @@ return StatisticsRecorder::RegisterOrDeleteDuplicate(existing); } -std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( - Reference ref) { - // Unfortunately, the histogram "pickle" methods cannot be used as part of - // the persistance because the deserialization methods always create local - // count data (while these must reference the persistent counts) and always - // add it to the local list of known histograms (while these may be simple - // references to histograms in other processes). - PersistentHistogramData* histogram_data = - memory_allocator_->GetAsObject<PersistentHistogramData>( - ref, kTypeIdHistogram); - size_t length = memory_allocator_->GetAllocSize(ref); - if (!histogram_data || - reinterpret_cast<char*>(histogram_data)[length - 1] != '\0') { - RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA); - NOTREACHED(); - return nullptr; - } - return CreateHistogram(histogram_data); -} - -void PersistentHistogramAllocator::FinalizeHistogram(Reference ref, - bool registered) { - // If the created persistent histogram was registered then it needs to - // be marked as "iterable" in order to be found by other processes. - if (registered) - memory_allocator_->MakeIterable(ref); - // If it wasn't registered then a race condition must have caused - // two to be created. The allocator does not support releasing the - // acquired memory so just change the type to be empty. - else - memory_allocator_->ChangeType(ref, 0, kTypeIdHistogram); -} - -void PersistentHistogramAllocator::MergeHistogramDeltaToStatisticsRecorder( - HistogramBase* histogram) { - DCHECK(histogram); - - HistogramBase* existing = GetOrCreateStatisticsRecorderHistogram(histogram); - if (!existing) { - // The above should never fail but if it does, no real harm is done. - // The data won't be merged but it also won't be recorded as merged - // so a future try, if successful, will get what was missed. If it - // continues to fail, some metric data will be lost but that is better - // than crashing. - NOTREACHED(); - return; - } - - // Merge the delta from the passed object to the one in the SR. - existing->AddSamples(*histogram->SnapshotDelta()); -} - -void PersistentHistogramAllocator::MergeHistogramFinalDeltaToStatisticsRecorder( - const HistogramBase* histogram) { - DCHECK(histogram); - - HistogramBase* existing = GetOrCreateStatisticsRecorderHistogram(histogram); - if (!existing) { - // The above should never fail but if it does, no real harm is done. - // Some metric data will be lost but that is better than crashing. - NOTREACHED(); - return; - } - - // Merge the delta from the passed object to the one in the SR. - existing->AddSamples(*histogram->SnapshotFinalDelta()); -} - -PersistentSampleMapRecords* PersistentHistogramAllocator::UseSampleMapRecords( - uint64_t id, - const void* user) { - return sparse_histogram_data_manager_.UseSampleMapRecords(id, user); -} - -std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram( - HistogramType histogram_type, - const std::string& name, - int minimum, - int maximum, - const BucketRanges* bucket_ranges, - int32_t flags, - Reference* ref_ptr) { - // If the allocator is corrupt, don't waste time trying anything else. - // This also allows differentiating on the dashboard between allocations - // failed due to a corrupt allocator and the number of process instances - // with one, the latter being idicated by "newly corrupt", below. - if (memory_allocator_->IsCorrupt()) { - RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT); - return nullptr; - } - - // Create the metadata necessary for a persistent sparse histogram. This - // is done first because it is a small subset of what is required for - // other histograms. - PersistentMemoryAllocator::Reference histogram_ref = - memory_allocator_->Allocate( - offsetof(PersistentHistogramData, name) + name.length() + 1, - kTypeIdHistogram); - PersistentHistogramData* histogram_data = - memory_allocator_->GetAsObject<PersistentHistogramData>(histogram_ref, - kTypeIdHistogram); - if (histogram_data) { - memcpy(histogram_data->name, name.c_str(), name.size() + 1); - histogram_data->histogram_type = histogram_type; - histogram_data->flags = flags | HistogramBase::kIsPersistent; - } - - // Create the remaining metadata necessary for regular histograms. - if (histogram_type != SPARSE_HISTOGRAM) { - size_t bucket_count = bucket_ranges->bucket_count(); - size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count); - if (counts_bytes == 0) { - // |bucket_count| was out-of-range. - NOTREACHED(); - return nullptr; - } - - size_t ranges_bytes = (bucket_count + 1) * sizeof(HistogramBase::Sample); - PersistentMemoryAllocator::Reference counts_ref = - memory_allocator_->Allocate(counts_bytes, kTypeIdCountsArray); - PersistentMemoryAllocator::Reference ranges_ref = - memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray); - HistogramBase::Sample* ranges_data = - memory_allocator_->GetAsObject<HistogramBase::Sample>( - ranges_ref, kTypeIdRangesArray); - - // Only continue here if all allocations were successful. If they weren't, - // there is no way to free the space but that's not really a problem since - // the allocations only fail because the space is full or corrupt and so - // any future attempts will also fail. - if (counts_ref && ranges_data && histogram_data) { - for (size_t i = 0; i < bucket_ranges->size(); ++i) - ranges_data[i] = bucket_ranges->range(i); - - histogram_data->minimum = minimum; - histogram_data->maximum = maximum; - // |bucket_count| must fit within 32-bits or the allocation of the counts - // array would have failed for being too large; the allocator supports - // less than 4GB total size. - histogram_data->bucket_count = static_cast<uint32_t>(bucket_count); - histogram_data->ranges_ref = ranges_ref; - histogram_data->ranges_checksum = bucket_ranges->checksum(); - histogram_data->counts_ref = counts_ref; - } else { - histogram_data = nullptr; // Clear this for proper handling below. - } - } - - if (histogram_data) { - // Create the histogram using resources in persistent memory. This ends up - // resolving the "ref" values stored in histogram_data instad of just - // using what is already known above but avoids duplicating the switch - // statement here and serves as a double-check that everything is - // correct before commiting the new histogram to persistent space. - std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data); - DCHECK(histogram); - if (ref_ptr != nullptr) - *ref_ptr = histogram_ref; - - // By storing the reference within the allocator to this histogram, the - // next import (which will happen before the next histogram creation) - // will know to skip it. - // See also the comment in ImportHistogramsToStatisticsRecorder(). - subtle::NoBarrier_Store(&last_created_, histogram_ref); - return histogram; - } - - CreateHistogramResultType result; - if (memory_allocator_->IsCorrupt()) { - RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT); - result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT; - } else if (memory_allocator_->IsFull()) { - result = CREATE_HISTOGRAM_ALLOCATOR_FULL; - } else { - result = CREATE_HISTOGRAM_ALLOCATOR_ERROR; - } - RecordCreateHistogramResult(result); - NOTREACHED() << "error=" << result; - - return nullptr; +// static +void PersistentHistogramAllocator::RecordCreateHistogramResult( + CreateHistogramResultType result) { + HistogramBase* result_histogram = GetCreateHistogramResultHistogram(); + if (result_histogram) + result_histogram->Add(result); } GlobalHistogramAllocator::~GlobalHistogramAllocator() {}
diff --git a/base/process/memory_win.cc b/base/process/memory_win.cc index 17d588a..406145af 100644 --- a/base/process/memory_win.cc +++ b/base/process/memory_win.cc
@@ -9,6 +9,7 @@ #include <stddef.h> #include "base/logging.h" +#include "base/strings/safe_sprintf.h" // malloc_unchecked is required to implement UncheckedMalloc properly. // It's provided by allocator_shim_win.cc but since that's not always present, @@ -33,9 +34,16 @@ #pragma warning(disable: 4702) int OnNoMemory(size_t size) { + // Make no additional allocations here to avoid getting into a death spiral + // when trying to log the error message. + char buf[64]; + strings::ssize_t result = + strings::SafeSPrintf(buf, "Out of memory, size = %d\n", size); + RAW_CHECK(result != -1); + // Kill the process. This is important for security since most of code // does not check the result of memory allocation. - LOG(FATAL) << "Out of memory, size = " << size; + RAW_LOG(FATAL, buf); // Safety check, make sure process exits here. _exit(1);
diff --git a/build/sanitizers/tsan_suppressions.cc b/build/sanitizers/tsan_suppressions.cc index 3f52b76..d550867 100644 --- a/build/sanitizers/tsan_suppressions.cc +++ b/build/sanitizers/tsan_suppressions.cc
@@ -151,9 +151,6 @@ // http://crbug.com/328868 "race:PR_Lock\n" -// http://crbug.com/329225 -"race:blink::currentTimeFunction\n" - // http://crbug.com/333244 "race:content::" "VideoCaptureImplTest::MockVideoCaptureImpl::~MockVideoCaptureImpl\n"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java index 28badf4..4ee943e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheController.java
@@ -21,7 +21,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordHistogram; @@ -414,20 +413,13 @@ * Cancels the current precache session. * @param event the failure reason. */ - private void cancelPrecaching(final int event) { - // cancelPrecaching() could be called from PrecacheManager::Shutdown(), precache GCM task, - // etc., where it could be a different thread. - ThreadUtils.runOnUiThread(new Runnable() { - @Override - public void run() { - Log.v(TAG, "canceling precache session"); - if (setIsPrecaching(false)) { - mPrecacheLauncher.cancel(); - shutdownPrecaching(true); - } - PrecacheUMA.record(event); - } - }); + private void cancelPrecaching(int event) { + Log.v(TAG, "canceling precache session"); + if (setIsPrecaching(false)) { + mPrecacheLauncher.cancel(); + shutdownPrecaching(true); + } + PrecacheUMA.record(event); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java index fbaf712..613fcbee 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/precache/PrecacheControllerTest.java
@@ -8,7 +8,6 @@ import android.content.Intent; import android.content.SharedPreferences.Editor; import android.test.InstrumentationTestCase; -import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import com.google.android.gms.gcm.GcmNetworkManager; @@ -195,7 +194,6 @@ } @SmallTest - @UiThreadTest @Feature({"Precache"}) public void testDeviceStateChangeCancels() { verifyBeginPrecaching(); @@ -235,7 +233,6 @@ } @SmallTest - @UiThreadTest @Feature({"Precache"}) public void testTimeoutCancelsPrecaching() { verifyBeginPrecaching();
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 24a1ed5..39d810a1 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -531,7 +531,6 @@ </if> <include name="IDR_BRAILLE_MANIFEST" file="resources\chromeos\braille_ime\manifest.json" type="BINDATA" /> </if> - <include name="IDR_WHISPERNET_PROXY_MANIFEST" file="resources\whispernet_proxy\manifest.json" type="BINDATA" /> <if expr="enable_media_router"> <part file="media_router_resources.grdp" /> </if>
diff --git a/chrome/browser/copresence/DEPS b/chrome/browser/copresence/DEPS deleted file mode 100644 index c3a5b96..0000000 --- a/chrome/browser/copresence/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+media", -]
diff --git a/chrome/browser/copresence/OWNERS b/chrome/browser/copresence/OWNERS deleted file mode 100644 index 2bc8d07..0000000 --- a/chrome/browser/copresence/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -rkc@chromium.org -ckehoe@chromium.org -xiyuan@chromium.org
diff --git a/chrome/browser/copresence/chrome_whispernet_client.cc b/chrome/browser/copresence/chrome_whispernet_client.cc deleted file mode 100644 index dbd74157..0000000 --- a/chrome/browser/copresence/chrome_whispernet_client.cc +++ /dev/null
@@ -1,236 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/copresence/chrome_whispernet_client.h" - -#include <stddef.h> - -#include <utility> - -#include "base/memory/ptr_util.h" -#include "chrome/browser/copresence/chrome_whispernet_config.h" -#include "chrome/browser/extensions/api/copresence_private/copresence_private_api.h" -#include "chrome/browser/extensions/component_loader.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/common/extensions/api/copresence_private.h" -#include "content/public/browser/browser_context.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/extension_system.h" -#include "grit/browser_resources.h" -#include "media/audio/audio_device_description.h" -#include "media/audio/audio_manager.h" -#include "media/base/audio_parameters.h" - -using audio_modem::AUDIBLE; -using audio_modem::AudioType; -using audio_modem::BOTH; -using audio_modem::INAUDIBLE; -using audio_modem::SamplesCallback; -using audio_modem::SuccessCallback; -using audio_modem::TokensCallback; -using audio_modem::TokenParameters; - -using extensions::api::copresence_private::AudioParameters; -using extensions::api::copresence_private::DecodeSamplesParameters; -using extensions::api::copresence_private::EncodeTokenParameters; -using ApiTokenParams = extensions::api::copresence_private::TokenParameters; - -namespace OnConfigAudio = - extensions::api::copresence_private::OnConfigAudio; -namespace OnDecodeSamplesRequest = - extensions::api::copresence_private::OnDecodeSamplesRequest; -namespace OnEncodeTokenRequest = - extensions::api::copresence_private::OnEncodeTokenRequest; - -using extensions::Event; - -namespace { - -AudioParamData GetDefaultAudioConfig() { - media::AudioParameters params = - media::AudioManager::Get()->GetInputStreamParameters( - media::AudioDeviceDescription::kDefaultDeviceId); - - AudioParamData config_data = {}; - - config_data.audio_dtmf.coder_sample_rate = - config_data.audio_dsss.coder_sample_rate = - audio_modem::kDefaultSampleRate; - - config_data.audio_dtmf.recording_sample_rate = - config_data.audio_dsss.recording_sample_rate = params.sample_rate(); - - config_data.audio_dtmf.num_repetitions_to_play = - config_data.audio_dsss.num_repetitions_to_play = - audio_modem::kDefaultRepetitions; - - config_data.audio_dsss.upsampling_factor = audio_modem::kDefaultBitsPerSample; - config_data.audio_dsss.desired_carrier_frequency = - audio_modem::kDefaultCarrierFrequency; - - config_data.recording_channels = params.channels(); - - return config_data; -} - -// ApiTokenParams is not copyable, so we must take it as an output argument. -// TODO(ckehoe): Pass protos to Whispernet to avoid all these conversions. -void ConvertTokenParams(const TokenParameters& in, ApiTokenParams* out) { - out->length = in.length; - out->crc = in.crc; - out->parity = in.parity; -} - -} // namespace - -// static -const char ChromeWhispernetClient::kWhispernetProxyExtensionId[] = - "bpfmnplchembfbdgieamdodgaencleal"; - - -// Public functions. - -ChromeWhispernetClient::ChromeWhispernetClient( - content::BrowserContext* browser_context) - : browser_context_(browser_context), - event_router_(extensions::EventRouter::Get(browser_context)), - extension_loaded_(false) { - DCHECK(browser_context_); -} - -ChromeWhispernetClient::~ChromeWhispernetClient() {} - -void ChromeWhispernetClient::Initialize( - const SuccessCallback& init_callback) { - DVLOG(3) << "Initializing whispernet proxy client."; - - DCHECK(!init_callback.is_null()); - init_callback_ = init_callback; - - ExtensionService* extension_service = - extensions::ExtensionSystem::Get(browser_context_)->extension_service(); - CHECK(extension_service); - - extensions::ComponentLoader* loader = extension_service->component_loader(); - CHECK(loader); - if (!loader->Exists(kWhispernetProxyExtensionId)) { - DVLOG(3) << "Loading Whispernet proxy."; - loader->Add(IDR_WHISPERNET_PROXY_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("whispernet_proxy"))); - } - - client_id_ = extensions::CopresencePrivateService::GetFactoryInstance() - ->Get(browser_context_)->RegisterWhispernetClient(this); - AudioConfiguration(GetDefaultAudioConfig()); -} - -void ChromeWhispernetClient::EncodeToken( - const std::string& token_str, - AudioType type, - const TokenParameters token_params[2]) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - - EncodeTokenParameters params; - params.token.token = token_str; - params.token.audible = (type == AUDIBLE); - ConvertTokenParams(token_params[type], ¶ms.token_params); - - SendEventIfLoaded(base::WrapUnique(new Event( - extensions::events::COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST, - OnEncodeTokenRequest::kEventName, - OnEncodeTokenRequest::Create(client_id_, params), browser_context_))); -} - -void ChromeWhispernetClient::DecodeSamples( - AudioType type, - const std::string& samples, - const TokenParameters token_params[2]) { - DecodeSamplesParameters params; - params.samples.assign(samples.begin(), samples.end()); - params.decode_audible = (type == AUDIBLE || type == BOTH); - params.decode_inaudible = (type == INAUDIBLE || type == BOTH); - ConvertTokenParams(token_params[AUDIBLE], ¶ms.audible_token_params); - ConvertTokenParams(token_params[INAUDIBLE], ¶ms.inaudible_token_params); - - SendEventIfLoaded(base::WrapUnique(new Event( - extensions::events::COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST, - OnDecodeSamplesRequest::kEventName, - OnDecodeSamplesRequest::Create(client_id_, params), browser_context_))); -} - -void ChromeWhispernetClient::RegisterTokensCallback( - const TokensCallback& tokens_callback) { - tokens_callback_ = tokens_callback; -} - -void ChromeWhispernetClient::RegisterSamplesCallback( - const SamplesCallback& samples_callback) { - samples_callback_ = samples_callback; -} - -TokensCallback ChromeWhispernetClient::GetTokensCallback() { - return tokens_callback_; -} - -SamplesCallback ChromeWhispernetClient::GetSamplesCallback() { - return samples_callback_; -} - -SuccessCallback ChromeWhispernetClient::GetInitializedCallback() { - return base::Bind(&ChromeWhispernetClient::OnExtensionLoaded, - base::Unretained(this)); -} - - -// Private functions. - -void ChromeWhispernetClient::AudioConfiguration(const AudioParamData& params) { - AudioParameters audio_params; - - // We serialize AudioConfigData to a string and send it to the whispernet - // nacl wrapper. - const size_t params_size = sizeof(params); - audio_params.param_data.resize(params_size); - memcpy(audio_params.param_data.data(), ¶ms, params_size); - - DVLOG(3) << "Configuring audio for client " << client_id_; - SendEventIfLoaded(base::WrapUnique(new Event( - extensions::events::COPRESENCE_PRIVATE_ON_CONFIG_AUDIO, - OnConfigAudio::kEventName, - OnConfigAudio::Create(client_id_, audio_params), browser_context_))); -} - -void ChromeWhispernetClient::SendEventIfLoaded( - std::unique_ptr<extensions::Event> event) { - DCHECK(event_router_); - - if (extension_loaded_) { - event_router_->DispatchEventToExtension(kWhispernetProxyExtensionId, - std::move(event)); - } else { - DVLOG(2) << "Queueing event " << event->event_name - << " for client " << client_id_; - queued_events_.push_back(event.release()); - } -} - -void ChromeWhispernetClient::OnExtensionLoaded(bool success) { - DCHECK(!init_callback_.is_null()); - init_callback_.Run(success); - - DVLOG(3) << "Sending " << queued_events_.size() - << " queued requests to whispernet from client " - << client_id_; - - // In this loop, ownership of each Event is passed to a scoped_ptr instead. - // Thus we can just discard the pointers at the end. - DCHECK(event_router_); - for (Event* event : queued_events_) { - event_router_->DispatchEventToExtension(kWhispernetProxyExtensionId, - base::WrapUnique(event)); - } - queued_events_.weak_clear(); - - extension_loaded_ = true; -}
diff --git a/chrome/browser/copresence/chrome_whispernet_client.h b/chrome/browser/copresence/chrome_whispernet_client.h deleted file mode 100644 index 62beccb..0000000 --- a/chrome/browser/copresence/chrome_whispernet_client.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CLIENT_H_ -#define CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CLIENT_H_ - -#include <string> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "chrome/browser/copresence/chrome_whispernet_config.h" -#include "components/audio_modem/public/whispernet_client.h" - -namespace content { -class BrowserContext; -} - -namespace extensions { - -struct Event; -class EventRouter; - -namespace api { -namespace copresence_private { -struct AudioParameters; -} -} - -} // namespace extensions - -namespace media { -class AudioBusRefCounted; -} - -// This class is responsible for communication with our whispernet_proxy -// extension that talks to the whispernet audio library. -class ChromeWhispernetClient final : public audio_modem::WhispernetClient { - public: - // The browser context needs to outlive this class. - explicit ChromeWhispernetClient(content::BrowserContext* browser_context); - ~ChromeWhispernetClient() override; - - // WhispernetClient overrides: - void Initialize(const audio_modem::SuccessCallback& init_callback) override; - void EncodeToken(const std::string& token_str, - audio_modem::AudioType type, - const audio_modem::TokenParameters token_params[2]) override; - void DecodeSamples( - audio_modem::AudioType type, - const std::string& samples, - const audio_modem::TokenParameters token_params[2]) override; - void RegisterTokensCallback( - const audio_modem::TokensCallback& tokens_callback) override; - void RegisterSamplesCallback( - const audio_modem::SamplesCallback& samples_callback) override; - - audio_modem::TokensCallback GetTokensCallback() override; - audio_modem::SamplesCallback GetSamplesCallback() override; - audio_modem::SuccessCallback GetInitializedCallback() override; - - static const char kWhispernetProxyExtensionId[]; - - private: - // Fire an event to configure whispernet with the given audio parameters. - void AudioConfiguration(const AudioParamData& params); - - void SendEventIfLoaded(std::unique_ptr<extensions::Event> event); - - // This gets called when the proxy extension loads. - void OnExtensionLoaded(bool success); - - content::BrowserContext* const browser_context_; - extensions::EventRouter* const event_router_; - std::string client_id_; - - audio_modem::SuccessCallback extension_loaded_callback_; - audio_modem::SuccessCallback init_callback_; - - audio_modem::TokensCallback tokens_callback_; - audio_modem::SamplesCallback samples_callback_; - - ScopedVector<extensions::Event> queued_events_; - bool extension_loaded_; - - DISALLOW_COPY_AND_ASSIGN(ChromeWhispernetClient); -}; - -#endif // CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CLIENT_H_
diff --git a/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc b/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc deleted file mode 100644 index d05c3794..0000000 --- a/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc +++ /dev/null
@@ -1,375 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/copresence/chrome_whispernet_client.h" - -#include <stddef.h> - -#include <cmath> -#include <cstdlib> -#include <memory> -#include <string> - -#include "base/bind.h" -#include "base/macros.h" -#include "base/run_loop.h" -#include "base/stl_util.h" -#include "build/build_config.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "components/audio_modem/public/whispernet_client.h" -#include "media/audio/audio_device_description.h" -#include "media/audio/audio_manager.h" -#include "media/audio/audio_manager_base.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_converter.h" -#include "media/base/audio_parameters.h" - -using audio_modem::WhispernetClient; -using audio_modem::AUDIBLE; -using audio_modem::INAUDIBLE; -using audio_modem::TokenParameters; - -namespace { - -// TODO(ckehoe): Use randomly generated tokens instead. -const char kSixZeros[] = "MDAwMDAw"; -const char kEightZeros[] = "MDAwMDAwMDA"; -const char kNineZeros[] = "MDAwMDAwMDAw"; - -const size_t kTokenLengths[2] = {6, 6}; - -// Copied from src/components/copresence/mediums/audio/audio_recorder.cc -std::string AudioBusToString(scoped_refptr<media::AudioBusRefCounted> source) { - std::string buffer; - buffer.resize(source->frames() * source->channels() * sizeof(float)); - float* buffer_view = reinterpret_cast<float*>(string_as_array(&buffer)); - - const int channels = source->channels(); - for (int ch = 0; ch < channels; ++ch) { - for (int si = 0, di = ch; si < source->frames(); ++si, di += channels) - buffer_view[di] = source->channel(ch)[si]; - } - - return buffer; -} - -void GetTokenParamsForLengths(const size_t token_lengths[2], - TokenParameters* params) { - params[0].length = token_lengths[0]; - params[1].length = token_lengths[1]; -} - -void IgnoreResult(bool success) {} - -} // namespace - -class ChromeWhispernetClientTest : public ExtensionBrowserTest, - public media::AudioConverter::InputCallback { - protected: - ChromeWhispernetClientTest() - : initialized_(false), - expected_audible_(false), - saved_samples_index_(0) {} - - ~ChromeWhispernetClientTest() override {} - - void InitializeWhispernet() { - std::unique_ptr<WhispernetClient> client( - new ChromeWhispernetClient(browser()->profile())); - client->Initialize(base::Bind( - &ChromeWhispernetClientTest::InitCallback, base::Unretained(this))); - - run_loop_.reset(new base::RunLoop()); - run_loop_->Run(); - EXPECT_TRUE(initialized_); - } - - // This needs to be called before any of the decoder tests are run. We can't - // run this code in the constructor or the SetUp methods because the audio - // manager seems to get initialized only *after* ExtensionBrowserTest::SetUp - // has finished executing. Setting up a testing AudioMager causes the actual - // create happening later in the browser initialization to fail. The only way - // around this at the moment seems to be to have this method called from - // every test before they try to decode. - void SetupDecode() { - // We get default parameters here instead of the constructor since - // initializing Whispernet also creates our AudioManager. Initializing from - // the test instead causes issues. - default_params_ = media::AudioManager::Get()->GetInputStreamParameters( - media::AudioDeviceDescription::kDefaultDeviceId); - - coder_params_ = media::AudioParameters( - default_params_.format(), audio_modem::kDefaultChannelLayout, - audio_modem::kDefaultSampleRate, audio_modem::kDefaultBitsPerSample, - default_params_.frames_per_buffer()); - - converter_.reset(new media::AudioConverter( - coder_params_, default_params_, - default_params_.sample_rate() == coder_params_.sample_rate())); - converter_->AddInput(this); - } - - void EncodeTokenAndSaveSamples(WhispernetClient* client, - bool audible, - const std::string& token, - const TokenParameters token_params[2]) { - run_loop_.reset(new base::RunLoop()); - client->RegisterSamplesCallback( - base::Bind(&ChromeWhispernetClientTest::SamplesCallback, - base::Unretained(this))); - expected_token_ = token; - expected_audible_ = audible; - - client->EncodeToken(token, audible ? AUDIBLE : INAUDIBLE, token_params); - run_loop_->Run(); - - EXPECT_GT(saved_samples_->frames(), 0); - } - - void DecodeSamplesAndVerifyToken(WhispernetClient* client, - bool expect_audible, - const std::string& expected_token, - const TokenParameters token_params[2]) { - run_loop_.reset(new base::RunLoop()); - client->RegisterTokensCallback(base::Bind( - &ChromeWhispernetClientTest::TokensCallback, base::Unretained(this))); - expected_token_ = expected_token; - expected_audible_ = expect_audible; - - ASSERT_GT(saved_samples_->frames(), 0); - - scoped_refptr<media::AudioBusRefCounted> samples_bus = - ConvertSavedSamplesToSystemParams(); - client->DecodeSamples(expect_audible ? AUDIBLE : INAUDIBLE, - AudioBusToString(samples_bus), token_params); - run_loop_->Run(); - } - - void InitCallback(bool success) { - EXPECT_TRUE(success); - initialized_ = true; - ASSERT_TRUE(run_loop_); - run_loop_->Quit(); - } - - void SamplesCallback( - audio_modem::AudioType type, - const std::string& token, - const scoped_refptr<media::AudioBusRefCounted>& samples) { - EXPECT_EQ(expected_token_, token); - EXPECT_EQ(expected_audible_, type == AUDIBLE); - saved_samples_ = samples; - ASSERT_TRUE(run_loop_); - run_loop_->Quit(); - } - - void TokensCallback(const std::vector<audio_modem::AudioToken>& tokens) { - ASSERT_TRUE(run_loop_); - run_loop_->Quit(); - - EXPECT_EQ(expected_token_, tokens[0].token); - EXPECT_EQ(expected_audible_, tokens[0].audible); - } - - private: - scoped_refptr<media::AudioBusRefCounted> ConvertSavedSamplesToSystemParams() { - int new_size = - saved_samples_->frames() * - std::ceil(static_cast<double>(default_params_.sample_rate()) / - coder_params_.sample_rate()); - new_size = - std::ceil(static_cast<double>(new_size) / converter_->ChunkSize()) * - converter_->ChunkSize(); - - scoped_refptr<media::AudioBusRefCounted> converted_samples = - media::AudioBusRefCounted::Create(default_params_.channels(), new_size); - - // Convert our single channel samples to two channel. Decode samples - // expects 2 channel data. - saved_samples_stereo_ = - media::AudioBusRefCounted::Create(2, saved_samples_->frames()); - memcpy(saved_samples_stereo_->channel(0), saved_samples_->channel(0), - sizeof(float) * saved_samples_->frames()); - memcpy(saved_samples_stereo_->channel(1), saved_samples_->channel(0), - sizeof(float) * saved_samples_->frames()); - - saved_samples_index_ = 0; - converter_->Convert(converted_samples.get()); - - return converted_samples; - } - - // AudioConverter::InputCallback overrides: - double ProvideInput(media::AudioBus* dest, - uint32_t /* frames_delayed */) override { - // Copy any saved samples we have to the output bus. - const int remaining_frames = - saved_samples_->frames() - saved_samples_index_; - const int frames_to_copy = std::min(remaining_frames, dest->frames()); - saved_samples_stereo_->CopyPartialFramesTo(saved_samples_index_, - frames_to_copy, 0, dest); - saved_samples_index_ += frames_to_copy; - - // Pad any remaining space with zeroes. - if (remaining_frames < dest->frames()) { - dest->ZeroFramesPartial(remaining_frames, - dest->frames() - remaining_frames); - } - - // Return the volume level. - return 1.0; - } - - std::unique_ptr<base::RunLoop> run_loop_; - bool initialized_; - - std::string expected_token_; - bool expected_audible_; - - scoped_refptr<media::AudioBusRefCounted> saved_samples_; - scoped_refptr<media::AudioBusRefCounted> saved_samples_stereo_; - int saved_samples_index_; - - std::unique_ptr<media::AudioConverter> converter_; - - media::AudioParameters default_params_; - media::AudioParameters coder_params_; - - DISALLOW_COPY_AND_ASSIGN(ChromeWhispernetClientTest); -}; - -// These tests are irrelevant if NACL is disabled. See crbug.com/449198. -#if defined(DISABLE_NACL) -#define MAYBE_Initialize DISABLED_Initialize -#define MAYBE_EncodeAndDecode DISABLED_EncodeAndDecode -#define MAYBE_TokenLengths DISABLED_TokenLengths -#define MAYBE_Crc DISABLED_Crc -#define MAYBE_Parity DISABLED_Parity -#else -#define MAYBE_Initialize Initialize -#define MAYBE_EncodeAndDecode EncodeAndDecode -#define MAYBE_TokenLengths TokenLengths -#define MAYBE_Crc Crc -#define MAYBE_Parity Parity -#endif - -// This test trips up ASAN on ChromeOS. See: -// https://code.google.com/p/address-sanitizer/issues/detail?id=189 -#if defined(DISABLE_NACL) || defined(OS_CHROMEOS) -#define MAYBE_MultipleClients DISABLED_MultipleClients -#else -#define MAYBE_MultipleClients MultipleClients -#endif - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_Initialize) { - InitializeWhispernet(); -} - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_EncodeAndDecode) { - std::unique_ptr<WhispernetClient> client( - new ChromeWhispernetClient(browser()->profile())); - client->Initialize(base::Bind(&IgnoreResult)); - SetupDecode(); - - TokenParameters token_params[2]; - GetTokenParamsForLengths(kTokenLengths, token_params); - - EncodeTokenAndSaveSamples(client.get(), true, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), true, kSixZeros, token_params); - - EncodeTokenAndSaveSamples(client.get(), false, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), false, kSixZeros, token_params); -} - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_TokenLengths) { - std::unique_ptr<WhispernetClient> client( - new ChromeWhispernetClient(browser()->profile())); - client->Initialize(base::Bind(&IgnoreResult)); - SetupDecode(); - - const size_t kLongTokenLengths[2] = {8, 9}; - TokenParameters token_params[2]; - GetTokenParamsForLengths(kLongTokenLengths, token_params); - - EncodeTokenAndSaveSamples(client.get(), true, kEightZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), true, kEightZeros, token_params); - - EncodeTokenAndSaveSamples(client.get(), false, kNineZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), false, kNineZeros, token_params); -} - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_Crc) { - std::unique_ptr<WhispernetClient> client( - new ChromeWhispernetClient(browser()->profile())); - client->Initialize(base::Bind(&IgnoreResult)); - SetupDecode(); - - TokenParameters token_params[2]; - GetTokenParamsForLengths(kTokenLengths, token_params); - token_params[0].crc = true; - token_params[1].crc = true; - - EncodeTokenAndSaveSamples(client.get(), true, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), true, kSixZeros, token_params); - - EncodeTokenAndSaveSamples(client.get(), false, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), false, kSixZeros, token_params); -} - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_Parity) { - std::unique_ptr<WhispernetClient> client( - new ChromeWhispernetClient(browser()->profile())); - client->Initialize(base::Bind(&IgnoreResult)); - SetupDecode(); - - TokenParameters token_params[2]; - GetTokenParamsForLengths(kTokenLengths, token_params); - token_params[0].parity = false; - token_params[1].parity = false; - - EncodeTokenAndSaveSamples(client.get(), true, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), true, kSixZeros, token_params); - - EncodeTokenAndSaveSamples(client.get(), false, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client.get(), false, kSixZeros, token_params); -} - -IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_MultipleClients) { - std::unique_ptr<WhispernetClient> client_1( - new ChromeWhispernetClient(browser()->profile())); - std::unique_ptr<WhispernetClient> client_2( - new ChromeWhispernetClient(browser()->profile())); - std::unique_ptr<WhispernetClient> client_3( - new ChromeWhispernetClient(browser()->profile())); - SetupDecode(); - - TokenParameters token_params[2]; - GetTokenParamsForLengths(kTokenLengths, token_params); - - // Test concurrent initialization. - client_1->Initialize(base::Bind(&IgnoreResult)); - client_2->Initialize(base::Bind(&IgnoreResult)); - - EncodeTokenAndSaveSamples(client_1.get(), true, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client_1.get(), true, kSixZeros, token_params); - - EncodeTokenAndSaveSamples(client_2.get(), false, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client_2.get(), false, kSixZeros, token_params); - - // Test sequential initialization. - client_3->Initialize(base::Bind(&IgnoreResult)); - - EncodeTokenAndSaveSamples(client_3.get(), true, kSixZeros, token_params); - DecodeSamplesAndVerifyToken(client_3.get(), true, kSixZeros, token_params); - - const size_t kLongTokenLengths[2] = {8, 9}; - GetTokenParamsForLengths(kLongTokenLengths, token_params); - - EncodeTokenAndSaveSamples(client_2.get(), true, kEightZeros, token_params); - DecodeSamplesAndVerifyToken(client_2.get(), true, kEightZeros, token_params); -}
diff --git a/chrome/browser/copresence/chrome_whispernet_config.h b/chrome/browser/copresence/chrome_whispernet_config.h deleted file mode 100644 index bc36967c..0000000 --- a/chrome/browser/copresence/chrome_whispernet_config.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CONFIG_H_ -#define CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CONFIG_H_ - -#include <stdint.h> - -// Shared structs with whispernet. TODO(rkc): These will be removed once we can -// get protobufs working with Nacl. At that point, we'll just pass in -// config_data.proto to the whispernet nacl wrapper directly. - -// We will be using fixed types in all these structures since they will be -// stuffed into a string and then read on the other side via a completely -// different toolchain. - -struct AudioDsssParams { - int64_t include_parity_symbol; - int64_t use_single_sideband; - double desired_carrier_frequency; - int64_t use_crc_16; - double coder_sample_rate; - double recording_sample_rate; - int64_t bits_per_symbol; - int64_t min_cycles_per_frame; - int64_t baseband_decimation_factor; - int64_t upsampling_factor; - int64_t num_repetitions_to_play; -}; - -struct AdsrParams { - int64_t attack_time_millis; - int64_t decay_time_millis; - int64_t sustain_time_millis; - int64_t release_time_millis; - double sustain_amplitude; -}; - -struct AudioDtmfParams { - int64_t include_parity_symbol; - int64_t use_crc_16; - double coder_sample_rate; - double recording_sample_rate; - int64_t baseband_decimation_factor; - int64_t frequencies_per_symbol; - int64_t window_duration_millis; - AdsrParams adsr_params; - int64_t num_repetitions_to_play; -}; - -struct LoggerParam { - int64_t clear_cached_request_duration_millis; - int64_t request_buffer_limit; -}; - -struct AudioParamData { - LoggerParam logger; - AudioDsssParams audio_dsss; - AudioDtmfParams audio_dtmf; - int64_t recording_channels; -}; - -#endif // CHROME_BROWSER_COPRESENCE_CHROME_WHISPERNET_CONFIG_H_
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index a57e40f..08bf9ded 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -46,7 +46,6 @@ "//chrome/common/extensions/api:api_registration", "//chrome/common/safe_browsing:proto", "//chrome/installer/util:with_no_strings", - "//components/audio_modem", "//components/data_reduction_proxy/proto:data_reduction_proxy_proto", "//components/dom_distiller/core", "//components/onc",
diff --git a/chrome/browser/extensions/api/audio_modem/OWNERS b/chrome/browser/extensions/api/audio_modem/OWNERS deleted file mode 100644 index 9364bf7..0000000 --- a/chrome/browser/extensions/api/audio_modem/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -ckehoe@chromium.org -rkc@chromium.org
diff --git a/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc b/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc deleted file mode 100644 index 65a90d5..0000000 --- a/chrome/browser/extensions/api/audio_modem/audio_modem_api.cc +++ /dev/null
@@ -1,366 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/audio_modem/audio_modem_api.h" - -#include <stdint.h> - -#include <map> -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/base64.h" -#include "base/bind.h" -#include "base/guid.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/strings/string_util.h" -#include "base/timer/timer.h" -#include "chrome/browser/copresence/chrome_whispernet_client.h" -#include "chrome/common/extensions/api/audio_modem.h" -#include "extensions/browser/event_router.h" - -// TODO(ckehoe): Implement transmit fail checking. - -namespace extensions { - -using api::audio_modem::AUDIOBAND_AUDIBLE; -using api::audio_modem::AUDIOBAND_INAUDIBLE; -using api::audio_modem::Audioband; -using api::audio_modem::STATUS_CODERERROR; -using api::audio_modem::STATUS_INUSE; -using api::audio_modem::STATUS_INVALIDREQUEST; -using api::audio_modem::STATUS_SUCCESS; -using api::audio_modem::ReceivedToken; -using api::audio_modem::RequestParams; -using api::audio_modem::Status; - -namespace Transmit = api::audio_modem::Transmit; -namespace StopTransmit = api::audio_modem::StopTransmit; -namespace Receive = api::audio_modem::Receive; -namespace StopReceive = api::audio_modem::StopReceive; -namespace OnReceived = api::audio_modem::OnReceived; - -using audio_modem::AUDIBLE; -using audio_modem::AudioToken; -using audio_modem::AudioType; -using audio_modem::INAUDIBLE; -using audio_modem::TokenParameters; - -namespace { - -const char kInitFailedError[] = "The audio modem is not available. " - "Failed to initialize the token encoder/decoder."; -const char kInvalidTokenLengthError[] = - "The token length must be greater than zero."; -const char kIncorrectTokenLengthError[] = - "The token provided did not match the declared token length."; -const char kInvalidTimeoutError[] = - "Transmit and receive timeouts must be greater than zero."; - -const int kMaxTransmitTimeout = 10 * 60 * 1000; // 10 minutes -const int kMaxReceiveTimeout = 60 * 60 * 1000; // 1 hour - -base::LazyInstance<BrowserContextKeyedAPIFactory<AudioModemAPI>> - g_factory = LAZY_INSTANCE_INITIALIZER; - -AudioType AudioTypeForBand(Audioband band) { - switch (band) { - case AUDIOBAND_AUDIBLE: - return AUDIBLE; - case AUDIOBAND_INAUDIBLE: - return INAUDIBLE; - default: - NOTREACHED(); - return audio_modem::AUDIO_TYPE_UNKNOWN; - } -} - -TokenParameters TokenParamsForEncoding( - const api::audio_modem::TokenEncoding& encoding) { - return TokenParameters(encoding.token_length, - encoding.crc ? *encoding.crc : false, - encoding.parity ? *encoding.parity : true); -} - -const std::string DecodeBase64Token(std::string encoded_token) { - // Make sure the token is padded correctly. - while (encoded_token.size() % 4 > 0) - encoded_token += "="; - - // Decode and return the token. - std::string raw_token; - bool decode_success = base::Base64Decode(encoded_token, &raw_token); - DCHECK(decode_success); - return raw_token; -} - -} // namespace - - -// Public functions. - -AudioModemAPI::AudioModemAPI(content::BrowserContext* context) - : AudioModemAPI(context, - base::WrapUnique(new ChromeWhispernetClient(context)), - audio_modem::Modem::Create()) {} - -AudioModemAPI::AudioModemAPI( - content::BrowserContext* context, - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client, - std::unique_ptr<audio_modem::Modem> modem) - : browser_context_(context), - whispernet_client_(std::move(whispernet_client)), - modem_(std::move(modem)), - init_failed_(false) { - // We own these objects, so these callbacks will not outlive us. - whispernet_client_->Initialize( - base::Bind(&AudioModemAPI::WhispernetInitComplete, - base::Unretained(this))); - modem_->Initialize(whispernet_client_.get(), - base::Bind(&AudioModemAPI::TokensReceived, - base::Unretained(this))); -} - -AudioModemAPI::~AudioModemAPI() { - for (const auto& timer_entry : receive_timers_[0]) - delete timer_entry.second; - for (const auto& timer_entry : receive_timers_[1]) - delete timer_entry.second; -} - -Status AudioModemAPI::StartTransmit(const std::string& app_id, - const RequestParams& params, - const std::string& token) { - AudioType audio_type = AudioTypeForBand(params.band); - if (transmitters_[audio_type].empty()) - transmitters_[audio_type] = app_id; - else if (transmitters_[audio_type] != app_id) - return STATUS_INUSE; - - DVLOG(3) << "Starting transmit for app " << app_id; - - std::string encoded_token; - base::Base64Encode(token, &encoded_token); - base::RemoveChars(encoded_token, "=", &encoded_token); - - modem_->SetTokenParams(audio_type, TokenParamsForEncoding(params.encoding)); - modem_->SetToken(audio_type, encoded_token); - modem_->StartPlaying(audio_type); - - transmit_timers_[audio_type].Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(params.timeout_millis), - base::Bind(base::IgnoreResult(&AudioModemAPI::StopTransmit), - base::Unretained(this), - app_id, - audio_type)); - return STATUS_SUCCESS; -} - -Status AudioModemAPI::StopTransmit(const std::string& app_id, - AudioType audio_type) { - if (transmitters_[audio_type] != app_id) - return STATUS_INVALIDREQUEST; - - DVLOG(3) << "Stopping transmit for app " << app_id; - transmitters_[audio_type].clear(); - modem_->StopPlaying(audio_type); - return STATUS_SUCCESS; -} - -void AudioModemAPI::StartReceive(const std::string& app_id, - const RequestParams& params) { - DVLOG(3) << "Starting receive for app " << app_id; - - AudioType audio_type = AudioTypeForBand(params.band); - modem_->SetTokenParams(audio_type, TokenParamsForEncoding(params.encoding)); - modem_->StartRecording(audio_type); - - if (receive_timers_[audio_type].count(app_id) == 0) - receive_timers_[audio_type][app_id] = new base::OneShotTimer; - DCHECK(receive_timers_[audio_type][app_id]); - receive_timers_[audio_type][app_id]->Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(params.timeout_millis), - base::Bind(base::IgnoreResult(&AudioModemAPI::StopReceive), - base::Unretained(this), - app_id, - audio_type)); -} - -Status AudioModemAPI::StopReceive(const std::string& app_id, - AudioType audio_type) { - if (receive_timers_[audio_type].count(app_id) == 0) - return STATUS_INVALIDREQUEST; - - DCHECK(receive_timers_[audio_type][app_id]); - delete receive_timers_[audio_type][app_id]; - receive_timers_[audio_type].erase(app_id); - - DVLOG(3) << "Stopping receive for app " << app_id; - if (receive_timers_[audio_type].empty()) - modem_->StopRecording(audio_type); - return STATUS_SUCCESS; -} - -// static -BrowserContextKeyedAPIFactory<AudioModemAPI>* -AudioModemAPI::GetFactoryInstance() { - return g_factory.Pointer(); -} - - -// Private functions. - -void AudioModemAPI::WhispernetInitComplete(bool success) { - if (success) { - VLOG(2) << "Whispernet initialized successfully."; - } else { - LOG(ERROR) << "Failed to initialize Whispernet!"; - init_failed_ = true; - } -} - -void AudioModemAPI::TokensReceived(const std::vector<AudioToken>& tokens) { - // Distribute the tokens to the appropriate app(s). - std::list<ReceivedToken> all_tokens; - std::map<std::string, std::vector<ReceivedToken*>> tokens_by_app; - for (const AudioToken& token : tokens) { - ReceivedToken api_token; - const std::string& raw_token = DecodeBase64Token(token.token); - api_token.token.assign(raw_token.c_str(), - raw_token.c_str() + raw_token.size()); - api_token.band = token.audible ? AUDIOBAND_AUDIBLE : AUDIOBAND_INAUDIBLE; - all_tokens.push_back(std::move(api_token)); - for (const auto& receiver : - receive_timers_[token.audible ? AUDIBLE : INAUDIBLE]) { - tokens_by_app[receiver.first].push_back(&all_tokens.back()); - } - } - - // Send events to the appropriate app(s). - for (const auto& app_entry : tokens_by_app) { - const std::string& app_id = app_entry.first; - const auto& app_tokens = app_entry.second; - if (app_id.empty()) - continue; - - // Construct the event arguments by hand because a given token can be - // present for multiple listeners, so constructing a - // std::vector<ReceivedToken> for each is inefficient. - std::unique_ptr<base::ListValue> tokens_value(new base::ListValue()); - for (const ReceivedToken* token : app_tokens) - tokens_value->Append(token->ToValue()); - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(std::move(tokens_value)); - - EventRouter::Get(browser_context_) - ->DispatchEventToExtension( - app_id, base::WrapUnique(new Event(events::AUDIO_MODEM_ON_RECEIVED, - OnReceived::kEventName, - std::move(args)))); - } -} - - -// Functions outside the API scope. - -template <> -void -BrowserContextKeyedAPIFactory<AudioModemAPI>::DeclareFactoryDependencies() { - DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -} - -ExtensionFunction::ResponseAction AudioModemTransmitFunction::Run() { - std::unique_ptr<Transmit::Params> params(Transmit::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - AudioModemAPI* api = - AudioModemAPI::GetFactoryInstance()->Get(browser_context()); - if (api->init_failed()) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_CODERERROR), - kInitFailedError)); - } - - // Check the token length. - int token_length = params->params.encoding.token_length; - if (token_length <= 0) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTokenLengthError)); - } - const char* token = params->token.data(); - std::string token_str(token, params->token.size()); - if (static_cast<int>(token_str.size()) != token_length) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kIncorrectTokenLengthError)); - } - - // Check the timeout. - int64_t timeout_millis = params->params.timeout_millis; - if (timeout_millis <= 0) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTimeoutError)); - } - if (timeout_millis > kMaxTransmitTimeout) - timeout_millis = kMaxTransmitTimeout; - - // Start transmission. - Status status = api->StartTransmit(extension_id(), params->params, token_str); - return RespondNow(ArgumentList(Transmit::Results::Create(status))); -} - -ExtensionFunction::ResponseAction AudioModemStopTransmitFunction::Run() { - std::unique_ptr<StopTransmit::Params> params( - StopTransmit::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - Status status = AudioModemAPI::GetFactoryInstance()->Get(browser_context()) - ->StopTransmit(extension_id(), AudioTypeForBand(params->band)); - return RespondNow(ArgumentList(StopTransmit::Results::Create(status))); -} - -ExtensionFunction::ResponseAction AudioModemReceiveFunction::Run() { - std::unique_ptr<Receive::Params> params(Receive::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - AudioModemAPI* api = - AudioModemAPI::GetFactoryInstance()->Get(browser_context()); - if (api->init_failed()) { - return RespondNow(ErrorWithArguments( - Transmit::Results::Create(STATUS_CODERERROR), - kInitFailedError)); - } - - // Check the timeout. - int64_t timeout_millis = params->params.timeout_millis; - if (timeout_millis <= 0) { - return RespondNow(ErrorWithArguments( - Receive::Results::Create(STATUS_INVALIDREQUEST), - kInvalidTimeoutError)); - } - if (timeout_millis > kMaxReceiveTimeout) - timeout_millis = kMaxReceiveTimeout; - - // Start receiving. - api->StartReceive(extension_id(), params->params); - return RespondNow(ArgumentList(Receive::Results::Create(STATUS_SUCCESS))); -} - -ExtensionFunction::ResponseAction AudioModemStopReceiveFunction::Run() { - std::unique_ptr<StopReceive::Params> params( - StopReceive::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - Status status = AudioModemAPI::GetFactoryInstance()->Get(browser_context()) - ->StopReceive(extension_id(), AudioTypeForBand(params->band)); - return RespondNow(ArgumentList(StopReceive::Results::Create(status))); -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/audio_modem/audio_modem_api.h b/chrome/browser/extensions/api/audio_modem/audio_modem_api.h deleted file mode 100644 index 557e606..0000000 --- a/chrome/browser/extensions/api/audio_modem/audio_modem_api.h +++ /dev/null
@@ -1,133 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_ - -#include <map> -#include <memory> -#include <string> -#include <vector> - -#include "base/macros.h" -#include "chrome/common/extensions/api/audio_modem.h" -#include "components/audio_modem/public/modem.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace extensions { - -// Implementation of the chrome.audioModem API. -class AudioModemAPI final : public BrowserContextKeyedAPI { - public: - // Default constructor. - explicit AudioModemAPI(content::BrowserContext* context); - - // Testing constructor: pass in dependencies. - AudioModemAPI( - content::BrowserContext* context, - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client, - std::unique_ptr<audio_modem::Modem> modem); - - ~AudioModemAPI() override; - - // Starts transmitting a token, and returns the associated API status. - // Fails if another app is already transmitting the same AudioType. - api::audio_modem::Status StartTransmit( - const std::string& app_id, - const api::audio_modem::RequestParams& params, - const std::string& token); - - // Stops an in-progress transmit, and returns the associated API status. - // Fails if the specified app is not currently transmitting. - api::audio_modem::Status StopTransmit(const std::string& app_id, - audio_modem::AudioType audio_type); - - // Starts receiving for the specified app. - // Multiple apps may receive the same AudioType simultaneously. - void StartReceive(const std::string& app_id, - const api::audio_modem::RequestParams& params); - - // Stops receiving for the specified app, and returns the associated - // API status. Fails if that app is not currently receiving. - api::audio_modem::Status StopReceive(const std::string& app_id, - audio_modem::AudioType audio_type); - - bool init_failed() const { return init_failed_; } - - // BrowserContextKeyedAPI implementation. - static BrowserContextKeyedAPIFactory<AudioModemAPI>* GetFactoryInstance(); - - private: - friend class BrowserContextKeyedAPIFactory<AudioModemAPI>; - - void WhispernetInitComplete(bool success); - void TokensReceived(const std::vector<audio_modem::AudioToken>& tokens); - - content::BrowserContext* const browser_context_; - std::unique_ptr<audio_modem::WhispernetClient> whispernet_client_; - std::unique_ptr<audio_modem::Modem> modem_; - bool init_failed_; - - // IDs for the currently transmitting app (if any), indexed by AudioType. - std::string transmitters_[2]; - - // Timeouts for the currently active transmits, indexed by AudioType. - base::OneShotTimer transmit_timers_[2]; - - // Maps of currently receiving app ID => timeouts. Indexed by AudioType. - // We own all of these pointers. Do not remove them without calling delete. - std::map<std::string, base::OneShotTimer*> receive_timers_[2]; - - // BrowserContextKeyedAPI implementation. - static const bool kServiceIsCreatedWithBrowserContext = false; - static const char* service_name() { return "AudioModemAPI"; } - - DISALLOW_COPY_AND_ASSIGN(AudioModemAPI); -}; - -template<> -void BrowserContextKeyedAPIFactory<AudioModemAPI>::DeclareFactoryDependencies(); - -class AudioModemTransmitFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.transmit", AUDIOMODEM_TRANSMIT); - - protected: - ~AudioModemTransmitFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemStopTransmitFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.stopTransmit", - AUDIOMODEM_STOPTRANSMIT); - - protected: - ~AudioModemStopTransmitFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemReceiveFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.receive", AUDIOMODEM_RECEIVE); - - protected: - ~AudioModemReceiveFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class AudioModemStopReceiveFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("audioModem.stopReceive", AUDIOMODEM_STOPRECEIVE); - - protected: - ~AudioModemStopReceiveFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_AUDIO_MODEM_AUDIO_MODEM_API_H_
diff --git a/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc b/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc deleted file mode 100644 index 22daaff..0000000 --- a/chrome/browser/extensions/api/audio_modem/audio_modem_api_unittest.cc +++ /dev/null
@@ -1,395 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/audio_modem/audio_modem_api.h" - -#include <map> -#include <memory> -#include <string> -#include <utility> -#include <vector> - -#include "base/callback.h" -#include "base/memory/ptr_util.h" -#include "base/memory/ref_counted.h" -#include "base/values.h" -#include "chrome/browser/extensions/extension_api_unittest.h" -#include "chrome/browser/extensions/extension_function_test_utils.h" -#include "chrome/browser/extensions/test_extension_system.h" -#include "components/audio_modem/public/modem.h" -#include "components/audio_modem/test/stub_modem.h" -#include "components/audio_modem/test/stub_whispernet_client.h" -#include "extensions/browser/api_test_utils.h" -#include "extensions/browser/event_router.h" -#include "extensions/browser/event_router_factory.h" - -using audio_modem::AUDIBLE; -using audio_modem::AudioToken; -using audio_modem::INAUDIBLE; -using audio_modem::StubModem; -using audio_modem::StubWhispernetClient; - -using base::BinaryValue; -using base::DictionaryValue; -using base::ListValue; -using base::StringValue; -using base::Value; - -using content::BrowserContext; - -namespace ext_test_utils = extension_function_test_utils; - -namespace extensions { - -namespace { - -// The TestingFactoryFunction uses a BrowserContext as its context pointer. -// But each BrowserContext is still associated with a unit test. -// So we store the StubModem created in each test. -std::map<BrowserContext*, StubModem*> g_modems; - -// Create a test AudioModemAPI and store the modem it uses. -std::unique_ptr<KeyedService> ApiFactoryFunction(BrowserContext* context) { - StubModem* modem = new StubModem; - g_modems[context] = modem; - return base::WrapUnique(new AudioModemAPI( - context, - base::WrapUnique<audio_modem::WhispernetClient>(new StubWhispernetClient), - base::WrapUnique<audio_modem::Modem>(modem))); -} - -std::unique_ptr<DictionaryValue> CreateParams(const std::string& audio_band) { - std::unique_ptr<DictionaryValue> params(new DictionaryValue); - params->SetInteger("timeoutMillis", 60000); - params->SetString("band", audio_band); - params->SetInteger("encoding.tokenLength", 4); - return params; -} - -std::unique_ptr<BinaryValue> CreateToken(const std::string& token) { - return BinaryValue::CreateWithCopiedBuffer(token.c_str(), token.size()); -} - -std::unique_ptr<ListValue> CreateList(std::unique_ptr<Value> single_elt) { - std::unique_ptr<ListValue> list(new ListValue); - list->Append(std::move(single_elt)); - return list; -} - -std::unique_ptr<ListValue> CreateList(std::unique_ptr<Value> elt1, - std::unique_ptr<Value> elt2) { - std::unique_ptr<ListValue> list(new ListValue); - list->Append(std::move(elt1)); - list->Append(std::move(elt2)); - return list; -} - -DictionaryValue* CreateReceivedToken(const std::string& token, - const std::string& audio_band) { - DictionaryValue* out = new DictionaryValue; - out->Set("token", CreateToken(token)); - out->SetString("band", audio_band); - return out; -} - -bool ReceivedSingleToken(const Event* event, - const DictionaryValue* expected_token) { - ListValue* received_tokens; - event->event_args->GetList(0, &received_tokens); - if (received_tokens->GetSize() != 1) - return false; - - DictionaryValue* received_token; - received_tokens->GetDictionary(0, &received_token); - return received_token->Equals(expected_token); -} - -// TODO(ckehoe): Put this in //extensions/test. -// Then replace the other EventRouter mocks. -class StubEventRouter : public EventRouter { - public: - // Callback to receive events. First argument is - // the extension id to receive the event. - using EventCallback = - base::Callback<void(const std::string&, std::unique_ptr<Event>)>; - - explicit StubEventRouter(BrowserContext* context) - : EventRouter(context, nullptr) {} - - void DispatchEventToExtension(const std::string& extension_id, - std::unique_ptr<Event> event) override { - event_callback_.Run(extension_id, std::move(event)); - } - - void SetEventCallBack(EventCallback event_callback) { - event_callback_ = event_callback; - } - - void ClearEventCallback() { - event_callback_.Reset(); - } - - private: - EventCallback event_callback_; -}; - -// StubEventRouter factory function -std::unique_ptr<KeyedService> StubEventRouterFactoryFunction( - content::BrowserContext* context) { - return base::WrapUnique(new StubEventRouter(context)); -} - -} // namespace - -class AudioModemApiUnittest : public ExtensionApiUnittest { - public: - AudioModemApiUnittest() {} - ~AudioModemApiUnittest() override {} - - protected: - template <typename Function> - const std::string RunFunction(std::unique_ptr<ListValue> args, - const Extension* extension) { - scoped_refptr<UIThreadExtensionFunction> function(new Function); - function->set_extension(extension); - function->set_browser_context(profile()); - function->set_has_callback(true); - ext_test_utils::RunFunction(function.get(), std::move(args), browser(), - ext_test_utils::NONE); - - std::string result_status; - CHECK(function->GetResultList()->GetString(0, &result_status)); - return result_status; - } - - template <typename Function> - const std::string RunFunction(std::unique_ptr<ListValue> args) { - return RunFunction<Function>(std::move(args), GetExtension(std::string())); - } - - StubModem* GetModem() const { - return g_modems[profile()]; - } - - const Extension* GetExtension(const std::string& name) { - if (!extensions_by_name_[name].get()) { - std::unique_ptr<DictionaryValue> extension_definition( - new DictionaryValue); - extension_definition->SetString("name", name); - extension_definition->SetString("version", "1.0"); - extensions_by_name_[name] = api_test_utils::CreateExtension( - Manifest::INTERNAL, extension_definition.get(), name); - DVLOG(2) << "Created extension " << extensions_by_name_[name]->id(); - } - return extensions_by_name_[name].get(); - } - - const std::vector<std::unique_ptr<const Event>>& GetEventsForExtension( - const std::string& name) { - const Extension* extension = extensions_by_name_[name].get(); - DCHECK(extension); - return events_by_extension_id_[extension->id()]; - } - - const std::vector<std::unique_ptr<const Event>>& GetEvents() { - return GetEventsForExtension(std::string()); - } - - private: - void SetUp() override { - ExtensionApiUnittest::SetUp(); - AudioModemAPI::GetFactoryInstance()->SetTestingFactory( - profile(), &ApiFactoryFunction); - - StubEventRouter* stub_event_router = static_cast<StubEventRouter*>( - extensions::EventRouterFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), &StubEventRouterFactoryFunction)); - stub_event_router->SetEventCallBack(base::Bind( - &AudioModemApiUnittest::CaptureEvent, base::Unretained(this))); - } - - void CaptureEvent(const std::string& extension_id, - std::unique_ptr<Event> event) { - events_by_extension_id_[extension_id].push_back(std::move(event)); - } - - std::map<std::string, scoped_refptr<Extension>> extensions_by_name_; - - std::map<std::string, std::vector<std::unique_ptr<const Event>>> - events_by_extension_id_; -}; - -TEST_F(AudioModemApiUnittest, TransmitBasic) { - // Start transmitting inaudibly. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("1234")))); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // Can't cancel audible transmit - we haven't started it yet. - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")))); - - // Start transmitting audibly. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("ABCD")))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // Stop audible transmit. We're still transmitting inaudibly. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>(CreateList( - base::MakeUnique<StringValue>("audible")))); - EXPECT_FALSE(GetModem()->IsPlaying(AUDIBLE)); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // Stop inaudible transmit. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>(CreateList( - base::MakeUnique<StringValue>("inaudible")))); - EXPECT_FALSE(GetModem()->IsPlaying(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, ReceiveBasic) { - // Start listening for audible tokens. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("audible")))); - EXPECT_TRUE(GetModem()->IsRecording(AUDIBLE)); - - // Can't cancel inaudible receive - we haven't started it yet. - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")))); - - // Send some audible tokens. - std::vector<AudioToken> tokens; - tokens.push_back(AudioToken("1234", true)); - tokens.push_back(AudioToken("ABCD", true)); - tokens.push_back(AudioToken("abcd", false)); - GetModem()->DeliverTokens(tokens); - - // Check the tokens received. - EXPECT_EQ(1u, GetEvents().size()); - std::unique_ptr<ListValue> expected_tokens(new ListValue); - expected_tokens->Append(CreateReceivedToken("1234", "audible")); - expected_tokens->Append(CreateReceivedToken("ABCD", "audible")); - ListValue* received_tokens; - GetEvents()[0]->event_args->GetList(0, &received_tokens); - EXPECT_TRUE(received_tokens->Equals(expected_tokens.get())); - - // Start listening for inaudible tokens. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Send some more tokens. - tokens.push_back(AudioToken("5678", false)); - GetModem()->DeliverTokens(tokens); - - // Check the tokens received. - EXPECT_EQ(2u, GetEvents().size()); - expected_tokens->Append(CreateReceivedToken("abcd", "inaudible")); - expected_tokens->Append(CreateReceivedToken("5678", "inaudible")); - GetEvents()[1]->event_args->GetList(0, &received_tokens); - EXPECT_TRUE(received_tokens->Equals(expected_tokens.get())); - - // Stop audible receive. We're still receiving inaudible. - EXPECT_EQ("success", RunFunction<AudioModemStopReceiveFunction>(CreateList( - base::MakeUnique<StringValue>("audible")))); - EXPECT_FALSE(GetModem()->IsRecording(AUDIBLE)); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Stop inaudible receive. - EXPECT_EQ("success", RunFunction<AudioModemStopReceiveFunction>(CreateList( - base::MakeUnique<StringValue>("inaudible")))); - EXPECT_FALSE(GetModem()->IsRecording(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, TransmitMultiple) { - // Start transmit. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("1234")), - GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // Another extension can't interfere with the first one. - EXPECT_EQ("inUse", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("ABCD")), - GetExtension("ext2"))); - EXPECT_EQ("invalidRequest", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")), - GetExtension("ext2"))); - EXPECT_TRUE(GetModem()->IsPlaying(AUDIBLE)); - - // The other extension can use the other audio band, however. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("ABCD")), - GetExtension("ext2"))); - EXPECT_TRUE(GetModem()->IsPlaying(INAUDIBLE)); - - // The first extension can change its token. - // But the other band is still in use. - EXPECT_EQ("success", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("audible"), CreateToken("abcd")), - GetExtension("ext1"))); - EXPECT_EQ("inUse", RunFunction<AudioModemTransmitFunction>( - CreateList(CreateParams("inaudible"), CreateToken("1234")), - GetExtension("ext1"))); - - // Stop transmission. - EXPECT_EQ("success", RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("audible")), - GetExtension("ext1"))); - EXPECT_FALSE(GetModem()->IsPlaying(AUDIBLE)); - EXPECT_EQ("success", - RunFunction<AudioModemStopTransmitFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext2"))); - EXPECT_FALSE(GetModem()->IsPlaying(INAUDIBLE)); -} - -TEST_F(AudioModemApiUnittest, ReceiveMultiple) { - // Start receive. Multiple extensions can receive on the same band. - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")), GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - EXPECT_EQ("success", RunFunction<AudioModemReceiveFunction>( - CreateList(CreateParams("inaudible")), GetExtension("ext2"))); - - // Receive a token. - GetModem()->DeliverTokens(std::vector<AudioToken>( - 1, AudioToken("abcd", false))); - EXPECT_EQ(1u, GetEventsForExtension("ext1").size()); - EXPECT_EQ(1u, GetEventsForExtension("ext2").size()); - - // Check the token received. - std::unique_ptr<DictionaryValue> expected_token( - CreateReceivedToken("abcd", "inaudible")); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext1")[0].get(), - expected_token.get())); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext2")[0].get(), - expected_token.get())); - - // If one extension stops, the modem is still receiving for the other. - EXPECT_EQ("success", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext1"))); - EXPECT_TRUE(GetModem()->IsRecording(INAUDIBLE)); - - // Receive another token. Should only go to ext2. - GetModem()->DeliverTokens(std::vector<AudioToken>( - 1, AudioToken("1234", false))); - EXPECT_EQ(1u, GetEventsForExtension("ext1").size()); - EXPECT_EQ(2u, GetEventsForExtension("ext2").size()); - expected_token.reset(CreateReceivedToken("1234", "inaudible")); - EXPECT_TRUE(ReceivedSingleToken(GetEventsForExtension("ext2")[1].get(), - expected_token.get())); - - EXPECT_EQ("success", - RunFunction<AudioModemStopReceiveFunction>( - CreateList(base::MakeUnique<StringValue>("inaudible")), - GetExtension("ext2"))); - EXPECT_FALSE(GetModem()->IsRecording(INAUDIBLE)); -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/copresence_private/OWNERS b/chrome/browser/extensions/api/copresence_private/OWNERS deleted file mode 100644 index 5f781a6..0000000 --- a/chrome/browser/extensions/api/copresence_private/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -rkc@chromium.org -ckehoe@chromium.org
diff --git a/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc b/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc deleted file mode 100644 index 4bdaf0f..0000000 --- a/chrome/browser/extensions/api/copresence_private/copresence_private_api.cc +++ /dev/null
@@ -1,150 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/copresence_private/copresence_private_api.h" - -#include <stddef.h> - -#include <map> -#include <string> -#include <vector> - -#include "base/guid.h" -#include "base/lazy_instance.h" -#include "chrome/browser/copresence/chrome_whispernet_client.h" -#include "chrome/common/extensions/api/copresence_private.h" -#include "content/public/browser/browser_thread.h" -#include "media/base/audio_bus.h" - -using audio_modem::WhispernetClient; -using content::BrowserThread; - -namespace extensions { - -namespace SendFound = api::copresence_private::SendFound; -namespace SendSamples = api::copresence_private::SendSamples; -namespace SendInitialized = api::copresence_private::SendInitialized; - -namespace { - -base::LazyInstance<BrowserContextKeyedAPIFactory<CopresencePrivateService>> - g_factory = LAZY_INSTANCE_INITIALIZER; - -void RunInitCallback(WhispernetClient* client, bool status) { - DCHECK(client); - audio_modem::SuccessCallback init_callback = - client->GetInitializedCallback(); - if (!init_callback.is_null()) - init_callback.Run(status); -} - -} // namespace - -CopresencePrivateService::CopresencePrivateService( - content::BrowserContext* context) - : initialized_(false) {} - -CopresencePrivateService::~CopresencePrivateService() {} - -const std::string CopresencePrivateService::RegisterWhispernetClient( - WhispernetClient* client) { - if (initialized_) - RunInitCallback(client, true); - - std::string id = base::GenerateGUID(); - whispernet_clients_[id] = client; - - return id; -} - -void CopresencePrivateService::OnWhispernetInitialized(bool success) { - if (success) - initialized_ = true; - - DVLOG(2) << "Notifying " << whispernet_clients_.size() - << " clients that initialization is complete."; - for (auto client_entry : whispernet_clients_) - RunInitCallback(client_entry.second, success); -} - -WhispernetClient* CopresencePrivateService::GetWhispernetClient( - const std::string& id) { - WhispernetClient* client = whispernet_clients_[id]; - DCHECK(client); - return client; -} - -// static -BrowserContextKeyedAPIFactory<CopresencePrivateService>* -CopresencePrivateService::GetFactoryInstance() { - return g_factory.Pointer(); -} - -template <> -void BrowserContextKeyedAPIFactory<CopresencePrivateService> - ::DeclareFactoryDependencies() { - DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); -} - - -// Copresence Private functions. - -// CopresenceSendFoundFunction implementation: -ExtensionFunction::ResponseAction CopresencePrivateSendFoundFunction::Run() { - std::unique_ptr<SendFound::Params> params(SendFound::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - WhispernetClient* whispernet_client = - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->GetWhispernetClient(params->client_id); - if (whispernet_client->GetTokensCallback().is_null()) - return RespondNow(NoArguments()); - - std::vector<audio_modem::AudioToken> tokens; - for (size_t i = 0; i < params->tokens.size(); ++i) { - tokens.push_back(audio_modem::AudioToken(params->tokens[i].token, - params->tokens[i].audible)); - } - whispernet_client->GetTokensCallback().Run(tokens); - return RespondNow(NoArguments()); -} - -// CopresenceSendEncodedFunction implementation: -ExtensionFunction::ResponseAction CopresencePrivateSendSamplesFunction::Run() { - std::unique_ptr<SendSamples::Params> params( - SendSamples::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - WhispernetClient* whispernet_client = - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->GetWhispernetClient(params->client_id); - if (whispernet_client->GetSamplesCallback().is_null()) - return RespondNow(NoArguments()); - - scoped_refptr<media::AudioBusRefCounted> samples = - media::AudioBusRefCounted::Create(1, // Mono - params->samples.size() / sizeof(float)); - - memcpy(samples->channel(0), params->samples.data(), params->samples.size()); - - whispernet_client->GetSamplesCallback().Run( - params->token.audible ? audio_modem::AUDIBLE : audio_modem::INAUDIBLE, - params->token.token, samples); - return RespondNow(NoArguments()); -} - -// CopresenceSendInitializedFunction implementation: -ExtensionFunction::ResponseAction -CopresencePrivateSendInitializedFunction::Run() { - std::unique_ptr<SendInitialized::Params> params( - SendInitialized::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - CopresencePrivateService::GetFactoryInstance()->Get(browser_context()) - ->OnWhispernetInitialized(params->success); - - return RespondNow(NoArguments()); -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/copresence_private/copresence_private_api.h b/chrome/browser/extensions/api/copresence_private/copresence_private_api.h deleted file mode 100644 index 3be29040..0000000 --- a/chrome/browser/extensions/api/copresence_private/copresence_private_api.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_ - -#include <string> - -#include "base/macros.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/extension_function_histogram_value.h" - -namespace audio_modem { -class WhispernetClient; -} - -namespace extensions { - -class CopresencePrivateService final : public BrowserContextKeyedAPI { - public: - explicit CopresencePrivateService(content::BrowserContext* context); - ~CopresencePrivateService() override; - - // Registers a client to receive events from Whispernet. - const std::string - RegisterWhispernetClient(audio_modem::WhispernetClient* client); - - // Gets the whispernet client by ID. - audio_modem::WhispernetClient* GetWhispernetClient(const std::string& id); - - // Called from the whispernet_proxy extension when it has initialized. - void OnWhispernetInitialized(bool success); - - // BrowserContextKeyedAPI implementation. - static BrowserContextKeyedAPIFactory<CopresencePrivateService>* - GetFactoryInstance(); - - private: - friend class BrowserContextKeyedAPIFactory<CopresencePrivateService>; - - // BrowserContextKeyedAPI implementation. - static const bool kServiceRedirectedInIncognito = true; - static const char* service_name() { return "CopresencePrivateService"; } - - bool initialized_; - std::map<std::string, audio_modem::WhispernetClient*> whispernet_clients_; - - DISALLOW_COPY_AND_ASSIGN(CopresencePrivateService); -}; - -template<> -void BrowserContextKeyedAPIFactory<CopresencePrivateService> - ::DeclareFactoryDependencies(); - -class CopresencePrivateSendFoundFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendFound", - COPRESENCEPRIVATE_SENDFOUND); - - protected: - ~CopresencePrivateSendFoundFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendSamplesFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendSamples", - COPRESENCEPRIVATE_SENDSAMPLES); - - protected: - ~CopresencePrivateSendSamplesFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendDetectFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendDetect", - COPRESENCEPRIVATE_SENDDETECT); - - protected: - ~CopresencePrivateSendDetectFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -class CopresencePrivateSendInitializedFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("copresencePrivate.sendInitialized", - COPRESENCEPRIVATE_SENDINITIALIZED); - - protected: - ~CopresencePrivateSendInitializedFunction() override {} - ExtensionFunction::ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_COPRESENCE_PRIVATE_COPRESENCE_PRIVATE_API_H_
diff --git a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc index a742acb..ddabb67 100644 --- a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc +++ b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc
@@ -83,7 +83,6 @@ IDR_SETTINGS_APP_MANIFEST, IDR_WALLPAPERMANAGER_MANIFEST, IDR_WEBSTORE_MANIFEST, - IDR_WHISPERNET_PROXY_MANIFEST, #if defined(IMAGE_LOADER_EXTENSION) IDR_IMAGE_LOADER_MANIFEST, #endif
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 854cccb..8aa3b212 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -200,7 +200,8 @@ // Open (with delete) and then immediately close the file by going out of // scope. This is the only cross-platform safe way to delete a file that may - // be open elsewhere. + // be open elsewhere. Open handles will continue to operate normally but + // new opens will not be possible. base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_DELETE_ON_CLOSE); }
diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index 84d0f8a..e87619cf 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd
@@ -246,17 +246,6 @@ <include name="IDR_CRYPTOTOKEN_CRYPTOTOKENAPPROVEDORIGIN_JS" file="cryptotoken/cryptotokenapprovedorigins.js" type="BINDATA" /> <include name="IDR_CRYPTOTOKEN_CRYPTOTOKENORIGINCHECK_JS" file="cryptotoken/cryptotokenorigincheck.js" type="BINDATA" /> <include name="IDR_CRYPTOTOKEN_CRYPTOTOKENBACKGROUND_JS" file="cryptotoken/cryptotokenbackground.js" type="BINDATA" /> - <include name="IDR_WHISPERNET_PROXY_BACKGROUND_HTML" file="whispernet_proxy/background.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_WHISPERNET_PROXY_INIT_JS" file="whispernet_proxy/js/init.js" type="BINDATA" /> - <include name="IDR_WHISPERNET_PROXY_NACL_JS" file="whispernet_proxy/js/nacl.js" type="BINDATA" /> - <include name="IDR_WHISPERNET_PROXY_WRAPPER_JS" file="whispernet_proxy/js/wrapper.js" type="BINDATA" /> - <!-- The next two files have a .png extension since grit for some reason - won't compile these files in if they are named .nmf/.pexe or - anything remotely similar to their actual extension. Naming these - .js or .html breaks all kinds of presubmit checks, hence .png seems - to be the only viable option at the moment. --> - <include name="IDR_WHISPERNET_PROXY_WHISPERNET_PROXY_PROXY_NMF" file="whispernet_proxy/whispernet_proxy.nmf.png" type="BINDATA" /> - <include name="IDR_WHISPERNET_PROXY_WHISPERNET_PROXY_PROXY_PEXE" file="whispernet_proxy/whispernet_proxy_pnacl.pexe.png" type="BINDATA" /> </includes> </release> </grit>
diff --git a/chrome/browser/resources/whispernet_proxy/OWNERS b/chrome/browser/resources/whispernet_proxy/OWNERS deleted file mode 100644 index 2bc8d07..0000000 --- a/chrome/browser/resources/whispernet_proxy/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -rkc@chromium.org -ckehoe@chromium.org -xiyuan@chromium.org
diff --git a/chrome/browser/resources/whispernet_proxy/background.html b/chrome/browser/resources/whispernet_proxy/background.html deleted file mode 100644 index b14945d..0000000 --- a/chrome/browser/resources/whispernet_proxy/background.html +++ /dev/null
@@ -1,12 +0,0 @@ -<!doctype html> -<html> -<head> -<meta charset="utf-8"> -<link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> -<script src="js/nacl.js"></script> -<script src="js/wrapper.js"></script> -<script src="js/init.js"></script> -</head> -<body> -</body> -</html>
diff --git a/chrome/browser/resources/whispernet_proxy/js/init.js b/chrome/browser/resources/whispernet_proxy/js/init.js deleted file mode 100644 index 93f60ab..0000000 --- a/chrome/browser/resources/whispernet_proxy/js/init.js +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -'use strict'; - -// Global holding our NaclBridge. -var whispernetNacl = null; - -// Encoders and decoders for each client. -var whisperEncoders = {}; -var whisperDecoders = {}; - -/** - * Initialize the whispernet encoder and decoder. - * Call this before any other functions. - * @param {string} clientId A string identifying the requester. - * @param {Object} audioParams Audio parameters for token encoding and decoding. - */ -function audioConfig(clientId, audioParams) { - if (!whispernetNacl) { - chrome.copresencePrivate.sendInitialized(false); - return; - } - - console.log('Configuring encoder and decoder for client ' + clientId); - whisperEncoders[clientId] = - new WhisperEncoder(audioParams.paramData, whispernetNacl, clientId); - whisperDecoders[clientId] = - new WhisperDecoder(audioParams.paramData, whispernetNacl, clientId); -} - -/** - * Sends a request to whispernet to encode a token. - * @param {string} clientId A string identifying the requester. - * @param {Object} params Encode token parameters object. - */ -function encodeTokenRequest(clientId, params) { - if (whisperEncoders[clientId]) { - whisperEncoders[clientId].encode(params); - } else { - console.error('encodeTokenRequest: Whisper not initialized for client ' + - clientId); - } -} - -/** - * Sends a request to whispernet to decode samples. - * @param {string} clientId A string identifying the requester. - * @param {Object} params Process samples parameters object. - */ -function decodeSamplesRequest(clientId, params) { - if (whisperDecoders[clientId]) { - whisperDecoders[clientId].processSamples(params); - } else { - console.error('decodeSamplesRequest: Whisper not initialized for client ' + - clientId); - } -} - -/** - * Initialize our listeners and signal that the extension is loaded. - */ -function onWhispernetLoaded() { - console.log('init: Nacl ready!'); - - // Setup all the listeners for the private API. - chrome.copresencePrivate.onConfigAudio.addListener(audioConfig); - chrome.copresencePrivate.onEncodeTokenRequest.addListener(encodeTokenRequest); - chrome.copresencePrivate.onDecodeSamplesRequest.addListener( - decodeSamplesRequest); - - // This first initialized is sent to indicate that the library is loaded. - // Every other time, it will be sent only when Chrome wants to reinitialize - // the encoder and decoder. - chrome.copresencePrivate.sendInitialized(true); -} - -/** - * Initialize the whispernet Nacl bridge. - */ -function initWhispernet() { - console.log('init: Starting Nacl bridge.'); - // TODO(rkc): Figure out how to embed the .nmf and the .pexe into component - // resources without having to rename them to .js. - whispernetNacl = new NaclBridge('whispernet_proxy.nmf.png', - onWhispernetLoaded); -} - -window.addEventListener('DOMContentLoaded', initWhispernet);
diff --git a/chrome/browser/resources/whispernet_proxy/js/nacl.js b/chrome/browser/resources/whispernet_proxy/js/nacl.js deleted file mode 100644 index da8e48ca..0000000 --- a/chrome/browser/resources/whispernet_proxy/js/nacl.js +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -'use strict'; - -/** - * Constructor for the Nacl bridge to the whispernet wrapper. - * @param {string} nmf The relative path to the nmf containing the location of - * the whispernet Nacl wrapper. - * @param {function()} readyCallback Callback to be called once we've loaded the - * whispernet wrapper. - */ -function NaclBridge(nmf, readyCallback) { - this.readyCallback_ = readyCallback; - this.callbacks_ = []; - this.isEnabled_ = false; - this.naclId_ = this.loadNacl_(nmf); -} - -/** - * Method to send generic byte data to the whispernet wrapper. - * @param {Object} data Raw data to send to the whispernet wrapper. - */ -NaclBridge.prototype.send = function(data) { - if (this.isEnabled_) { - this.embed_.postMessage(data); - } else { - console.error('Whisper Nacl Bridge not initialized!'); - } -}; - -/** - * Method to add a listener to Nacl messages received by this bridge. - * @param {function(Event)} messageCallback Callback to receive the messsage. - */ -NaclBridge.prototype.addListener = function(messageCallback) { - this.callbacks_.push(messageCallback); -}; - -/** - * Method that receives Nacl messages and forwards them to registered - * callbacks. - * @param {Event} e Event from the whispernet wrapper. - * @private - */ -NaclBridge.prototype.onMessage_ = function(e) { - if (this.isEnabled_) { - this.callbacks_.forEach(function(callback) { - callback(e); - }); - } -}; - -/** - * Injects the <embed> for this nacl manifest URL, generating a unique ID. - * @param {string} manifestUrl Url to the nacl manifest to load. - * @return {number} generated ID. - * @private - */ -NaclBridge.prototype.loadNacl_ = function(manifestUrl) { - var id = 'nacl-' + Math.floor(Math.random() * 10000); - this.embed_ = document.createElement('embed'); - this.embed_.name = 'nacl_module'; - this.embed_.width = 1; - this.embed_.height = 1; - this.embed_.src = manifestUrl; - this.embed_.id = id; - this.embed_.type = 'application/x-pnacl'; - - // Wait for the element to load and callback. - this.embed_.addEventListener('load', this.onNaclReady_.bind(this)); - this.embed_.addEventListener('error', this.onNaclError_.bind(this)); - - // Inject the embed string into the page. - document.body.appendChild(this.embed_); - - // Listen for messages from the NaCl module. - window.addEventListener('message', this.onMessage_.bind(this), true); - return id; -}; - -/** - * Called when the Whispernet wrapper is loaded. - * @private - */ -NaclBridge.prototype.onNaclReady_ = function() { - this.isEnabled_ = true; - if (this.readyCallback_) - this.readyCallback_(); -}; - -/** - * Callback that handles Nacl errors. - * @param {string} msg Error string. - * @private - */ -NaclBridge.prototype.onNaclError_ = function(msg) { - // TODO(rkc): Handle error from NaCl better. - console.error('NaCl error', msg); -};
diff --git a/chrome/browser/resources/whispernet_proxy/js/wrapper.js b/chrome/browser/resources/whispernet_proxy/js/wrapper.js deleted file mode 100644 index 29b57f7f..0000000 --- a/chrome/browser/resources/whispernet_proxy/js/wrapper.js +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -'use strict'; - -/** - * Function to convert an array of bytes to a base64 string - * TODO(rkc): Change this to use a Uint8array instead of a string. - * @param {string} bytes String containing the bytes we want to convert. - * @return {string} String containing the base64 representation. - */ -function bytesToBase64(bytes) { - var bstr = ''; - for (var i = 0; i < bytes.length; ++i) - bstr += String.fromCharCode(bytes[i]); - return btoa(bstr).replace(/=/g, ''); -} - -/** - * Function to convert a string to an array of bytes. - * @param {string} str String to convert. - * @return {Array} Array containing the string. - */ -function stringToArray(str) { - var buffer = []; - for (var i = 0; i < str.length; ++i) - buffer[i] = str.charCodeAt(i); - return buffer; -} - -/** - * Creates a whispernet encoder. - * @constructor - * @param {Object} params Audio parameters for the whispernet encoder. - * @param {Object} whisperNacl The NaclBridge object, used to communicate with - * the whispernet wrapper. - * @param {string} clientId A string identifying the requester. - */ -function WhisperEncoder(params, whisperNacl, clientId) { - this.whisperNacl_ = whisperNacl; - this.whisperNacl_.addListener(this.onNaclMessage_.bind(this)); - this.clientId_ = clientId; - - var msg = { - type: 'initialize_encoder', - client_id: clientId, - params: params - }; - - this.whisperNacl_.send(msg); -} - -/** - * Method to encode a token. - * @param {Object} params Encode token parameters object. - */ -WhisperEncoder.prototype.encode = function(params) { - // Pad the token before decoding it. - var token = params.token.token; - while (token.length % 4 > 0) - token += '='; - - var msg = { - type: 'encode_token', - client_id: this.clientId_, - // Trying to send the token in binary form to Nacl doesn't work correctly. - // We end up with the correct string + a bunch of extra characters. This is - // true of returning a binary string too; hence we communicate back and - // forth by converting the bytes into an array of integers. - token: stringToArray(atob(token)), - repetitions: params.repetitions, - use_dtmf: params.token.audible, - use_crc: params.tokenParams.crc, - use_parity: params.tokenParams.parity - }; - - this.whisperNacl_.send(msg); -}; - -/** - * Method to handle messages from the whispernet NaCl wrapper. - * @param {Event} e Event from the whispernet wrapper. - * @private - */ -WhisperEncoder.prototype.onNaclMessage_ = function(e) { - var msg = e.data; - if (msg.type == 'encode_token_response' && msg.client_id == this.clientId_) { - chrome.copresencePrivate.sendSamples(this.clientId_, - { token: bytesToBase64(msg.token), audible: msg.audible }, msg.samples); - } -}; - -/** - * Creates a whispernet decoder. - * @constructor - * @param {Object} params Audio parameters for the whispernet decoder. - * @param {Object} whisperNacl The NaclBridge object, used to communicate with - * the whispernet wrapper. - * @param {string} clientId A string identifying the requester. - */ -function WhisperDecoder(params, whisperNacl, clientId) { - this.whisperNacl_ = whisperNacl; - this.whisperNacl_.addListener(this.onNaclMessage_.bind(this)); - this.clientId_ = clientId; - - var msg = { - type: 'initialize_decoder', - client_id: clientId, - params: params - }; - this.whisperNacl_.send(msg); -} - -/** - * Method to request the decoder to process samples. - * @param {Object} params Process samples parameters object. - */ -WhisperDecoder.prototype.processSamples = function(params) { - var msg = { - type: 'decode_tokens', - client_id: this.clientId_, - data: params.samples, - - decode_audible: params.decodeAudible, - token_length_dtmf: params.audibleTokenParams.length, - crc_dtmf: params.audibleTokenParams.crc, - parity_dtmf: params.audibleTokenParams.parity, - - decode_inaudible: params.decodeInaudible, - token_length_dsss: params.inaudibleTokenParams.length, - crc_dsss: params.inaudibleTokenParams.crc, - parity_dsss: params.inaudibleTokenParams.parity, - }; - - this.whisperNacl_.send(msg); -}; - -/** - * Method to handle messages from the whispernet NaCl wrapper. - * @param {Event} e Event from the whispernet wrapper. - * @private - */ -WhisperDecoder.prototype.onNaclMessage_ = function(e) { - var msg = e.data; - if (msg.type == 'decode_tokens_response' && msg.client_id == this.clientId_) { - this.handleCandidates_(msg.tokens, msg.audible); - } -}; - -/** - * Method to receive tokens from the decoder and process and forward them to the - * token callback registered with us. - * @param {!Array.string} candidates Array of token candidates. - * @param {boolean} audible Whether the received candidates are from the audible - * decoder or not. - * @private - */ -WhisperDecoder.prototype.handleCandidates_ = function(candidates, audible) { - if (!candidates || candidates.length == 0) - return; - - var returnCandidates = []; - for (var i = 0; i < candidates.length; ++i) { - returnCandidates[i] = { token: bytesToBase64(candidates[i]), - audible: audible }; - } - chrome.copresencePrivate.sendFound(this.clientId_, returnCandidates); -};
diff --git a/chrome/browser/resources/whispernet_proxy/manifest.json b/chrome/browser/resources/whispernet_proxy/manifest.json deleted file mode 100644 index 6b15ef9..0000000 --- a/chrome/browser/resources/whispernet_proxy/manifest.json +++ /dev/null
@@ -1,13 +0,0 @@ -{ - // chrome-extension://bpfmnplchembfbdgieamdodgaencleal/ - "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxY7MIAZJdh8y5zmU3kRtxMtOWwHl/Yu+c700YQncON0OaqNLcWD/vrPBsMW/4SkkHIBtJDUmLAzPfXyUtbxYo3Vi3E7xJ028BN0Z+KMhPMvFYnHiS4NlFTRDHvQbWi7P+4bvOvS8RZe1VBgSQMhaJSsa6zzE+UNRPsiWNOaX2O08N3oyxo1Z2SU8Q9eE283NOgY8fVg8TJFVqGHPmbcblpM2A+dk7YFBIT1dFemRxJFW2DdLoCXojrNWXqzYstj/muuefRTgnNmwlCjCeDyK6R6x71GRTUnkVOiBgETgsTfOJRvKQCy65/EENZdX/u4e1LM1PWq0ePJ+xMwEXfuHtQIDAQAB", - "name": "Whispernet Proxy", - "version": "1.0", - "manifest_version": 2, - "description": "Proxy whispernet calls.", - "permissions": [ "copresencePrivate" ], - "background": { - "page": "background.html", - "persistent": true - } -}
diff --git a/chrome/browser/resources/whispernet_proxy/whispernet_proxy.nmf.png b/chrome/browser/resources/whispernet_proxy/whispernet_proxy.nmf.png deleted file mode 100644 index a552308..0000000 --- a/chrome/browser/resources/whispernet_proxy/whispernet_proxy.nmf.png +++ /dev/null
@@ -1,7 +0,0 @@ -{ - "program": { - "portable": { - "pnacl-translate": { "url": "whispernet_proxy_pnacl.pexe.png?v00008" } - } - } -}
diff --git a/chrome/browser/resources/whispernet_proxy/whispernet_proxy_pnacl.pexe.png b/chrome/browser/resources/whispernet_proxy/whispernet_proxy_pnacl.pexe.png deleted file mode 100644 index fe8e69e7..0000000 --- a/chrome/browser/resources/whispernet_proxy/whispernet_proxy_pnacl.pexe.png +++ /dev/null Binary files differ
diff --git a/chrome/chrome_browser_extensions.gypi b/chrome/chrome_browser_extensions.gypi index 121014a..2b65aa70 100644 --- a/chrome/chrome_browser_extensions.gypi +++ b/chrome/chrome_browser_extensions.gypi
@@ -100,9 +100,6 @@ 'browser/apps/shortcut_manager.h', 'browser/apps/shortcut_manager_factory.cc', 'browser/apps/shortcut_manager_factory.h', - 'browser/copresence/chrome_whispernet_client.cc', - 'browser/copresence/chrome_whispernet_client.h', - 'browser/copresence/chrome_whispernet_config.h', 'browser/extensions/active_install_data.cc', 'browser/extensions/active_install_data.h', 'browser/extensions/active_tab_permission_granter.cc', @@ -125,8 +122,6 @@ 'browser/extensions/activity_log/fullstream_ui_policy.h', 'browser/extensions/api/activity_log_private/activity_log_private_api.cc', 'browser/extensions/api/activity_log_private/activity_log_private_api.h', - 'browser/extensions/api/audio_modem/audio_modem_api.cc', - 'browser/extensions/api/audio_modem/audio_modem_api.h', 'browser/extensions/api/autofill_private/autofill_private_api.cc', 'browser/extensions/api/autofill_private/autofill_private_api.h', 'browser/extensions/api/autofill_private/autofill_private_event_router.cc', @@ -205,8 +200,6 @@ 'browser/extensions/api/cookies/cookies_api_constants.h', 'browser/extensions/api/cookies/cookies_helpers.cc', 'browser/extensions/api/cookies/cookies_helpers.h', - 'browser/extensions/api/copresence_private/copresence_private_api.cc', - 'browser/extensions/api/copresence_private/copresence_private_api.h', 'browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc', 'browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h', 'browser/extensions/api/dashboard_private/dashboard_private_api.cc', @@ -957,7 +950,6 @@ 'debugger', 'installer_util', 'safe_browsing_proto', - '../components/components.gyp:audio_modem', '../components/components.gyp:dom_distiller_core', '../components/components.gyp:onc_component', '../components/components.gyp:policy',
diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index 7990a805..8a69a728 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi
@@ -2661,16 +2661,6 @@ 'browser/ui/webui/log_web_ui_url_browsertest.cc', ], }], - ['OS!="android" and OS!="ios"', { - 'sources': [ - 'browser/copresence/chrome_whispernet_client_browsertest.cc', - ], - 'dependencies': [ - '../components/components.gyp:audio_modem', - # build time dependency. - '../v8/samples/samples.gyp:v8_shell#host', - ], - }], ['enable_app_list==1', { 'sources': [ '<@(chrome_browser_tests_app_list_sources)' ], 'conditions': [
diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index f4f028c..23787082 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi
@@ -414,7 +414,6 @@ 'browser/extensions/activity_log/database_string_table_unittest.cc', 'browser/extensions/activity_log/fullstream_ui_policy_unittest.cc', 'browser/extensions/api/activity_log_private/activity_log_private_api_unittest.cc', - 'browser/extensions/api/audio_modem/audio_modem_api_unittest.cc', 'browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc', 'browser/extensions/api/content_settings/content_settings_store_unittest.cc', 'browser/extensions/api/content_settings/content_settings_unittest.cc', @@ -2409,7 +2408,6 @@ 'dependencies': [ 'common/extensions/api/api.gyp:chrome_api', '../device/hid/hid.gyp:device_hid_mocks', - '../components/components.gyp:audio_modem_test_support', '../extensions/extensions_resources.gyp:extensions_resources', '../extensions/extensions_strings.gyp:extensions_strings', ],
diff --git a/chrome/common/extensions/api/audio_modem.idl b/chrome/common/extensions/api/audio_modem.idl deleted file mode 100644 index a306f7c2..0000000 --- a/chrome/common/extensions/api/audio_modem.idl +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Use the <code>chrome.audio_modem</code> API -// to transmit and receive short tokens over audio. -namespace audioModem { - // The audio bands supported. - enum Audioband { - // Audible (up to 3 kHz) - audible, - // Inaudible (18-20 kHz) - inaudible - }; - - // Details for how a token is encoded in audio. - dictionary TokenEncoding { - // The length of the tokens to transmit, in bytes. - // For now, apps must always use the same token length. - long tokenLength; - // Whether to use a 2-byte CRC checksum. Defaults to false. - boolean? crc; - // Whether to use a parity symbol. Defaults to false. - boolean? parity; - }; - - // Details of a transmit or receive request. - dictionary RequestParams { - // How long to transmit or receive for. - // The timeout has a maximum of 10 minutes for transmit, - // or 1 hour for receive. - long timeoutMillis; - // The audio band to use. - Audioband band; - // The token encoding details. - TokenEncoding encoding; - }; - - // Results of token decoding. - dictionary ReceivedToken { - // The token contents in raw bytes. - ArrayBuffer token; - // The audio band the token was heard on. - Audioband band; - }; - - // The result of a requested operation. - enum Status { - // The requested operation was processed successfully. - success, - // The request was invalid. See chrome.runtime.lastError for details. - invalidRequest, - // The requested audio band is already in use by another client. - // Eventually, simultaneous tokens will be time-sliced, - // and this error will no longer occur. - inUse, - // Audio encoding or decoding failed. - coderError - }; - - // A callback to report the status of a request. - callback StatusCallback = void(Status status); - - interface Functions { - // Transmit a token. Only one can be transmitted at a time. - // Transmission of any previous tokens (by this app) will stop. - static void transmit( - RequestParams params, ArrayBuffer token, StatusCallback callback); - // Stop any active transmission on the specified band. - static void stopTransmit(Audioband band, StatusCallback callback); - // Start listening for audio tokens. For now, - // only one app will be able to listen at a time. - static void receive(RequestParams params, StatusCallback callback); - // Stop any active listening on the specified band. - static void stopReceive(Audioband band, StatusCallback callback); - }; - - interface Events { - // Audio tokens have been received. - static void onReceived(ReceivedToken[] tokens); - // Transmit could not be confirmed. - // The speaker volume might be too low. - static void onTransmitFail(Audioband band); - }; -}; -
diff --git a/chrome/common/extensions/api/copresence_private.idl b/chrome/common/extensions/api/copresence_private.idl deleted file mode 100644 index 6db3420..0000000 --- a/chrome/common/extensions/api/copresence_private.idl +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Use the <code>chrome.copresencePrivate</code> API to interface with Chrome -// from the whispernet_proxy extension. -namespace copresencePrivate { - dictionary Token { - DOMString token; - boolean audible; - }; - - dictionary TokenParameters { - long length; - boolean crc; - boolean parity; - }; - - dictionary DecodeSamplesParameters { - ArrayBuffer samples; - - boolean decodeAudible; - boolean decodeInaudible; - - TokenParameters audibleTokenParams; - TokenParameters inaudibleTokenParams; - }; - - dictionary EncodeTokenParameters { - Token token; - long repetitions; - TokenParameters tokenParams; - }; - - dictionary AudioParameters { - // This string contains marshalling of a custom parameters structure - // that Chrome and the Whispernet wrapper both know about. These are - // based off //components/copresence/proto/config_data.proto. - ArrayBuffer paramData; - }; - - interface Functions { - // Send a boolean indicating whether our initialization was successful. - static void sendInitialized(boolean success); - - // Sends an array of found tokens to Chrome. - static void sendFound(DOMString clientId, Token[] tokens); - - // Send an array buffer of samples encoded for the specified token. - static void sendSamples(DOMString clientId, - Token token, - ArrayBuffer samples); - }; - - interface Events { - // Fired to request audio configuration of the whisper.net library. - static void onConfigAudio(DOMString clientId, AudioParameters audioParams); - - // Fired to request encoding of the given token. - static void onEncodeTokenRequest(DOMString clientId, - EncodeTokenParameters encodeParams); - - // Fired when we have new samples to decode. - static void onDecodeSamplesRequest(DOMString clientId, - DecodeSamplesParameters decodeParams); - }; -};
diff --git a/chrome/common/extensions/api/schemas.gypi b/chrome/common/extensions/api/schemas.gypi index db9ec033..e912684 100644 --- a/chrome/common/extensions/api/schemas.gypi +++ b/chrome/common/extensions/api/schemas.gypi
@@ -11,7 +11,6 @@ 'accessibility_features.json', 'accessibility_private.json', 'activity_log_private.json', - 'audio_modem.idl', 'autofill_private.idl', 'automation.idl', 'automation_internal.idl', @@ -28,7 +27,6 @@ 'context_menus_internal.json', 'context_menus.json', 'cookies.json', - 'copresence_private.idl', 'cryptotoken_private.idl', 'dashboard_private.json', 'data_reduction_proxy.json',
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index dc5a3bb..1e608bbd 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1384,14 +1384,6 @@ if (is_android || is_ios || is_chromeos) { sources -= [ "../browser/profiles/profile_statistics_browsertest.cc" ] } - if (!is_android && !is_ios) { - sources += - [ "../browser/copresence/chrome_whispernet_client_browsertest.cc" ] - deps += [ - "//components/audio_modem", - "//third_party/libaddressinput", - ] - } if (enable_app_list) { sources += rebase_path( chrome_tests_gypi_values.chrome_browser_tests_app_list_sources, @@ -1941,7 +1933,6 @@ "//chrome") deps += [ "//chrome/common/extensions/api", - "//components/audio_modem:test_support", "//extensions:extensions_resources", "//extensions/strings", ]
diff --git a/components/BUILD.gn b/components/BUILD.gn index 73e906e2..e1921d16 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -263,7 +263,6 @@ # Desktop-only deps. if (!is_android && !is_ios) { deps += [ - "//components/audio_modem:unit_tests", "//components/feedback:unit_tests", "//components/proximity_auth:unit_tests", "//components/storage_monitor:unit_tests",
diff --git a/components/OWNERS b/components/OWNERS index b70debf..632d80d 100644 --- a/components/OWNERS +++ b/components/OWNERS
@@ -10,8 +10,6 @@ per-file arc.gypi=file://components/arc/OWNERS -per-file audio_modem.gypi=file://components/audio_modem/OWNERS - per-file autofill.gypi=file://components/autofill/OWNERS per-file autofill_strings.grdp=file://components/autofill/OWNERS
diff --git a/components/audio_modem.gypi b/components/audio_modem.gypi deleted file mode 100644 index 58d89288..0000000 --- a/components/audio_modem.gypi +++ /dev/null
@@ -1,54 +0,0 @@ -# Copyright 2015 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'targets': [ - { - 'target_name': 'audio_modem', - 'type': 'static_library', - 'dependencies': [ - '../base/base.gyp:base', - '../content/content.gyp:content_common', - '../media/media.gyp:media', - '../media/media.gyp:shared_memory_support', - '../third_party/webrtc/common_audio/common_audio.gyp:common_audio', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'audio_modem/audio_player.h', - 'audio_modem/audio_player_impl.cc', - 'audio_modem/audio_player_impl.h', - 'audio_modem/audio_recorder.h', - 'audio_modem/audio_recorder_impl.cc', - 'audio_modem/audio_recorder_impl.h', - 'audio_modem/constants.cc', - 'audio_modem/modem_impl.cc', - 'audio_modem/modem_impl.h', - 'audio_modem/public/modem.h', - 'audio_modem/public/audio_modem_types.h', - 'audio_modem/public/whispernet_client.h', - 'audio_modem/audio_modem_switches.cc', - 'audio_modem/audio_modem_switches.h', - ], - }, - { - 'target_name': 'audio_modem_test_support', - 'type': 'static_library', - 'include_dirs': [ - '..', - ], - 'sources': [ - 'audio_modem/test/random_samples.cc', - 'audio_modem/test/random_samples.h', - 'audio_modem/test/stub_modem.cc', - 'audio_modem/test/stub_modem.h', - 'audio_modem/test/stub_whispernet_client.cc', - 'audio_modem/test/stub_whispernet_client.h', - ], - }, - ], -}
diff --git a/components/audio_modem/BUILD.gn b/components/audio_modem/BUILD.gn deleted file mode 100644 index 83cd882..0000000 --- a/components/audio_modem/BUILD.gn +++ /dev/null
@@ -1,72 +0,0 @@ -# Copyright 2015 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -source_set("audio_modem") { - sources = [ - "audio_modem_switches.cc", - "audio_modem_switches.h", - "audio_player.h", - "audio_player_impl.cc", - "audio_player_impl.h", - "audio_recorder.h", - "audio_recorder_impl.cc", - "audio_recorder_impl.h", - "constants.cc", - "modem_impl.cc", - "modem_impl.h", - "public/audio_modem_types.h", - "public/modem.h", - "public/whispernet_client.h", - ] - - deps = [ - "//base", - "//content/public/browser", - "//media", - "//media:shared_memory_support", - "//third_party/webrtc/common_audio", - ] -} - -source_set("test_support") { - testonly = true - sources = [ - "test/random_samples.cc", - "test/random_samples.h", - "test/stub_modem.cc", - "test/stub_modem.h", - "test/stub_whispernet_client.cc", - "test/stub_whispernet_client.h", - ] - - public_deps = [ - ":audio_modem", - ] - deps = [ - "//base", - "//media", - "//media:shared_memory_support", - ] -} - -source_set("unit_tests") { - testonly = true - sources = [ - "audio_player_unittest.cc", - "audio_recorder_unittest.cc", - "modem_unittest.cc", - ] - - configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] - - deps = [ - ":test_support", - "//base", - "//base/test:test_support", - "//content/test:test_support", - "//media", - "//media:shared_memory_support", - "//testing/gtest", - ] -}
diff --git a/components/audio_modem/DEPS b/components/audio_modem/DEPS deleted file mode 100644 index 3853989..0000000 --- a/components/audio_modem/DEPS +++ /dev/null
@@ -1,5 +0,0 @@ -include_rules = [ - "+content/public", - "+media", - "+third_party/webrtc/common_audio", -]
diff --git a/components/audio_modem/OWNERS b/components/audio_modem/OWNERS deleted file mode 100644 index f9882eb..0000000 --- a/components/audio_modem/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -ckehoe@chromium.org -rkc@chromium.org -xiyuan@chromium.org
diff --git a/components/audio_modem/audio_modem_switches.cc b/components/audio_modem/audio_modem_switches.cc deleted file mode 100644 index 9f559db..0000000 --- a/components/audio_modem/audio_modem_switches.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/audio_modem_switches.h" - -namespace switches { - -// Directory to dump encoded tokens to, for debugging. -// If empty (the default), tokens are not dumped. -// If invalid (not a writable directory), Chrome will crash! -const char kAudioModemDumpTokensToDir[] = "audio-modem-dump-tokens-to-dir"; - -// Allow broadcast of audible audio tokens. Defaults to true. -const char kAudioModemEnableAudibleBroadcast[] = - "audio-modem-enable-audible-broadcast"; - -// Allow broadcast of inaudible audio tokens. Defaults to true. -const char kAudioModemEnableInaudibleBroadcast[] = - "audio-modem-enable-inaudible-broadcast"; - -} // namespace switches
diff --git a/components/audio_modem/audio_modem_switches.h b/components/audio_modem/audio_modem_switches.h deleted file mode 100644 index 6ae4429..0000000 --- a/components/audio_modem/audio_modem_switches.h +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_AUDIO_MODEM_SWITCHES_H_ -#define COMPONENTS_AUDIO_MODEM_AUDIO_MODEM_SWITCHES_H_ - -namespace switches { - -// All switches in alphabetical order. The switches should be documented -// alongside the definition of their values in the .cc file. -extern const char kAudioModemDumpTokensToDir[]; -extern const char kAudioModemEnableAudibleBroadcast[]; -extern const char kAudioModemEnableInaudibleBroadcast[]; - -} // namespace switches - -#endif // COMPONENTS_AUDIO_MODEM_AUDIO_MODEM_SWITCHES_H_
diff --git a/components/audio_modem/audio_player.h b/components/audio_modem/audio_player.h deleted file mode 100644 index 53f838d7..0000000 --- a/components/audio_modem/audio_player.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_H_ -#define COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_H_ - -#include <vector> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" - -namespace media { -class AudioBusRefCounted; -} - -namespace audio_modem { - -// The AudioPlayerImpl class will play a set of samples till it is told to stop. -class AudioPlayer { - public: - // Initializes the object. Do not use this object before calling this method. - virtual void Initialize() = 0; - - // Play the given samples. These samples will keep on being played in a loop - // till we explicitly tell the player to stop playing. If we are already - // playing, this call will be ignored. - virtual void Play( - const scoped_refptr<media::AudioBusRefCounted>& samples) = 0; - - // Stop playing. If we're already stopped, this call will be ignored. - virtual void Stop() = 0; - - // Cleans up and deletes this object. Do not use object after this call. - virtual void Finalize() = 0; - - protected: - virtual ~AudioPlayer() {} -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_H_
diff --git a/components/audio_modem/audio_player_impl.cc b/components/audio_modem/audio_player_impl.cc deleted file mode 100644 index c968adf4..0000000 --- a/components/audio_modem/audio_player_impl.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/audio_player_impl.h" - -#include <algorithm> -#include <string> - -#include "base/bind.h" -#include "base/location.h" -#include "base/logging.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "media/audio/audio_manager.h" -#include "media/base/audio_bus.h" -#include "media/base/audio_parameters.h" - -namespace { - -const int kDefaultFrameCount = 1024; -const double kOutputVolumePercent = 1.0f; - -} // namespace - -namespace audio_modem { - -// Public methods. - -AudioPlayerImpl::AudioPlayerImpl() - : is_playing_(false), stream_(nullptr), frame_index_(0) { -} - -AudioPlayerImpl::~AudioPlayerImpl() { -} - -void AudioPlayerImpl::Initialize() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioPlayerImpl::InitializeOnAudioThread, - base::Unretained(this))); -} - -void AudioPlayerImpl::Play( - const scoped_refptr<media::AudioBusRefCounted>& samples) { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioPlayerImpl::PlayOnAudioThread, - base::Unretained(this), - samples)); -} - -void AudioPlayerImpl::Stop() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioPlayerImpl::StopOnAudioThread, base::Unretained(this))); -} - -void AudioPlayerImpl::Finalize() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioPlayerImpl::FinalizeOnAudioThread, - base::Unretained(this))); -} - -// Private methods. - -void AudioPlayerImpl::InitializeOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - stream_ = output_stream_for_testing_ - ? output_stream_for_testing_.get() - : media::AudioManager::Get()->MakeAudioOutputStreamProxy( - media::AudioParameters( - media::AudioParameters::AUDIO_PCM_LOW_LATENCY, - media::CHANNEL_LAYOUT_MONO, - kDefaultSampleRate, - kDefaultBitsPerSample, - kDefaultFrameCount), - std::string()); - - if (!stream_ || !stream_->Open()) { - LOG(ERROR) << "Failed to open an output stream."; - if (stream_) { - stream_->Close(); - stream_ = nullptr; - } - return; - } - stream_->SetVolume(kOutputVolumePercent); -} - -void AudioPlayerImpl::PlayOnAudioThread( - const scoped_refptr<media::AudioBusRefCounted>& samples) { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_ || is_playing_) - return; - - { - base::AutoLock al(state_lock_); - samples_ = samples; - frame_index_ = 0; - } - - VLOG(3) << "Starting playback."; - is_playing_ = true; - stream_->Start(this); -} - -void AudioPlayerImpl::StopOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_ || !is_playing_) - return; - - VLOG(3) << "Stopping playback."; - stream_->Stop(); - is_playing_ = false; -} - -void AudioPlayerImpl::StopAndCloseOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_) - return; - - StopOnAudioThread(); - stream_->Close(); - stream_ = nullptr; -} - -void AudioPlayerImpl::FinalizeOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - StopAndCloseOnAudioThread(); - delete this; -} - -int AudioPlayerImpl::OnMoreData(media::AudioBus* dest, - uint32_t /* total_bytes_delay */, - uint32_t /* frames_skipped */) { - base::AutoLock al(state_lock_); - // Continuously play our samples till explicitly told to stop. - const int leftover_frames = samples_->frames() - frame_index_; - const int frames_to_copy = std::min(dest->frames(), leftover_frames); - - samples_->CopyPartialFramesTo(frame_index_, frames_to_copy, 0, dest); - frame_index_ += frames_to_copy; - - // If we didn't fill the destination audio bus, wrap around and fill the rest. - if (leftover_frames <= dest->frames()) { - samples_->CopyPartialFramesTo( - 0, dest->frames() - frames_to_copy, frames_to_copy, dest); - frame_index_ = dest->frames() - frames_to_copy; - } - - return dest->frames(); -} - -void AudioPlayerImpl::OnError(media::AudioOutputStream* /* stream */) { - LOG(ERROR) << "Error during system sound reproduction."; - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioPlayerImpl::StopAndCloseOnAudioThread, - base::Unretained(this))); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/audio_player_impl.h b/components/audio_modem/audio_player_impl.h deleted file mode 100644 index 3507c699..0000000 --- a/components/audio_modem/audio_player_impl.h +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_IMPL_H_ -#define COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_IMPL_H_ - -#include <stdint.h> - -#include <memory> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/synchronization/lock.h" -#include "components/audio_modem/audio_player.h" -#include "media/audio/audio_io.h" - -namespace media { -class AudioBus; -class AudioBusRefCounted; -} - -namespace audio_modem { - -// The AudioPlayerImpl class will play a set of samples till it is told to stop. -class AudioPlayerImpl final - : public AudioPlayer, - public media::AudioOutputStream::AudioSourceCallback { - public: - AudioPlayerImpl(); - - // AudioPlayer overrides: - void Initialize() override; - void Play(const scoped_refptr<media::AudioBusRefCounted>& samples) override; - void Stop() override; - void Finalize() override; - - // Takes ownership of the stream. - void set_output_stream_for_testing( - media::AudioOutputStream* output_stream_for_testing) { - output_stream_for_testing_.reset(output_stream_for_testing); - } - - private: - friend class AudioPlayerTest; - FRIEND_TEST_ALL_PREFIXES(AudioPlayerTest, BasicPlayAndStop); - FRIEND_TEST_ALL_PREFIXES(AudioPlayerTest, OutOfOrderPlayAndStopMultiple); - - ~AudioPlayerImpl() override; - - // Methods to do our various operations; all of these need to be run on the - // audio thread. - void InitializeOnAudioThread(); - void PlayOnAudioThread( - const scoped_refptr<media::AudioBusRefCounted>& samples); - void StopOnAudioThread(); - void StopAndCloseOnAudioThread(); - void FinalizeOnAudioThread(); - - // AudioOutputStream::AudioSourceCallback overrides: - // Following methods could be called from *ANY* thread. - int OnMoreData(media::AudioBus* dest, - uint32_t total_bytes_delay, - uint32_t frames_skipped) override; - void OnError(media::AudioOutputStream* stream) override; - - bool is_playing_; - - // Self-deleting object. - media::AudioOutputStream* stream_; - - std::unique_ptr<media::AudioOutputStream> output_stream_for_testing_; - - // All fields below here are protected by this lock. - base::Lock state_lock_; - - scoped_refptr<media::AudioBusRefCounted> samples_; - - // Index to the frame in the samples that we need to play next. - int frame_index_; - - DISALLOW_COPY_AND_ASSIGN(AudioPlayerImpl); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_AUDIO_PLAYER_IMPL_H_
diff --git a/components/audio_modem/audio_player_unittest.cc b/components/audio_modem/audio_player_unittest.cc deleted file mode 100644 index ed2c71b..0000000 --- a/components/audio_modem/audio_player_unittest.cc +++ /dev/null
@@ -1,224 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/audio_player.h" - -#include <memory> - -#include "base/bind.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/run_loop.h" -#include "base/test/test_message_loop.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/audio_modem/audio_player_impl.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "components/audio_modem/test/random_samples.h" -#include "media/audio/audio_manager_base.h" -#include "media/base/audio_bus.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -class TestAudioOutputStream : public media::AudioOutputStream { - public: - using GatherSamplesCallback = - base::Callback<void(std::unique_ptr<media::AudioBus>, int frames)>; - TestAudioOutputStream(int default_frame_count, - int max_frame_count, - GatherSamplesCallback gather_callback) - : default_frame_count_(default_frame_count), - max_frame_count_(max_frame_count), - gather_callback_(gather_callback), - callback_(nullptr) { - caller_loop_ = base::MessageLoop::current(); - } - - ~TestAudioOutputStream() override {} - - bool Open() override { return true; } - void Start(AudioSourceCallback* callback) override { - callback_ = callback; - GatherPlayedSamples(); - } - void Stop() override {} - void SetVolume(double volume) override {} - void GetVolume(double* volume) override {} - void Close() override {} - - private: - void GatherPlayedSamples() { - int frames = 0, total_frames = 0; - do { - // Call back into the player to get samples that it wants us to play. - std::unique_ptr<media::AudioBus> dest = - media::AudioBus::Create(1, default_frame_count_); - frames = callback_->OnMoreData(dest.get(), 0, 0); - total_frames += frames; - // Send the samples given to us by the player to the gather callback. - caller_loop_->task_runner()->PostTask( - FROM_HERE, base::Bind(gather_callback_, base::Passed(&dest), frames)); - } while (frames && total_frames < max_frame_count_); - } - - int default_frame_count_; - int max_frame_count_; - GatherSamplesCallback gather_callback_; - AudioSourceCallback* callback_; - base::MessageLoop* caller_loop_; - - DISALLOW_COPY_AND_ASSIGN(TestAudioOutputStream); -}; - -} // namespace - -namespace audio_modem { - -class AudioPlayerTest : public testing::Test, - public base::SupportsWeakPtr<AudioPlayerTest> { - public: - AudioPlayerTest() : buffer_index_(0), player_(nullptr) { - audio_manager_ = media::AudioManager::CreateForTesting( - base::ThreadTaskRunnerHandle::Get()); - base::RunLoop().RunUntilIdle(); - } - - ~AudioPlayerTest() override { DeletePlayer(); } - - void CreatePlayer() { - DeletePlayer(); - player_ = new AudioPlayerImpl(); - player_->set_output_stream_for_testing(new TestAudioOutputStream( - kDefaultFrameCount, - kMaxFrameCount, - base::Bind(&AudioPlayerTest::GatherSamples, AsWeakPtr()))); - player_->Initialize(); - base::RunLoop().RunUntilIdle(); - } - - void DeletePlayer() { - if (!player_) - return; - player_->Finalize(); - player_ = nullptr; - base::RunLoop().RunUntilIdle(); - } - - void PlayAndVerifySamples( - const scoped_refptr<media::AudioBusRefCounted>& samples) { - DCHECK_LT(samples->frames(), kMaxFrameCount); - - buffer_ = media::AudioBus::Create(1, kMaxFrameCount); - buffer_index_ = 0; - player_->Play(samples); - player_->Stop(); - base::RunLoop().RunUntilIdle(); - - int differences = 0; - for (int i = 0; i < kMaxFrameCount; ++i) { - differences += (buffer_->channel(0)[i] != - samples->channel(0)[i % samples->frames()]); - } - ASSERT_EQ(0, differences); - - buffer_.reset(); - } - - void GatherSamples(std::unique_ptr<media::AudioBus> bus, int frames) { - if (!buffer_.get()) - return; - bus->CopyPartialFramesTo(0, frames, buffer_index_, buffer_.get()); - buffer_index_ += frames; - } - - protected: - bool IsPlaying() { - base::RunLoop().RunUntilIdle(); - return player_->is_playing_; - } - - static const int kDefaultFrameCount = 1024; - static const int kMaxFrameCount = 1024 * 100; - - base::TestMessageLoop message_loop_; - media::ScopedAudioManagerPtr audio_manager_; - std::unique_ptr<media::AudioBus> buffer_; - int buffer_index_; - - // Deleted by calling Finalize() on the object. - AudioPlayerImpl* player_; -}; - -TEST_F(AudioPlayerTest, BasicPlayAndStop) { - CreatePlayer(); - scoped_refptr<media::AudioBusRefCounted> samples = - media::AudioBusRefCounted::Create(1, 7331); - - player_->Play(samples); - EXPECT_TRUE(IsPlaying()); - - player_->Stop(); - EXPECT_FALSE(IsPlaying()); - - player_->Play(samples); - EXPECT_TRUE(IsPlaying()); - - player_->Stop(); - EXPECT_FALSE(IsPlaying()); - - player_->Play(samples); - EXPECT_TRUE(IsPlaying()); - - player_->Stop(); - EXPECT_FALSE(IsPlaying()); - - DeletePlayer(); -} - -TEST_F(AudioPlayerTest, OutOfOrderPlayAndStopMultiple) { - CreatePlayer(); - scoped_refptr<media::AudioBusRefCounted> samples = - media::AudioBusRefCounted::Create(1, 1337); - - player_->Stop(); - player_->Stop(); - player_->Stop(); - EXPECT_FALSE(IsPlaying()); - - player_->Play(samples); - player_->Play(samples); - EXPECT_TRUE(IsPlaying()); - - player_->Stop(); - player_->Stop(); - EXPECT_FALSE(IsPlaying()); - - DeletePlayer(); -} - -TEST_F(AudioPlayerTest, PlayingEndToEnd) { - const int kNumSamples = kDefaultFrameCount * 7 + 321; - CreatePlayer(); - - PlayAndVerifySamples(CreateRandomAudioRefCounted(0x1337, 1, kNumSamples)); - - DeletePlayer(); -} - -TEST_F(AudioPlayerTest, PlayingEndToEndRepeated) { - const int kNumSamples = kDefaultFrameCount * 7 + 537; - CreatePlayer(); - - PlayAndVerifySamples(CreateRandomAudioRefCounted(0x1337, 1, kNumSamples)); - - PlayAndVerifySamples( - CreateRandomAudioRefCounted(0x7331, 1, kNumSamples - 3123)); - - PlayAndVerifySamples(CreateRandomAudioRefCounted(0xf00d, 1, kNumSamples * 2)); - - DeletePlayer(); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/audio_recorder.h b/components/audio_modem/audio_recorder.h deleted file mode 100644 index 259e188b..0000000 --- a/components/audio_modem/audio_recorder.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_H_ -#define COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_H_ - -#include <string> - -#include "base/macros.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_converter.h" -#include "media/base/audio_parameters.h" - -namespace audio_modem { - -// The AudioRecorder class will record audio until told to stop. -class AudioRecorder { - public: - using RecordedSamplesCallback = base::Callback<void(const std::string&)>; - - // Initializes the object. Do not use this object before calling this method. - virtual void Initialize(const RecordedSamplesCallback& decode_callback) = 0; - - // If we are already recording, this function will do nothing. - virtual void Record() = 0; - // If we are already stopped, this function will do nothing. - virtual void Stop() = 0; - - // Cleans up and deletes this object. Do not use object after this call. - virtual void Finalize() = 0; - - protected: - virtual ~AudioRecorder() {} -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_H_
diff --git a/components/audio_modem/audio_recorder_impl.cc b/components/audio_modem/audio_recorder_impl.cc deleted file mode 100644 index 43633fa..0000000 --- a/components/audio_modem/audio_recorder_impl.cc +++ /dev/null
@@ -1,205 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/audio_recorder_impl.h" - -#include <algorithm> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/logging.h" -#include "base/run_loop.h" -#include "base/synchronization/waitable_event.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "content/public/browser/browser_thread.h" -#include "media/audio/audio_device_description.h" -#include "media/audio/audio_manager.h" -#include "media/base/audio_bus.h" - -namespace audio_modem { - -namespace { - -const float kProcessIntervalMs = 500.0f; // milliseconds. - -void AudioBusToString(std::unique_ptr<media::AudioBus> source, - std::string* buffer) { - buffer->resize(source->frames() * source->channels() * sizeof(float)); - float* buffer_view = reinterpret_cast<float*>(string_as_array(buffer)); - - const int channels = source->channels(); - for (int ch = 0; ch < channels; ++ch) { - for (int si = 0, di = ch; si < source->frames(); ++si, di += channels) - buffer_view[di] = source->channel(ch)[si]; - } -} - -// Called every kProcessIntervalMs to process the recorded audio. This -// converts our samples to the required sample rate, interleaves the samples -// and sends them to the whispernet decoder to process. -void ProcessSamples( - std::unique_ptr<media::AudioBus> bus, - const AudioRecorderImpl::RecordedSamplesCallback& callback) { - std::string samples; - AudioBusToString(std::move(bus), &samples); - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, base::Bind(callback, samples)); -} - -void OnLogMessage(const std::string& message) {} - -} // namespace - -// Public methods. - -AudioRecorderImpl::AudioRecorderImpl() - : is_recording_(false), - stream_(nullptr), - total_buffer_frames_(0), - buffer_frame_index_(0) { -} - -void AudioRecorderImpl::Initialize( - const RecordedSamplesCallback& decode_callback) { - decode_callback_ = decode_callback; - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioRecorderImpl::InitializeOnAudioThread, - base::Unretained(this))); -} - -AudioRecorderImpl::~AudioRecorderImpl() { -} - -void AudioRecorderImpl::Record() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioRecorderImpl::RecordOnAudioThread, - base::Unretained(this))); -} - -void AudioRecorderImpl::Stop() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioRecorderImpl::StopOnAudioThread, - base::Unretained(this))); -} - -void AudioRecorderImpl::Finalize() { - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioRecorderImpl::FinalizeOnAudioThread, - base::Unretained(this))); -} - -// Private methods. - -void AudioRecorderImpl::InitializeOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - - media::AudioParameters params; - if (params_for_testing_) { - params = *params_for_testing_; - } else { - params = media::AudioManager::Get()->GetInputStreamParameters( - media::AudioDeviceDescription::kDefaultDeviceId); - params.set_effects(media::AudioParameters::NO_EFFECTS); - } - - total_buffer_frames_ = kProcessIntervalMs * params.sample_rate() / 1000; - buffer_ = media::AudioBus::Create(params.channels(), total_buffer_frames_); - buffer_frame_index_ = 0; - - stream_ = input_stream_for_testing_ - ? input_stream_for_testing_.get() - : media::AudioManager::Get()->MakeAudioInputStream( - params, media::AudioDeviceDescription::kDefaultDeviceId, - base::Bind(&OnLogMessage)); - - if (!stream_ || !stream_->Open()) { - LOG(ERROR) << "Failed to open an input stream."; - if (stream_) { - stream_->Close(); - stream_ = nullptr; - } - return; - } - stream_->SetVolume(stream_->GetMaxVolume()); -} - -void AudioRecorderImpl::RecordOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_ || is_recording_) - return; - - VLOG(3) << "Starting recording."; - stream_->Start(this); - is_recording_ = true; -} - -void AudioRecorderImpl::StopOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_ || !is_recording_) - return; - - VLOG(3) << "Stopping recording."; - stream_->Stop(); - is_recording_ = false; -} - -void AudioRecorderImpl::StopAndCloseOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - if (!stream_) - return; - - StopOnAudioThread(); - stream_->Close(); - stream_ = nullptr; -} - -void AudioRecorderImpl::FinalizeOnAudioThread() { - DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - StopAndCloseOnAudioThread(); - delete this; -} - -void AudioRecorderImpl::OnData(media::AudioInputStream* stream, - const media::AudioBus* source, - uint32_t /* hardware_delay_bytes */, - double /* volume */) { - // source->frames() == source_params.frames_per_buffer(), so we only have - // one chunk of data in the source; correspondingly set the destination - // size to one chunk. - - int remaining_buffer_frames = buffer_->frames() - buffer_frame_index_; - int frames_to_copy = std::min(remaining_buffer_frames, source->frames()); - source->CopyPartialFramesTo(0, frames_to_copy, buffer_frame_index_, - buffer_.get()); - buffer_frame_index_ += frames_to_copy; - - // Buffer full, send it for processing. - if (buffer_->frames() == buffer_frame_index_) { - ProcessSamples(std::move(buffer_), decode_callback_); - buffer_ = media::AudioBus::Create(source->channels(), total_buffer_frames_); - buffer_frame_index_ = 0; - - // Copy any remaining frames in the source to our buffer. - int remaining_source_frames = source->frames() - frames_to_copy; - source->CopyPartialFramesTo(frames_to_copy, remaining_source_frames, - buffer_frame_index_, buffer_.get()); - buffer_frame_index_ += remaining_source_frames; - } -} - -void AudioRecorderImpl::OnError(media::AudioInputStream* /* stream */) { - LOG(ERROR) << "Error during sound recording."; - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&AudioRecorderImpl::StopAndCloseOnAudioThread, - base::Unretained(this))); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/audio_recorder_impl.h b/components/audio_modem/audio_recorder_impl.h deleted file mode 100644 index f98a95ff..0000000 --- a/components/audio_modem/audio_recorder_impl.h +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_IMPL_H_ -#define COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_IMPL_H_ - -#include <stdint.h> - -#include <memory> -#include <string> - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "components/audio_modem/audio_recorder.h" -#include "media/audio/audio_io.h" -#include "media/base/audio_parameters.h" - -namespace base { -class MessageLoop; -} - -namespace media { -class AudioBus; -} - -namespace audio_modem { - -// The AudioRecorder class will record audio until told to stop. -class AudioRecorderImpl final - : public AudioRecorder, - public media::AudioInputStream::AudioInputCallback { - public: - using RecordedSamplesCallback = base::Callback<void(const std::string&)>; - - AudioRecorderImpl(); - - // AudioRecorder overrides: - void Initialize(const RecordedSamplesCallback& decode_callback) override; - void Record() override; - void Stop() override; - void Finalize() override; - - // Takes ownership of the stream. - void set_input_stream_for_testing( - media::AudioInputStream* input_stream_for_testing) { - input_stream_for_testing_.reset(input_stream_for_testing); - } - - // Takes ownership of the params. - void set_params_for_testing(media::AudioParameters* params_for_testing) { - params_for_testing_.reset(params_for_testing); - } - - protected: - ~AudioRecorderImpl() override; - void set_is_recording(bool is_recording) { is_recording_ = is_recording; } - - private: - friend class AudioRecorderTest; - FRIEND_TEST_ALL_PREFIXES(AudioRecorderTest, BasicRecordAndStop); - FRIEND_TEST_ALL_PREFIXES(AudioRecorderTest, OutOfOrderRecordAndStopMultiple); - - // Methods to do our various operations; all of these need to be run on the - // audio thread. - void InitializeOnAudioThread(); - void RecordOnAudioThread(); - void StopOnAudioThread(); - void StopAndCloseOnAudioThread(); - void FinalizeOnAudioThread(); - - // AudioInputStream::AudioInputCallback overrides: - // Called by the audio recorder when a full packet of audio data is - // available. This is called from a special audio thread and the - // implementation should return as soon as possible. - void OnData(media::AudioInputStream* stream, - const media::AudioBus* source, - uint32_t hardware_delay_bytes, - double volume) override; - void OnError(media::AudioInputStream* stream) override; - - bool is_recording_; - - media::AudioInputStream* stream_; - - RecordedSamplesCallback decode_callback_; - - // Outside of the ctor/Initialize method, only access the next variables on - // the recording thread. - std::unique_ptr<media::AudioBus> buffer_; - int total_buffer_frames_; - int buffer_frame_index_; - - std::unique_ptr<media::AudioInputStream> input_stream_for_testing_; - std::unique_ptr<media::AudioParameters> params_for_testing_; - - DISALLOW_COPY_AND_ASSIGN(AudioRecorderImpl); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_AUDIO_RECORDER_IMPL_H_
diff --git a/components/audio_modem/audio_recorder_unittest.cc b/components/audio_modem/audio_recorder_unittest.cc deleted file mode 100644 index 5d922fc..0000000 --- a/components/audio_modem/audio_recorder_unittest.cc +++ /dev/null
@@ -1,282 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/audio_recorder.h" - -#include <stddef.h> - -#include <memory> -#include <vector> - -#include "base/bind.h" -#include "base/macros.h" -#include "base/memory/aligned_memory.h" -#include "base/run_loop.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build/build_config.h" -#include "components/audio_modem/audio_recorder_impl.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "components/audio_modem/test/random_samples.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "media/audio/audio_device_description.h" -#include "media/audio/audio_manager.h" -#include "media/base/audio_bus.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -const size_t kSomeNumber = 0x9999; - -class TestAudioInputStream : public media::AudioInputStream { - public: - TestAudioInputStream(const media::AudioParameters& params, - const std::vector<float*> channel_data, - size_t samples) - : callback_(nullptr), params_(params) { - buffer_ = media::AudioBus::CreateWrapper(2); - for (size_t i = 0; i < channel_data.size(); ++i) - buffer_->SetChannelData(i, channel_data[i]); - buffer_->set_frames(samples); - } - - ~TestAudioInputStream() override {} - - bool Open() override { return true; } - void Start(AudioInputCallback* callback) override { - DCHECK(callback); - callback_ = callback; - media::AudioManager::Get()->GetTaskRunner()->PostTask( - FROM_HERE, - base::Bind(&TestAudioInputStream::SimulateRecording, - base::Unretained(this))); - } - void Stop() override {} - void Close() override {} - double GetMaxVolume() override { return 1.0; } - void SetVolume(double volume) override {} - double GetVolume() override { return 1.0; } - bool SetAutomaticGainControl(bool enabled) override { return false; } - bool GetAutomaticGainControl() override { return true; } - bool IsMuted() override { return false; } - - private: - void SimulateRecording() { - const int fpb = params_.frames_per_buffer(); - for (int i = 0; i < buffer_->frames() / fpb; ++i) { - std::unique_ptr<media::AudioBus> source = media::AudioBus::Create(2, fpb); - buffer_->CopyPartialFramesTo(i * fpb, fpb, 0, source.get()); - callback_->OnData(this, source.get(), fpb, 1.0); - } - } - - AudioInputCallback* callback_; - media::AudioParameters params_; - std::unique_ptr<media::AudioBus> buffer_; - - DISALLOW_COPY_AND_ASSIGN(TestAudioInputStream); -}; - -} // namespace - -namespace audio_modem { - -class AudioRecorderTest : public testing::Test { - public: - AudioRecorderTest() : total_samples_(0), recorder_(nullptr) { - audio_manager_ = media::AudioManager::CreateForTesting( - base::ThreadTaskRunnerHandle::Get()); - base::RunLoop().RunUntilIdle(); - } - - ~AudioRecorderTest() override { - DeleteRecorder(); - for (size_t i = 0; i < channel_data_.size(); ++i) - base::AlignedFree(channel_data_[i]); - } - - void CreateSimpleRecorder() { - // If we have input devices, we'll create a recorder which uses a real - // input stream, if not, we'll create a recorder which uses our mock input - // stream. - if (media::AudioManager::Get()->HasAudioInputDevices()) { - DeleteRecorder(); - recorder_ = new AudioRecorderImpl(); - recorder_->Initialize(base::Bind(&AudioRecorderTest::DecodeSamples, - base::Unretained(this))); - base::RunLoop().RunUntilIdle(); - } else { - CreateRecorder(kSomeNumber); - } - } - - void CreateRecorder(size_t samples) { - DeleteRecorder(); - - params_ = media::AudioManager::Get()->GetInputStreamParameters( - media::AudioDeviceDescription::kDefaultDeviceId); - - channel_data_.clear(); - channel_data_.push_back(GenerateSamples(0x1337, samples)); - channel_data_.push_back(GenerateSamples(0x7331, samples)); - - total_samples_ = samples; - - recorder_ = new AudioRecorderImpl(); - recorder_->set_input_stream_for_testing( - new TestAudioInputStream(params_, channel_data_, samples)); - recorder_->set_params_for_testing(new media::AudioParameters(params_)); - recorder_->Initialize( - base::Bind(&AudioRecorderTest::DecodeSamples, base::Unretained(this))); - base::RunLoop().RunUntilIdle(); - } - - void DeleteRecorder() { - if (!recorder_) - return; - recorder_->Finalize(); - recorder_ = nullptr; - base::RunLoop().RunUntilIdle(); - } - - void RecordAndVerifySamples() { - received_samples_.clear(); - run_loop_.reset(new base::RunLoop()); - recorder_->Record(); - run_loop_->Run(); - } - - void DecodeSamples(const std::string& samples) { - received_samples_ += samples; - // We expect one less decode than our total samples would ideally have - // triggered since we process data in 4k chunks. So our sample processing - // will never rarely be perfectly aligned with 0.5s worth of samples, hence - // we will almost always run with a buffer of leftover samples that will - // not get sent to this callback since the recorder will be waiting for - // more data. - const size_t decode_buffer = params_.sample_rate() / 2; // 0.5s - const size_t expected_samples = - (total_samples_ / decode_buffer - 1) * decode_buffer; - const size_t expected_samples_size = - expected_samples * sizeof(float) * params_.channels(); - if (received_samples_.size() == expected_samples_size) { - VerifySamples(); - run_loop_->Quit(); - } - } - - void VerifySamples() { - int differences = 0; - - float* buffer_view = - reinterpret_cast<float*>(string_as_array(&received_samples_)); - const int channels = params_.channels(); - const int frames = - received_samples_.size() / sizeof(float) / params_.channels(); - for (int ch = 0; ch < channels; ++ch) { - for (int si = 0, di = ch; si < frames; ++si, di += channels) - differences += (buffer_view[di] != channel_data_[ch][si]); - } - - ASSERT_EQ(0, differences); - } - - protected: - float* GenerateSamples(int random_seed, size_t size) { - float* samples = static_cast<float*>(base::AlignedAlloc( - size * sizeof(float), media::AudioBus::kChannelAlignment)); - PopulateSamples(0x1337, size, samples); - return samples; - } - bool IsRecording() { - base::RunLoop().RunUntilIdle(); - return recorder_->is_recording_; - } - - content::TestBrowserThreadBundle thread_bundle_; - media::ScopedAudioManagerPtr audio_manager_; - - std::vector<float*> channel_data_; - media::AudioParameters params_; - size_t total_samples_; - - // Deleted by calling Finalize() on the object. - AudioRecorderImpl* recorder_; - - std::string received_samples_; - - std::unique_ptr<base::RunLoop> run_loop_; -}; - - -// http://crbug.com/463854 -#if defined(OS_MACOSX) -#define MAYBE_BasicRecordAndStop DISABLED_BasicRecordAndStop -#else -#define MAYBE_BasicRecordAndStop BasicRecordAndStop -#endif - -TEST_F(AudioRecorderTest, MAYBE_BasicRecordAndStop) { - CreateSimpleRecorder(); - - recorder_->Record(); - EXPECT_TRUE(IsRecording()); - - recorder_->Stop(); - EXPECT_FALSE(IsRecording()); - - recorder_->Record(); - EXPECT_TRUE(IsRecording()); - - recorder_->Stop(); - EXPECT_FALSE(IsRecording()); - - recorder_->Record(); - EXPECT_TRUE(IsRecording()); - - recorder_->Stop(); - EXPECT_FALSE(IsRecording()); - - DeleteRecorder(); -} - -// http://crbug.com/460685 -#if defined(OS_MACOSX) -#define MAYBE_OutOfOrderRecordAndStopMultiple \ - DISABLED_OutOfOrderRecordAndStopMultiple -#else -#define MAYBE_OutOfOrderRecordAndStopMultiple \ - OutOfOrderRecordAndStopMultiple -#endif - -TEST_F(AudioRecorderTest, MAYBE_OutOfOrderRecordAndStopMultiple) { - CreateSimpleRecorder(); - - recorder_->Stop(); - recorder_->Stop(); - recorder_->Stop(); - EXPECT_FALSE(IsRecording()); - - recorder_->Record(); - recorder_->Record(); - EXPECT_TRUE(IsRecording()); - - recorder_->Stop(); - recorder_->Stop(); - EXPECT_FALSE(IsRecording()); - - DeleteRecorder(); -} - -TEST_F(AudioRecorderTest, RecordingEndToEnd) { - const int kNumSamples = 48000 * 3; - CreateRecorder(kNumSamples); - - RecordAndVerifySamples(); - - DeleteRecorder(); -} - -// TODO(rkc): Add tests with recording different sample rates. - -} // namespace audio_modem
diff --git a/components/audio_modem/constants.cc b/components/audio_modem/constants.cc deleted file mode 100644 index d85da14..0000000 --- a/components/audio_modem/constants.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/public/audio_modem_types.h" - -namespace audio_modem { - -const int kDefaultRepetitions = 5; -const float kDefaultSampleRate = 48000.0f; -const int kDefaultBitsPerSample = 16; -const float kDefaultCarrierFrequency = 18500.0f; -const media::ChannelLayout kDefaultChannelLayout = media::CHANNEL_LAYOUT_STEREO; - -} // namespace audio_modem
diff --git a/components/audio_modem/modem_impl.cc b/components/audio_modem/modem_impl.cc deleted file mode 100644 index 447250ca..0000000 --- a/components/audio_modem/modem_impl.cc +++ /dev/null
@@ -1,344 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/modem_impl.h" - -#include <stdint.h> - -#include <algorithm> -#include <limits> -#include <memory> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "components/audio_modem/audio_modem_switches.h" -#include "components/audio_modem/audio_player_impl.h" -#include "components/audio_modem/audio_recorder_impl.h" -#include "components/audio_modem/public/whispernet_client.h" -#include "content/public/browser/browser_thread.h" -#include "media/audio/audio_manager.h" -#include "media/audio/audio_manager_base.h" -#include "media/base/audio_bus.h" -#include "third_party/webrtc/common_audio/wav_file.h" - -namespace audio_modem { - -namespace { - -const int kMaxSamples = 10000; -const int kTokenTimeoutMs = 2000; -const int kMonoChannelCount = 1; - -// UrlSafe is defined as: -// '/' represented by a '_' and '+' represented by a '-' -// TODO(ckehoe): Move this to a central place. -std::string FromUrlSafe(std::string token) { - base::ReplaceChars(token, "-", "+", &token); - base::ReplaceChars(token, "_", "/", &token); - return token; -} -std::string ToUrlSafe(std::string token) { - base::ReplaceChars(token, "+", "-", &token); - base::ReplaceChars(token, "/", "_", &token); - return token; -} - -// TODO(ckehoe): Move this to a central place. -std::string AudioTypeToString(AudioType audio_type) { - if (audio_type == AUDIBLE) - return "audible"; - if (audio_type == INAUDIBLE) - return "inaudible"; - - NOTREACHED() << "Got unexpected token type " << audio_type; - return std::string(); -} - -bool ReadBooleanFlag(const std::string& flag, bool default_value) { - const std::string flag_value = base::ToLowerASCII( - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(flag)); - if (flag_value == "true" || flag_value == "1") - return true; - if (flag_value == "false" || flag_value == "0") - return false; - LOG_IF(ERROR, !flag_value.empty()) - << "Unrecognized value \"" << flag_value << " for flag " - << flag << ". Defaulting to " << default_value; - return default_value; -} - -} // namespace - - -// Public functions. - -ModemImpl::ModemImpl() : client_(nullptr), recorder_(nullptr) { - // TODO(rkc): Move all of these into initializer lists once it is allowed. - should_be_playing_[AUDIBLE] = false; - should_be_playing_[INAUDIBLE] = false; - should_be_recording_[AUDIBLE] = false; - should_be_recording_[INAUDIBLE] = false; - - player_enabled_[AUDIBLE] = ReadBooleanFlag( - switches::kAudioModemEnableAudibleBroadcast, true); - player_enabled_[INAUDIBLE] = ReadBooleanFlag( - switches::kAudioModemEnableInaudibleBroadcast, true); - player_[AUDIBLE] = nullptr; - player_[INAUDIBLE] = nullptr; - - samples_caches_.resize(2); - samples_caches_[AUDIBLE] = new SamplesMap(kMaxSamples); - samples_caches_[INAUDIBLE] = new SamplesMap(kMaxSamples); -} - -void ModemImpl::Initialize(WhispernetClient* client, - const TokensCallback& tokens_cb) { - DCHECK(client); - client_ = client; - tokens_cb_ = tokens_cb; - - // These will be unregistered on destruction, so unretained is safe to use. - client_->RegisterTokensCallback( - base::Bind(&ModemImpl::OnTokensFound, base::Unretained(this))); - client_->RegisterSamplesCallback( - base::Bind(&ModemImpl::OnTokenEncoded, base::Unretained(this))); - - if (!player_[AUDIBLE]) - player_[AUDIBLE] = new AudioPlayerImpl(); - player_[AUDIBLE]->Initialize(); - - if (!player_[INAUDIBLE]) - player_[INAUDIBLE] = new AudioPlayerImpl(); - player_[INAUDIBLE]->Initialize(); - - decode_cancelable_cb_.Reset(base::Bind( - &ModemImpl::DecodeSamplesConnector, base::Unretained(this))); - if (!recorder_) - recorder_ = new AudioRecorderImpl(); - recorder_->Initialize(decode_cancelable_cb_.callback()); - - dump_tokens_dir_ = base::FilePath(base::CommandLine::ForCurrentProcess() - ->GetSwitchValueNative(switches::kAudioModemDumpTokensToDir)); -} - -ModemImpl::~ModemImpl() { - if (player_[AUDIBLE]) - player_[AUDIBLE]->Finalize(); - if (player_[INAUDIBLE]) - player_[INAUDIBLE]->Finalize(); - if (recorder_) - recorder_->Finalize(); - - // Whispernet initialization may never have completed. - if (client_) { - client_->RegisterTokensCallback(TokensCallback()); - client_->RegisterSamplesCallback(SamplesCallback()); - } -} - -void ModemImpl::StartPlaying(AudioType type) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - should_be_playing_[type] = true; - // If we don't have our token encoded yet, this check will be false, for now. - // Once our token is encoded, OnTokenEncoded will call UpdateToken, which - // will call this code again (if we're still supposed to be playing). - SamplesMap::iterator samples = - samples_caches_[type]->Get(playing_token_[type]); - if (samples != samples_caches_[type]->end()) { - DCHECK(!playing_token_[type].empty()); - if (player_enabled_[type]) { - started_playing_[type] = base::Time::Now(); - player_[type]->Play(samples->second); - - // If we're playing, we always record to hear what we are playing. - recorder_->Record(); - } else { - DVLOG(3) << "Skipping playback for disabled " << AudioTypeToString(type) - << " player."; - } - } -} - -void ModemImpl::StopPlaying(AudioType type) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - should_be_playing_[type] = false; - player_[type]->Stop(); - // If we were only recording to hear our own played tokens, stop. - if (!should_be_recording_[AUDIBLE] && !should_be_recording_[INAUDIBLE]) - recorder_->Stop(); - playing_token_[type] = std::string(); -} - -void ModemImpl::StartRecording(AudioType type) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - should_be_recording_[type] = true; - recorder_->Record(); -} - -void ModemImpl::StopRecording(AudioType type) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - should_be_recording_[type] = false; - recorder_->Stop(); -} - -void ModemImpl::SetToken(AudioType type, - const std::string& url_safe_token) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - std::string token = FromUrlSafe(url_safe_token); - if (samples_caches_[type]->Get(token) == samples_caches_[type]->end()) { - client_->EncodeToken(token, type, token_params_); - } else { - UpdateToken(type, token); - } -} - -const std::string ModemImpl::GetToken(AudioType type) const { - return playing_token_[type]; -} - -bool ModemImpl::IsPlayingTokenHeard(AudioType type) const { - base::TimeDelta tokenTimeout = - base::TimeDelta::FromMilliseconds(kTokenTimeoutMs); - - // This is a bit of a hack. If we haven't been playing long enough, - // return true to avoid tripping an audio fail alarm. - if (base::Time::Now() - started_playing_[type] < tokenTimeout) - return true; - - return base::Time::Now() - heard_own_token_[type] < tokenTimeout; -} - -void ModemImpl::SetTokenParams(AudioType type, const TokenParameters& params) { - DCHECK_GT(params.length, 0u); - token_params_[type] = params; - - // TODO(ckehoe): Make whispernet handle different token lengths - // simultaneously without reinitializing the decoder over and over. -} - -// static -std::unique_ptr<Modem> Modem::Create() { - return base::WrapUnique<Modem>(new ModemImpl); -} - -// Private functions. - -void ModemImpl::OnTokenEncoded( - AudioType type, - const std::string& token, - const scoped_refptr<media::AudioBusRefCounted>& samples) { - samples_caches_[type]->Put(token, samples); - DumpToken(type, token, samples.get()); - UpdateToken(type, token); -} - -void ModemImpl::OnTokensFound(const std::vector<AudioToken>& tokens) { - std::vector<AudioToken> tokens_to_report; - for (const auto& token : tokens) { - AudioType type = token.audible ? AUDIBLE : INAUDIBLE; - if (playing_token_[type] == token.token) - heard_own_token_[type] = base::Time::Now(); - - if (should_be_recording_[AUDIBLE] && token.audible) { - tokens_to_report.push_back(token); - } else if (should_be_recording_[INAUDIBLE] && !token.audible) { - tokens_to_report.push_back(token); - } - } - - if (!tokens_to_report.empty()) - tokens_cb_.Run(tokens_to_report); -} - -void ModemImpl::UpdateToken(AudioType type, const std::string& token) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - if (playing_token_[type] == token) - return; - - // Update token. - playing_token_[type] = token; - - // If we are supposed to be playing this token type at this moment, switch - // out playback with the new samples. - if (should_be_playing_[type]) - RestartPlaying(type); -} - -void ModemImpl::RestartPlaying(AudioType type) { - DCHECK(type == AUDIBLE || type == INAUDIBLE); - // We should already have this token in the cache. This function is not - // called from anywhere except update token and only once we have our samples - // in the cache. - DCHECK(samples_caches_[type]->Get(playing_token_[type]) != - samples_caches_[type]->end()); - - player_[type]->Stop(); - StartPlaying(type); -} - -void ModemImpl::DecodeSamplesConnector(const std::string& samples) { - // If we are either supposed to be recording *or* playing, audible or - // inaudible, we should be decoding that type. This is so that if we are - // just playing, we will still decode our recorded token so we can check - // if we heard our own token. Whether or not we report the token to the - // server is checked for and handled in OnTokensFound. - - bool decode_audible = - should_be_recording_[AUDIBLE] || should_be_playing_[AUDIBLE]; - bool decode_inaudible = - should_be_recording_[INAUDIBLE] || should_be_playing_[INAUDIBLE]; - - if (decode_audible && decode_inaudible) { - client_->DecodeSamples(BOTH, samples, token_params_); - } else if (decode_audible) { - client_->DecodeSamples(AUDIBLE, samples, token_params_); - } else if (decode_inaudible) { - client_->DecodeSamples(INAUDIBLE, samples, token_params_); - } -} - -void ModemImpl::DumpToken(AudioType audio_type, - const std::string& token, - const media::AudioBus* samples) { - if (dump_tokens_dir_.empty()) - return; - - // Convert the samples to 16-bit integers. - std::vector<int16_t> int_samples; - int_samples.reserve(samples->frames()); - for (int i = 0; i < samples->frames(); i++) { - int_samples.push_back(round( - samples->channel(0)[i] * std::numeric_limits<int16_t>::max())); - } - DCHECK_EQ(static_cast<int>(int_samples.size()), samples->frames()); - DCHECK_EQ(kMonoChannelCount, samples->channels()); - - const std::string filename = base::StringPrintf("%s %s.wav", - AudioTypeToString(audio_type).c_str(), ToUrlSafe(token).c_str()); - DVLOG(3) << "Dumping token " << filename; - - std::string file_str; -#if defined(OS_WIN) - base::FilePath file_path = dump_tokens_dir_.Append( - base::SysNativeMBToWide(filename)); - file_str = base::SysWideToNativeMB(file_path.value()); -#else - file_str = dump_tokens_dir_.Append(filename).value(); -#endif - - webrtc::WavWriter writer(file_str, kDefaultSampleRate, kMonoChannelCount); - writer.WriteSamples(int_samples.data(), int_samples.size()); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/modem_impl.h b/components/audio_modem/modem_impl.h deleted file mode 100644 index ec6beb5..0000000 --- a/components/audio_modem/modem_impl.h +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_MODEM_IMPL_H_ -#define COMPONENTS_AUDIO_MODEM_MODEM_IMPL_H_ - -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/cancelable_callback.h" -#include "base/containers/mru_cache.h" -#include "base/files/file_path.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_vector.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "components/audio_modem/public/modem.h" -#include "media/base/audio_bus.h" - -namespace base { -class Time; -} - -namespace audio_modem { - -class AudioPlayer; -class AudioRecorder; -class WhispernetClient; - -// The ModemImpl class manages the playback and recording of tokens. -// Clients should not necessary expect the modem to play or record continuously. -// In the future, it may timeslice multiple tokens, or implement carrier sense. -class ModemImpl final : public Modem { - public: - ModemImpl(); - ~ModemImpl() override; - - // Modem overrides: - void Initialize(WhispernetClient* client, - const TokensCallback& tokens_cb) override; - void StartPlaying(AudioType type) override; - void StopPlaying(AudioType type) override; - void StartRecording(AudioType type) override; - void StopRecording(AudioType type) override; - void SetToken(AudioType type, const std::string& url_safe_token) override; - const std::string GetToken(AudioType type) const override; - bool IsPlayingTokenHeard(AudioType type) const override; - void SetTokenParams(AudioType type, const TokenParameters& params) override; - - void set_player_for_testing(AudioType type, AudioPlayer* player) { - player_[type] = player; - } - void set_recorder_for_testing(AudioRecorder* recorder) { - recorder_ = recorder; - } - - private: - using SamplesMap = base::MRUCache<std::string, - scoped_refptr<media::AudioBusRefCounted>>; - - // Receives the audio samples from encoding a token. - void OnTokenEncoded(AudioType type, - const std::string& token, - const scoped_refptr<media::AudioBusRefCounted>& samples); - - // Receives any tokens found by decoding audio samples. - void OnTokensFound(const std::vector<AudioToken>& tokens); - - // Update our currently playing token with the new token. Change the playing - // samples if needed. Prerequisite: Samples corresponding to this token - // should already be in the samples cache. - void UpdateToken(AudioType type, const std::string& token); - - void RestartPlaying(AudioType type); - - void DecodeSamplesConnector(const std::string& samples); - - void DumpToken(AudioType audio_type, - const std::string& token, - const media::AudioBus* samples); - - WhispernetClient* client_; - - // Callbacks to send tokens back to the client. - TokensCallback tokens_cb_; - - // This cancelable callback is passed to the recorder. The recorder's - // destruction will happen on the audio thread, so it can outlive us. - base::CancelableCallback<void(const std::string&)> decode_cancelable_cb_; - - // We use the AudioType enum to index into all our data structures that work - // on values for both audible and inaudible. - static_assert(AUDIBLE == 0, "AudioType::AUDIBLE should be 0."); - static_assert(INAUDIBLE == 1, "AudioType::INAUDIBLE should be 1."); - - // Indexed using enum AudioType. - bool player_enabled_[2]; - bool should_be_playing_[2]; - bool should_be_recording_[2]; - - // AudioPlayer and AudioRecorder objects are self-deleting. When we call - // Finalize on them, they clean themselves up on the Audio thread. - // Indexed using enum AudioType. - AudioPlayer* player_[2]; - AudioRecorder* recorder_; - - // Indexed using enum AudioType. - std::string playing_token_[2]; - TokenParameters token_params_[2]; - base::Time started_playing_[2]; - base::Time heard_own_token_[2]; - - // Cache that holds the encoded samples. After reaching its limit, the cache - // expires the oldest samples first. - // Indexed using enum AudioType. - ScopedVector<SamplesMap> samples_caches_; - - base::FilePath dump_tokens_dir_; - - DISALLOW_COPY_AND_ASSIGN(ModemImpl); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_MODEM_IMPL_H_
diff --git a/components/audio_modem/modem_unittest.cc b/components/audio_modem/modem_unittest.cc deleted file mode 100644 index b18c7f8..0000000 --- a/components/audio_modem/modem_unittest.cc +++ /dev/null
@@ -1,155 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/public/modem.h" - -#include <memory> -#include <vector> - -#include "base/bind.h" -#include "base/macros.h" -#include "base/message_loop/message_loop.h" -#include "components/audio_modem/audio_player.h" -#include "components/audio_modem/audio_recorder.h" -#include "components/audio_modem/modem_impl.h" -#include "components/audio_modem/test/random_samples.h" -#include "components/audio_modem/test/stub_whispernet_client.h" -#include "media/base/audio_bus.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace audio_modem { - -class AudioPlayerStub final : public AudioPlayer { - public: - AudioPlayerStub() : is_playing_(false) {} - ~AudioPlayerStub() override {} - - // AudioPlayer overrides: - void Initialize() override {} - void Play(const scoped_refptr<media::AudioBusRefCounted>&) override { - is_playing_ = true; - } - void Stop() override { is_playing_ = false; } - void Finalize() override { delete this; } - - bool IsPlaying() { return is_playing_; } - - private: - bool is_playing_; - DISALLOW_COPY_AND_ASSIGN(AudioPlayerStub); -}; - -class AudioRecorderStub final : public AudioRecorder { - public: - AudioRecorderStub() : is_recording_(false) {} - ~AudioRecorderStub() override {} - - // AudioRecorder overrides: - void Initialize(const RecordedSamplesCallback& cb) override { cb_ = cb; } - void Record() override { is_recording_ = true; } - void Stop() override { is_recording_ = false; } - void Finalize() override { delete this; } - - bool IsRecording() { return is_recording_; } - - void TriggerDecodeRequest() { - if (!cb_.is_null()) - cb_.Run(std::string(0x1337, 'a')); - } - - private: - RecordedSamplesCallback cb_; - bool is_recording_; - - DISALLOW_COPY_AND_ASSIGN(AudioRecorderStub); -}; - -class ModemTest : public testing::Test { - public: - ModemTest() - : modem_(new ModemImpl), - audible_player_(new AudioPlayerStub), - inaudible_player_(new AudioPlayerStub), - recorder_(new AudioRecorderStub), - last_received_decode_type_(AUDIO_TYPE_UNKNOWN) { - std::vector<AudioToken> tokens; - tokens.push_back(AudioToken("abcdef", true)); - tokens.push_back(AudioToken("123456", false)); - client_.reset(new StubWhispernetClient( - CreateRandomAudioRefCounted(0x123, 1, 0x321), tokens)); - - // TODO(ckehoe): Pass these into the Modem constructor instead. - modem_->set_player_for_testing(AUDIBLE, audible_player_); - modem_->set_player_for_testing(INAUDIBLE, inaudible_player_); - modem_->set_recorder_for_testing(recorder_); - modem_->Initialize( - client_.get(), - base::Bind(&ModemTest::GetTokens, base::Unretained(this))); - } - - ~ModemTest() override {} - - protected: - void GetTokens(const std::vector<AudioToken>& tokens) { - last_received_decode_type_ = AUDIO_TYPE_UNKNOWN; - for (const auto& token : tokens) { - if (token.audible && last_received_decode_type_ == INAUDIBLE) { - last_received_decode_type_ = BOTH; - } else if (!token.audible && last_received_decode_type_ == AUDIBLE) { - last_received_decode_type_ = BOTH; - } else if (token.audible) { - last_received_decode_type_ = AUDIBLE; - } else { - last_received_decode_type_ = INAUDIBLE; - } - } - } - - base::MessageLoop message_loop_; - // This order is important. The WhispernetClient needs to outlive the Modem. - std::unique_ptr<WhispernetClient> client_; - std::unique_ptr<ModemImpl> modem_; - - // These will be deleted by the Modem's destructor calling finalize on them. - AudioPlayerStub* audible_player_; - AudioPlayerStub* inaudible_player_; - AudioRecorderStub* recorder_; - - AudioType last_received_decode_type_; - - private: - DISALLOW_COPY_AND_ASSIGN(ModemTest); -}; - -TEST_F(ModemTest, EncodeToken) { - modem_->StartPlaying(AUDIBLE); - // No token yet, player shouldn't be playing. - EXPECT_FALSE(audible_player_->IsPlaying()); - - modem_->SetToken(INAUDIBLE, "abcd"); - // No *audible* token yet, so player still shouldn't be playing. - EXPECT_FALSE(audible_player_->IsPlaying()); - - modem_->SetToken(AUDIBLE, "abcd"); - EXPECT_TRUE(audible_player_->IsPlaying()); -} - -TEST_F(ModemTest, Record) { - recorder_->TriggerDecodeRequest(); - EXPECT_EQ(AUDIO_TYPE_UNKNOWN, last_received_decode_type_); - - modem_->StartRecording(AUDIBLE); - recorder_->TriggerDecodeRequest(); - EXPECT_EQ(AUDIBLE, last_received_decode_type_); - - modem_->StartRecording(INAUDIBLE); - recorder_->TriggerDecodeRequest(); - EXPECT_EQ(BOTH, last_received_decode_type_); - - modem_->StopRecording(AUDIBLE); - recorder_->TriggerDecodeRequest(); - EXPECT_EQ(INAUDIBLE, last_received_decode_type_); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/public/audio_modem_types.h b/components/audio_modem/public/audio_modem_types.h deleted file mode 100644 index 3ccf688..0000000 --- a/components/audio_modem/public/audio_modem_types.h +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_PUBLIC_AUDIO_MODEM_TYPES_H_ -#define COMPONENTS_AUDIO_MODEM_PUBLIC_AUDIO_MODEM_TYPES_H_ - -#include <stddef.h> - -#include <string> -#include <vector> - -#include "base/callback_forward.h" -#include "base/memory/ref_counted.h" -#include "media/base/channel_layout.h" - -// Various constants and types used for the audio modem. -// TODO(ckehoe): Move the constants out into their own header. - -namespace audio_modem { - -// Number of repetitions of the audio token in one sequence of samples. -extern const int kDefaultRepetitions; - -// Whispernet encoding parameters. These need to be the same on all platforms. -extern const float kDefaultSampleRate; -extern const int kDefaultBitsPerSample; -extern const float kDefaultCarrierFrequency; - -// This really needs to be configurable since it doesn't need -// to be consistent across platforms, or even playing/recording. -extern const media::ChannelLayout kDefaultChannelLayout; - -// Enum to represent the audio band (audible vs. ultrasound). -// AUDIBLE and INAUDIBLE are used as array indices. -enum AudioType { - AUDIBLE = 0, - INAUDIBLE = 1, - BOTH = 2, - AUDIO_TYPE_UNKNOWN = 3, -}; - -// Struct representing an audio token. -// TODO(ckehoe): Make this use the AudioType enum instead of a boolean. -struct AudioToken final { - AudioToken(const std::string& token, bool audible) - : token(token), - audible(audible) {} - - std::string token; - bool audible; -}; - -// Struct to hold the encoding parameters for tokens. -// Parity is on by default. -struct TokenParameters { - TokenParameters() : TokenParameters(0, false, true) {} - - explicit TokenParameters(size_t length) - : TokenParameters(length, false, true) {} - - TokenParameters(size_t length, bool crc, bool parity) - : length(length), crc(crc), parity(parity) {} - - size_t length; - bool crc; - bool parity; -}; - -// Callback to pass around found tokens. -using TokensCallback = base::Callback<void(const std::vector<AudioToken>&)>; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_PUBLIC_AUDIO_MODEM_TYPES_H_
diff --git a/components/audio_modem/public/modem.h b/components/audio_modem/public/modem.h deleted file mode 100644 index 4dfeeead..0000000 --- a/components/audio_modem/public/modem.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_PUBLIC_MODEM_H_ -#define COMPONENTS_AUDIO_MODEM_PUBLIC_MODEM_H_ - -#include <memory> -#include <string> - -#include "components/audio_modem/public/audio_modem_types.h" - -namespace audio_modem { - -class WhispernetClient; - -class Modem { - public: - virtual ~Modem() {} - - // Initializes the object. Do not use this object before calling this method. - virtual void Initialize(WhispernetClient* client, - const TokensCallback& tokens_cb) = 0; - - virtual void StartPlaying(AudioType type) = 0; - virtual void StopPlaying(AudioType type) = 0; - - virtual void StartRecording(AudioType type) = 0; - virtual void StopRecording(AudioType type) = 0; - - virtual void SetToken(AudioType type, - const std::string& url_safe_token) = 0; - - virtual const std::string GetToken(AudioType type) const = 0; - - virtual bool IsPlayingTokenHeard(AudioType type) const = 0; - - virtual void SetTokenParams(AudioType type, - const TokenParameters& params) = 0; - - static std::unique_ptr<Modem> Create(); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_PUBLIC_MODEM_H_
diff --git a/components/audio_modem/public/whispernet_client.h b/components/audio_modem/public/whispernet_client.h deleted file mode 100644 index 48d1efa9..0000000 --- a/components/audio_modem/public/whispernet_client.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_PUBLIC_WHISPERNET_CLIENT_H_ -#define COMPONENTS_AUDIO_MODEM_PUBLIC_WHISPERNET_CLIENT_H_ - -#include <string> - -#include "base/memory/ref_counted.h" -#include "components/audio_modem/public/audio_modem_types.h" -#include "media/base/audio_bus.h" - -namespace audio_modem { - -// Generic callback to indicate a boolean success or failure. -using SuccessCallback = base::Callback<void(bool)>; - -// Callback to receive encoded samples from Whispernet. -// AudioType type: Type of audio encoding - AUDIBLE or INAUDIBLE. -// const std::string& token: The token that we encoded. -// const scoped_refptr<media::AudioBusRefCounted>& samples - Encoded samples. -using SamplesCallback = - base::Callback<void(AudioType, - const std::string&, - const scoped_refptr<media::AudioBusRefCounted>&)>; - -// A client for the Whispernet audio library, -// responsible for the actual encoding and decoding of tokens. -class WhispernetClient { - public: - // Initialize the whispernet client and call the callback when done. The - // parameter indicates whether we succeeded or failed. - virtual void Initialize(const SuccessCallback& init_callback) = 0; - - // Fires an event to request a token encode. - virtual void EncodeToken(const std::string& token, - AudioType type, - const TokenParameters token_params[2]) = 0; - // Fires an event to request a decode for the given samples. - virtual void DecodeSamples(AudioType type, - const std::string& samples, - const TokenParameters token_params[2]) = 0; - - // Callback registration methods. The modem will set these to receive data. - virtual void RegisterTokensCallback( - const TokensCallback& tokens_callback) = 0; - virtual void RegisterSamplesCallback( - const SamplesCallback& samples_callback) = 0; - - // Don't cache these callbacks, as they may become invalid at any time. - // Always invoke callbacks directly through these accessors. - virtual TokensCallback GetTokensCallback() = 0; - virtual SamplesCallback GetSamplesCallback() = 0; - virtual SuccessCallback GetInitializedCallback() = 0; - - virtual ~WhispernetClient() {} -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_PUBLIC_WHISPERNET_CLIENT_H_
diff --git a/components/audio_modem/test/random_samples.cc b/components/audio_modem/test/random_samples.cc deleted file mode 100644 index 86a59cb6..0000000 --- a/components/audio_modem/test/random_samples.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/test/random_samples.h" - -#include <cstdlib> - -#include "build/build_config.h" -#include "media/base/audio_bus.h" - -namespace audio_modem { - -void PopulateSamples(unsigned int random_seed, size_t size, float* samples) { -// On Windows, rand() is threadsafe, and rand_r() is not available. -#if defined(OS_WIN) - srand(random_seed); - for (size_t i = 0; i < size; ++i) - samples[i] = (2.0 * rand() / RAND_MAX) - 1; // NOLINT -#else - for (size_t i = 0; i < size; ++i) - samples[i] = (2.0 * rand_r(&random_seed) / RAND_MAX) - 1; -#endif -} - -scoped_refptr<media::AudioBusRefCounted> -CreateRandomAudioRefCounted(int random_seed, int channels, int samples) { - scoped_refptr<media::AudioBusRefCounted> bus = - media::AudioBusRefCounted::Create(channels, samples); - for (int ch = 0; ch < channels; ++ch) - PopulateSamples(random_seed, samples, bus->channel(ch)); - return bus; -} - -} // namespace audio_modem
diff --git a/components/audio_modem/test/random_samples.h b/components/audio_modem/test/random_samples.h deleted file mode 100644 index a786648..0000000 --- a/components/audio_modem/test/random_samples.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_TEST_RANDOM_SAMPLES_H_ -#define COMPONENTS_AUDIO_MODEM_TEST_RANDOM_SAMPLES_H_ - -#include <stddef.h> - -#include "base/memory/ref_counted.h" - -namespace media { -class AudioBus; -class AudioBusRefCounted; -} - -namespace audio_modem { - -// Populate random samples given a random seed into the samples array. -void PopulateSamples(unsigned int random_seed, size_t size, float* samples); - -// Create an ref counted audio bus populated with random samples. -scoped_refptr<media::AudioBusRefCounted> - CreateRandomAudioRefCounted(int random_seed, int channels, int samples); - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_TEST_RANDOM_SAMPLES_H_
diff --git a/components/audio_modem/test/stub_modem.cc b/components/audio_modem/test/stub_modem.cc deleted file mode 100644 index ea0fb08..0000000 --- a/components/audio_modem/test/stub_modem.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/test/stub_modem.h" - -#include "base/base64.h" -#include "base/logging.h" - -namespace audio_modem { - -StubModem::StubModem() { - playing_[AUDIBLE] = false; - playing_[INAUDIBLE] = false; - recording_[AUDIBLE] = false; - recording_[INAUDIBLE] = false; -} - -StubModem::~StubModem() {} - -void StubModem::Initialize(WhispernetClient* whispernet_client, - const TokensCallback& tokens_cb) { - tokens_callback_ = tokens_cb; -} - -void StubModem::StartPlaying(AudioType type) { - playing_[type] = true; -} - -void StubModem::StopPlaying(AudioType type) { - playing_[type] = false; -} - -void StubModem::StartRecording(AudioType type) { - recording_[type] = true; -} - -void StubModem::StopRecording(AudioType type) { - recording_[type] = false; -} - -const std::string StubModem::GetToken(AudioType type) const { - return std::string(); -} - -bool StubModem::IsPlayingTokenHeard(AudioType type) const { - return false; -} - -bool StubModem::IsRecording(AudioType type) const { - return recording_[type]; -} - -bool StubModem::IsPlaying(AudioType type) const { - return playing_[type]; -} - -void StubModem::DeliverTokens(const std::vector<AudioToken>& tokens) { - std::vector<AudioToken> encoded_tokens; - for (const AudioToken& token : tokens) { - std::string encoded_token; - base::Base64Encode(token.token, & encoded_token); - encoded_tokens.push_back(AudioToken(encoded_token, token.audible)); - } - DCHECK_EQ(tokens.size(), encoded_tokens.size()); - tokens_callback_.Run(encoded_tokens); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/test/stub_modem.h b/components/audio_modem/test/stub_modem.h deleted file mode 100644 index 63f7f000..0000000 --- a/components/audio_modem/test/stub_modem.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_TEST_STUB_MODEM_H_ -#define COMPONENTS_AUDIO_MODEM_TEST_STUB_MODEM_H_ - -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "components/audio_modem/public/modem.h" - -namespace audio_modem { - -class StubModem final : public Modem { - public: - StubModem(); - ~StubModem() override; - - // AudioManager overrides: - void Initialize(WhispernetClient* whispernet_client, - const TokensCallback& tokens_cb) override; - void StartPlaying(AudioType type) override; - void StopPlaying(AudioType type) override; - void StartRecording(AudioType type) override; - void StopRecording(AudioType type) override; - void SetToken(AudioType type, const std::string& url_unsafe_token) override {} - const std::string GetToken(AudioType type) const override; - bool IsPlayingTokenHeard(AudioType type) const override; - void SetTokenParams(AudioType type, const TokenParameters& params) override {} - - bool IsRecording(AudioType type) const; - bool IsPlaying(AudioType type) const; - - // Encodes tokens as base64 and then delivers them. - void DeliverTokens(const std::vector<AudioToken>& tokens); - - private: - // Indexed using enum AudioType. - bool playing_[2]; - bool recording_[2]; - - TokensCallback tokens_callback_; - - DISALLOW_COPY_AND_ASSIGN(StubModem); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_TEST_STUB_MODEM_H_
diff --git a/components/audio_modem/test/stub_whispernet_client.cc b/components/audio_modem/test/stub_whispernet_client.cc deleted file mode 100644 index e2763ce..0000000 --- a/components/audio_modem/test/stub_whispernet_client.cc +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/audio_modem/test/stub_whispernet_client.h" - -namespace audio_modem { - -StubWhispernetClient::StubWhispernetClient( - scoped_refptr<media::AudioBusRefCounted> samples, - const std::vector<AudioToken>& tokens) - : samples_(samples), - tokens_(tokens) { -} - -StubWhispernetClient::~StubWhispernetClient() {} - -void StubWhispernetClient::Initialize(const SuccessCallback& init_callback) {} - -void StubWhispernetClient::EncodeToken(const std::string& token, - AudioType type, - const TokenParameters token_params[2]) { - if (!samples_cb_.is_null()) - samples_cb_.Run(type, token, samples_); -} - -void StubWhispernetClient::DecodeSamples( - AudioType type, - const std::string& samples, - const TokenParameters token_params[2]) { - if (!tokens_cb_.is_null()) - tokens_cb_.Run(tokens_); -} - -void StubWhispernetClient::RegisterTokensCallback( - const TokensCallback& tokens_cb) { - tokens_cb_ = tokens_cb; -} - -void StubWhispernetClient::RegisterSamplesCallback( - const SamplesCallback& samples_cb) { - samples_cb_ = samples_cb; -} - -TokensCallback StubWhispernetClient::GetTokensCallback() { - return tokens_cb_; -} - -SamplesCallback StubWhispernetClient::GetSamplesCallback() { - return samples_cb_; -} - -SuccessCallback StubWhispernetClient::GetInitializedCallback() { - return SuccessCallback(); -} - -} // namespace audio_modem
diff --git a/components/audio_modem/test/stub_whispernet_client.h b/components/audio_modem/test/stub_whispernet_client.h deleted file mode 100644 index 9a0e8c6..0000000 --- a/components/audio_modem/test/stub_whispernet_client.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_AUDIO_MODEM_TEST_STUB_WHISPERNET_CLIENT_H_ -#define COMPONENTS_AUDIO_MODEM_TEST_STUB_WHISPERNET_CLIENT_H_ - -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "components/audio_modem/public/whispernet_client.h" -#include "media/base/audio_bus.h" - -namespace audio_modem { - -// A simple WhispernetClient for testing. -class StubWhispernetClient final : public WhispernetClient { - public: - // Constructor. |samples| and |tokens|, if specified, - // will be returned for any encoding and decoding requests. - StubWhispernetClient( - scoped_refptr<media::AudioBusRefCounted> samples = - scoped_refptr<media::AudioBusRefCounted>(), - const std::vector<AudioToken>& tokens = std::vector<AudioToken>()); - - ~StubWhispernetClient() override; - - void Initialize(const SuccessCallback& init_callback) override; - - void EncodeToken(const std::string& token, - AudioType type, - const TokenParameters token_params[2]) override; - void DecodeSamples(AudioType type, - const std::string& samples, - const TokenParameters token_params[2]) override; - - void RegisterTokensCallback(const TokensCallback& tokens_cb) override; - void RegisterSamplesCallback(const SamplesCallback& samples_cb) override; - - TokensCallback GetTokensCallback() override; - SamplesCallback GetSamplesCallback() override; - SuccessCallback GetInitializedCallback() override; - - private: - TokensCallback tokens_cb_; - SamplesCallback samples_cb_; - scoped_refptr<media::AudioBusRefCounted> samples_; - std::vector<AudioToken> tokens_; - - DISALLOW_COPY_AND_ASSIGN(StubWhispernetClient); -}; - -} // namespace audio_modem - -#endif // COMPONENTS_AUDIO_MODEM_TEST_STUB_WHISPERNET_CLIENT_H_
diff --git a/components/components.gyp b/components/components.gyp index 71bbc45b..a4ac3c8 100644 --- a/components/components.gyp +++ b/components/components.gyp
@@ -151,7 +151,6 @@ }], ['OS != "ios" and OS != "android"', { 'includes': [ - 'audio_modem.gypi', 'feedback.gypi', 'proximity_auth.gypi', 'storage_monitor.gypi',
diff --git a/components/components_tests.gyp b/components/components_tests.gyp index 4927f0c..6700418 100644 --- a/components/components_tests.gyp +++ b/components/components_tests.gyp
@@ -245,12 +245,6 @@ 'undo/bookmark_undo_service_test.cc', 'undo/undo_manager_test.cc', ], - - 'audio_modem_unittest_sources': [ - 'audio_modem/audio_player_unittest.cc', - 'audio_modem/audio_recorder_unittest.cc', - 'audio_modem/modem_unittest.cc', - ], 'data_use_measurement_unittest_sources': [ 'data_use_measurement/content/data_use_measurement_unittest.cc', ], @@ -1522,7 +1516,6 @@ }], ['OS != "ios" and OS != "android"', { 'sources': [ - '<@(audio_modem_unittest_sources)', '<@(feedback_unittest_sources)', '<@(proximity_auth_unittest_sources)', '<@(webusb_detector_unittest_sources)', @@ -1540,8 +1533,6 @@ '../device/usb/usb.gyp:device_usb_mocks', '../google_apis/google_apis.gyp:google_apis_test_support', '../third_party/protobuf/protobuf.gyp:protobuf_lite', - 'components.gyp:audio_modem', - 'components.gyp:audio_modem_test_support', 'components.gyp:cryptauth', 'components.gyp:cryptauth_proto', 'components.gyp:cryptauth_test_support',
diff --git a/components/precache/content/precache_manager.cc b/components/precache/content/precache_manager.cc index 2f896f3e..9a81fbb 100644 --- a/components/precache/content/precache_manager.cc +++ b/components/precache/content/precache_manager.cc
@@ -197,12 +197,12 @@ if (precache_fetcher_) { std::unique_ptr<PrecacheUnfinishedWork> unfinished_work = precache_fetcher_->CancelPrecaching(); - if (unfinished_work) { - BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&PrecacheDatabase::SaveUnfinishedWork, - precache_database_->GetWeakPtr(), - base::Passed(&unfinished_work))); - } + BrowserThread::PostTask( + BrowserThread::DB, + FROM_HERE, + base::Bind(&PrecacheDatabase::SaveUnfinishedWork, + precache_database_->GetWeakPtr(), + base::Passed(&unfinished_work))); // Destroying the |precache_fetcher_| will cancel any fetch in progress. precache_fetcher_.reset(); }
diff --git a/components/precache/core/precache_fetcher.cc b/components/precache/core/precache_fetcher.cc index a5cf650..dc0d3a2 100644 --- a/components/precache/core/precache_fetcher.cc +++ b/components/precache/core/precache_fetcher.cc
@@ -359,10 +359,6 @@ } std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { - // This could get called multiple times, and it should be handled gracefully. - if (!unfinished_work_) - return nullptr; - unfinished_work_->clear_manifest(); unfinished_work_->clear_resource(); for (const auto& manifest : manifest_urls_to_fetch_)
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 1baeba0..9e5c99ab 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -930,15 +930,11 @@ // Test that scrolling a nested out-of-process iframe bubbles unused scroll // delta to a parent frame. -#if defined(OS_ANDROID) // Browser process hit testing is not implemented on Android. // https://crbug.com/491334 -#define MAYBE_ScrollBubblingFromOOPIFTest DISABLED_ScrollBubblingFromOOPIFTest -#else -#define MAYBE_ScrollBubblingFromOOPIFTest ScrollBubblingFromOOPIFTest -#endif +// Flaky https://crbug.com/627238. IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, - MAYBE_ScrollBubblingFromOOPIFTest) { + DISABLED_ScrollBubblingFromOOPIFTest) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url);
diff --git a/content/test/gpu/gpu_tests/cloud_storage_test_base.py b/content/test/gpu/gpu_tests/cloud_storage_test_base.py index 458e1fe5..73a32479 100644 --- a/content/test/gpu/gpu_tests/cloud_storage_test_base.py +++ b/content/test/gpu/gpu_tests/cloud_storage_test_base.py
@@ -265,7 +265,7 @@ raise -class TestBase(gpu_test_base.TestBase): +class CloudStorageTestBase(gpu_test_base.TestBase): @classmethod def AddBenchmarkCommandLineArgs(cls, group): group.add_option('--build-revision',
diff --git a/content/test/gpu/gpu_tests/gpu_rasterization.py b/content/test/gpu/gpu_tests/gpu_rasterization.py index fdeb7c7..f313d8b 100644 --- a/content/test/gpu/gpu_tests/gpu_rasterization.py +++ b/content/test/gpu/gpu_tests/gpu_rasterization.py
@@ -68,7 +68,7 @@ device_pixel_ratio) -class GpuRasterization(cloud_storage_test_base.TestBase): +class GpuRasterization(cloud_storage_test_base.CloudStorageTestBase): """Tests that GPU rasterization produces valid content""" test = GpuRasterizationValidator
diff --git a/content/test/gpu/gpu_tests/maps.py b/content/test/gpu/gpu_tests/maps.py index 0f72f20..c3fbaee0 100644 --- a/content/test/gpu/gpu_tests/maps.py +++ b/content/test/gpu/gpu_tests/maps.py
@@ -103,7 +103,7 @@ 'window.testDone', timeout_in_seconds=180) -class Maps(cloud_storage_test_base.TestBase): +class Maps(cloud_storage_test_base.CloudStorageTestBase): """Google Maps pixel tests. Note: the WPR for this test was recorded from the smoothness.maps
diff --git a/content/test/gpu/gpu_tests/pixel.py b/content/test/gpu/gpu_tests/pixel.py index ec193415..1adf35c5 100644 --- a/content/test/gpu/gpu_tests/pixel.py +++ b/content/test/gpu/gpu_tests/pixel.py
@@ -165,7 +165,7 @@ json_contents = json.load(f) return json_contents -class Pixel(cloud_storage_test_base.TestBase): +class Pixel(cloud_storage_test_base.CloudStorageTestBase): test = PixelValidator @classmethod
diff --git a/extensions/browser/extension_event_histogram_value.h b/extensions/browser/extension_event_histogram_value.h index 1dd3a0f..69c2cd0 100644 --- a/extensions/browser/extension_event_histogram_value.h +++ b/extensions/browser/extension_event_histogram_value.h
@@ -40,8 +40,8 @@ APP_WINDOW_ON_MAXIMIZED, APP_WINDOW_ON_MINIMIZED, APP_WINDOW_ON_RESTORED, - AUDIO_MODEM_ON_RECEIVED, - AUDIO_MODEM_ON_TRANSMIT_FAIL, + DELETED_AUDIO_MODEM_ON_RECEIVED, + DELETED_AUDIO_MODEM_ON_TRANSMIT_FAIL, AUDIO_ON_DEVICE_CHANGED, AUDIO_ON_DEVICES_CHANGED, AUDIO_ON_LEVEL_CHANGED, @@ -87,9 +87,9 @@ COOKIES_ON_CHANGED, DELETED_COPRESENCE_ON_MESSAGES_RECEIVED, DELETED_COPRESENCE_ON_STATUS_UPDATED, - COPRESENCE_PRIVATE_ON_CONFIG_AUDIO, - COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST, - COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST, + DELETED_COPRESENCE_PRIVATE_ON_CONFIG_AUDIO, + DELETED_COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST, + DELETED_COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST, DEBUGGER_ON_DETACH, DEBUGGER_ON_EVENT, DECLARATIVE_CONTENT_ON_PAGE_CHANGED,
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 94156c9..be02472e 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -922,10 +922,10 @@ NOTIFICATIONPROVIDER_GETALLNOTIFIERS, GCDPRIVATE_GETPREFETCHEDWIFINAMELIST, GUESTVIEWINTERNAL_SETAUTOSIZE, - COPRESENCEPRIVATE_SENDFOUND, - COPRESENCEPRIVATE_SENDSAMPLES, - COPRESENCEPRIVATE_SENDDETECT, - COPRESENCEPRIVATE_SENDINITIALIZED, + DELETED_COPRESENCEPRIVATE_SENDFOUND, + DELETED_COPRESENCEPRIVATE_SENDSAMPLES, + DELETED_COPRESENCEPRIVATE_SENDDETECT, + DELETED_COPRESENCEPRIVATE_SENDINITIALIZED, DELETED_COPRESENCE_EXECUTE, DELETED_COPRESENCE_SETAPIKEY, FILESYSTEM_OBSERVEDIRECTORY, @@ -1022,10 +1022,10 @@ WEBVIEWINTERNAL_SETALLOWSCALING, PLATFORMKEYSINTERNAL_GETPUBLICKEY, RUNTIME_OPENOPTIONSPAGE, - AUDIOMODEM_TRANSMIT, - AUDIOMODEM_STOPTRANSMIT, - AUDIOMODEM_RECEIVE, - AUDIOMODEM_STOPRECEIVE, + DELETED_AUDIOMODEM_TRANSMIT, + DELETED_AUDIOMODEM_STOPTRANSMIT, + DELETED_AUDIOMODEM_RECEIVE, + DELETED_AUDIOMODEM_STOPRECEIVE, WEBRTCLOGGINGPRIVATE_STORE, WEBRTCLOGGINGPRIVATE_UPLOADSTORED, FILEMANAGERPRIVATEINTERNAL_SETENTRYTAG,
diff --git a/ios/web/public/test/web_test_with_web_state.h b/ios/web/public/test/web_test_with_web_state.h index f2578374..8cbdabd 100644 --- a/ios/web/public/test/web_test_with_web_state.h +++ b/ios/web/public/test/web_test_with_web_state.h
@@ -51,6 +51,9 @@ // Synchronously executes JavaScript and returns result as id. id ExecuteJavaScript(NSString* script); + // Returns the base URL of the loaded page. + std::string BaseUrl() const; + // Returns web state for this web controller. web::WebState* web_state(); const web::WebState* web_state() const;
diff --git a/ios/web/public/test/web_test_with_web_state.mm b/ios/web/public/test/web_test_with_web_state.mm index 55f964a3..0ab646a0 100644 --- a/ios/web/public/test/web_test_with_web_state.mm +++ b/ios/web/public/test/web_test_with_web_state.mm
@@ -8,6 +8,7 @@ #include "base/test/ios/wait_util.h" #import "ios/testing/ocmock_complex_type_helper.h" #import "ios/web/navigation/crw_session_controller.h" +#import "ios/web/public/web_state/url_verification_constants.h" #import "ios/web/web_state/ui/crw_web_controller.h" #import "ios/web/web_state/web_state_impl.h" @@ -173,6 +174,11 @@ return [[executionResult retain] autorelease]; } +std::string WebTestWithWebState::BaseUrl() const { + web::URLVerificationTrustLevel unused_level; + return web_state()->GetCurrentURL(&unused_level).spec(); +} + web::WebState* WebTestWithWebState::web_state() { return web_state_.get(); }
diff --git a/media/gpu/video_encode_accelerator_unittest.cc b/media/gpu/video_encode_accelerator_unittest.cc index b887d74..f32fc45a 100644 --- a/media/gpu/video_encode_accelerator_unittest.cc +++ b/media/gpu/video_encode_accelerator_unittest.cc
@@ -792,7 +792,8 @@ bool test_perf, bool mid_stream_bitrate_switch, bool mid_stream_framerate_switch, - bool verify_output); + bool verify_output, + bool verify_output_timestamp); ~VEAClient() override; void CreateEncoder(); void DestroyEncoder(); @@ -879,6 +880,9 @@ // Called when the quality validator fails to decode a frame. void DecodeFailed(); + // Verify that the output timestamp matches input timestamp. + void VerifyOutputTimestamp(base::TimeDelta timestamp); + ClientState state_; std::unique_ptr<VideoEncodeAccelerator> encoder_; @@ -956,6 +960,9 @@ // Check the output frame quality of the encoder. bool verify_output_; + // Check whether the output timestamps match input timestamps. + bool verify_output_timestamp_; + // Used to perform codec-specific sanity checks on the stream. std::unique_ptr<StreamValidator> stream_validator_; @@ -985,6 +992,12 @@ // The timer used to feed the encoder with the input frames. std::unique_ptr<base::RepeatingTimer> input_timer_; + + // The timestamps for each frame in the order of CreateFrame() invocation. + std::queue<base::TimeDelta> frame_timestamps_; + + // The last timestamp popped from |frame_timestamps_|. + base::TimeDelta previous_timestamp_; }; VEAClient::VEAClient(TestStream* test_stream, @@ -995,7 +1008,8 @@ bool test_perf, bool mid_stream_bitrate_switch, bool mid_stream_framerate_switch, - bool verify_output) + bool verify_output, + bool verify_output_timestamp) : state_(CS_CREATED), test_stream_(test_stream), note_(note), @@ -1018,6 +1032,7 @@ encoded_stream_size_since_last_check_(0), test_perf_(test_perf), verify_output_(verify_output), + verify_output_timestamp_(verify_output_timestamp), requested_bitrate_(0), requested_framerate_(0), requested_subsequent_bitrate_(0), @@ -1244,6 +1259,18 @@ } } +void VEAClient::VerifyOutputTimestamp(base::TimeDelta timestamp) { + // One input frame may be mapped to multiple output frames, so the current + // timestamp should be equal to previous timestamp or the top of + // frame_timestamps_. + if (timestamp != previous_timestamp_) { + ASSERT_TRUE(!frame_timestamps_.empty()); + EXPECT_EQ(frame_timestamps_.front(), timestamp); + previous_timestamp_ = frame_timestamps_.front(); + frame_timestamps_.pop(); + } +} + void VEAClient::BitstreamBufferReady(int32_t bitstream_buffer_id, size_t payload_size, bool key_frame, @@ -1259,6 +1286,10 @@ if (state_ == CS_FINISHED || state_ == CS_VALIDATED) return; + if (verify_output_timestamp_) { + VerifyOutputTimestamp(timestamp); + } + encoded_stream_size_since_last_check_ += payload_size; const uint8_t* stream_ptr = static_cast<const uint8_t*>(shm->memory()); @@ -1340,7 +1371,8 @@ test_stream_->visible_size, input_coded_size_.width(), input_coded_size_.width() / 2, input_coded_size_.width() / 2, frame_data_y, frame_data_u, frame_data_v, - base::TimeDelta().FromMilliseconds(next_input_id_ * + // Timestamp needs to avoid starting from 0. + base::TimeDelta().FromMilliseconds((next_input_id_ + 1) * base::Time::kMillisecondsPerSecond / current_framerate_)); EXPECT_NE(nullptr, video_frame.get()); @@ -1395,6 +1427,7 @@ int32_t input_id; scoped_refptr<VideoFrame> video_frame = PrepareInputFrame(pos_in_input_stream_, &input_id); + frame_timestamps_.push(video_frame->timestamp()); pos_in_input_stream_ += test_stream_->aligned_buffer_size; bool force_keyframe = false; @@ -1488,6 +1521,12 @@ SetState(CS_FINISHED); if (!quality_validator_) SetState(CS_VALIDATED); + if (verify_output_timestamp_) { + // There may be some timestamps left because we push extra frames to flush + // encoder. + EXPECT_LE(frame_timestamps_.size(), + static_cast<size_t>(next_input_id_ - num_frames_to_encode_)); + } return false; } @@ -1587,9 +1626,10 @@ // - If true, switch bitrate mid-stream. // - If true, switch framerate mid-stream. // - If true, verify the output frames of encoder. +// - If true, verify the timestamps of output frames. class VideoEncodeAcceleratorTest : public ::testing::TestWithParam< - std::tuple<int, bool, int, bool, bool, bool, bool, bool>> {}; + std::tuple<int, bool, int, bool, bool, bool, bool, bool, bool>> {}; TEST_P(VideoEncodeAcceleratorTest, TestSimpleEncode) { size_t num_concurrent_encoders = std::get<0>(GetParam()); @@ -1601,6 +1641,7 @@ const bool mid_stream_framerate_switch = std::get<6>(GetParam()); const bool verify_output = std::get<7>(GetParam()) || g_env->verify_all_output(); + const bool verify_output_timestamp = std::get<8>(GetParam()); ScopedVector<ClientStateNotification<ClientState>> notes; ScopedVector<VEAClient> clients; @@ -1622,7 +1663,8 @@ clients.push_back(new VEAClient( g_env->test_streams_[test_stream_index], notes.back(), encoder_save_to_file, keyframe_period, force_bitrate, test_perf, - mid_stream_bitrate_switch, mid_stream_framerate_switch, verify_output)); + mid_stream_bitrate_switch, mid_stream_framerate_switch, verify_output, + verify_output_timestamp)); encoder_thread.task_runner()->PostTask( FROM_HERE, base::Bind(&VEAClient::CreateEncoder, @@ -1661,65 +1703,84 @@ SimpleEncode, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, true, 0, false, false, false, false, false), - std::make_tuple(1, true, 0, false, false, false, false, true))); + std::make_tuple(1, true, 0, false, false, false, false, false, false), + std::make_tuple(1, true, 0, false, false, false, false, true, false))); INSTANTIATE_TEST_CASE_P( EncoderPerf, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, false, 0, false, true, false, false, false))); + std::make_tuple(1, false, 0, false, true, false, false, false, false))); -INSTANTIATE_TEST_CASE_P( - ForceKeyframes, - VideoEncodeAcceleratorTest, - ::testing::Values( - std::make_tuple(1, false, 10, false, false, false, false, false))); +INSTANTIATE_TEST_CASE_P(ForceKeyframes, + VideoEncodeAcceleratorTest, + ::testing::Values(std::make_tuple(1, + false, + 10, + false, + false, + false, + false, + false, + false))); INSTANTIATE_TEST_CASE_P( ForceBitrate, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, false, 0, true, false, false, false, false))); + std::make_tuple(1, false, 0, true, false, false, false, false, false))); INSTANTIATE_TEST_CASE_P( MidStreamParamSwitchBitrate, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, false, 0, true, false, true, false, false))); + std::make_tuple(1, false, 0, true, false, true, false, false, false))); INSTANTIATE_TEST_CASE_P( MidStreamParamSwitchFPS, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, false, 0, true, false, false, true, false))); + std::make_tuple(1, false, 0, true, false, false, true, false, false))); INSTANTIATE_TEST_CASE_P( MultipleEncoders, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(3, false, 0, false, false, false, false, false), - std::make_tuple(3, false, 0, true, false, false, true, false), - std::make_tuple(3, false, 0, true, false, true, false, false))); + std::make_tuple(3, false, 0, false, false, false, false, false, false), + std::make_tuple(3, false, 0, true, false, false, true, false, false), + std::make_tuple(3, false, 0, true, false, true, false, false, false))); + +INSTANTIATE_TEST_CASE_P( + VerifyTimestamp, + VideoEncodeAcceleratorTest, + ::testing::Values( + std::make_tuple(1, false, 0, false, false, false, false, false, true))); + #else INSTANTIATE_TEST_CASE_P( SimpleEncode, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, true, 0, false, false, false, false, false), - std::make_tuple(1, true, 0, false, false, false, false, true))); + std::make_tuple(1, true, 0, false, false, false, false, false, false), + std::make_tuple(1, true, 0, false, false, false, false, true, false))); INSTANTIATE_TEST_CASE_P( EncoderPerf, VideoEncodeAcceleratorTest, ::testing::Values( - std::make_tuple(1, false, 0, false, true, false, false, false))); + std::make_tuple(1, false, 0, false, true, false, false, false, false))); -INSTANTIATE_TEST_CASE_P( - MultipleEncoders, - VideoEncodeAcceleratorTest, - ::testing::Values( - std::make_tuple(3, false, 0, false, false, false, false, false))); +INSTANTIATE_TEST_CASE_P(MultipleEncoders, + VideoEncodeAcceleratorTest, + ::testing::Values(std::make_tuple(3, + false, + 0, + false, + false, + false, + false, + false, + false))); #endif // TODO(posciak): more tests:
diff --git a/net/cert/internal/parse_ocsp.cc b/net/cert/internal/parse_ocsp.cc index 21ce878b..0243d95 100644 --- a/net/cert/internal/parse_ocsp.cc +++ b/net/cert/internal/parse_ocsp.cc
@@ -7,7 +7,6 @@ #include "base/sha1.h" #include "crypto/sha2.h" #include "net/cert/internal/parse_ocsp.h" -#include "net/der/encode_values.h" namespace net { @@ -530,28 +529,4 @@ return found; } -bool CheckOCSPDateValid(const OCSPSingleResponse& response, - const base::Time& verify_time, - const base::TimeDelta& max_age) { - der::GeneralizedTime verify_time_der; - if (!der::EncodeTimeAsGeneralizedTime(verify_time, &verify_time_der)) - return false; - - if (response.this_update > verify_time_der) - return false; // Response is not yet valid. - - if (response.has_next_update && (response.next_update <= verify_time_der)) - return false; // Response is no longer valid. - - der::GeneralizedTime earliest_this_update; - if (!der::EncodeTimeAsGeneralizedTime(verify_time - max_age, - &earliest_this_update)) { - return false; - } - if (response.this_update < earliest_this_update) - return false; // Response is too old. - - return true; -} - } // namespace net
diff --git a/net/cert/internal/parse_ocsp.h b/net/cert/internal/parse_ocsp.h index af5541d..b9052ae 100644 --- a/net/cert/internal/parse_ocsp.h +++ b/net/cert/internal/parse_ocsp.h
@@ -17,10 +17,6 @@ #include "net/der/parser.h" #include "net/der/tag.h" -namespace base { -class Time; -} - namespace net { // OCSPCertID contains a representation of a DER-encoded RFC 6960 "CertID". @@ -282,15 +278,6 @@ const der::Input& cert_tbs_certificate_tlv, OCSPCertStatus* out); -// Returns true if |response|, a valid OCSP response with a thisUpdate field and -// potentially a nextUpdate field, is valid at |verify_time| and not older than -// |max_age|. Expressed differently, returns true if |response.thisUpdate| <= -// |verify_time| < response.nextUpdate, and |response.thisUpdate| >= -// |verify_time| - |max_age|. -NET_EXPORT_PRIVATE bool CheckOCSPDateValid(const OCSPSingleResponse& response, - const base::Time& verify_time, - const base::TimeDelta& max_age); - } // namespace net #endif // NET_CERT_INTERNAL_PARSE_OCSP_H_
diff --git a/net/cert/internal/parse_ocsp_unittest.cc b/net/cert/internal/parse_ocsp_unittest.cc index bc4e1e1e..c0fc061b 100644 --- a/net/cert/internal/parse_ocsp_unittest.cc +++ b/net/cert/internal/parse_ocsp_unittest.cc
@@ -8,7 +8,6 @@ #include "base/logging.h" #include "net/cert/internal/test_helpers.h" #include "net/cert/x509_certificate.h" -#include "net/der/encode_values.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -16,8 +15,6 @@ namespace { -const base::TimeDelta kOCSPAgeOneWeek = base::TimeDelta::FromDays(7); - std::string GetFilePath(const std::string& file_name) { return std::string("net/data/parse_ocsp_unittest/") + file_name; } @@ -185,131 +182,4 @@ ASSERT_EQ(PARSE_OCSP_SINGLE_RESPONSE, ParseOCSP("missing_response.pem")); } -TEST(OCSPDateTest, Valid) { - OCSPSingleResponse response; - - base::Time now = base::Time::Now(); - base::Time this_update = now - base::TimeDelta::FromHours(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - base::Time next_update = this_update + base::TimeDelta::FromDays(7); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, ThisUpdateInTheFuture) { - OCSPSingleResponse response; - - base::Time now = base::Time::Now(); - base::Time this_update = now + base::TimeDelta::FromHours(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - base::Time next_update = this_update + base::TimeDelta::FromDays(7); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, NextUpdatePassed) { - OCSPSingleResponse response; - - base::Time now = base::Time::Now(); - base::Time this_update = now - base::TimeDelta::FromDays(6); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - base::Time next_update = now - base::TimeDelta::FromHours(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, NextUpdateBeforeThisUpdate) { - OCSPSingleResponse response; - - base::Time now = base::Time::Now(); - base::Time this_update = now - base::TimeDelta::FromDays(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - base::Time next_update = this_update - base::TimeDelta::FromDays(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, ThisUpdateOlderThanMaxAge) { - OCSPSingleResponse response; - - base::Time now = base::Time::Now(); - base::Time this_update = now - kOCSPAgeOneWeek; - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - base::Time next_update = now + base::TimeDelta::FromHours(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_TRUE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - - ASSERT_TRUE(der::EncodeTimeAsGeneralizedTime( - this_update - base::TimeDelta::FromSeconds(1), &response.this_update)); - response.has_next_update = false; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); - response.has_next_update = true; - EXPECT_FALSE(CheckOCSPDateValid(response, now, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, VerifyTimeFromBeforeWindowsEpoch) { - OCSPSingleResponse response; - base::Time windows_epoch; - base::Time verify_time = windows_epoch - base::TimeDelta::FromDays(1); - - base::Time now = base::Time::Now(); - base::Time this_update = now - base::TimeDelta::FromHours(1); - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; - EXPECT_FALSE(CheckOCSPDateValid(response, verify_time, kOCSPAgeOneWeek)); - - base::Time next_update = this_update + kOCSPAgeOneWeek; - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(next_update, &response.next_update)); - response.has_next_update = true; - EXPECT_FALSE(CheckOCSPDateValid(response, verify_time, kOCSPAgeOneWeek)); -} - -TEST(OCSPDateTest, VerifyTimeMinusAgeFromBeforeWindowsEpoch) { - OCSPSingleResponse response; - base::Time windows_epoch; - base::Time verify_time = windows_epoch + base::TimeDelta::FromDays(1); - - base::Time this_update = windows_epoch; - ASSERT_TRUE( - der::EncodeTimeAsGeneralizedTime(this_update, &response.this_update)); - response.has_next_update = false; -#ifdef OS_WIN - EXPECT_FALSE(CheckOCSPDateValid(response, verify_time, kOCSPAgeOneWeek)); -#else - EXPECT_TRUE(CheckOCSPDateValid(response, verify_time, kOCSPAgeOneWeek)); -#endif -} - } // namespace net
diff --git a/net/der/encode_values.cc b/net/der/encode_values.cc deleted file mode 100644 index af7098a..0000000 --- a/net/der/encode_values.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/time/time.h" -#include "net/der/encode_values.h" - -namespace net { - -namespace der { - -bool EncodeTimeAsGeneralizedTime(const base::Time& time, - der::GeneralizedTime* generalized_time) { - base::Time::Exploded exploded; - time.UTCExplode(&exploded); - if (!exploded.HasValidValues()) - return false; - - generalized_time->year = exploded.year; - generalized_time->month = exploded.month; - generalized_time->day = exploded.day_of_month; - generalized_time->hours = exploded.hour; - generalized_time->minutes = exploded.minute; - generalized_time->seconds = exploded.second; - return true; -} - -} // namespace der - -} // namespace net
diff --git a/net/der/encode_values.h b/net/der/encode_values.h deleted file mode 100644 index e0b04423..0000000 --- a/net/der/encode_values.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef NET_DER_ENCODE_VALUES_H_ -#define NET_DER_ENCODE_VALUES_H_ - -#include "net/base/net_export.h" -#include "net/der/parse_values.h" - -namespace base { -class Time; -} - -namespace net { - -namespace der { - -// Encodes |time|, a UTC-based time, to DER |generalized_time|, for comparing -// against other GeneralizedTime objects. -NET_EXPORT bool EncodeTimeAsGeneralizedTime( - const base::Time& time, - der::GeneralizedTime* generalized_time); - -} // namespace der - -} // namespace net - -#endif // NET_DER_ENCODE_VALUES_H
diff --git a/net/der/encode_values_unittest.cc b/net/der/encode_values_unittest.cc deleted file mode 100644 index 604f6a4..0000000 --- a/net/der/encode_values_unittest.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/time/time.h" -#include "net/der/encode_values.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace net { -namespace der { -namespace test { - -TEST(EncodeValuesTest, EncodeTimeAsGeneralizedTime) { - // Fri, 24 Jun 2016 17:04:54 GMT - base::Time time = - base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1466787894); - GeneralizedTime generalized_time; - ASSERT_TRUE(EncodeTimeAsGeneralizedTime(time, &generalized_time)); - EXPECT_EQ(2016, generalized_time.year); - EXPECT_EQ(6, generalized_time.month); - EXPECT_EQ(24, generalized_time.day); - EXPECT_EQ(17, generalized_time.hours); - EXPECT_EQ(4, generalized_time.minutes); - EXPECT_EQ(54, generalized_time.seconds); -} - -TEST(EncodeValuesTest, EncodeTimeFromBeforeWindows) { - // 1 Jan 1570 00:00:00 GMT - base::Time time = - base::Time::UnixEpoch() - base::TimeDelta::FromSeconds(12622780800UL); - GeneralizedTime generalized_time; -#if defined(OS_WIN) - EXPECT_FALSE(EncodeTimeAsGeneralizedTime(time, &generalized_time)); -#else - ASSERT_TRUE(EncodeTimeAsGeneralizedTime(time, &generalized_time)); - EXPECT_EQ(1570, generalized_time.year); - EXPECT_EQ(1, generalized_time.month); - EXPECT_EQ(1, generalized_time.day); - EXPECT_EQ(0, generalized_time.hours); - EXPECT_EQ(0, generalized_time.minutes); - EXPECT_EQ(0, generalized_time.seconds); -#endif -} - -TEST(EncodeValuesTest, EncodeTimeAfterTimeTMax) { - // 1 Jan 2039 00:00:00 GMT - base::Time time = - base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(2177452800UL); - GeneralizedTime generalized_time; - ASSERT_TRUE(EncodeTimeAsGeneralizedTime(time, &generalized_time)); - EXPECT_EQ(2039, generalized_time.year); - EXPECT_EQ(1, generalized_time.month); - EXPECT_EQ(1, generalized_time.day); - EXPECT_EQ(0, generalized_time.hours); - EXPECT_EQ(0, generalized_time.minutes); - EXPECT_EQ(0, generalized_time.seconds); -} - -} // namespace test - -} // namespace der - -} // namespace net
diff --git a/net/net.gypi b/net/net.gypi index 65bce087..744f6e8 100644 --- a/net/net.gypi +++ b/net/net.gypi
@@ -142,8 +142,6 @@ 'cert/x509_util_openssl.h', 'der/input.cc', 'der/input.h', - 'der/encode_values.cc', - 'der/encode_values.h', 'der/parse_values.cc', 'der/parse_values.h', 'der/parser.cc', @@ -1444,7 +1442,6 @@ 'cookies/cookie_util_unittest.cc', 'cookies/parsed_cookie_unittest.cc', 'der/input_unittest.cc', - 'der/encode_values_unittest.cc', 'der/parse_values_unittest.cc', 'der/parser_unittest.cc', 'disk_cache/backend_unittest.cc',
diff --git a/testing/scripts/common.py b/testing/scripts/common.py index d07548c..ee49a89 100644 --- a/testing/scripts/common.py +++ b/testing/scripts/common.py
@@ -63,9 +63,9 @@ return args.func(args) -def run_command(argv, env=None): - print 'Running %r' % argv - rc = subprocess.call(argv, env=env) +def run_command(argv, env=None, cwd=None): + print 'Running %r in %r (env: %r)' % (argv, cwd, env) + rc = subprocess.call(argv, env=env, cwd=cwd) print 'Command %r returned exit code %d' % (argv, rc) return rc
diff --git a/testing/scripts/webkit_python_tests.py b/testing/scripts/webkit_python_tests.py index b0c2fbc..e1e9d34a 100755 --- a/testing/scripts/webkit_python_tests.py +++ b/testing/scripts/webkit_python_tests.py
@@ -18,7 +18,7 @@ os.path.join(common.SRC_DIR, 'third_party', 'WebKit', 'Tools', 'Scripts', 'test-webkitpy'), '--write-full-results-to', tempfile_path, - ]) + ], cwd=args.paths['checkout']) with open(tempfile_path) as f: results = json.load(f)
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index fc5adae..84a0cdd 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -72954,8 +72954,8 @@ <int value="19" label="APP_WINDOW_ON_MAXIMIZED"/> <int value="20" label="APP_WINDOW_ON_MINIMIZED"/> <int value="21" label="APP_WINDOW_ON_RESTORED"/> - <int value="22" label="AUDIO_MODEM_ON_RECEIVED"/> - <int value="23" label="AUDIO_MODEM_ON_TRANSMIT_FAIL"/> + <int value="22" label="DELETED_AUDIO_MODEM_ON_RECEIVED"/> + <int value="23" label="DELETED_AUDIO_MODEM_ON_TRANSMIT_FAIL"/> <int value="24" label="AUDIO_ON_DEVICE_CHANGED"/> <int value="25" label="AUDIO_ON_DEVICES_CHANGED"/> <int value="26" label="AUDIO_ON_LEVEL_CHANGED"/> @@ -73001,9 +73001,9 @@ <int value="66" label="COOKIES_ON_CHANGED"/> <int value="67" label="DELETED_COPRESENCE_ON_MESSAGES_RECEIVED"/> <int value="68" label="DELETED_COPRESENCE_ON_STATUS_UPDATED"/> - <int value="69" label="COPRESENCE_PRIVATE_ON_CONFIG_AUDIO"/> - <int value="70" label="COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST"/> - <int value="71" label="COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST"/> + <int value="69" label="DELETED_COPRESENCE_PRIVATE_ON_CONFIG_AUDIO"/> + <int value="70" label="DELETED_COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST"/> + <int value="71" label="DELETED_COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST"/> <int value="72" label="DEBUGGER_ON_DETACH"/> <int value="73" label="DEBUGGER_ON_EVENT"/> <int value="74" label="DECLARATIVE_CONTENT_ON_PAGE_CHANGED"/> @@ -74244,10 +74244,10 @@ <int value="861" label="NOTIFICATIONPROVIDER_GETALLNOTIFIERS"/> <int value="862" label="GCDPRIVATE_GETPREFETCHEDWIFINAMELIST"/> <int value="863" label="GUESTVIEWINTERNAL_SETAUTOSIZE"/> - <int value="864" label="COPRESENCEPRIVATE_SENDFOUND"/> - <int value="865" label="COPRESENCEPRIVATE_SENDSAMPLES"/> - <int value="866" label="COPRESENCEPRIVATE_SENDDETECT"/> - <int value="867" label="COPRESENCEPRIVATE_SENDINITIALIZED"/> + <int value="864" label="DELETED_COPRESENCEPRIVATE_SENDFOUND"/> + <int value="865" label="DELETED_COPRESENCEPRIVATE_SENDSAMPLES"/> + <int value="866" label="DELETED_COPRESENCEPRIVATE_SENDDETECT"/> + <int value="867" label="DELETED_COPRESENCEPRIVATE_SENDINITIALIZED"/> <int value="868" label="DELETED_COPRESENCE_EXECUTE"/> <int value="869" label="DELETED_COPRESENCE_SETAPIKEY"/> <int value="870" label="FILESYSTEM_OBSERVEDIRECTORY"/> @@ -74346,10 +74346,10 @@ <int value="961" label="WEBVIEWINTERNAL_SETALLOWSCALING"/> <int value="962" label="PLATFORMKEYSINTERNAL_GETPUBLICKEY"/> <int value="963" label="RUNTIME_OPENOPTIONSPAGE"/> - <int value="964" label="AUDIOMODEM_TRANSMIT"/> - <int value="965" label="AUDIOMODEM_STOPTRANSMIT"/> - <int value="966" label="AUDIOMODEM_RECEIVE"/> - <int value="967" label="AUDIOMODEM_STOPRECEIVE"/> + <int value="964" label="DELETED_AUDIOMODEM_TRANSMIT"/> + <int value="965" label="DELETED_AUDIOMODEM_STOPTRANSMIT"/> + <int value="966" label="DELETED_AUDIOMODEM_RECEIVE"/> + <int value="967" label="DELETED_AUDIOMODEM_STOPRECEIVE"/> <int value="968" label="WEBRTCLOGGINGPRIVATE_STORE"/> <int value="969" label="WEBRTCLOGGINGPRIVATE_UPLOADSTORED"/> <int value="970" label="FILEMANAGERPRIVATEINTERNAL_SETENTRYTAG"/>
diff --git a/tools/perf/benchmarks/system_health_smoke_test.py b/tools/perf/benchmarks/system_health_smoke_test.py index 84f5922d..95d326a3a 100644 --- a/tools/perf/benchmarks/system_health_smoke_test.py +++ b/tools/perf/benchmarks/system_health_smoke_test.py
@@ -23,13 +23,6 @@ from benchmarks import system_health -# We only cover memory system health -_SH_BENCHMARKS_TO_SMOKE_TEST = [ - system_health.DesktopMemorySystemHealth, - system_health.MobileMemorySystemHealth, -] - - def GetSystemHealthBenchmarksToSmokeTest(): sh_benchmark_classes = discover.DiscoverClassesInModule( system_health, perf_benchmark.PerfBenchmark,