.. SPDX-License-Identifier: CC-BY-SA-4.0 Tracing Guide ============= Guide to tracing in libcamera. Profiling vs Tracing -------------------- Tracing is recording timestamps at specific locations. libcamera provides a tracing facility. This guide shows how to use this tracing facility. Tracing should not be confused with profiling, which samples execution at periodic points in time. This can be done with other tools such as callgrind, perf, gprof, etc., without modification to the application, and is out of scope for this guide. Compiling --------- To compile libcamera with tracing support, it must be enabled through the meson ``tracing`` option. It depends on the lttng-ust library (available in the ``liblttng-ust-dev`` package for Debian-based distributions). By default the tracing option in meson is set to ``auto``, so if liblttng is detected, it will be enabled by default. Conversely, if the option is set to disabled, then libcamera will be compiled without tracing support. Defining tracepoints -------------------- libcamera already contains a set of tracepoints. To define additional tracepoints, create a file ``include/libcamera/internal/tracepoints/{file}.tp``, where ``file`` is a reasonable name related to the category of tracepoints that you wish to define. For example, the tracepoints file for the Request object is called ``request.tp``. An entry for this file must be added in ``include/libcamera/internal/tracepoints/meson.build``. In this tracepoints file, define your tracepoints `as mandated by lttng `_. The header boilerplate must *not* be included (as it will conflict with the rest of our infrastructure), and only the tracepoint definitions (with the ``TRACEPOINT_*`` macros) should be included. All tracepoint providers shall be ``libcamera``. According to lttng, the tracepoint provider should be per-project; this is the rationale for this decision. To group tracepoint events, we recommend using ``{class_name}_{tracepoint_name}``, for example, ``request_construct`` for a tracepoint for the constructor of the Request class. Tracepoint arguments may take C++ objects pointers, in which case the usual C++ namespacing rules apply. The header that contains the necessary class definitions must be included at the top of the tracepoint provider file. Note: the final parameter in ``TP_ARGS`` *must not* have a trailing comma, and the parameters to ``TP_FIELDS`` are *space-separated*. Not following these will cause compilation errors. Using tracepoints (in libcamera) -------------------------------- To use tracepoints in libcamera, first the header needs to be included: ``#include "libcamera/internal/tracepoints.h"`` Then to use the tracepoint: ``LIBCAMERA_TRACEPOINT({tracepoint_event}, args...)`` This macro must be used, as opposed to lttng's macros directly, because lttng is an optional dependency of libcamera, so the code must compile and run even when lttng is not present or when tracing is disabled. The tracepoint provider name, as declared in the tracepoint definition, is not included in the parameters of the tracepoint. There are also two special tracepoints available for tracing IPA calls: ``LIBCAMERA_TRACEPOINT_IPA_BEGIN({pipeline_name}, {ipa_function})`` ``LIBCAMERA_TRACEPOINT_IPA_END({pipeline_name}, {ipa_function})`` These shall be placed where an IPA function is called from the pipeline handler, and when the pipeline handler receives the corresponding response from the IPA, respectively. These are the tracepoints that our sample analysis script (see "Analyzing a trace") scans for when computing statistics on IPA call time. Using tracepoints (from an application) --------------------------------------- As applications are not part of libcamera, but rather users of libcamera, applications should seek their own tracing mechanisms. For ease of tracing the application alongside tracing libcamera, it is recommended to also `use lttng `_. Using tracepoints (from closed-source IPA) ------------------------------------------ Similar to applications, closed-source IPAs can simply use lttng on their own, or any other tracing mechanism if desired. Collecting a trace ------------------ A trace can be collected fairly simply from lttng: .. code-block:: bash lttng create $SESSION_NAME lttng enable-event -u libcamera:\* lttng start # run libcamera application lttng stop lttng view lttng destroy $SESSION_NAME See the `lttng documentation `_ for further details. The location of the trace file is printed when running ``lttng create $SESSION_NAME``. After destroying the session, it can still be viewed by: ``lttng view -t $PATH_TO_TRACE``, where ``$PATH_TO_TRACE`` is the path that was printed when the session was created. This is the same path that is used when analyzing traces programatically, as described in the next section. Analyzing a trace ----------------- As mentioned above, while an lttng tracing session exists and the trace is not running, the trace output can be viewed as text by ``lttng view``. The trace log can also be viewed as text using babeltrace2. See the `lttng trace analysis documentation `_ for further details. babeltrace2 also has a C API and python bindings that can be used to process traces. See the `lttng python bindings documentation `_ and the `lttng C API documentation `_ for more details. As an example, there is a script ``utils/tracepoints/analyze-ipa-trace.py`` that gathers statistics for the time taken for an IPA function call, by measuring the time difference between pairs of events ``libcamera:ipa_call_start`` and ``libcamera:ipa_call_finish``. 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * control_serializer.cpp - Control (de)serializer
 */

#include "libcamera/internal/control_serializer.h"

#include <algorithm>
#include <memory>
#include <vector>

#include <libcamera/control_ids.h>
#include <libcamera/controls.h>
#include <libcamera/ipa/ipa_controls.h>
#include <libcamera/span.h>

#include "libcamera/internal/byte_stream_buffer.h"
#include "libcamera/internal/log.h"

/**
 * \file control_serializer.h
 * \brief Serialization and deserialization helpers for controls
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(Serializer)

/**
 * \class ControlSerializer
 * \brief Serializer and deserializer for control-related classes
 *
 * The control serializer is a helper to serialize and deserialize
 * ControlInfoMap and ControlValue instances for the purpose of communication
 * with IPA modules.
 *
 * Neither the ControlInfoMap nor the ControlList are self-contained data
 * container. ControlInfoMap references an external ControlId in each of its
 * entries, and ControlList references a ControlInfoMap for the purpose of
 * validation. Serializing and deserializing those objects thus requires a
 * context that maintains the associations between them. The control serializer
 * fulfils this task.
 *
 * ControlInfoMap instances can be serialized on their own, but require
 * ControlId instances to be provided at deserialization time. The serializer
 * recreates those ControlId instances and stores them in an internal cache,
 * from which the ControlInfoMap is populated.
 *
 * ControlList instances need to be associated with a ControlInfoMap when
 * deserialized. To make this possible, the control lists are serialized with a
 * handle to their ControlInfoMap, and the map is looked up from the handle at
 * deserialization time. To make this possible, the serializer assigns a
 * numerical handle to ControlInfoMap instances when they are serialized, and
 * stores the mapping between handle and ControlInfoMap both when serializing
 * (for the pipeline handler side) and deserializing (for the IPA side) them.
 * This mapping is used when serializing a ControlList to include the
 * corresponding ControlInfoMap handle in the binary data, and when
 * deserializing to retrieve the corresponding ControlInfoMap.
 *
 * In order to perform those tasks, the serializer keeps an internal state that
 * needs to be properly populated. This mechanism requires the ControlInfoMap
 * corresponding to a ControlList to have been serialized or deserialized
 * before the ControlList is serialized or deserialized. Failure to comply with
 * that constraint results in serialization or deserialization failure of the
 * ControlList.
 *
 * The serializer can be reset() to clear its internal state. This may be
 * performed when reconfiguring an IPA to avoid constant growth of the internal
 * state, especially if the contents of the ControlInfoMap instances change at
 * that time. A reset of the serializer invalidates all ControlList and
 * ControlInfoMap that have been previously deserialized. The caller shall thus
 * proceed with care to avoid stale references.
 */

ControlSerializer::ControlSerializer()
	: serial_(0)
{
}

/**
 * \brief Reset the serializer
 *
 * Reset the internal state of the serializer. This invalidates all the
 * ControlList and ControlInfoMap that have been previously deserialized.
 */
void ControlSerializer::reset()
{
	serial_ = 0;

	infoMapHandles_.clear();
	infoMaps_.clear();
	controlIds_.clear();
}

size_t ControlSerializer::binarySize(const ControlValue &value)
{
	return value.data().size_bytes();
}

size_t ControlSerializer::binarySize(const ControlInfo &info)
{
	return binarySize(info.min()) + binarySize(info.max());
}

/**
 * \brief Retrieve the size in bytes required to serialize a ControlInfoMap
 * \param[in] infoMap The control info map
 *
 * Compute and return the size in bytes required to store the serialized
 * ControlInfoMap.
 *
 * \return The size in bytes required to store the serialized ControlInfoMap
 */
size_t ControlSerializer::binarySize(const ControlInfoMap &infoMap)
{
	size_t size = sizeof(struct ipa_controls_header)
		    + infoMap.size() * sizeof(struct ipa_control_info_entry);

	for (const auto &ctrl : infoMap)
		size += binarySize(ctrl.second);

	return size;
}

/**
 * \brief Retrieve the size in bytes required to serialize a ControlList
 * \param[in] list The control list
 *
 * Compute and return the size in bytes required to store the serialized
 * ControlList.
 *
 * \return The size in bytes required to store the serialized ControlList
 */
size_t ControlSerializer::binarySize(const ControlList &list)
{
	size_t size = sizeof(struct ipa_controls_header)
		    + list.size() * sizeof(struct ipa_control_value_entry);

	for (const auto &ctrl : list)
		size += binarySize(ctrl.second);

	return size;
}

void ControlSerializer::store(const ControlValue &value,
			      ByteStreamBuffer &buffer)
{
	buffer.write(value.data());
}

void ControlSerializer::store(const ControlInfo &info, ByteStreamBuffer &buffer)
{
	store(info.min(), buffer);
	store(info.max(), buffer);
}

/**
 * \brief Serialize a ControlInfoMap in a buffer
 * \param[in] infoMap The control info map to serialize
 * \param[in] buffer The memory buffer where to serialize the ControlInfoMap
 *
 * Serialize the \a infoMap into the \a buffer using the serialization format
 * defined by the IPA context interface in ipa_controls.h.
 *
 * The serializer stores a reference to the \a infoMap internally. The caller
 * shall ensure that \a infoMap stays valid until the serializer is reset().
 *
 * \return 0 on success, a negative error code otherwise
 * \retval -ENOSPC Not enough space is available in the buffer
 */
int ControlSerializer::serialize(const ControlInfoMap &infoMap,
				 ByteStreamBuffer &buffer)
{
	if (isCached(infoMap)) {
		LOG(Serializer, Debug)
			<< "Skipping already serialized ControlInfoMap";
		return 0;
	}

	/* Compute entries and data required sizes. */
	size_t entriesSize = infoMap.size()
			   * sizeof(struct ipa_control_info_entry);
	size_t valuesSize = 0;
	for (const auto &ctrl : infoMap)
		valuesSize += binarySize(ctrl.second);

	/* Prepare the packet header, assign a handle to the ControlInfoMap. */
	struct ipa_controls_header hdr;
	hdr.version = IPA_CONTROLS_FORMAT_VERSION;
	hdr.handle = ++serial_;
	hdr.entries = infoMap.size();
	hdr.size = sizeof(hdr) + entriesSize + valuesSize;
	hdr.data_offset = sizeof(hdr) + entriesSize;

	buffer.write(&hdr);

	/*
	 * Serialize all entries.
	 * \todo Serialize the control name too
	 */
	ByteStreamBuffer entries = buffer.carveOut(entriesSize);
	ByteStreamBuffer values = buffer.carveOut(valuesSize);

	for (const auto &ctrl : infoMap) {
		const ControlId *id = ctrl.first;
		const ControlInfo &info = ctrl.second;

		struct ipa_control_info_entry entry;
		entry.id = id->id();
		entry.type = id->type();
		entry.offset = values.offset();
		entries.write(&entry);

		store(info, values);
	}

	if (buffer.overflow())
		return -ENOSPC;

	/*
	 * Store the map to handle association, to be used to serialize and
	 * deserialize control lists.
	 */
	infoMapHandles_[&infoMap] = hdr.handle;

	return 0;
}

/**
 * \brief Serialize a ControlList in a buffer
 * \param[in] list The control list to serialize
 * \param[in] buffer The memory buffer where to serialize the ControlList
 *
 * Serialize the \a list into the \a buffer using the serialization format
 * defined by the IPA context interface in ipa_controls.h.
 *
 * \return 0 on success, a negative error code otherwise
 * \retval -ENOENT The ControlList is related to an unknown ControlInfoMap
 * \retval -ENOSPC Not enough space is available in the buffer
 */
int ControlSerializer::serialize(const ControlList &list,
				 ByteStreamBuffer &buffer)
{
	/*
	 * Find the ControlInfoMap handle for the ControlList if it has one, or
	 * use 0 for ControlList without a ControlInfoMap.
	 */
	unsigned int infoMapHandle;
	if (list.infoMap()) {