add vad code.

This commit is contained in:
luocai
2024-09-06 18:26:45 +08:00
parent 35bf68338f
commit 2bed1dacf2
93 changed files with 12362 additions and 2 deletions

View File

@ -0,0 +1,210 @@
/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/event.h"
#if defined(WEBRTC_WIN)
#include <windows.h>
#elif defined(WEBRTC_POSIX)
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#else
#error "Must define either WEBRTC_WIN or WEBRTC_POSIX."
#endif
#include "absl/types/optional.h"
#include "rtc_base/checks.h"
#include "rtc_base/synchronization/yield_policy.h"
#include "rtc_base/system/warn_current_thread_is_deadlocked.h"
#include "rtc_base/time_utils.h"
namespace rtc {
using ::webrtc::TimeDelta;
Event::Event() : Event(false, false) {}
#if defined(WEBRTC_WIN)
Event::Event(bool manual_reset, bool initially_signaled) {
event_handle_ = ::CreateEvent(nullptr, // Security attributes.
manual_reset, initially_signaled,
nullptr); // Name.
RTC_CHECK(event_handle_);
}
Event::~Event() {
CloseHandle(event_handle_);
}
void Event::Set() {
SetEvent(event_handle_);
}
void Event::Reset() {
ResetEvent(event_handle_);
}
bool Event::Wait(TimeDelta give_up_after, TimeDelta /*warn_after*/) {
ScopedYieldPolicy::YieldExecution();
const DWORD ms =
give_up_after.IsPlusInfinity()
? INFINITE
: give_up_after.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms();
return (WaitForSingleObject(event_handle_, ms) == WAIT_OBJECT_0);
}
#elif defined(WEBRTC_POSIX)
// On MacOS, clock_gettime is available from version 10.12, and on
// iOS, from version 10.0. So we can't use it yet.
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
#define USE_CLOCK_GETTIME 0
#define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 0
// On Android, pthread_condattr_setclock is available from version 21. By
// default, we target a new enough version for 64-bit platforms but not for
// 32-bit platforms. For older versions, use
// pthread_cond_timedwait_monotonic_np.
#elif defined(WEBRTC_ANDROID) && (__ANDROID_API__ < 21)
#define USE_CLOCK_GETTIME 1
#define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 1
#else
#define USE_CLOCK_GETTIME 1
#define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 0
#endif
Event::Event(bool manual_reset, bool initially_signaled)
: is_manual_reset_(manual_reset), event_status_(initially_signaled) {
RTC_CHECK(pthread_mutex_init(&event_mutex_, nullptr) == 0);
pthread_condattr_t cond_attr;
RTC_CHECK(pthread_condattr_init(&cond_attr) == 0);
#if USE_CLOCK_GETTIME && !USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP
RTC_CHECK(pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC) == 0);
#endif
RTC_CHECK(pthread_cond_init(&event_cond_, &cond_attr) == 0);
pthread_condattr_destroy(&cond_attr);
}
Event::~Event() {
pthread_mutex_destroy(&event_mutex_);
pthread_cond_destroy(&event_cond_);
}
void Event::Set() {
pthread_mutex_lock(&event_mutex_);
event_status_ = true;
pthread_cond_broadcast(&event_cond_);
pthread_mutex_unlock(&event_mutex_);
}
void Event::Reset() {
pthread_mutex_lock(&event_mutex_);
event_status_ = false;
pthread_mutex_unlock(&event_mutex_);
}
namespace {
timespec GetTimespec(TimeDelta duration_from_now) {
timespec ts;
// Get the current time.
#if USE_CLOCK_GETTIME
clock_gettime(CLOCK_MONOTONIC, &ts);
#else
timeval tv;
gettimeofday(&tv, nullptr);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * kNumNanosecsPerMicrosec;
#endif
// Add the specified number of milliseconds to it.
int64_t microsecs_from_now = duration_from_now.us();
ts.tv_sec += microsecs_from_now / kNumMicrosecsPerSec;
ts.tv_nsec +=
(microsecs_from_now % kNumMicrosecsPerSec) * kNumNanosecsPerMicrosec;
// Normalize.
if (ts.tv_nsec >= kNumNanosecsPerSec) {
ts.tv_sec++;
ts.tv_nsec -= kNumNanosecsPerSec;
}
return ts;
}
} // namespace
bool Event::Wait(TimeDelta give_up_after, TimeDelta warn_after) {
// Instant when we'll log a warning message (because we've been waiting so
// long it might be a bug), but not yet give up waiting. nullopt if we
// shouldn't log a warning.
const absl::optional<timespec> warn_ts =
warn_after >= give_up_after
? absl::nullopt
: absl::make_optional(GetTimespec(warn_after));
// Instant when we'll stop waiting and return an error. nullopt if we should
// never give up.
const absl::optional<timespec> give_up_ts =
give_up_after.IsPlusInfinity()
? absl::nullopt
: absl::make_optional(GetTimespec(give_up_after));
ScopedYieldPolicy::YieldExecution();
pthread_mutex_lock(&event_mutex_);
// Wait for `event_cond_` to trigger and `event_status_` to be set, with the
// given timeout (or without a timeout if none is given).
const auto wait = [&](const absl::optional<timespec> timeout_ts) {
int error = 0;
while (!event_status_ && error == 0) {
if (timeout_ts == absl::nullopt) {
error = pthread_cond_wait(&event_cond_, &event_mutex_);
} else {
#if USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP
error = pthread_cond_timedwait_monotonic_np(&event_cond_, &event_mutex_,
&*timeout_ts);
#else
error =
pthread_cond_timedwait(&event_cond_, &event_mutex_, &*timeout_ts);
#endif
}
}
return error;
};
int error;
if (warn_ts == absl::nullopt) {
error = wait(give_up_ts);
} else {
error = wait(warn_ts);
if (error == ETIMEDOUT) {
webrtc::WarnThatTheCurrentThreadIsProbablyDeadlocked();
error = wait(give_up_ts);
}
}
// NOTE(liulk): Exactly one thread will auto-reset this event. All
// the other threads will think it's unsignaled. This seems to be
// consistent with auto-reset events in WEBRTC_WIN
if (error == 0 && !is_manual_reset_)
event_status_ = false;
pthread_mutex_unlock(&event_mutex_);
return (error == 0);
}
#endif
} // namespace rtc

View File

@ -0,0 +1,137 @@
/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_EVENT_H_
#define RTC_BASE_EVENT_H_
#include "api/units/time_delta.h"
#if defined(WEBRTC_WIN)
#include <windows.h>
#elif defined(WEBRTC_POSIX)
#include <pthread.h>
#else
#error "Must define either WEBRTC_WIN or WEBRTC_POSIX."
#endif
#include "rtc_base/synchronization/yield_policy.h"
namespace rtc {
// RTC_DISALLOW_WAIT() utility
//
// Sets a stack-scoped flag that disallows use of `rtc::Event::Wait` by means
// of raising a DCHECK when a call to `rtc::Event::Wait()` is made..
// This is useful to guard synchronization-free scopes against regressions.
//
// Example of what this would catch (`ScopeToProtect` calls `Foo`):
//
// void Foo(TaskQueue* tq) {
// Event event;
// tq->PostTask([&event]() {
// event.Set();
// });
// event.Wait(Event::kForever); // <- Will trigger a DCHECK.
// }
//
// void ScopeToProtect() {
// TaskQueue* tq = GetSomeTaskQueue();
// RTC_DISALLOW_WAIT(); // Policy takes effect.
// Foo(tq);
// }
//
#if RTC_DCHECK_IS_ON
#define RTC_DISALLOW_WAIT() ScopedDisallowWait disallow_wait_##__LINE__
#else
#define RTC_DISALLOW_WAIT()
#endif
class Event {
public:
// TODO(bugs.webrtc.org/14366): Consider removing this redundant alias.
static constexpr webrtc::TimeDelta kForever =
webrtc::TimeDelta::PlusInfinity();
Event();
Event(bool manual_reset, bool initially_signaled);
Event(const Event&) = delete;
Event& operator=(const Event&) = delete;
~Event();
void Set();
void Reset();
// Waits for the event to become signaled, but logs a warning if it takes more
// than `warn_after`, and gives up completely if it takes more than
// `give_up_after`. (If `warn_after >= give_up_after`, no warning will be
// logged.) Either or both may be `kForever`, which means wait indefinitely.
//
// Care is taken so that the underlying OS wait call isn't requested to sleep
// shorter than `give_up_after`.
//
// Returns true if the event was signaled, false if there was a timeout or
// some other error.
bool Wait(webrtc::TimeDelta give_up_after, webrtc::TimeDelta warn_after);
// Waits with the given timeout and a reasonable default warning timeout.
bool Wait(webrtc::TimeDelta give_up_after) {
return Wait(give_up_after, give_up_after.IsPlusInfinity()
? webrtc::TimeDelta::Seconds(3)
: kForever);
}
private:
#if defined(WEBRTC_WIN)
HANDLE event_handle_;
#elif defined(WEBRTC_POSIX)
pthread_mutex_t event_mutex_;
pthread_cond_t event_cond_;
const bool is_manual_reset_;
bool event_status_;
#endif
};
// These classes are provided for compatibility with Chromium.
// The rtc::Event implementation is overriden inside of Chromium for the
// purposes of detecting when threads are blocked that shouldn't be as well as
// to use the more accurate event implementation that's there than is provided
// by default on some platforms (e.g. Windows).
// When building with standalone WebRTC, this class is a noop.
// For further information, please see the
// ScopedAllowBaseSyncPrimitives(ForTesting) classes in Chromium.
class ScopedAllowBaseSyncPrimitives {
public:
ScopedAllowBaseSyncPrimitives() {}
~ScopedAllowBaseSyncPrimitives() {}
};
class ScopedAllowBaseSyncPrimitivesForTesting {
public:
ScopedAllowBaseSyncPrimitivesForTesting() {}
~ScopedAllowBaseSyncPrimitivesForTesting() {}
};
#if RTC_DCHECK_IS_ON
class ScopedDisallowWait {
public:
ScopedDisallowWait() = default;
private:
class DisallowYieldHandler : public YieldInterface {
public:
void YieldExecution() override { RTC_DCHECK_NOTREACHED(); }
} handler_;
rtc::ScopedYieldPolicy policy{&handler_};
};
#endif
} // namespace rtc
#endif // RTC_BASE_EVENT_H_

View File

@ -0,0 +1,449 @@
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/event_tracer.h"
#include <stdio.h>
#include "rtc_base/trace_event.h"
#if defined(RTC_USE_PERFETTO)
#include "rtc_base/trace_categories.h"
#include "third_party/perfetto/include/perfetto/tracing/tracing.h"
#else
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <atomic>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "api/sequence_checker.h"
#include "rtc_base/checks.h"
#include "rtc_base/event.h"
#include "rtc_base/logging.h"
#include "rtc_base/platform_thread.h"
#include "rtc_base/platform_thread_types.h"
#include "rtc_base/synchronization/mutex.h"
#include "rtc_base/thread_annotations.h"
#include "rtc_base/time_utils.h"
#endif
namespace webrtc {
namespace {
#if !defined(RTC_USE_PERFETTO)
GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
AddTraceEventPtr g_add_trace_event_ptr = nullptr;
#endif
} // namespace
#if defined(RTC_USE_PERFETTO)
void RegisterPerfettoTrackEvents() {
if (perfetto::Tracing::IsInitialized()) {
webrtc::TrackEvent::Register();
}
}
#else
void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
AddTraceEventPtr add_trace_event_ptr) {
g_get_category_enabled_ptr = get_category_enabled_ptr;
g_add_trace_event_ptr = add_trace_event_ptr;
}
const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
if (g_get_category_enabled_ptr)
return g_get_category_enabled_ptr(name);
// A string with null terminator means category is disabled.
return reinterpret_cast<const unsigned char*>("\0");
}
// Arguments to this function (phase, etc.) are as defined in
// webrtc/rtc_base/trace_event.h.
void EventTracer::AddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
unsigned char flags) {
if (g_add_trace_event_ptr) {
g_add_trace_event_ptr(phase, category_enabled, name, id, num_args,
arg_names, arg_types, arg_values, flags);
}
}
#endif
} // namespace webrtc
#if defined(RTC_USE_PERFETTO)
// TODO(bugs.webrtc.org/15917): Implement for perfetto.
namespace rtc::tracing {
void SetupInternalTracer(bool enable_all_categories) {}
bool StartInternalCapture(absl::string_view filename) {
return false;
}
void StartInternalCaptureToFile(FILE* file) {}
void StopInternalCapture() {}
void ShutdownInternalTracer() {}
} // namespace rtc::tracing
#else
// This is a guesstimate that should be enough in most cases.
static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
static const size_t kTraceArgBufferLength = 32;
namespace rtc {
namespace tracing {
namespace {
// Atomic-int fast path for avoiding logging when disabled.
static std::atomic<int> g_event_logging_active(0);
// TODO(pbos): Log metadata for all threads, etc.
class EventLogger final {
public:
~EventLogger() { RTC_DCHECK(thread_checker_.IsCurrent()); }
void AddTraceEvent(const char* name,
const unsigned char* category_enabled,
char phase,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
uint64_t timestamp,
int pid,
rtc::PlatformThreadId thread_id) {
std::vector<TraceArg> args(num_args);
for (int i = 0; i < num_args; ++i) {
TraceArg& arg = args[i];
arg.name = arg_names[i];
arg.type = arg_types[i];
arg.value.as_uint = arg_values[i];
// Value is a pointer to a temporary string, so we have to make a copy.
if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
// Space for the string and for the terminating null character.
size_t str_length = strlen(arg.value.as_string) + 1;
char* str_copy = new char[str_length];
memcpy(str_copy, arg.value.as_string, str_length);
arg.value.as_string = str_copy;
}
}
webrtc::MutexLock lock(&mutex_);
trace_events_.push_back(
{name, category_enabled, phase, args, timestamp, 1, thread_id});
}
// The TraceEvent format is documented here:
// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
void Log() {
RTC_DCHECK(output_file_);
static constexpr webrtc::TimeDelta kLoggingInterval =
webrtc::TimeDelta::Millis(100);
fprintf(output_file_, "{ \"traceEvents\": [\n");
bool has_logged_event = false;
while (true) {
bool shutting_down = shutdown_event_.Wait(kLoggingInterval);
std::vector<TraceEvent> events;
{
webrtc::MutexLock lock(&mutex_);
trace_events_.swap(events);
}
std::string args_str;
args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
for (TraceEvent& e : events) {
args_str.clear();
if (!e.args.empty()) {
args_str += ", \"args\": {";
bool is_first_argument = true;
for (TraceArg& arg : e.args) {
if (!is_first_argument)
args_str += ",";
is_first_argument = false;
args_str += " \"";
args_str += arg.name;
args_str += "\": ";
args_str += TraceArgValueAsString(arg);
// Delete our copy of the string.
if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
delete[] arg.value.as_string;
arg.value.as_string = nullptr;
}
}
args_str += " }";
}
fprintf(output_file_,
"%s{ \"name\": \"%s\""
", \"cat\": \"%s\""
", \"ph\": \"%c\""
", \"ts\": %" PRIu64
", \"pid\": %d"
#if defined(WEBRTC_WIN)
", \"tid\": %lu"
#else
", \"tid\": %d"
#endif // defined(WEBRTC_WIN)
"%s"
"}\n",
has_logged_event ? "," : " ", e.name, e.category_enabled,
e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
has_logged_event = true;
}
if (shutting_down)
break;
}
fprintf(output_file_, "]}\n");
if (output_file_owned_)
fclose(output_file_);
output_file_ = nullptr;
}
void Start(FILE* file, bool owned) {
RTC_DCHECK(thread_checker_.IsCurrent());
RTC_DCHECK(file);
RTC_DCHECK(!output_file_);
output_file_ = file;
output_file_owned_ = owned;
{
webrtc::MutexLock lock(&mutex_);
// Since the atomic fast-path for adding events to the queue can be
// bypassed while the logging thread is shutting down there may be some
// stale events in the queue, hence the vector needs to be cleared to not
// log events from a previous logging session (which may be days old).
trace_events_.clear();
}
// Enable event logging (fast-path). This should be disabled since starting
// shouldn't be done twice.
int zero = 0;
RTC_CHECK(g_event_logging_active.compare_exchange_strong(zero, 1));
// Finally start, everything should be set up now.
logging_thread_ =
PlatformThread::SpawnJoinable([this] { Log(); }, "EventTracingThread");
TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start",
TRACE_EVENT_SCOPE_GLOBAL);
}
void Stop() {
RTC_DCHECK(thread_checker_.IsCurrent());
TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop",
TRACE_EVENT_SCOPE_GLOBAL);
// Try to stop. Abort if we're not currently logging.
int one = 1;
if (g_event_logging_active.compare_exchange_strong(one, 0))
return;
// Wake up logging thread to finish writing.
shutdown_event_.Set();
// Join the logging thread.
logging_thread_.Finalize();
}
private:
struct TraceArg {
const char* name;
unsigned char type;
// Copied from webrtc/rtc_base/trace_event.h TraceValueUnion.
union TraceArgValue {
bool as_bool;
unsigned long long as_uint;
long long as_int;
double as_double;
const void* as_pointer;
const char* as_string;
} value;
// Assert that the size of the union is equal to the size of the as_uint
// field since we are assigning to arbitrary types using it.
static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
"Size of TraceArg value union is not equal to the size of "
"the uint field of that union.");
};
struct TraceEvent {
const char* name;
const unsigned char* category_enabled;
char phase;
std::vector<TraceArg> args;
uint64_t timestamp;
int pid;
rtc::PlatformThreadId tid;
};
static std::string TraceArgValueAsString(TraceArg arg) {
std::string output;
if (arg.type == TRACE_VALUE_TYPE_STRING ||
arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
// Space for every character to be an espaced character + two for
// quatation marks.
output.reserve(strlen(arg.value.as_string) * 2 + 2);
output += '\"';
const char* c = arg.value.as_string;
do {
if (*c == '"' || *c == '\\') {
output += '\\';
output += *c;
} else {
output += *c;
}
} while (*++c);
output += '\"';
} else {
output.resize(kTraceArgBufferLength);
size_t print_length = 0;
switch (arg.type) {
case TRACE_VALUE_TYPE_BOOL:
if (arg.value.as_bool) {
strcpy(&output[0], "true");
print_length = 4;
} else {
strcpy(&output[0], "false");
print_length = 5;
}
break;
case TRACE_VALUE_TYPE_UINT:
print_length = snprintf(&output[0], kTraceArgBufferLength, "%llu",
arg.value.as_uint);
break;
case TRACE_VALUE_TYPE_INT:
print_length = snprintf(&output[0], kTraceArgBufferLength, "%lld",
arg.value.as_int);
break;
case TRACE_VALUE_TYPE_DOUBLE:
print_length = snprintf(&output[0], kTraceArgBufferLength, "%f",
arg.value.as_double);
break;
case TRACE_VALUE_TYPE_POINTER:
print_length = snprintf(&output[0], kTraceArgBufferLength, "\"%p\"",
arg.value.as_pointer);
break;
}
size_t output_length = print_length < kTraceArgBufferLength
? print_length
: kTraceArgBufferLength - 1;
// This will hopefully be very close to nop. On most implementations, it
// just writes null byte and sets the length field of the string.
output.resize(output_length);
}
return output;
}
webrtc::Mutex mutex_;
std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(mutex_);
rtc::PlatformThread logging_thread_;
rtc::Event shutdown_event_;
webrtc::SequenceChecker thread_checker_;
FILE* output_file_ = nullptr;
bool output_file_owned_ = false;
};
static std::atomic<EventLogger*> g_event_logger(nullptr);
static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
const unsigned char* InternalGetCategoryEnabled(const char* name) {
const char* prefix_ptr = &kDisabledTracePrefix[0];
const char* name_ptr = name;
// Check whether name contains the default-disabled prefix.
while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
++prefix_ptr;
++name_ptr;
}
return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
: name);
}
const unsigned char* InternalEnableAllCategories(const char* name) {
return reinterpret_cast<const unsigned char*>(name);
}
void InternalAddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
unsigned char flags) {
// Fast path for when event tracing is inactive.
if (g_event_logging_active.load() == 0)
return;
g_event_logger.load()->AddTraceEvent(
name, category_enabled, phase, num_args, arg_names, arg_types, arg_values,
rtc::TimeMicros(), 1, rtc::CurrentThreadId());
}
} // namespace
void SetupInternalTracer(bool enable_all_categories) {
EventLogger* null_logger = nullptr;
RTC_CHECK(
g_event_logger.compare_exchange_strong(null_logger, new EventLogger()));
webrtc::SetupEventTracer(enable_all_categories ? InternalEnableAllCategories
: InternalGetCategoryEnabled,
InternalAddTraceEvent);
}
void StartInternalCaptureToFile(FILE* file) {
EventLogger* event_logger = g_event_logger.load();
if (event_logger) {
event_logger->Start(file, false);
}
}
bool StartInternalCapture(absl::string_view filename) {
EventLogger* event_logger = g_event_logger.load();
if (!event_logger)
return false;
FILE* file = fopen(std::string(filename).c_str(), "w");
if (!file) {
RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
<< "' for writing.";
return false;
}
event_logger->Start(file, true);
return true;
}
void StopInternalCapture() {
EventLogger* event_logger = g_event_logger.load();
if (event_logger) {
event_logger->Stop();
}
}
void ShutdownInternalTracer() {
StopInternalCapture();
EventLogger* old_logger = g_event_logger.load(std::memory_order_acquire);
RTC_DCHECK(old_logger);
RTC_CHECK(g_event_logger.compare_exchange_strong(old_logger, nullptr));
delete old_logger;
webrtc::SetupEventTracer(nullptr, nullptr);
}
} // namespace tracing
} // namespace rtc
#endif // defined(RTC_USE_PERFETTO)

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_EVENT_TRACER_H_
#define RTC_BASE_EVENT_TRACER_H_
// This file defines the interface for event tracing in WebRTC.
//
// Event log handlers are set through SetupEventTracer(). User of this API will
// provide two function pointers to handle event tracing calls.
//
// * GetCategoryEnabledPtr
// Event tracing system calls this function to determine if a particular
// event category is enabled.
//
// * AddTraceEventPtr
// Adds a tracing event. It is the user's responsibility to log the data
// provided.
//
// Parameters for the above two functions are described in trace_event.h.
#include <stdio.h>
#include "absl/strings/string_view.h"
#include "rtc_base/system/rtc_export.h"
namespace webrtc {
#if defined(RTC_USE_PERFETTO)
void RegisterPerfettoTrackEvents();
#else
typedef const unsigned char* (*GetCategoryEnabledPtr)(const char* name);
typedef void (*AddTraceEventPtr)(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
unsigned char flags);
// User of WebRTC can call this method to setup event tracing.
//
// This method must be called before any WebRTC methods. Functions
// provided should be thread-safe.
void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
AddTraceEventPtr add_trace_event_ptr);
// This class defines interface for the event tracing system to call
// internally. Do not call these methods directly.
class EventTracer {
public:
static const unsigned char* GetCategoryEnabled(const char* name);
static void AddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
unsigned char flags);
};
#endif
} // namespace webrtc
namespace rtc::tracing {
// Set up internal event tracer.
// TODO(webrtc:15917): Implement for perfetto.
RTC_EXPORT void SetupInternalTracer(bool enable_all_categories = true);
RTC_EXPORT bool StartInternalCapture(absl::string_view filename);
RTC_EXPORT void StartInternalCaptureToFile(FILE* file);
RTC_EXPORT void StopInternalCapture();
// Make sure we run this, this will tear down the internal tracing.
RTC_EXPORT void ShutdownInternalTracer();
} // namespace rtc::tracing
#endif // RTC_BASE_EVENT_TRACER_H_

View File

@ -0,0 +1,213 @@
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/platform_thread.h"
#include <algorithm>
#include <memory>
#if !defined(WEBRTC_WIN)
#include <sched.h>
#endif
#include "rtc_base/checks.h"
namespace rtc {
namespace {
#if defined(WEBRTC_WIN)
int Win32PriorityFromThreadPriority(ThreadPriority priority) {
switch (priority) {
case ThreadPriority::kLow:
return THREAD_PRIORITY_BELOW_NORMAL;
case ThreadPriority::kNormal:
return THREAD_PRIORITY_NORMAL;
case ThreadPriority::kHigh:
return THREAD_PRIORITY_ABOVE_NORMAL;
case ThreadPriority::kRealtime:
return THREAD_PRIORITY_TIME_CRITICAL;
}
}
#endif
bool SetPriority(ThreadPriority priority) {
#if defined(WEBRTC_WIN)
return SetThreadPriority(GetCurrentThread(),
Win32PriorityFromThreadPriority(priority)) != FALSE;
#elif defined(__native_client__) || defined(WEBRTC_FUCHSIA) || \
(defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__))
// Setting thread priorities is not supported in NaCl, Fuchsia or Emscripten
// without pthreads.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
const int policy = SCHED_FIFO;
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case ThreadPriority::kLow:
param.sched_priority = low_prio;
break;
case ThreadPriority::kNormal:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case ThreadPriority::kHigh:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case ThreadPriority::kRealtime:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(pthread_self(), policy, &param) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI RunPlatformThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
auto function = static_cast<std::function<void()>*>(param);
(*function)();
delete function;
return 0;
}
#else
void* RunPlatformThread(void* param) {
auto function = static_cast<std::function<void()>*>(param);
(*function)();
delete function;
return 0;
}
#endif // defined(WEBRTC_WIN)
} // namespace
PlatformThread::PlatformThread(Handle handle, bool joinable)
: handle_(handle), joinable_(joinable) {}
PlatformThread::PlatformThread(PlatformThread&& rhs)
: handle_(rhs.handle_), joinable_(rhs.joinable_) {
rhs.handle_ = absl::nullopt;
}
PlatformThread& PlatformThread::operator=(PlatformThread&& rhs) {
Finalize();
handle_ = rhs.handle_;
joinable_ = rhs.joinable_;
rhs.handle_ = absl::nullopt;
return *this;
}
PlatformThread::~PlatformThread() {
Finalize();
}
PlatformThread PlatformThread::SpawnJoinable(
std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes) {
return SpawnThread(std::move(thread_function), name, attributes,
/*joinable=*/true);
}
PlatformThread PlatformThread::SpawnDetached(
std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes) {
return SpawnThread(std::move(thread_function), name, attributes,
/*joinable=*/false);
}
absl::optional<PlatformThread::Handle> PlatformThread::GetHandle() const {
return handle_;
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(handle_.has_value());
return handle_.has_value() ? QueueUserAPC(function, *handle_, data) != FALSE
: false;
}
#endif
void PlatformThread::Finalize() {
if (!handle_.has_value())
return;
#if defined(WEBRTC_WIN)
if (joinable_)
WaitForSingleObject(*handle_, INFINITE);
CloseHandle(*handle_);
#else
if (joinable_)
RTC_CHECK_EQ(0, pthread_join(*handle_, nullptr));
#endif
handle_ = absl::nullopt;
}
PlatformThread PlatformThread::SpawnThread(
std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes,
bool joinable) {
RTC_DCHECK(thread_function);
RTC_DCHECK(!name.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name.length() < 64);
auto start_thread_function_ptr =
new std::function<void()>([thread_function = std::move(thread_function),
name = std::string(name), attributes] {
rtc::SetCurrentThreadName(name.c_str());
SetPriority(attributes.priority);
thread_function();
});
#if defined(WEBRTC_WIN)
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
DWORD thread_id = 0;
PlatformThread::Handle handle = ::CreateThread(
nullptr, 1024 * 1024, &RunPlatformThread, start_thread_function_ptr,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id);
RTC_CHECK(handle) << "CreateThread failed";
#else
pthread_attr_t attr;
pthread_attr_init(&attr);
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
pthread_attr_setdetachstate(
&attr, joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
PlatformThread::Handle handle;
RTC_CHECK_EQ(0, pthread_create(&handle, &attr, &RunPlatformThread,
start_thread_function_ptr));
pthread_attr_destroy(&attr);
#endif // defined(WEBRTC_WIN)
return PlatformThread(handle, joinable);
}
} // namespace rtc

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_PLATFORM_THREAD_H_
#define RTC_BASE_PLATFORM_THREAD_H_
#include <functional>
#include <string>
#if !defined(WEBRTC_WIN)
#include <pthread.h>
#endif
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "rtc_base/platform_thread_types.h"
namespace rtc {
enum class ThreadPriority {
kLow = 1,
kNormal,
kHigh,
kRealtime,
};
struct ThreadAttributes {
ThreadPriority priority = ThreadPriority::kNormal;
ThreadAttributes& SetPriority(ThreadPriority priority_param) {
priority = priority_param;
return *this;
}
};
// Represents a simple worker thread.
class PlatformThread final {
public:
// Handle is the base platform thread handle.
#if defined(WEBRTC_WIN)
using Handle = HANDLE;
#else
using Handle = pthread_t;
#endif // defined(WEBRTC_WIN)
// This ctor creates the PlatformThread with an unset handle (returning true
// in empty()) and is provided for convenience.
// TODO(bugs.webrtc.org/12727) Look into if default and move support can be
// removed.
PlatformThread() = default;
// Moves `rhs` into this, storing an empty state in `rhs`.
// TODO(bugs.webrtc.org/12727) Look into if default and move support can be
// removed.
PlatformThread(PlatformThread&& rhs);
// Copies won't work since we'd have problems with joinable threads.
PlatformThread(const PlatformThread&) = delete;
PlatformThread& operator=(const PlatformThread&) = delete;
// Moves `rhs` into this, storing an empty state in `rhs`.
// TODO(bugs.webrtc.org/12727) Look into if default and move support can be
// removed.
PlatformThread& operator=(PlatformThread&& rhs);
// For a PlatformThread that's been spawned joinable, the destructor suspends
// the calling thread until the created thread exits unless the thread has
// already exited.
virtual ~PlatformThread();
// Finalizes any allocated resources.
// For a PlatformThread that's been spawned joinable, Finalize() suspends
// the calling thread until the created thread exits unless the thread has
// already exited.
// empty() returns true after completion.
void Finalize();
// Returns true if default constructed, moved from, or Finalize()ed.
bool empty() const { return !handle_.has_value(); }
// Creates a started joinable thread which will be joined when the returned
// PlatformThread destructs or Finalize() is called.
static PlatformThread SpawnJoinable(
std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes = ThreadAttributes());
// Creates a started detached thread. The caller has to use external
// synchronization as nothing is provided by the PlatformThread construct.
static PlatformThread SpawnDetached(
std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes = ThreadAttributes());
// Returns the base platform thread handle of this thread.
absl::optional<Handle> GetHandle() const;
#if defined(WEBRTC_WIN)
// Queue a Windows APC function that runs when the thread is alertable.
bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data);
#endif
private:
PlatformThread(Handle handle, bool joinable);
static PlatformThread SpawnThread(std::function<void()> thread_function,
absl::string_view name,
ThreadAttributes attributes,
bool joinable);
absl::optional<Handle> handle_;
bool joinable_ = false;
};
} // namespace rtc
#endif // RTC_BASE_PLATFORM_THREAD_H_

View File

@ -0,0 +1,29 @@
/*
* Copyright 2011 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_REF_COUNT_H_
#define RTC_BASE_REF_COUNT_H_
// Transition file for backwards compatibility with source code
// that includes the non-API file.
#include "api/ref_count.h"
namespace rtc {
// TODO(bugs.webrtc.org/15622): Deprecate and remove these aliases.
using RefCountInterface [[deprecated("Use webrtc::RefCountInterface")]] =
webrtc::RefCountInterface;
using RefCountReleaseStatus
[[deprecated("Use webrtc::RefCountReleaseStatus")]] =
webrtc::RefCountReleaseStatus;
} // namespace rtc
#endif // RTC_BASE_REF_COUNT_H_

View File

@ -0,0 +1,142 @@
/*
* Copyright 2016 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_REF_COUNTED_OBJECT_H_
#define RTC_BASE_REF_COUNTED_OBJECT_H_
#include "api/scoped_refptr.h"
#include "rtc_base/ref_count.h"
#include "rtc_base/ref_counter.h"
namespace webrtc {
template <class T>
class RefCountedObject : public T {
public:
RefCountedObject() {}
RefCountedObject(const RefCountedObject&) = delete;
RefCountedObject& operator=(const RefCountedObject&) = delete;
template <class P0>
explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {}
template <class P0, class P1, class... Args>
RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
: T(std::forward<P0>(p0),
std::forward<P1>(p1),
std::forward<Args>(args)...) {}
void AddRef() const override { ref_count_.IncRef(); }
RefCountReleaseStatus Release() const override {
const auto status = ref_count_.DecRef();
if (status == RefCountReleaseStatus::kDroppedLastRef) {
delete this;
}
return status;
}
// Return whether the reference count is one. If the reference count is used
// in the conventional way, a reference count of 1 implies that the current
// thread owns the reference and no other thread shares it. This call
// performs the test for a reference count of one, and performs the memory
// barrier needed for the owning thread to act on the object, knowing that it
// has exclusive access to the object.
virtual bool HasOneRef() const { return ref_count_.HasOneRef(); }
protected:
~RefCountedObject() override {}
mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
};
template <class T>
class FinalRefCountedObject final : public T {
public:
using T::T;
// Above using declaration propagates a default move constructor
// FinalRefCountedObject(FinalRefCountedObject&& other), but we also need
// move construction from T.
explicit FinalRefCountedObject(T&& other) : T(std::move(other)) {}
FinalRefCountedObject(const FinalRefCountedObject&) = delete;
FinalRefCountedObject& operator=(const FinalRefCountedObject&) = delete;
void AddRef() const { ref_count_.IncRef(); }
RefCountReleaseStatus Release() const {
const auto status = ref_count_.DecRef();
if (status == RefCountReleaseStatus::kDroppedLastRef) {
delete this;
}
return status;
}
bool HasOneRef() const { return ref_count_.HasOneRef(); }
private:
~FinalRefCountedObject() = default;
mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
};
} // namespace webrtc
// Backwards compatibe aliases.
// TODO: https://issues.webrtc.org/42225969 - deprecate and remove.
namespace rtc {
// Because there are users of this template that use "friend
// rtc::RefCountedObject<>" to give access to a private destructor, some
// indirection is needed; "friend" declarations cannot span an "using"
// declaration. Since a templated class on top of a templated class can't access
// the subclass' protected members, we duplicate the entire class instead.
template <class T>
class RefCountedObject : public T {
public:
RefCountedObject() {}
RefCountedObject(const RefCountedObject&) = delete;
RefCountedObject& operator=(const RefCountedObject&) = delete;
template <class P0>
explicit RefCountedObject(P0&& p0) : T(std::forward<P0>(p0)) {}
template <class P0, class P1, class... Args>
RefCountedObject(P0&& p0, P1&& p1, Args&&... args)
: T(std::forward<P0>(p0),
std::forward<P1>(p1),
std::forward<Args>(args)...) {}
void AddRef() const override { ref_count_.IncRef(); }
webrtc::RefCountReleaseStatus Release() const override {
const auto status = ref_count_.DecRef();
if (status == webrtc::RefCountReleaseStatus::kDroppedLastRef) {
delete this;
}
return status;
}
// Return whether the reference count is one. If the reference count is used
// in the conventional way, a reference count of 1 implies that the current
// thread owns the reference and no other thread shares it. This call
// performs the test for a reference count of one, and performs the memory
// barrier needed for the owning thread to act on the object, knowing that it
// has exclusive access to the object.
virtual bool HasOneRef() const { return ref_count_.HasOneRef(); }
protected:
~RefCountedObject() override {}
mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
};
template <typename T>
using FinalRefCountedObject = webrtc::FinalRefCountedObject<T>;
} // namespace rtc
#endif // RTC_BASE_REF_COUNTED_OBJECT_H_

View File

@ -0,0 +1,75 @@
/*
* Copyright 2017 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_REF_COUNTER_H_
#define RTC_BASE_REF_COUNTER_H_
#include <atomic>
#include "rtc_base/ref_count.h"
namespace webrtc {
namespace webrtc_impl {
class RefCounter {
public:
explicit RefCounter(int ref_count) : ref_count_(ref_count) {}
RefCounter() = delete;
void IncRef() {
// Relaxed memory order: The current thread is allowed to act on the
// resource protected by the reference counter both before and after the
// atomic op, so this function doesn't prevent memory access reordering.
ref_count_.fetch_add(1, std::memory_order_relaxed);
}
// Returns kDroppedLastRef if this call dropped the last reference; the caller
// should therefore free the resource protected by the reference counter.
// Otherwise, returns kOtherRefsRemained (note that in case of multithreading,
// some other caller may have dropped the last reference by the time this call
// returns; all we know is that we didn't do it).
RefCountReleaseStatus DecRef() {
// Use release-acquire barrier to ensure all actions on the protected
// resource are finished before the resource can be freed.
// When ref_count_after_subtract > 0, this function require
// std::memory_order_release part of the barrier.
// When ref_count_after_subtract == 0, this function require
// std::memory_order_acquire part of the barrier.
// In addition std::memory_order_release is used for synchronization with
// the HasOneRef function to make sure all actions on the protected resource
// are finished before the resource is assumed to have exclusive access.
int ref_count_after_subtract =
ref_count_.fetch_sub(1, std::memory_order_acq_rel) - 1;
return ref_count_after_subtract == 0
? RefCountReleaseStatus::kDroppedLastRef
: RefCountReleaseStatus::kOtherRefsRemained;
}
// Return whether the reference count is one. If the reference count is used
// in the conventional way, a reference count of 1 implies that the current
// thread owns the reference and no other thread shares it. This call performs
// the test for a reference count of one, and performs the memory barrier
// needed for the owning thread to act on the resource protected by the
// reference counter, knowing that it has exclusive access.
bool HasOneRef() const {
// To ensure resource protected by the reference counter has exclusive
// access, all changes to the resource before it was released by other
// threads must be visible by current thread. That is provided by release
// (in DecRef) and acquire (in this function) ordering.
return ref_count_.load(std::memory_order_acquire) == 1;
}
private:
std::atomic<int> ref_count_;
};
} // namespace webrtc_impl
} // namespace webrtc
#endif // RTC_BASE_REF_COUNTER_H_

View File

@ -0,0 +1,86 @@
/*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/synchronization/sequence_checker_internal.h"
#include <string>
#include "rtc_base/checks.h"
#include "rtc_base/strings/string_builder.h"
namespace webrtc {
namespace webrtc_sequence_checker_internal {
SequenceCheckerImpl::SequenceCheckerImpl(bool attach_to_current_thread)
: attached_(attach_to_current_thread),
valid_thread_(rtc::CurrentThreadRef()),
valid_queue_(TaskQueueBase::Current()) {}
SequenceCheckerImpl::SequenceCheckerImpl(TaskQueueBase* attached_queue)
: attached_(attached_queue != nullptr),
valid_thread_(rtc::PlatformThreadRef()),
valid_queue_(attached_queue) {}
bool SequenceCheckerImpl::IsCurrent() const {
const TaskQueueBase* const current_queue = TaskQueueBase::Current();
const rtc::PlatformThreadRef current_thread = rtc::CurrentThreadRef();
MutexLock scoped_lock(&lock_);
if (!attached_) { // Previously detached.
attached_ = true;
valid_thread_ = current_thread;
valid_queue_ = current_queue;
return true;
}
if (valid_queue_) {
return valid_queue_ == current_queue;
}
return rtc::IsThreadRefEqual(valid_thread_, current_thread);
}
void SequenceCheckerImpl::Detach() {
MutexLock scoped_lock(&lock_);
attached_ = false;
// We don't need to touch the other members here, they will be
// reset on the next call to IsCurrent().
}
#if RTC_DCHECK_IS_ON
std::string SequenceCheckerImpl::ExpectationToString() const {
const TaskQueueBase* const current_queue = TaskQueueBase::Current();
const rtc::PlatformThreadRef current_thread = rtc::CurrentThreadRef();
MutexLock scoped_lock(&lock_);
if (!attached_)
return "Checker currently not attached.";
// The format of the string is meant to compliment the one we have inside of
// FatalLog() (checks.cc). Example:
//
// # Expected: TQ: 0x0 SysQ: 0x7fff69541330 Thread: 0x11dcf6dc0
// # Actual: TQ: 0x7fa8f0604190 SysQ: 0x7fa8f0604a30 Thread: 0x700006f1a000
// TaskQueue doesn't match
rtc::StringBuilder message;
message.AppendFormat(
"# Expected: TQ: %p Thread: %p\n"
"# Actual: TQ: %p Thread: %p\n",
valid_queue_, reinterpret_cast<const void*>(valid_thread_), current_queue,
reinterpret_cast<const void*>(current_thread));
if ((valid_queue_ || current_queue) && valid_queue_ != current_queue) {
message << "TaskQueue doesn't match\n";
} else if (!rtc::IsThreadRefEqual(valid_thread_, current_thread)) {
message << "Threads don't match\n";
}
return message.Release();
}
#endif // RTC_DCHECK_IS_ON
} // namespace webrtc_sequence_checker_internal
} // namespace webrtc

View File

@ -0,0 +1,90 @@
/*
* Copyright 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SYNCHRONIZATION_SEQUENCE_CHECKER_INTERNAL_H_
#define RTC_BASE_SYNCHRONIZATION_SEQUENCE_CHECKER_INTERNAL_H_
#include <string>
#include <type_traits>
#include "api/task_queue/task_queue_base.h"
#include "rtc_base/platform_thread_types.h"
#include "rtc_base/synchronization/mutex.h"
#include "rtc_base/system/rtc_export.h"
#include "rtc_base/thread_annotations.h"
namespace webrtc {
namespace webrtc_sequence_checker_internal {
// Real implementation of SequenceChecker, for use in debug mode, or
// for temporary use in release mode (e.g. to RTC_CHECK on a threading issue
// seen only in the wild).
//
// Note: You should almost always use the SequenceChecker class to get the
// right version for your build configuration.
class RTC_EXPORT SequenceCheckerImpl {
public:
explicit SequenceCheckerImpl(bool attach_to_current_thread);
explicit SequenceCheckerImpl(TaskQueueBase* attached_queue);
~SequenceCheckerImpl() = default;
bool IsCurrent() const;
// Changes the task queue or thread that is checked for in IsCurrent. This can
// be useful when an object may be created on one task queue / thread and then
// used exclusively on another thread.
void Detach();
// Returns a string that is formatted to match with the error string printed
// by RTC_CHECK() when a condition is not met.
// This is used in conjunction with the RTC_DCHECK_RUN_ON() macro.
std::string ExpectationToString() const;
private:
mutable Mutex lock_;
// These are mutable so that IsCurrent can set them.
mutable bool attached_ RTC_GUARDED_BY(lock_);
mutable rtc::PlatformThreadRef valid_thread_ RTC_GUARDED_BY(lock_);
mutable const TaskQueueBase* valid_queue_ RTC_GUARDED_BY(lock_);
};
// Do nothing implementation, for use in release mode.
//
// Note: You should almost always use the SequenceChecker class to get the
// right version for your build configuration.
class SequenceCheckerDoNothing {
public:
explicit SequenceCheckerDoNothing(bool attach_to_current_thread) {}
explicit SequenceCheckerDoNothing(TaskQueueBase* attached_queue) {}
bool IsCurrent() const { return true; }
void Detach() {}
};
template <typename ThreadLikeObject>
std::enable_if_t<std::is_base_of_v<SequenceCheckerImpl, ThreadLikeObject>,
std::string>
ExpectationToString(const ThreadLikeObject* checker) {
#if RTC_DCHECK_IS_ON
return checker->ExpectationToString();
#else
return std::string();
#endif
}
// Catch-all implementation for types other than explicitly supported above.
template <typename ThreadLikeObject>
std::enable_if_t<!std::is_base_of_v<SequenceCheckerImpl, ThreadLikeObject>,
std::string>
ExpectationToString(const ThreadLikeObject*) {
return std::string();
}
} // namespace webrtc_sequence_checker_internal
} // namespace webrtc
#endif // RTC_BASE_SYNCHRONIZATION_SEQUENCE_CHECKER_INTERNAL_H_

View File

@ -0,0 +1,82 @@
/*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/synchronization/yield_policy.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "rtc_base/checks.h"
#if !defined(ABSL_HAVE_THREAD_LOCAL) && defined(WEBRTC_POSIX)
#include <pthread.h>
#endif
namespace rtc {
namespace {
#if defined(ABSL_HAVE_THREAD_LOCAL)
ABSL_CONST_INIT thread_local YieldInterface* current_yield_policy = nullptr;
YieldInterface* GetCurrentYieldPolicy() {
return current_yield_policy;
}
void SetCurrentYieldPolicy(YieldInterface* ptr) {
current_yield_policy = ptr;
}
#elif defined(WEBRTC_POSIX)
// Emscripten does not support the C++11 thread_local keyword but does support
// the pthread thread-local storage API.
// https://github.com/emscripten-core/emscripten/issues/3502
ABSL_CONST_INIT pthread_key_t g_current_yield_policy_tls = 0;
void InitializeTls() {
RTC_CHECK_EQ(pthread_key_create(&g_current_yield_policy_tls, nullptr), 0);
}
pthread_key_t GetCurrentYieldPolicyTls() {
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
RTC_CHECK_EQ(pthread_once(&init_once, &InitializeTls), 0);
return g_current_yield_policy_tls;
}
YieldInterface* GetCurrentYieldPolicy() {
return static_cast<YieldInterface*>(
pthread_getspecific(GetCurrentYieldPolicyTls()));
}
void SetCurrentYieldPolicy(YieldInterface* ptr) {
pthread_setspecific(GetCurrentYieldPolicyTls(), ptr);
}
#else
#error Unsupported platform
#endif
} // namespace
ScopedYieldPolicy::ScopedYieldPolicy(YieldInterface* policy)
: previous_(GetCurrentYieldPolicy()) {
SetCurrentYieldPolicy(policy);
}
ScopedYieldPolicy::~ScopedYieldPolicy() {
SetCurrentYieldPolicy(previous_);
}
void ScopedYieldPolicy::YieldExecution() {
YieldInterface* current = GetCurrentYieldPolicy();
if (current)
current->YieldExecution();
}
} // namespace rtc

View File

@ -0,0 +1,38 @@
/*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SYNCHRONIZATION_YIELD_POLICY_H_
#define RTC_BASE_SYNCHRONIZATION_YIELD_POLICY_H_
namespace rtc {
class YieldInterface {
public:
virtual ~YieldInterface() = default;
virtual void YieldExecution() = 0;
};
// Sets the current thread-local yield policy while it's in scope and reverts
// to the previous policy when it leaves the scope.
class ScopedYieldPolicy final {
public:
explicit ScopedYieldPolicy(YieldInterface* policy);
ScopedYieldPolicy(const ScopedYieldPolicy&) = delete;
ScopedYieldPolicy& operator=(const ScopedYieldPolicy&) = delete;
~ScopedYieldPolicy();
// Will yield as specified by the currently active thread-local yield policy
// (which by default is a no-op).
static void YieldExecution();
private:
YieldInterface* const previous_;
};
} // namespace rtc
#endif // RTC_BASE_SYNCHRONIZATION_YIELD_POLICY_H_

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SYSTEM_IGNORE_WARNINGS_H_
#define RTC_BASE_SYSTEM_IGNORE_WARNINGS_H_
#ifdef __clang__
#define RTC_PUSH_IGNORING_WFRAME_LARGER_THAN() \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wframe-larger-than=\"")
#define RTC_POP_IGNORING_WFRAME_LARGER_THAN() _Pragma("clang diagnostic pop")
#elif __GNUC__
#define RTC_PUSH_IGNORING_WFRAME_LARGER_THAN() \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wframe-larger-than=\"")
#define RTC_POP_IGNORING_WFRAME_LARGER_THAN() _Pragma("GCC diagnostic pop")
#else
#define RTC_PUSH_IGNORING_WFRAME_LARGER_THAN()
#define RTC_POP_IGNORING_WFRAME_LARGER_THAN()
#endif
#endif // RTC_BASE_SYSTEM_IGNORE_WARNINGS_H_

View File

@ -0,0 +1,19 @@
/*
* Copyright 2019 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/system/warn_current_thread_is_deadlocked.h"
#include "rtc_base/logging.h"
namespace webrtc {
} // namespace webrtc

View File

@ -0,0 +1,24 @@
/*
* Copyright 2019 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SYSTEM_WARN_CURRENT_THREAD_IS_DEADLOCKED_H_
#define RTC_BASE_SYSTEM_WARN_CURRENT_THREAD_IS_DEADLOCKED_H_
namespace webrtc {
#if defined(WEBRTC_ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
void WarnThatTheCurrentThreadIsProbablyDeadlocked();
#else
inline void WarnThatTheCurrentThreadIsProbablyDeadlocked() {}
#endif
} // namespace webrtc
#endif // RTC_BASE_SYSTEM_WARN_CURRENT_THREAD_IS_DEADLOCKED_H_

View File

@ -0,0 +1,807 @@
/*
* Copyright (c) 2024 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_TRACE_EVENT_H_
#define RTC_BASE_TRACE_EVENT_H_
#if defined(RTC_DISABLE_TRACE_EVENTS)
#define RTC_TRACE_EVENTS_ENABLED 0
#else
#define RTC_TRACE_EVENTS_ENABLED 1
#endif
// IWYU pragma: begin_exports
#if defined(RTC_USE_PERFETTO)
#include "rtc_base/trace_categories.h"
#endif
// IWYU pragma: end_exports
#if !defined(RTC_USE_PERFETTO)
#include <string>
#include "rtc_base/event_tracer.h"
#define RTC_NOOP() \
do { \
} while (0)
// TODO(b/42226290): Add implementation for these events with Perfetto.
#define TRACE_EVENT_BEGIN(category, name, ...) RTC_NOOP();
#define TRACE_EVENT_END(category, ...) RTC_NOOP();
#define TRACE_EVENT(category, name, ...) RTC_NOOP();
#define TRACE_EVENT_INSTANT(category, name, ...) RTC_NOOP();
#define TRACE_EVENT_CATEGORY_ENABLED(category) RTC_NOOP();
#define TRACE_COUNTER(category, track, ...) RTC_NOOP();
// Type values for identifying types in the TraceValue union.
#define TRACE_VALUE_TYPE_BOOL (static_cast<unsigned char>(1))
#define TRACE_VALUE_TYPE_UINT (static_cast<unsigned char>(2))
#define TRACE_VALUE_TYPE_INT (static_cast<unsigned char>(3))
#define TRACE_VALUE_TYPE_DOUBLE (static_cast<unsigned char>(4))
#define TRACE_VALUE_TYPE_POINTER (static_cast<unsigned char>(5))
#define TRACE_VALUE_TYPE_STRING (static_cast<unsigned char>(6))
#define TRACE_VALUE_TYPE_COPY_STRING (static_cast<unsigned char>(7))
#if defined(TRACE_EVENT0)
#error "Another copy of trace_event.h has already been included."
#endif
#if RTC_TRACE_EVENTS_ENABLED
// Extracted from Chromium's src/base/debug/trace_event.h.
// This header is designed to give you trace_event macros without specifying
// how the events actually get collected and stored. If you need to expose trace
// event to some other universe, you can copy-and-paste this file,
// implement the TRACE_EVENT_API macros, and do any other necessary fixup for
// the target platform. The end result is that multiple libraries can funnel
// events through to a shared trace event collector.
// Trace events are for tracking application performance and resource usage.
// Macros are provided to track:
// Begin and end of function calls
// Counters
//
// Events are issued against categories. Whereas RTC_LOG's
// categories are statically defined, TRACE categories are created
// implicitly with a string. For example:
// TRACE_EVENT_INSTANT0("MY_SUBSYSTEM", "SomeImportantEvent")
//
// Events can be INSTANT, or can be pairs of BEGIN and END in the same scope:
// TRACE_EVENT_BEGIN0("MY_SUBSYSTEM", "SomethingCostly")
// doSomethingCostly()
// TRACE_EVENT_END0("MY_SUBSYSTEM", "SomethingCostly")
// Note: our tools can't always determine the correct BEGIN/END pairs unless
// these are used in the same scope. Use ASYNC_BEGIN/ASYNC_END macros if you
// need them to be in separate scopes.
//
// A common use case is to trace entire function scopes. This
// issues a trace BEGIN and END automatically:
// void doSomethingCostly() {
// TRACE_EVENT0("MY_SUBSYSTEM", "doSomethingCostly");
// ...
// }
//
// Additional parameters can be associated with an event:
// void doSomethingCostly2(int howMuch) {
// TRACE_EVENT1("MY_SUBSYSTEM", "doSomethingCostly",
// "howMuch", howMuch);
// ...
// }
//
// The trace system will automatically add to this information the
// current process id, thread id, and a timestamp in microseconds.
//
// To trace an asynchronous procedure such as an IPC send/receive, use
// ASYNC_BEGIN and ASYNC_END:
// [single threaded sender code]
// static int send_count = 0;
// ++send_count;
// TRACE_EVENT_ASYNC_BEGIN0("ipc", "message", send_count);
// Send(new MyMessage(send_count));
// [receive code]
// void OnMyMessage(send_count) {
// TRACE_EVENT_ASYNC_END0("ipc", "message", send_count);
// }
// The third parameter is a unique ID to match ASYNC_BEGIN/ASYNC_END pairs.
// ASYNC_BEGIN and ASYNC_END can occur on any thread of any traced process.
// Pointers can be used for the ID parameter, and they will be mangled
// internally so that the same pointer on two different processes will not
// match. For example:
// class MyTracedClass {
// public:
// MyTracedClass() {
// TRACE_EVENT_ASYNC_BEGIN0("category", "MyTracedClass", this);
// }
// ~MyTracedClass() {
// TRACE_EVENT_ASYNC_END0("category", "MyTracedClass", this);
// }
// }
//
// Trace event also supports counters, which is a way to track a quantity
// as it varies over time. Counters are created with the following macro:
// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter", g_myCounterValue);
//
// Counters are process-specific. The macro itself can be issued from any
// thread, however.
//
// Sometimes, you want to track two counters at once. You can do this with two
// counter macros:
// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter0", g_myCounterValue[0]);
// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter1", g_myCounterValue[1]);
// Or you can do it with a combined macro:
// TRACE_COUNTER2("MY_SUBSYSTEM", "myCounter",
// "bytesPinned", g_myCounterValue[0],
// "bytesAllocated", g_myCounterValue[1]);
// This indicates to the tracing UI that these counters should be displayed
// in a single graph, as a summed area chart.
//
// Since counters are in a global namespace, you may want to disembiguate with a
// unique ID, by using the TRACE_COUNTER_ID* variations.
//
// By default, trace collection is compiled in, but turned off at runtime.
// Collecting trace data is the responsibility of the embedding
// application. In Chrome's case, navigating to about:tracing will turn on
// tracing and display data collected across all active processes.
//
// When are string argument values copied:
// const char* arg_values are only referenced by default:
// TRACE_EVENT1("category", "name",
// "arg1", "literal string is only referenced");
// Use TRACE_STR_COPY to force copying of a const char*:
// TRACE_EVENT1("category", "name",
// "arg1", TRACE_STR_COPY("string will be copied"));
// std::string arg_values are always copied:
// TRACE_EVENT1("category", "name",
// "arg1", std::string("string will be copied"));
//
//
// Thread Safety:
// Thread safety is provided by methods defined in event_tracer.h. See the file
// for details.
// By default, const char* argument values are assumed to have long-lived scope
// and will not be copied. Use this macro to force a const char* to be copied.
#define TRACE_STR_COPY(str) \
webrtc::trace_event_internal::TraceStringWithCopy(str)
// This will mark the trace event as disabled by default. The user will need
// to explicitly enable the event.
#define TRACE_DISABLED_BY_DEFAULT(name) "disabled-by-default-" name
// By default, uint64 ID argument values are not mangled with the Process ID in
// TRACE_EVENT_ASYNC macros. Use this macro to force Process ID mangling.
#define TRACE_ID_MANGLE(id) \
webrtc::trace_event_internal::TraceID::ForceMangle(id)
// Records a pair of begin and end events called "name" for the current
// scope, with 0, 1 or 2 associated arguments. If the category is not
// enabled, then this does nothing.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_EVENT0(category, name) \
INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name)
#define TRACE_EVENT1(category, name, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, arg1_name, arg1_val)
#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, arg1_name, arg1_val, \
arg2_name, arg2_val)
// Enum reflecting the scope of an INSTANT event. Must fit within
// TRACE_EVENT_FLAG_SCOPE_MASK.
static constexpr uint8_t TRACE_EVENT_SCOPE_GLOBAL = 0u << 2;
static constexpr uint8_t TRACE_EVENT_SCOPE_PROCESS = 1u << 2;
static constexpr uint8_t TRACE_EVENT_SCOPE_THREAD = 2u << 2;
// Records a single event called "name" immediately, with 0, 1 or 2
// associated arguments. If the category is not enabled, then this
// does nothing.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_EVENT_INSTANT0(category, name, scope) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, category, name, \
TRACE_EVENT_FLAG_NONE)
#define TRACE_EVENT_INSTANT1(category, name, scope, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
#define TRACE_EVENT_INSTANT2(category, name, scope, arg1_name, arg1_val, \
arg2_name, arg2_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
arg2_name, arg2_val)
// Records a single BEGIN event called "name" immediately, with 0, 1 or 2
// associated arguments. If the category is not enabled, then this
// does nothing.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_EVENT_BEGIN0(category, name) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, category, name, \
TRACE_EVENT_FLAG_NONE)
#define TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
arg2_name, arg2_val)
// Records a single END event for "name" immediately. If the category
// is not enabled, then this does nothing.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_EVENT_END0(category, name) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, category, name, \
TRACE_EVENT_FLAG_NONE)
#define TRACE_EVENT_END1(category, name, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, category, name, \
TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
arg2_name, arg2_val)
// Records the value of a counter called "name" immediately. Value
// must be representable as a 32 bit integer.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_COUNTER1(category, name, value) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, category, name, \
TRACE_EVENT_FLAG_NONE, "value", \
static_cast<int>(value))
// Records the values of a multi-parted counter called "name" immediately.
// The UI will treat value1 and value2 as parts of a whole, displaying their
// values as a stacked-bar chart.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
#define TRACE_COUNTER2(category, name, value1_name, value1_val, value2_name, \
value2_val) \
INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, category, name, \
TRACE_EVENT_FLAG_NONE, value1_name, \
static_cast<int>(value1_val), value2_name, \
static_cast<int>(value2_val))
// Records the value of a counter called "name" immediately. Value
// must be representable as a 32 bit integer.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
// - `id` is used to disambiguate counters with the same name. It must either
// be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
// will be xored with a hash of the process ID so that the same pointer on
// two different processes will not collide.
#define TRACE_COUNTER_ID1(category, name, id, value) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, category, name, \
id, TRACE_EVENT_FLAG_NONE, "value", \
static_cast<int>(value))
// Records the values of a multi-parted counter called "name" immediately.
// The UI will treat value1 and value2 as parts of a whole, displaying their
// values as a stacked-bar chart.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
// - `id` is used to disambiguate counters with the same name. It must either
// be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
// will be xored with a hash of the process ID so that the same pointer on
// two different processes will not collide.
#define TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, \
value2_name, value2_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, category, name, \
id, TRACE_EVENT_FLAG_NONE, value1_name, \
static_cast<int>(value1_val), value2_name, \
static_cast<int>(value2_val))
// Records a single ASYNC_BEGIN event called "name" immediately, with 0, 1 or 2
// associated arguments. If the category is not enabled, then this
// does nothing.
// - category and name strings must have application lifetime (statics or
// literals). They may not include " chars.
// - `id` is used to match the ASYNC_BEGIN event with the ASYNC_END event. ASYNC
// events are considered to match if their category, name and id values all
// match. `id` must either be a pointer or an integer value up to 64 bits. If
// it's a pointer, the bits will be xored with a hash of the process ID so
// that the same pointer on two different processes will not collide.
// An asynchronous operation can consist of multiple phases. The first phase is
// defined by the ASYNC_BEGIN calls. Additional phases can be defined using the
// ASYNC_STEP macros. When the operation completes, call ASYNC_END.
// An ASYNC trace typically occur on a single thread (if not, they will only be
// drawn on the thread defined in the ASYNC_BEGIN event), but all events in that
// operation must use the same `name` and `id`. Each event can have its own
// args.
#define TRACE_EVENT_ASYNC_BEGIN0(category, name, id) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, category, \
name, id, TRACE_EVENT_FLAG_NONE)
#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, category, \
name, id, TRACE_EVENT_FLAG_NONE, arg1_name, \
arg1_val)
#define TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \
arg2_name, arg2_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, category, \
name, id, TRACE_EVENT_FLAG_NONE, arg1_name, \
arg1_val, arg2_name, arg2_val)
// Records a single ASYNC_STEP event for `step` immediately. If the category
// is not enabled, then this does nothing. The `name` and `id` must match the
// ASYNC_BEGIN event above. The `step` param identifies this step within the
// async event. This should be called at the beginning of the next phase of an
// asynchronous operation.
#define TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, category, \
name, id, TRACE_EVENT_FLAG_NONE, "step", \
step)
#define TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, arg1_name, \
arg1_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, category, \
name, id, TRACE_EVENT_FLAG_NONE, "step", \
step, arg1_name, arg1_val)
// Records a single ASYNC_END event for "name" immediately. If the category
// is not enabled, then this does nothing.
#define TRACE_EVENT_ASYNC_END0(category, name, id) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, category, \
name, id, TRACE_EVENT_FLAG_NONE)
#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, category, \
name, id, TRACE_EVENT_FLAG_NONE, arg1_name, \
arg1_val)
#define TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, arg1_val, \
arg2_name, arg2_val) \
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, category, \
name, id, TRACE_EVENT_FLAG_NONE, arg1_name, \
arg1_val, arg2_name, arg2_val)
////////////////////////////////////////////////////////////////////////////////
// Implementation specific tracing API definitions.
// Get a pointer to the enabled state of the given trace category. Only
// long-lived literal strings should be given as the category name. The returned
// pointer can be held permanently in a local static for example. If the
// unsigned char is non-zero, tracing is enabled. If tracing is enabled,
// TRACE_EVENT_API_ADD_TRACE_EVENT can be called. It's OK if tracing is disabled
// between the load of the tracing state and the call to
// TRACE_EVENT_API_ADD_TRACE_EVENT, because this flag only provides an early out
// for best performance when tracing is disabled.
// const unsigned char*
// TRACE_EVENT_API_GET_CATEGORY_ENABLED(const char* category_name)
#define TRACE_EVENT_API_GET_CATEGORY_ENABLED \
webrtc::EventTracer::GetCategoryEnabled
// Add a trace event to the platform tracing system.
// void TRACE_EVENT_API_ADD_TRACE_EVENT(
// char phase,
// const unsigned char* category_enabled,
// const char* name,
// unsigned long long id,
// int num_args,
// const char** arg_names,
// const unsigned char* arg_types,
// const unsigned long long* arg_values,
// unsigned char flags)
#define TRACE_EVENT_API_ADD_TRACE_EVENT webrtc::EventTracer::AddTraceEvent
////////////////////////////////////////////////////////////////////////////////
// Implementation detail: trace event macros create temporary variables
// to keep instrumentation overhead low. These macros give each temporary
// variable a unique name based on the line number to prevent name collissions.
#define INTERNAL_TRACE_EVENT_UID3(a, b) trace_event_unique_##a##b
#define INTERNAL_TRACE_EVENT_UID2(a, b) INTERNAL_TRACE_EVENT_UID3(a, b)
#define INTERNAL_TRACE_EVENT_UID(name_prefix) \
INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__)
#if WEBRTC_NON_STATIC_TRACE_EVENT_HANDLERS
#define INTERNAL_TRACE_EVENT_INFO_TYPE const unsigned char*
#else
#define INTERNAL_TRACE_EVENT_INFO_TYPE static const unsigned char*
#endif // WEBRTC_NON_STATIC_TRACE_EVENT_HANDLERS
// Implementation detail: internal macro to create static category.
#define INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category) \
INTERNAL_TRACE_EVENT_INFO_TYPE INTERNAL_TRACE_EVENT_UID(catstatic) = \
TRACE_EVENT_API_GET_CATEGORY_ENABLED(category);
// Implementation detail: internal macro to create static category and add
// event if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD(phase, category, name, flags, ...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (*INTERNAL_TRACE_EVENT_UID(catstatic)) { \
webrtc::trace_event_internal::AddTraceEvent( \
phase, INTERNAL_TRACE_EVENT_UID(catstatic), name, \
webrtc::trace_event_internal::kNoEventId, flags, ##__VA_ARGS__); \
} \
} while (0)
// Implementation detail: internal macro to create static category and add begin
// event if the category is enabled. Also adds the end event when the scope
// ends.
#define INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, ...) \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
webrtc::trace_event_internal::TraceEndOnScopeClose INTERNAL_TRACE_EVENT_UID( \
profileScope); \
if (*INTERNAL_TRACE_EVENT_UID(catstatic)) { \
webrtc::trace_event_internal::AddTraceEvent( \
TRACE_EVENT_PHASE_BEGIN, INTERNAL_TRACE_EVENT_UID(catstatic), name, \
webrtc::trace_event_internal::kNoEventId, TRACE_EVENT_FLAG_NONE, \
##__VA_ARGS__); \
INTERNAL_TRACE_EVENT_UID(profileScope) \
.Initialize(INTERNAL_TRACE_EVENT_UID(catstatic), name); \
}
// Implementation detail: internal macro to create static category and add
// event if the category is enabled.
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID(phase, category, name, id, flags, \
...) \
do { \
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
if (*INTERNAL_TRACE_EVENT_UID(catstatic)) { \
unsigned char trace_event_flags = flags | TRACE_EVENT_FLAG_HAS_ID; \
webrtc::trace_event_internal::TraceID trace_event_trace_id( \
id, &trace_event_flags); \
webrtc::trace_event_internal::AddTraceEvent( \
phase, INTERNAL_TRACE_EVENT_UID(catstatic), name, \
trace_event_trace_id.data(), trace_event_flags, ##__VA_ARGS__); \
} \
} while (0)
// Notes regarding the following definitions:
// New values can be added and propagated to third party libraries, but existing
// definitions must never be changed, because third party libraries may use old
// definitions.
// Phase indicates the nature of an event entry. E.g. part of a begin/end pair.
#define TRACE_EVENT_PHASE_BEGIN ('B')
#define TRACE_EVENT_PHASE_END ('E')
#define TRACE_EVENT_PHASE_INSTANT ('I')
#define TRACE_EVENT_PHASE_ASYNC_BEGIN ('S')
#define TRACE_EVENT_PHASE_ASYNC_STEP ('T')
#define TRACE_EVENT_PHASE_ASYNC_END ('F')
#define TRACE_EVENT_PHASE_METADATA ('M')
#define TRACE_EVENT_PHASE_COUNTER ('C')
// Flags for changing the behavior of TRACE_EVENT_API_ADD_TRACE_EVENT.
#define TRACE_EVENT_FLAG_NONE (static_cast<unsigned char>(0))
#define TRACE_EVENT_FLAG_HAS_ID (static_cast<unsigned char>(1 << 1))
#define TRACE_EVENT_FLAG_MANGLE_ID (static_cast<unsigned char>(1 << 2))
namespace webrtc {
namespace trace_event_internal {
// Specify these values when the corresponding argument of AddTraceEvent is not
// used.
const int kZeroNumArgs = 0;
const unsigned long long kNoEventId = 0;
// TraceID encapsulates an ID that can either be an integer or pointer. Pointers
// are mangled with the Process ID so that they are unlikely to collide when the
// same pointer is used on different processes.
class TraceID {
public:
class ForceMangle {
public:
explicit ForceMangle(unsigned long long id) : data_(id) {}
explicit ForceMangle(unsigned long id) : data_(id) {}
explicit ForceMangle(unsigned int id) : data_(id) {}
explicit ForceMangle(unsigned short id) : data_(id) {}
explicit ForceMangle(unsigned char id) : data_(id) {}
explicit ForceMangle(long long id)
: data_(static_cast<unsigned long long>(id)) {}
explicit ForceMangle(long id)
: data_(static_cast<unsigned long long>(id)) {}
explicit ForceMangle(int id) : data_(static_cast<unsigned long long>(id)) {}
explicit ForceMangle(short id)
: data_(static_cast<unsigned long long>(id)) {}
explicit ForceMangle(signed char id)
: data_(static_cast<unsigned long long>(id)) {}
unsigned long long data() const { return data_; }
private:
unsigned long long data_;
};
explicit TraceID(const void* id, unsigned char* flags)
: data_(
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(id))) {
*flags |= TRACE_EVENT_FLAG_MANGLE_ID;
}
explicit TraceID(ForceMangle id, unsigned char* flags) : data_(id.data()) {
*flags |= TRACE_EVENT_FLAG_MANGLE_ID;
}
explicit TraceID(unsigned long long id, unsigned char* flags) : data_(id) {
(void)flags;
}
explicit TraceID(unsigned long id, unsigned char* flags) : data_(id) {
(void)flags;
}
explicit TraceID(unsigned int id, unsigned char* flags) : data_(id) {
(void)flags;
}
explicit TraceID(unsigned short id, unsigned char* flags) : data_(id) {
(void)flags;
}
explicit TraceID(unsigned char id, unsigned char* flags) : data_(id) {
(void)flags;
}
explicit TraceID(long long id, unsigned char* flags)
: data_(static_cast<unsigned long long>(id)) {
(void)flags;
}
explicit TraceID(long id, unsigned char* flags)
: data_(static_cast<unsigned long long>(id)) {
(void)flags;
}
explicit TraceID(int id, unsigned char* flags)
: data_(static_cast<unsigned long long>(id)) {
(void)flags;
}
explicit TraceID(short id, unsigned char* flags)
: data_(static_cast<unsigned long long>(id)) {
(void)flags;
}
explicit TraceID(signed char id, unsigned char* flags)
: data_(static_cast<unsigned long long>(id)) {
(void)flags;
}
unsigned long long data() const { return data_; }
private:
unsigned long long data_;
};
// Simple union to store various types as unsigned long long.
union TraceValueUnion {
bool as_bool;
unsigned long long as_uint;
long long as_int;
double as_double;
const void* as_pointer;
const char* as_string;
};
// Simple container for const char* that should be copied instead of retained.
class TraceStringWithCopy {
public:
explicit TraceStringWithCopy(const char* str) : str_(str) {}
operator const char*() const { return str_; }
private:
const char* str_;
};
// Define SetTraceValue for each allowed type. It stores the type and
// value in the return arguments. This allows this API to avoid declaring any
// structures so that it is portable to third_party libraries.
#define INTERNAL_DECLARE_SET_TRACE_VALUE(actual_type, union_member, \
value_type_id) \
static inline void SetTraceValue(actual_type arg, unsigned char* type, \
unsigned long long* value) { \
TraceValueUnion type_value; \
type_value.union_member = arg; \
*type = value_type_id; \
*value = type_value.as_uint; \
}
// Simpler form for int types that can be safely casted.
#define INTERNAL_DECLARE_SET_TRACE_VALUE_INT(actual_type, value_type_id) \
static inline void SetTraceValue(actual_type arg, unsigned char* type, \
unsigned long long* value) { \
*type = value_type_id; \
*value = static_cast<unsigned long long>(arg); \
}
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long long, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned int, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned short, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned char, TRACE_VALUE_TYPE_UINT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(long long, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(long, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(int, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(short, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(signed char, TRACE_VALUE_TYPE_INT)
INTERNAL_DECLARE_SET_TRACE_VALUE(bool, as_bool, TRACE_VALUE_TYPE_BOOL)
INTERNAL_DECLARE_SET_TRACE_VALUE(double, as_double, TRACE_VALUE_TYPE_DOUBLE)
INTERNAL_DECLARE_SET_TRACE_VALUE(const void*,
as_pointer,
TRACE_VALUE_TYPE_POINTER)
INTERNAL_DECLARE_SET_TRACE_VALUE(const char*,
as_string,
TRACE_VALUE_TYPE_STRING)
INTERNAL_DECLARE_SET_TRACE_VALUE(const TraceStringWithCopy&,
as_string,
TRACE_VALUE_TYPE_COPY_STRING)
#undef INTERNAL_DECLARE_SET_TRACE_VALUE
#undef INTERNAL_DECLARE_SET_TRACE_VALUE_INT
// std::string version of SetTraceValue so that trace arguments can be strings.
static inline void SetTraceValue(const std::string& arg,
unsigned char* type,
unsigned long long* value) {
TraceValueUnion type_value;
type_value.as_string = arg.c_str();
*type = TRACE_VALUE_TYPE_COPY_STRING;
*value = type_value.as_uint;
}
// These AddTraceEvent template functions are defined here instead of in the
// macro, because the arg_values could be temporary objects, such as
// std::string. In order to store pointers to the internal c_str and pass
// through to the tracing API, the arg_values must live throughout
// these procedures.
static inline void AddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
unsigned char flags) {
TRACE_EVENT_API_ADD_TRACE_EVENT(phase, category_enabled, name, id,
kZeroNumArgs, nullptr, nullptr, nullptr,
flags);
}
template <class ARG1_TYPE>
static inline void AddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
unsigned char flags,
const char* arg1_name,
const ARG1_TYPE& arg1_val) {
const int num_args = 1;
unsigned char arg_types[1];
unsigned long long arg_values[1];
SetTraceValue(arg1_val, &arg_types[0], &arg_values[0]);
TRACE_EVENT_API_ADD_TRACE_EVENT(phase, category_enabled, name, id, num_args,
&arg1_name, arg_types, arg_values, flags);
}
template <class ARG1_TYPE, class ARG2_TYPE>
static inline void AddTraceEvent(char phase,
const unsigned char* category_enabled,
const char* name,
unsigned long long id,
unsigned char flags,
const char* arg1_name,
const ARG1_TYPE& arg1_val,
const char* arg2_name,
const ARG2_TYPE& arg2_val) {
const int num_args = 2;
const char* arg_names[2] = {arg1_name, arg2_name};
unsigned char arg_types[2];
unsigned long long arg_values[2];
SetTraceValue(arg1_val, &arg_types[0], &arg_values[0]);
SetTraceValue(arg2_val, &arg_types[1], &arg_values[1]);
TRACE_EVENT_API_ADD_TRACE_EVENT(phase, category_enabled, name, id, num_args,
arg_names, arg_types, arg_values, flags);
}
// Used by TRACE_EVENTx macro. Do not use directly.
class TraceEndOnScopeClose {
public:
// Note: members of data_ intentionally left uninitialized. See Initialize.
TraceEndOnScopeClose() : p_data_(nullptr) {}
~TraceEndOnScopeClose() {
if (p_data_)
AddEventIfEnabled();
}
void Initialize(const unsigned char* category_enabled, const char* name) {
data_.category_enabled = category_enabled;
data_.name = name;
p_data_ = &data_;
}
private:
// Add the end event if the category is still enabled.
void AddEventIfEnabled() {
// Only called when p_data_ is non-null.
if (*p_data_->category_enabled) {
TRACE_EVENT_API_ADD_TRACE_EVENT(TRACE_EVENT_PHASE_END,
p_data_->category_enabled, p_data_->name,
kNoEventId, kZeroNumArgs, nullptr,
nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
}
}
// This Data struct workaround is to avoid initializing all the members
// in Data during construction of this object, since this object is always
// constructed, even when tracing is disabled. If the members of Data were
// members of this class instead, compiler warnings occur about potential
// uninitialized accesses.
struct Data {
const unsigned char* category_enabled;
const char* name;
};
Data* p_data_;
Data data_;
};
} // namespace trace_event_internal
} // namespace webrtc
#else
////////////////////////////////////////////////////////////////////////////////
// This section defines no-op alternatives to the tracing macros when
// RTC_DISABLE_TRACE_EVENTS is defined.
#define TRACE_DISABLED_BY_DEFAULT(name) "disabled-by-default-" name
#define TRACE_ID_MANGLE(id) 0
#define TRACE_EVENT0(category, name) RTC_NOOP()
#define TRACE_EVENT1(category, name, arg1_name, arg1_val) RTC_NOOP()
#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
RTC_NOOP()
#define TRACE_EVENT_INSTANT0(category, name, scope) RTC_NOOP()
#define TRACE_EVENT_INSTANT1(category, name, scope, arg1_name, arg1_val) \
RTC_NOOP()
#define TRACE_EVENT_INSTANT2(category, name, scope, arg1_name, arg1_val, \
arg2_name, arg2_val) \
RTC_NOOP()
#define TRACE_EVENT_BEGIN0(category, name) RTC_NOOP()
#define TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val) RTC_NOOP()
#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
RTC_NOOP()
#define TRACE_EVENT_END0(category, name) RTC_NOOP()
#define TRACE_EVENT_END1(category, name, arg1_name, arg1_val) RTC_NOOP()
#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
RTC_NOOP()
#define TRACE_COUNTER1(category, name, value) RTC_NOOP()
#define TRACE_COUNTER2(category, name, value1_name, value1_val, value2_name, \
value2_val) \
RTC_NOOP()
#define TRACE_COUNTER_ID1(category, name, id, value) RTC_NOOP()
#define TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, \
value2_name, value2_val) \
RTC_NOOP()
#define TRACE_EVENT_ASYNC_BEGIN0(category, name, id) RTC_NOOP()
#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \
RTC_NOOP()
#define TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \
arg2_name, arg2_val) \
RTC_NOOP()
#define TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step) RTC_NOOP()
#define TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, arg1_name, \
arg1_val) \
RTC_NOOP()
#define TRACE_EVENT_ASYNC_END0(category, name, id) RTC_NOOP()
#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \
RTC_NOOP()
#define TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, arg1_val, \
arg2_name, arg2_val) \
RTC_NOOP()
#define TRACE_EVENT_API_GET_CATEGORY_ENABLED ""
#define TRACE_EVENT_API_ADD_TRACE_EVENT RTC_NOOP()
#endif // RTC_TRACE_EVENTS_ENABLED
#endif // RTC_USE_PERFETTO
#endif // RTC_BASE_TRACE_EVENT_H_