/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2021, Ideas on Board Oy * * drm.cpp - DRM/KMS Helpers */ #include "drm.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "event_loop.h" namespace DRM { Object::Object(Device *dev, uint32_t id, Type type) : id_(id), dev_(dev), type_(type) { /* Retrieve properties from the objects that support them. */ if (type != TypeConnector && type != TypeCrtc && type != TypeEncoder && type != TypePlane) return; /* * We can't distinguish between failures due to the object having no * property and failures due to other conditions. Assume we use the API * correctly and consider the object has no property. */ drmModeObjectProperties *properties = drmModeObjectGetProperties(dev->fd(), id, type); if (!properties) return; properties_.reserve(properties->count_props); for (uint32_t i = 0; i < properties->count_props; ++i) properties_.emplace_back(properties->props[i], properties->prop_values[i]); drmModeFreeObjectProperties(properties); } Object::~Object() { } const Property *Object::property(const std::string &name) const { for (const PropertyValue &pv : properties_) { const Property *property = static_cast(dev_->object(pv.id())); if (property && property->name() == name) return property; } return nullptr; } const PropertyValue *Object::propertyValue(const std::string &name) const { for (const PropertyValue &pv : properties_) { const Property *property = static_cast(dev_->object(pv.id())); if (property && property->name() == name) return &pv; } return nullptr; } Property::Property(Device *dev, drmModePropertyRes *property) : Object(dev, property->prop_id, TypeProperty), name_(property->name), flags_(property->flags), values_(property->values, property->values + property->count_values), blobs_(property->blob_ids, property->blob_ids + property->count_blobs) { if (drm_property_type_is(property, DRM_MODE_PROP_RANGE)) type_ = TypeRange; else if (drm_property_type_is(property, DRM_MODE_PROP_ENUM)) type_ = TypeEnum; else if (drm_property_type_is(property, DRM_MODE_PROP_BLOB)) type_ = TypeBlob; else if (drm_property_type_is(property, DRM_MODE_PROP_BITMASK)) type_ = TypeBitmask; else if (drm_property_type_is(property, DRM_MODE_PROP_OBJECT)) type_ = TypeObject; else if (drm_property_type_is(property, DRM_MODE_PROP_SIGNED_RANGE)) type_ = TypeSignedRange; else type_ = TypeUnknown; for (int i = 0; i < property->count_enums; ++i) enums_[property->enums[i].value] = property->enums[i].name; } Blob::Blob(Device *dev, const libcamera::Span &data) : Object(dev, 0, Object::TypeBlob) { drmModeCreatePropertyBlob(dev->fd(), data.data(), data.size(), &id_); } Blob::~Blob() { if (isValid()) drmModeDestroyPropertyBlob(device()->fd(), id()); } Mode::Mode(const drmModeModeInfo &mode) : drmModeModeInfo(mode) { } std::unique_ptr Mode::toBlob(Device *dev) const { libcamera::Span data{ reinterpret_cast(this), sizeof(*this) }; return std::make_unique(dev, data); } Crtc::Crtc(Device *dev, const drmModeCrtc *crtc, unsigned int index) : Object(dev, crtc->crtc_id, Object::TypeCrtc), index_(index) { } Encoder::Encoder(Device *dev, const drmModeEncoder *encoder) : Object(dev, encoder->encoder_id, Object::TypeEncoder), type_(encoder->encoder_type) { const std::list &crtcs = dev->crtcs(); possibleCrtcs_.reserve(crtcs.size()); for (const Crtc &crtc : crtcs) { if (encoder->possible_crtcs & (1 << crtc.index())) possibleCrtcs_.push_back(&crtc); } possibleCrtcs_.shrink_to_fit(); } namespace { const std::map connectorTypeNames{ { DRM_MODE_CONNECTOR_Unknown, "Unknown" }, { DRM_MODE_CONNECTOR_VGA, "VGA" }, { DRM_MODE_CONNECTOR_DVII, "DVI-I" }, { DRM_MODE_CONNECTOR_DVID, "DVI-D" }, { DRM_MODE_CONNECTOR_DVIA, "DVI-A" }, { DRM_MODE_CONNECTOR_Composite, "Composite" }, { DRM_MODE_CONNECTOR_SVIDEO, "S-Video" }, { DRM_MODE_CONNECTOR_LVDS, "LVDS" }, { DRM_MODE_CONNECTOR_Component, "Component" }, { DRM_MODE_CONNECTOR_9PinDIN, "9-Pin-DIN" }, { DRM_MODE_CONNECTOR_DisplayPort, "DP" }, { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" }, { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" }, { DRM_MODE_CONNECTOR_TV, "TV" }, { DRM_MODE_CONNECTOR_eDP, "eDP" }, { DRM_MODE_CONNECTOR_VIRTUAL, "Virtual" }, { DRM_MODE_CONNECTOR_DSI, "DSI" }, { DRM_MODE_CONNECTOR_DPI, "DPI" }, }; } /* namespace */ Connector::Connector(Device *dev, const drmModeConnector *connector) : Object(dev, connector->connector_id, Object::TypeConnector), type_(connector->connector_type) { auto typeName = connectorTypeNames.find(connector->connector_type); if (typeName == connectorTypeNames.end()) { std::cerr << "Invalid connector type " << connector->connector_type << std::endl; typeName = connectorTypeNames.find(DRM_MODE_CONNECTOR_Unknown); } name_ = std::string(typeName->second) + "-" + std::to_string(connector->connector_type_id); switch (connector->connection) { case DRM_MODE_CONNECTED: status_ = Status::Connected; break; case DRM_MODE_DISCONNECTED: status_ = Status::Disconnected; break; case DRM_MODE_UNKNOWNCONNECTION: default: status_ = Status::Unknown; break; } const std::list &encoders = dev->encoders(); encoders_.reserve(connector->count_encoders); for (int i = 0; i < connector->count_encoders; ++i) { uint32_t encoderId = connector->encoders[i]; auto encoder = std::find_if(encoders.begin(), encoders.end(), [=](const Encoder &e) { return e.id() == encoderId; }); if (encoder == encoders.end()) { std::cerr << "Encoder " << encoderId << " not found" << std::endl; continue; } encoders_.push_back(&*encoder); } encoders_.shrink_to_fit(); modes_ = { connector->modes, connector->modes + connector->count_modes }; } Plane::Plane(Device *dev, const drmModePlane *plane) : Object(dev, plane->plane_id, Object::TypePlane), possibleCrtcsMask_(plane->possible_crtcs) { formats_ = { plane->formats, plane->formats + plane->count_formats }; const std::list &crtcs = dev->crtcs(); possibleCrtcs_.reserve(crtcs.size()); for (const Crtc &crtc : crtcs) { if (plane->possible_crtcs & (1 << crtc.index())) possibleCrtcs_.push_back(&crtc); } possibleCrtcs_.shrink_to_fit(); } bool Plane::supportsFormat(const libcamera::PixelFormat &format) const { return std::find(formats_.begin(), formats_.end(), format.fourcc()) != formats_.end(); } int Plane::setup() { const PropertyValue *pv = propertyValue("type"); if (!pv) return -EINVAL; switch (pv->value()) { case DRM_PLANE_TYPE_OVERLAY: type_ = TypeOverlay; break; case DRM_PLANE_TYPE_PRIMARY: type_ = TypePrimary; break; case DRM_PLANE_TYPE_CURSOR: type_ = TypeCursor; break; default: return -EINVAL; } return 0; } FrameBuffer::FrameBuffer(Device *dev) : Object(dev, 0, Object::TypeFb) { } FrameBuffer::~FrameBuffer() { for (FrameBuffer::Plane &plane : planes_) { struct drm_gem_close gem_close = { .handle = plane.handle, .pad = 0, }; int ret; do { ret = ioctl(device()->fd(), DRM_IOCTL_GEM_CLOSE, &gem_close); } while (ret == -1 && (errno == EINTR || errno == EAGAIN)); if (ret == -1) { ret = -errno; std::cerr << "Failed to close GEM object: " << strerror(-ret) << std::endl; } } drmModeRmFB(device()->fd(), id()); } AtomicRequest::AtomicRequest(Device *dev) : dev_(dev), valid_(true) { request_ = drmModeAtomicAlloc(); if (!request_) valid_ = false; } AtomicRequest::~AtomicRequest() { if (request_) drmModeAtomicFree(request_); } int AtomicRequest::addProperty(const Object *object, const std::string &property, uint64_t value) { if (!valid_) return -EINVAL; const Property *prop = object->property(property); if (!prop) { valid_ = false; return -EINVAL; } return addProperty(object->id(), prop->id(), value); } int AtomicRequest::addProperty(const Object *object, const std::string &property, std::unique_ptr blob) { if (!valid_) return -EINVAL; const Property *prop = object->property(property); if (!prop) { valid_ = false; return -EINVAL; } int ret = addProperty(object->id(), prop->id(), blob->id()); if (ret < 0) return ret; blobs_.emplace_back(std::move(blob)); return 0; } int AtomicRequest::addProperty(uint32_t object, uint32_t property, uint64_t value) { int ret = drmModeAtomicAddProperty(request_, object, property, value); if (ret < 0) { valid_ = false; return ret; } return 0; } int AtomicRequest::commit(unsigned int flags) { if (!valid_) return -EINVAL; uint32_t drmFlags = 0; if (flags & FlagAllowModeset) drmFlags |= DRM_MODE_ATOMIC_ALLOW_MODESET; if (flags & FlagAsync) drmFlags |= DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_NONBLOCK; return drmModeAtomicCommit(dev_->fd(), request_, drmFlags, this); } Device::Device() : fd_(-1) { } Device::~Device() { if (fd_ != -1) drmClose(fd_); } int Device::init() { constexpr size_t NODE_NAME_MAX = sizeof("/dev/dri/card255"); char name[NODE_NAME_MAX]; int ret; /* * Open the first DRM/KMS device. The libdrm drmOpen*() functions * require either a module name or a bus ID, which we don't have, so * bypass them. The automatic module loading and device node creation * from drmOpen() is of no practical use as any modern system will * handle that through udev or an equivalent component. */ snprintf(name, sizeof(name), "/dev/dri/card%u", 0); fd_ = open(name, O_RDWR | O_CLOEXEC); if (fd_ < 0) { ret = -errno; std::cerr << "Failed to open DRM/KMS device " << name << ": " << strerror(-ret) << std::endl; return ret; } /* * Enable the atomic APIs. This also automatically enables the * universal planes API. */ ret = drmSetClientCap(fd_, DRM_CLIENT_CAP_ATOMIC, 1); if (ret < 0) { ret = -errno; std::cerr << "Failed to enable atomic capability: " << strerror(-ret) << std::endl; return ret; } /* List all the resources. */ ret = getResources(); if (ret < 0) return ret; EventLoop::instance()->addEvent(fd_, EventLoop::Read, std::bind(&Device::drmEvent, this)); return 0; } int Device::getResources() { int ret; std::unique_ptr resources{ drmModeGetResources(fd_), &drmModeFreeResources }; if (!resources) { ret = -errno; std::cerr << "Failed to get DRM/KMS resources: " << strerror(-ret) << std::endl; return ret; } for (int i = 0; i < resources->count_crtcs; ++i) { drmModeCrtc *crtc = drmModeGetCrtc(fd_, resources->crtcs[i]); if (!crtc) { ret = -errno; std::cerr << "Failed to get CRTC: " << strerror(-ret) << std::endl; return ret; } crtcs_.emplace_back(this, crtc, i); drmModeFreeCrtc(crtc); Crtc &obj = crtcs_.back(); objects_[obj.id()] = &obj; } for (int i = 0; i < resources->count_encoders; ++i) { drmModeEncoder *encoder = drmModeGetEncoder(fd_, resources->encoders[i]); if (!encoder) { ret = -errno; std::cerr << "Failed to get encoder: " << strerror(-ret) << std::endl; return ret; } encoders_.emplace_back(this, encoder); drmModeFreeEncoder(encoder); Encoder &obj = encoders_.back(); objects_[obj.id()] = &obj; } for (int i = 0; i < resources->count_connectors; ++i) { drmModeConnector *connector = drmModeGetConnector(fd_, resources->connectors[i]); if (!connector) { ret = -errno; std::cerr << "Failed to get connector: " << strerror(-ret) << std::endl; return ret; } connectors_.emplace_back(this, connector); drmModeFreeConnector(connector); Connector &obj = connectors_.back(); objects_[obj.id()] = &obj; } std::unique_ptr planes{ drmModeGetPlaneResources(fd_), &drmModeFreePlaneResources }; if (!planes) { ret = -errno; std::cerr << "Failed to get DRM/KMS planes: " << strerror(-ret) << std::endl; return ret; } for (uint32_t i = 0; i < planes->count_planes; ++i) { drmModePlane *plane = drmModeGetPlane(fd_, planes->planes[i]); if (!plane) { ret = -errno; std::cerr << "Failed to get plane: " << strerror(-ret) << std::endl; return ret; } planes_.emplace_back(this, plane); drmModeFreePlane(plane); Plane &obj = planes_.back(); objects_[obj.id()] = &obj; } /* Set the possible planes for each CRTC. */ for (Crtc &crtc : crtcs_) { for (const Plane &plane : planes_) { if (plane.possibleCrtcsMask_ & (1 << crtc.index())) crtc.planes_.push_back(&plane); } } /* Collect all property IDs and create Property instances. */ std::set properties; for (const auto &object : objects_) { for (const PropertyValue &value : object.second->properties()) properties.insert(value.id()); } for (uint32_t id : properties) { drmModePropertyRes *property = drmModeGetProperty(fd_, id); if (!property) { ret = -errno; std::cerr << "Failed to get property: " << strerror(-ret) << std::endl; continue; } properties_.emplace_back(this, property); drmModeFreeProperty(property); Property &obj = properties_.back(); objects_[obj.id()] = &obj; } /* Finally, perform all delayed setup of mode objects. */ for (auto &object : objects_) { ret = object.second->setup(); if (ret < 0) { std::cerr << "Failed to setup object " << object.second->id() << ": " << strerror(-ret) << std::endl; return ret; } } return 0; } const Object *Device::object(uint32_t id) { const auto iter = objects_.find(id); if (iter == objects_.end()) return nullptr; return iter->second; } std::unique_ptr Device::createFrameBuffer( const libcamera::FrameBuffer &buffer, const libcamera::PixelFormat &format, const libcamera::Size &size, const std::array &strides) { std::unique_ptr fb{ new FrameBuffer(this) }; uint32_t handles[4] = {}; uint32_t offsets[4] = {}; int ret; const std::vector &planes = buffer.planes(); fb->planes_.reserve(planes.size()); unsigned int i = 0; for (const libcamera::FrameBuffer::Plane &plane : planes) { uint32_t handle; ret = drmPrimeFDToHandle(fd_, plane.fd.fd(), &handle); if (ret < 0) { ret = -errno; std::cerr << "Unable to import framebuffer dmabuf: " << strerror(-ret) << std::endl; return nullptr; } fb->planes_.push_back({ handle }); handles[i] = handle; offsets[i] = plane.offset; ++i; } ret = drmModeAddFB2(fd_, size.width, size.height, format.fourcc(), handles, strides.data(), offsets, &fb->id_, 0); if (ret < 0) { ret = -errno; std::cerr << "Failed to add framebuffer: " << strerror(-ret) << std::endl; return nullptr; } return fb; } void Device::drmEvent() { drmEventContext ctx{}; ctx.version = DRM_EVENT_CONTEXT_VERSION; ctx.page_flip_handler = &Device::pageFlipComplete; drmHandleEvent(fd_, &ctx); } void Device::pageFlipComplete([[maybe_unused]] int fd, [[maybe_unused]] unsigned int sequence, [[maybe_unused]] unsigned int tv_sec, [[maybe_unused]] unsigned int tv_usec, void *user_data) { AtomicRequest *request = static_cast(user_data); request->device()->requestComplete.emit(request); } } /* namespace DRM */ 'n316' href='#n316'>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 515 516 517 518 519 520 521 522 523 524 525
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2020, Google Inc.
 *
 * exif.cpp - EXIF tag creation using libexif
 */

#include "exif.h"

#include <cmath>
#include <iomanip>
#include <map>
#include <sstream>
#include <tuple>
#include <uchar.h>

#include <libcamera/base/log.h>
#include <libcamera/base/utils.h>

using namespace libcamera;

LOG_DEFINE_CATEGORY(EXIF)

/*
 * List of EXIF tags that we set directly because they are not supported
 * by libexif version 0.6.21.
 */
enum class _ExifTag {
	OFFSET_TIME              = 0x9010,
	OFFSET_TIME_ORIGINAL     = 0x9011,
	OFFSET_TIME_DIGITIZED    = 0x9012,
};

/*
 * The Exif class should be instantiated and specific properties set
 * through the exposed public API.
 *
 * Once all desired properties have been set, the user shall call
 * generate() to process the entries and generate the Exif data.
 *
 * Calls to generate() must check the return code to determine if any error
 * occurred during the construction of the Exif data, and if successful the
 * data can be obtained using the data() function.
 */
Exif::Exif()
	: valid_(false), data_(nullptr), order_(EXIF_BYTE_ORDER_INTEL),
	  exifData_(0), size_(0)
{
	/* Create an ExifMem allocator to construct entries. */
	mem_ = exif_mem_new_default();
	if (!mem_) {
		LOG(EXIF, Error) << "Failed to allocate ExifMem Allocator";
		return;
	}

	data_ = exif_data_new_mem(mem_);
	if (!data_) {
		LOG(EXIF, Error) << "Failed to allocate an ExifData structure";
		return;
	}

	valid_ = true;

	exif_data_set_option(data_, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION);
	exif_data_set_data_type(data_, EXIF_DATA_TYPE_COMPRESSED);

	/*
	 * Big-Endian: EXIF_BYTE_ORDER_MOTOROLA
	 * Little Endian: EXIF_BYTE_ORDER_INTEL
	 */
	exif_data_set_byte_order(data_, order_);

	setString(EXIF_IFD_EXIF, EXIF_TAG_EXIF_VERSION,
		  EXIF_FORMAT_UNDEFINED, "0231");

	/* Create the mandatory EXIF fields with default data. */
	exif_data_fix(data_);
}

Exif::~Exif()
{
	if (exifData_)
		free(exifData_);

	if (data_) {
		/*
		 * Reset thumbnail data to avoid getting double-freed by
		 * libexif. It is owned by the caller (i.e. PostProcessorJpeg).
		 */
		data_->data = nullptr;
		data_->size = 0;

		exif_data_unref(data_);
	}

	if (mem_)
		exif_mem_unref(mem_);
}

ExifEntry *Exif::createEntry(ExifIfd ifd, ExifTag tag)
{
	ExifContent *content = data_->ifd[ifd];
	ExifEntry *entry = exif_content_get_entry(content, tag);

	if (entry) {
		exif_entry_ref(entry);
		return entry;
	}

	entry = exif_entry_new_mem(mem_);
	if (!entry) {
		LOG(EXIF, Error) << "Failed to allocated new entry";
		valid_ = false;
		return nullptr;
	}

	exif_content_add_entry(content, entry);
	exif_entry_initialize(entry, tag);

	return entry;
}

ExifEntry *Exif::createEntry(ExifIfd ifd, ExifTag tag, ExifFormat format,
			     unsigned long components, unsigned int size)
{
	ExifContent *content = data_->ifd[ifd];

	/* Replace any existing entry with the same tag. */
	ExifEntry *existing = exif_content_get_entry(content, tag);
	exif_content_remove_entry(content, existing);

	ExifEntry *entry = exif_entry_new_mem(mem_);
	if (!entry) {
		LOG(EXIF, Error) << "Failed to allocated new entry";
		valid_ = false;
		return nullptr;
	}

	void *buffer = exif_mem_alloc(mem_, size);
	if (!buffer) {
		LOG(EXIF, Error) << "Failed to allocate buffer for variable entry";
		exif_mem_unref(mem_);
		valid_ = false;
		return nullptr;
	}

	entry->data = static_cast<unsigned char *>(buffer);
	entry->components = components;
	entry->format = format;
	entry->size = size;
	entry->tag = tag;

	exif_content_add_entry(content, entry);

	return entry;
}

void Exif::setByte(ExifIfd ifd, ExifTag tag, uint8_t item)
{
	ExifEntry *entry = createEntry(ifd, tag, EXIF_FORMAT_BYTE, 1, 1);
	if (!entry)
		return;

	entry->data[0] = item;
	exif_entry_unref(entry);
}

void Exif::setShort(ExifIfd ifd, ExifTag tag, uint16_t item)
{
	ExifEntry *entry = createEntry(ifd, tag);
	if (!entry)
		return;

	exif_set_short(entry->data, order_, item);
	exif_entry_unref(entry);
}

void Exif::setLong(ExifIfd ifd, ExifTag tag, uint32_t item)
{
	ExifEntry *entry = createEntry(ifd, tag);
	if (!entry)
		return;

	exif_set_long(entry->data, order_, item);
	exif_entry_unref(entry);
}

void Exif::setRational(ExifIfd ifd, ExifTag tag, ExifRational item)
{
	setRational(ifd, tag, { &item, 1 });
}

void Exif::setRational(ExifIfd ifd, ExifTag tag, Span<const ExifRational> items)
{
	ExifEntry *entry = createEntry(ifd, tag, EXIF_FORMAT_RATIONAL,
				       items.size(),
				       items.size() * sizeof(ExifRational));
	if (!entry)
		return;

	for (size_t i = 0; i < items.size(); i++)
		exif_set_rational(entry->data + i * sizeof(ExifRational),
				  order_, items[i]);
	exif_entry_unref(entry);
}

static const std::map<Exif::StringEncoding, std::array<uint8_t, 8>> stringEncodingCodes = {
	{ Exif::ASCII,     { 0x41, 0x53, 0x43, 0x49, 0x49, 0x00, 0x00, 0x00 } },
	{ Exif::Unicode,   { 0x55, 0x4e, 0x49, 0x43, 0x4f, 0x44, 0x45, 0x00 } },
};

void Exif::setString(ExifIfd ifd, ExifTag tag, ExifFormat format,
		     const std::string &item, StringEncoding encoding)
{
	std::string ascii;
	size_t length;
	const char *str;
	std::vector<uint8_t> buf;

	if (format == EXIF_FORMAT_ASCII) {
		ascii = utils::toAscii(item);
		str = ascii.c_str();

		/* Pad 1 extra byte to null-terminate the ASCII string. */
		length = ascii.length() + 1;
	} else {
		std::u16string u16str;

		auto encodingString = stringEncodingCodes.find(encoding);
		if (encodingString != stringEncodingCodes.end()) {
			buf = {
				encodingString->second.begin(),
				encodingString->second.end()
			};
		}

		switch (encoding) {
		case Unicode:
			u16str = utf8ToUtf16(item);

			buf.resize(8 + u16str.size() * 2);
			for (size_t i = 0; i < u16str.size(); i++) {
				if (order_ == EXIF_BYTE_ORDER_INTEL) {
					buf[8 + 2 * i] = u16str[i] & 0xff;
					buf[8 + 2 * i + 1] = (u16str[i] >> 8) & 0xff;
				} else {
					buf[8 + 2 * i] = (u16str[i] >> 8) & 0xff;
					buf[8 + 2 * i + 1] = u16str[i] & 0xff;
				}
			}

			break;

		case ASCII:
		case NoEncoding:
			buf.insert(buf.end(), item.begin(), item.end());
			break;
		}

		str = reinterpret_cast<const char *>(buf.data());

		/*
		 * Strings stored in different formats (EXIF_FORMAT_UNDEFINED)
		 * are not null-terminated.
		 */
		length = buf.size();
	}

	ExifEntry *entry = createEntry(ifd, tag, format, length, length);
	if (!entry)
		return;

	memcpy(entry->data, str, length);
	exif_entry_unref(entry);
}

void Exif::setMake(const std::string &make)
{
	setString(EXIF_IFD_0, EXIF_TAG_MAKE, EXIF_FORMAT_ASCII, make);
}

void Exif::setModel(const std::string &model)
{
	setString(EXIF_IFD_0, EXIF_TAG_MODEL, EXIF_FORMAT_ASCII, model);
}

void Exif::setSize(const Size &size)
{
	setLong(EXIF_IFD_EXIF, EXIF_TAG_PIXEL_Y_DIMENSION, size.height);
	setLong(EXIF_IFD_EXIF, EXIF_TAG_PIXEL_X_DIMENSION, size.width);
}

void Exif::setTimestamp(time_t timestamp, std::chrono::milliseconds msec)
{
	struct tm tm;
	localtime_r(&timestamp, &tm);

	char str[20];
	strftime(str, sizeof(str), "%Y:%m:%d %H:%M:%S", &tm);
	std::string ts(str);

	setString(EXIF_IFD_0, EXIF_TAG_DATE_TIME, EXIF_FORMAT_ASCII, ts);
	setString(EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_ORIGINAL, EXIF_FORMAT_ASCII, ts);
	setString(EXIF_IFD_EXIF, EXIF_TAG_DATE_TIME_DIGITIZED, EXIF_FORMAT_ASCII, ts);

	/* Query and set timezone information if available. */
	int r = strftime(str, sizeof(str), "%z", &tm);
	if (r <= 0)
		return;

	std::string tz(str);
	tz.insert(3, 1, ':');
	setString(EXIF_IFD_EXIF,
		  static_cast<ExifTag>(_ExifTag::OFFSET_TIME),
		  EXIF_FORMAT_ASCII, tz);
	setString(EXIF_IFD_EXIF,
		  static_cast<ExifTag>(_ExifTag::OFFSET_TIME_ORIGINAL),
		  EXIF_FORMAT_ASCII, tz);
	setString(EXIF_IFD_EXIF,
		  static_cast<ExifTag>(_ExifTag::OFFSET_TIME_DIGITIZED),
		  EXIF_FORMAT_ASCII, tz);

	std::stringstream sstr;
	sstr << std::setfill('0') << std::setw(3) << msec.count();
	std::string subsec = sstr.str();

	setString(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME,
		  EXIF_FORMAT_ASCII, subsec);
	setString(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
		  EXIF_FORMAT_ASCII, subsec);
	setString(EXIF_IFD_EXIF, EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
		  EXIF_FORMAT_ASCII, subsec);
}

void Exif::setGPSDateTimestamp(time_t timestamp)
{
	struct tm tm;
	gmtime_r(&timestamp, &tm);

	char str[11];
	strftime(str, sizeof(str), "%Y:%m:%d", &tm);
	std::string tsStr(str);

	setString(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_DATE_STAMP),
		  EXIF_FORMAT_ASCII, tsStr);

	/* Set GPS_TIME_STAMP */
	ExifRational ts[] = {
		{ static_cast<ExifLong>(tm.tm_hour), 1 },
		{ static_cast<ExifLong>(tm.tm_min),  1 },
		{ static_cast<ExifLong>(tm.tm_sec),  1 },
	};

	setRational(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_TIME_STAMP),
		    ts);
}

std::tuple<int, int, int> Exif::degreesToDMS(double decimalDegrees)
{
	int degrees = std::trunc(decimalDegrees);
	double minutes = std::abs((decimalDegrees - degrees) * 60);
	double seconds = (minutes - std::trunc(minutes)) * 60;

	return { degrees, std::trunc(minutes), std::round(seconds) };
}

void Exif::setGPSDMS(ExifIfd ifd, ExifTag tag, int deg, int min, int sec)
{
	ExifRational coords[] = {
		{ static_cast<ExifLong>(deg), 1 },
		{ static_cast<ExifLong>(min), 1 },
		{ static_cast<ExifLong>(sec), 1 },
	};

	setRational(ifd, tag, coords);
}

/*
 * \brief Set GPS location (lat, long, alt)
 * \param[in] coords Pointer to coordinates latitude, longitude, and altitude,
 * first two in degrees, the third in meters
 */
void Exif::setGPSLocation(const double *coords)
{
	int deg, min, sec;

	std::tie<int, int, int>(deg, min, sec) = degreesToDMS(coords[0]);
	setString(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_LATITUDE_REF),
		  EXIF_FORMAT_ASCII, deg >= 0 ? "N" : "S");
	setGPSDMS(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_LATITUDE),
		  std::abs(deg), min, sec);

	std::tie<int, int, int>(deg, min, sec) = degreesToDMS(coords[1]);
	setString(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_LONGITUDE_REF),
		  EXIF_FORMAT_ASCII, deg >= 0 ? "E" : "W");
	setGPSDMS(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_LONGITUDE),
		  std::abs(deg), min, sec);

	setByte(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_ALTITUDE_REF),
		coords[2] >= 0 ? 0 : 1);
	setRational(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_ALTITUDE),
		    ExifRational{ static_cast<ExifLong>(std::abs(coords[2])), 1 });
}

void Exif::setGPSMethod(const std::string &method)
{
	setString(EXIF_IFD_GPS, static_cast<ExifTag>(EXIF_TAG_GPS_PROCESSING_METHOD),
		  EXIF_FORMAT_UNDEFINED, method, NoEncoding);
}

void Exif::setOrientation(int orientation)
{
	int value;
	switch (orientation) {
	case 0:
	default:
		value = 1;
		break;
	case 90:
		value = 6;
		break;
	case 180:
		value = 3;
		break;
	case 270:
		value = 8;
		break;
	}

	setShort(EXIF_IFD_0, EXIF_TAG_ORIENTATION, value);
}

/*
 * The thumbnail data should remain valid until the Exif object is destroyed.
 * Failing to do so, might result in no thumbnail data being set even after a
 * call to Exif::setThumbnail().
 */
void Exif::setThumbnail(Span<const unsigned char> thumbnail,
			Compression compression)
{
	data_->data = const_cast<unsigned char *>(thumbnail.data());
	data_->size = thumbnail.size();

	setShort(EXIF_IFD_0, EXIF_TAG_COMPRESSION, compression);
}

void Exif::setFocalLength(float length)
{
	ExifRational rational = { static_cast<ExifLong>(length * 1000), 1000 };
	setRational(EXIF_IFD_EXIF, EXIF_TAG_FOCAL_LENGTH, rational);
}

void Exif::setExposureTime(uint64_t nsec)
{
	ExifRational rational = { static_cast<ExifLong>(nsec), 1000000000 };
	setRational(EXIF_IFD_EXIF, EXIF_TAG_EXPOSURE_TIME, rational);
}

void Exif::setAperture(float size)
{
	ExifRational rational = { static_cast<ExifLong>(size * 10000), 10000 };
	setRational(EXIF_IFD_EXIF, EXIF_TAG_FNUMBER, rational);
}

void Exif::setISO(uint16_t iso)
{
	setShort(EXIF_IFD_EXIF, EXIF_TAG_ISO_SPEED_RATINGS, iso);
}

void Exif::setFlash(Flash flash)
{
	setShort(EXIF_IFD_EXIF, EXIF_TAG_FLASH, static_cast<ExifShort>(flash));
}

void Exif::setWhiteBalance(WhiteBalance wb)
{
	setShort(EXIF_IFD_EXIF, EXIF_TAG_WHITE_BALANCE, static_cast<ExifShort>(wb));
}

/**
 * \brief Convert UTF-8 string to UTF-16 string
 * \param[in] str String to convert
 *
 * \return \a str in UTF-16
 */
std::u16string Exif::utf8ToUtf16(const std::string &str)
{
	mbstate_t state{};
	char16_t c16;
	const char *ptr = str.data();
	const char *end = ptr + str.size();

	std::u16string ret;
	while (size_t rc = mbrtoc16(&c16, ptr, end - ptr + 1, &state)) {
		if (rc == static_cast<size_t>(-2) ||
		    rc == static_cast<size_t>(-1))
			break;

		ret.push_back(c16);

		if (rc > 0)
			ptr += rc;
	}

	return ret;
}

[[nodiscard]] int Exif::generate()
{
	if (exifData_) {
		free(exifData_);
		exifData_ = nullptr;
	}

	if (!valid_) {
		LOG(EXIF, Error) << "Generated EXIF data is invalid";
		return -1;
	}

	exif_data_save_data(data_, &exifData_, &size_);

	LOG(EXIF, Debug) << "Created EXIF instance (" << size_ << " bytes)";

	return 0;
}