/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * encoder_libjpeg.cpp - JPEG encoding using libjpeg native API */ #include "encoder_libjpeg.h" #include #include #include #include #include #include #include #include #include #include #include #include "libcamera/internal/formats.h" #include "libcamera/internal/log.h" using namespace libcamera; LOG_DECLARE_CATEGORY(JPEG) namespace { struct JPEGPixelFormatInfo { J_COLOR_SPACE colorSpace; const PixelFormatInfo &pixelFormatInfo; bool nvSwap; }; const std::map pixelInfo{ { formats::R8, { JCS_GRAYSCALE, PixelFormatInfo::info(formats::R8), false } }, { formats::RGB888, { JCS_EXT_BGR, PixelFormatInfo::info(formats::RGB888), false } }, { formats::BGR888, { JCS_EXT_RGB, PixelFormatInfo::info(formats::BGR888), false } }, { formats::NV12, { JCS_YCbCr, PixelFormatInfo::info(formats::NV12), false } }, { formats::NV21, { JCS_YCbCr, PixelFormatInfo::info(formats::NV21), true } }, { formats::NV16, { JCS_YCbCr, PixelFormatInfo::info(formats::NV16), false } }, { formats::NV61, { JCS_YCbCr, PixelFormatInfo::info(formats::NV61), true } }, { formats::NV24, { JCS_YCbCr, PixelFormatInfo::info(formats::NV24), false } }, { formats::NV42, { JCS_YCbCr, PixelFormatInfo::info(formats::NV42), true } }, }; const struct JPEGPixelFormatInfo &findPixelInfo(const PixelFormat &format) { static const struct JPEGPixelFormatInfo invalidPixelFormat { JCS_UNKNOWN, PixelFormatInfo(), false }; const auto iter = pixelInfo.find(format); if (iter == pixelInfo.end()) { LOG(JPEG, Error) << "Unsupported pixel format for JPEG encoder: " << format.toString(); return invalidPixelFormat; } return iter->second; } } /* namespace */ EncoderLibJpeg::EncoderLibJpeg() { /* \todo Expand error handling coverage with a custom handler. */ compress_.err = jpeg_std_error(&jerr_); jpeg_create_compress(&compress_); } EncoderLibJpeg::~EncoderLibJpeg() { jpeg_destroy_compress(&compress_); } int EncoderLibJpeg::configure(const StreamConfiguration &cfg) { const struct JPEGPixelFormatInfo info = findPixelInfo(cfg.pixelFormat); if (info.colorSpace == JCS_UNKNOWN) return -ENOTSUP; compress_.image_width = cfg.size.width; compress_.image_height = cfg.size.height; compress_.in_color_space = info.colorSpace; compress_.input_components = info.colorSpace == JCS_GRAYSCALE ? 1 : 3; jpeg_set_defaults(&compress_); pixelFormatInfo_ = &info.pixelFormatInfo; nv_ = pixelFormatInfo_->numPlanes() == 2; nvSwap_ = info.nvSwap; return 0; } void EncoderLibJpeg::compressRGB(Span frame) { unsigned char *src = const_cast(frame.data()); /* \todo Stride information should come from buffer configuration. */ unsigned int stride = pixelFormatInfo_->stride(compress_.image_width, 0); JSAMPROW row_pointer[1]; while (compress_.next_scanline < compress_.image_height) { row_pointer[0] = &src[compress_.next_scanline * stride]; jpeg_write_scanlines(&compress_, row_pointer, 1); } } /* * Compress the incoming buffer from a supported NV format. * This naively unpacks the semi-planar NV12 to a YUV888 format for libjpeg. */ void EncoderLibJpeg::compressNV(Span frame) { uint8_t tmprowbuf[compress_.image_width * 3]; /* * \todo Use the raw api, and only unpack the cb/cr samples to new line * buffers. If possible, see if we can set appropriate pixel strides * too to save even that copy. * * Possible hints at: * https://sourceforge.net/p/libjpeg/mailman/message/30815123/ */ unsigned int y_stride = pixelFormatInfo_->stride(compress_.image_width, 0); unsigned int c_stride = pixelFormatInfo_->stride(compress_.image_width, 1); unsigned int horzSubSample = 2 * compress_.image_width / c_stride; unsigned int vertSubSample = pixelFormatInfo_->planes[1].verticalSubSampling; unsigned int c_inc = horzSubSample == 1 ? 2 : 0; unsigned int cb_pos = nvSwap_ ? 1 : 0; unsigned int cr_pos = nvSwap_ ? 0 : 1; const unsigned char *src = frame.data(); const unsigned char *src_c = src + y_stride * compress_.image_height; JSAMPROW row_pointer[1]; row_pointer[0] = &tmprowbuf[0]; for (unsigned int y = 0; y < compress_.image_height; y++) { unsigned char *dst = &tmprowbuf[0]; const unsigned char *src_y = src + y * compress_.image_width; const unsigned char *src_cb = src_c + (y / vertSubSample) * c_stride + cb_pos; const unsigned char *src_cr = src_c + (y / vertSubSample) * c_stride + cr_pos; for (unsigned int x = 0; x < compress_.image_width; x += 2) { dst[0] = *src_y; dst[1] = *src_cb; dst[2] = *src_cr; src_y++; src_cb += c_inc; src_cr += c_inc; dst += 3; dst[0] = *src_y; dst[1] = *src_cb; dst[2] = *src_cr; src_y++; src_cb += 2; src_cr += 2; dst += 3; } jpeg_write_scanlines(&compress_, row_pointer, 1); } } int EncoderLibJpeg::encode(const FrameBuffer &source, Span dest, Span exifData, unsigned int quality) { MappedFrameBuffer frame(&source, PROT_READ); if (!frame.isValid()) { LOG(JPEG, Error) << "Failed to map FrameBuffer : " << strerror(frame.error()); return frame.error(); } return encode(frame.maps()[0], dest, exifData, quality); } int EncoderLibJpeg::encode(Span src, Span dest, Span exifData, unsigned int quality) { unsigned char *destination = dest.data(); unsigned long size = dest.size(); jpeg_set_quality(&compress_, quality, TRUE); /* * The jpeg_mem_dest will reallocate if the required size is not * sufficient. That means the output won't be written to the correct * buffers. * * \todo Implement our own custom memory destination to prevent * reallocation and prefer failure with correct reporting. */ jpeg_mem_dest(&compress_, &destination, &size); jpeg_start_compress(&compress_, TRUE); if (exifData.size()) /* Store Exif data in the JPEG_APP1 data block. */ jpeg_write_marker(&compress_, JPEG_APP0 + 1, static_cast(exifData.data()), exifData.size()); LOG(JPEG, Debug) << "JPEG Encode Starting:" << compress_.image_width << "x" << compress_.image_height; if (nv_) compressNV(src); else compressRGB(src); jpeg_finish_compress(&compress_); return size; } 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 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 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2018, Google Inc.
 *
 * log.cpp - Logging infrastructure
 */

#include <libcamera/base/log.h>

#include <array>
#include <fstream>
#include <iostream>
#include <list>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unordered_set>

#include <libcamera/logging.h>

#include <libcamera/base/backtrace.h>
#include <libcamera/base/thread.h>
#include <libcamera/base/utils.h>

/**
 * \file base/log.h
 * \brief Logging infrastructure
 *
 * libcamera includes a logging infrastructure used through the library that
 * allows inspection of internal operation in a user-configurable way. The log
 * messages are grouped in categories that represent areas of libcamera, and
 * output of messages for each category can be controlled by independent log
 * levels.
 *
 * The levels are configurable through the LIBCAMERA_LOG_LEVELS environment
 * variable that contains a comma-separated list of 'category:level' pairs.
 *
 * The category names are strings and can include a wildcard ('*') character at
 * the end to match multiple categories.
 *
 * The level are either numeric values, or strings containing the log level
 * name. The available log levels are DEBUG, INFO, WARN, ERROR and FATAL. Log
 * message with a level higher than or equal to the configured log level for
 * their category are output to the log, while other messages are silently
 * discarded.
 *
 * By default log messages are output to std::cerr. They can be redirected to a
 * log file by setting the LIBCAMERA_LOG_FILE environment variable to the name
 * of the file. The file must be writable and is truncated if it exists. If any
 * error occurs when opening the file, the file is ignored and the log is output
 * to std::cerr.
 */

/**
 * \file logging.h
 * \brief Logging management
 *
 * API to change the logging output destination and log levels programatically.
 */

namespace libcamera {

static int log_severity_to_syslog(LogSeverity severity)
{
	switch (severity) {
	case LogDebug:
		return LOG_DEBUG;
	case LogInfo:
		return LOG_INFO;
	case LogWarning:
		return LOG_WARNING;
	case LogError:
		return LOG_ERR;
	case LogFatal:
		return LOG_ALERT;
	default:
		return LOG_NOTICE;
	}
}

static const char *log_severity_name(LogSeverity severity)
{
	static const char *const names[] = {
		"DEBUG",
		" INFO",
		" WARN",
		"ERROR",
		"FATAL",
	};

	if (static_cast<unsigned int>(severity) < std::size(names))
		return names[severity];
	else
		return "UNKWN";
}

/**
 * \brief Log output
 *
 * The LogOutput class models a log output destination
 */
class LogOutput
{
public:
	LogOutput(const char *path, bool color);
	LogOutput(std::ostream *stream, bool color);
	LogOutput();
	~LogOutput();

	bool isValid() const;
	void write(const LogMessage &msg);
	void write(const std::string &msg);

private:
	void writeSyslog(LogSeverity severity, const std::string &msg);
	void writeStream(const std::string &msg);

	std::ostream *stream_;
	LoggingTarget target_;
	bool color_;
};

/**
 * \brief Construct a log output based on a file
 * \param[in] path Full path to log file
 * \param[in] color True to output colored messages
 */
LogOutput::LogOutput(const char *path, bool color)
	: target_(LoggingTargetFile), color_(color)
{
	stream_ = new std::ofstream(path);
}

/**
 * \brief Construct a log output based on a stream
 * \param[in] stream Stream to send log output to
 * \param[in] color True to output colored messages
 */
LogOutput::LogOutput(std::ostream *stream, bool color)
	: stream_(stream), target_(LoggingTargetStream), color_(color)
{
}

/**
 * \brief Construct a log output to syslog
 */
LogOutput::LogOutput()
	: stream_(nullptr), target_(LoggingTargetSyslog), color_(false)
{
	openlog("libcamera", LOG_PID, 0);
}

LogOutput::~LogOutput()
{
	switch (target_) {
	case LoggingTargetFile:
		delete stream_;
		break;
	case LoggingTargetSyslog:
		closelog();
		break;
	default:
		break;
	}
}

/**
 * \brief Check if the log output is valid
 * \return True if the log output is valid
 */
bool LogOutput::isValid() const
{
	switch (target_) {
	case LoggingTargetFile:
		return stream_->good();
	case LoggingTargetStream:
		return stream_ != nullptr;
	default:
		return true;
	}
}

namespace {

/*
 * For more information about ANSI escape codes, see
 * https://en.wikipedia.org/wiki/ANSI_escape_code#Colors.
 */
constexpr const char *kColorReset = "\033[0m";
constexpr const char *kColorGreen = "\033[0;32m";
constexpr const char *kColorBrightRed = "\033[1;31m";
constexpr const char *kColorBrightGreen = "\033[1;32m";
constexpr const char *kColorBrightYellow = "\033[1;33m";
constexpr const char *kColorBrightBlue = "\033[1;34m";
constexpr const char *kColorBrightMagenta = "\033[1;35m";
constexpr const char *kColorBrightCyan = "\033[1;36m";
constexpr const char *kColorBrightWhite = "\033[1;37m";

} /* namespace */

/**
 * \brief Write message to log output
 * \param[in] msg Message to write
 */
void LogOutput::write(const LogMessage &msg)
{
	static const char *const severityColors[] = {
		kColorBrightCyan,
		kColorBrightGreen,
		kColorBrightYellow,
		kColorBrightRed,
		kColorBrightMagenta,
	};

	const char *categoryColor = color_ ? kColorBrightWhite : "";
	const char *fileColor = color_ ? kColorBrightBlue : "";
	const char *prefixColor = color_ ? kColorGreen : "";
	const char *resetColor = color_ ? kColorReset : "";
	const char *severityColor = "";
	LogSeverity severity = msg.severity();
	std::string str;

	if (color_) {
		if (static_cast<unsigned int>(severity) < std::size(severityColors))
			severityColor = severityColors[severity];
		else
			severityColor = kColorBrightWhite;
	}

	switch (target_) {
	case LoggingTargetSyslog:
		str = std::string(log_severity_name(severity)) + " "
		    + msg.category().name() + " " + msg.fileInfo() + " ";
		if (!msg.prefix().empty())
			str += msg.prefix() + ": ";
		str += msg.msg();
		writeSyslog(severity, str);
		break;
	case LoggingTargetStream:
	case LoggingTargetFile:
		str = "[" + utils::time_point_to_string(msg.timestamp()) + "] ["
		    + std::to_string(Thread::currentId()) + "] "
		    + severityColor + log_severity_name(severity) + " "
		    + categoryColor + msg.category().name() + " "
		    + fileColor + msg.fileInfo() + " ";
		if (!msg.prefix().empty())
			str += prefixColor + msg.prefix() + ": ";
		str += resetColor + msg.msg();
		writeStream(str);
		break;
	default:
		break;
	}
}

/**
 * \brief Write string to log output
 * \param[in] str String to write
 */
void LogOutput::write(const std::string &str)
{
	switch (target_) {
	case LoggingTargetSyslog:
		writeSyslog(LogDebug, str);
		break;
	case LoggingTargetStream:
	case LoggingTargetFile:
		writeStream(str);
		break;
	default:
		break;
	}
}

void LogOutput::writeSyslog(LogSeverity severity, const std::string &str)
{
	syslog(log_severity_to_syslog(severity), "%s", str.c_str());
}

void LogOutput::writeStream(const std::string &str)
{
	stream_->write(str.c_str(), str.size());
	stream_->flush();
}

/**
 * \brief Message logger
 *