Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/ipa/ipa_interface.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Image Processing Algorithm interface */ #pragma once #include <stddef.h> #include <stdint.h> #include <map> #include <vector> #include <libcamera/base/flags.h> #include <libcamera/base/signal.h> #include <libcamera/controls.h> #include <libcamera/framebuffer.h> #include <libcamera/geometry.h> namespace libcamera { /* * Structs and enums that are defined in core.mojom that have the skipHeader * tag must be #included here. */ class IPAInterface { public: virtual ~IPAInterface() = default; }; } /* namespace libcamera */ extern "C" { libcamera::IPAInterface *ipaCreate(); }
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/ipa/ipa_module_info.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Image Processing Algorithm module information */ #pragma once #include <stdint.h> #define IPA_MODULE_API_VERSION 1 namespace libcamera { struct IPAModuleInfo { int moduleAPIVersion; uint32_t pipelineVersion; char pipelineName[256]; char name[256]; } __attribute__((packed)); extern "C" { extern const struct IPAModuleInfo ipaModuleInfo; } } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/ipa/ipa_controls.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * IPA Control handling */ #pragma once #include <stdint.h> #ifdef __cplusplus namespace libcamera { extern "C" { #endif #define IPA_CONTROLS_FORMAT_VERSION 1 enum ipa_controls_id_map_type { IPA_CONTROL_ID_MAP_CONTROLS, IPA_CONTROL_ID_MAP_PROPERTIES, IPA_CONTROL_ID_MAP_V4L2, }; struct ipa_controls_header { uint32_t version; uint32_t handle; uint32_t entries; uint32_t size; uint32_t data_offset; enum ipa_controls_id_map_type id_map_type; uint32_t reserved[2]; }; struct ipa_control_value_entry { uint32_t id; uint8_t type; uint8_t is_array; uint16_t count; uint32_t offset; uint32_t padding[1]; }; struct ipa_control_info_entry { uint32_t id; uint32_t type; uint32_t offset; uint32_t padding[1]; }; #ifdef __cplusplus } /* namespace libcamera */ } #endif
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/signal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Signal & slot implementation */ #pragma once #include <functional> #include <list> #include <type_traits> #include <vector> #include <libcamera/base/bound_method.h> namespace libcamera { class Object; class SignalBase { public: void disconnect(Object *object); protected: using SlotList = std::list<BoundMethodBase *>; void connect(BoundMethodBase *slot); void disconnect(std::function<bool(SlotList::iterator &)> match); SlotList slots(); private: SlotList slots_; }; template<typename... Args> class Signal : public SignalBase { public: ~Signal() { disconnect(); } #ifndef __DOXYGEN__ template<typename T, typename R, std::enable_if_t<std::is_base_of<Object, T>::value> * = nullptr> void connect(T *obj, R (T::*func)(Args...), ConnectionType type = ConnectionTypeAuto) { Object *object = static_cast<Object *>(obj); SignalBase::connect(new BoundMethodMember<T, R, Args...>(obj, object, func, type)); } template<typename T, typename R, std::enable_if_t<!std::is_base_of<Object, T>::value> * = nullptr> #else template<typename T, typename R> #endif void connect(T *obj, R (T::*func)(Args...)) { SignalBase::connect(new BoundMethodMember<T, R, Args...>(obj, nullptr, func)); } #ifndef __DOXYGEN__ template<typename T, typename Func, std::enable_if_t<std::is_base_of<Object, T>::value #if __cplusplus >= 201703L && std::is_invocable_v<Func, Args...> #endif > * = nullptr> void connect(T *obj, Func func, ConnectionType type = ConnectionTypeAuto) { Object *object = static_cast<Object *>(obj); SignalBase::connect(new BoundMethodFunctor<T, void, Func, Args...>(obj, object, func, type)); } template<typename T, typename Func, std::enable_if_t<!std::is_base_of<Object, T>::value #if __cplusplus >= 201703L && std::is_invocable_v<Func, Args...> #endif > * = nullptr> #else template<typename T, typename Func> #endif void connect(T *obj, Func func) { SignalBase::connect(new BoundMethodFunctor<T, void, Func, Args...>(obj, nullptr, func)); } template<typename R> void connect(R (*func)(Args...)) { SignalBase::connect(new BoundMethodStatic<R, Args...>(func)); } void disconnect() { SignalBase::disconnect([]([[maybe_unused]] SlotList::iterator &iter) { return true; }); } template<typename T> void disconnect(T *obj) { SignalBase::disconnect([obj](SlotList::iterator &iter) { return (*iter)->match(obj); }); } template<typename T, typename R> void disconnect(T *obj, R (T::*func)(Args...)) { SignalBase::disconnect([obj, func](SlotList::iterator &iter) { BoundMethodArgs<R, Args...> *slot = static_cast<BoundMethodArgs<R, Args...> *>(*iter); if (!slot->match(obj)) return false; /* * If the object matches the slot, the slot is * guaranteed to be a member slot, so we can safely * cast it to BoundMethodMember<T, Args...> to match * func. */ return static_cast<BoundMethodMember<T, R, Args...> *>(slot)->match(func); }); } template<typename R> void disconnect(R (*func)(Args...)) { SignalBase::disconnect([func](SlotList::iterator &iter) { BoundMethodArgs<R, Args...> *slot = static_cast<BoundMethodArgs<R, Args...> *>(*iter); if (!slot->match(nullptr)) return false; return static_cast<BoundMethodStatic<R, Args...> *>(slot)->match(func); }); } void emit(Args... args) { /* * Make a copy of the slots list as the slot could call the * disconnect operation, invalidating the iterator. */ for (BoundMethodBase *slot : slots()) static_cast<BoundMethodArgs<void, Args...> *>(slot)->activate(args...); } }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/thread_annotations.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Macro of Clang thread safety analysis */ #pragma once #include <libcamera/base/private.h> /* * Enable thread safety attributes only with clang. * The attributes can be safely erased when compiling with other compilers. */ #if defined(__clang__) && !defined(SWIG) #define LIBCAMERA_TSA_ATTRIBUTE__(x) __attribute__((x)) #else #define LIBCAMERA_TSA_ATTRIBUTE__(x) /* no-op */ #endif /* See https://clang.llvm.org/docs/ThreadSafetyAnalysis.html for these usages. */ #define LIBCAMERA_TSA_CAPABILITY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(capability(x)) #define LIBCAMERA_TSA_SCOPED_CAPABILITY \ LIBCAMERA_TSA_ATTRIBUTE__(scoped_lockable) #define LIBCAMERA_TSA_GUARDED_BY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(guarded_by(x)) #define LIBCAMERA_TSA_PT_GUARDED_BY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(pt_guarded_by(x)) #define LIBCAMERA_TSA_ACQUIRED_BEFORE(...) \ LIBCAMERA_TSA_ATTRIBUTE__(acquired_before(__VA_ARGS__)) #define LIBCAMERA_TSA_ACQUIRED_AFTER(...) \ LIBCAMERA_TSA_ATTRIBUTE__(acquired_after(__VA_ARGS__)) #define LIBCAMERA_TSA_REQUIRES(...) \ LIBCAMERA_TSA_ATTRIBUTE__(requires_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_REQUIRES_SHARED(...) \ LIBCAMERA_TSA_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_ACQUIRE(...) \ LIBCAMERA_TSA_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_ACQUIRE_SHARED(...) \ LIBCAMERA_TSA_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_RELEASE(...) \ LIBCAMERA_TSA_ATTRIBUTE__(release_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_RELEASE_SHARED(...) \ LIBCAMERA_TSA_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_RELEASE_GENERIC(...) \ LIBCAMERA_TSA_ATTRIBUTE__(release_generic_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_TRY_ACQUIRE(...) \ LIBCAMERA_TSA_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_TRY_ACQUIRE_SHARED(...) \ LIBCAMERA_TSA_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) #define LIBCAMERA_TSA_EXCLUDES(...) \ LIBCAMERA_TSA_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) #define LIBCAMERA_TSA_ASSERT_CAPABILITY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(assert_capability(x)) #define LIBCAMERA_TSA_ASSERT_SHARED_CAPABILITY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(assert_shared_capability(x)) #define LIBCAMERA_TSA_RETURN_CAPABILITY(x) \ LIBCAMERA_TSA_ATTRIBUTE__(lock_returned(x)) #define LIBCAMERA_TSA_NO_THREAD_SAFETY_ANALYSIS \ LIBCAMERA_TSA_ATTRIBUTE__(no_thread_safety_analysis)
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/mutex.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Mutex classes with clang thread safety annotation */ #pragma once #include <condition_variable> #include <mutex> #include <libcamera/base/private.h> #include <libcamera/base/thread_annotations.h> namespace libcamera { /* \todo using Mutex = std::mutex if libc++ is used. */ #ifndef __DOXYGEN__ class LIBCAMERA_TSA_CAPABILITY("mutex") Mutex final { public: constexpr Mutex() { } void lock() LIBCAMERA_TSA_ACQUIRE() { mutex_.lock(); } void unlock() LIBCAMERA_TSA_RELEASE() { mutex_.unlock(); } private: friend class MutexLocker; std::mutex mutex_; }; class LIBCAMERA_TSA_SCOPED_CAPABILITY MutexLocker final { public: explicit MutexLocker(Mutex &mutex) LIBCAMERA_TSA_ACQUIRE(mutex) : lock_(mutex.mutex_) { } MutexLocker(Mutex &mutex, std::defer_lock_t t) noexcept LIBCAMERA_TSA_EXCLUDES(mutex) : lock_(mutex.mutex_, t) { } ~MutexLocker() LIBCAMERA_TSA_RELEASE() { } void lock() LIBCAMERA_TSA_ACQUIRE() { lock_.lock(); } bool try_lock() LIBCAMERA_TSA_TRY_ACQUIRE(true) { return lock_.try_lock(); } void unlock() LIBCAMERA_TSA_RELEASE() { lock_.unlock(); } private: friend class ConditionVariable; std::unique_lock<std::mutex> lock_; }; class ConditionVariable final { public: ConditionVariable() { } void notify_one() noexcept { cv_.notify_one(); } void notify_all() noexcept { cv_.notify_all(); } template<class Predicate> void wait(MutexLocker &locker, Predicate stopWaiting) { cv_.wait(locker.lock_, stopWaiting); } template<class Rep, class Period, class Predicate> bool wait_for(MutexLocker &locker, const std::chrono::duration<Rep, Period> &relTime, Predicate stopWaiting) { return cv_.wait_for(locker.lock_, relTime, stopWaiting); } private: std::condition_variable cv_; }; #else /* __DOXYGEN__ */ class Mutex final { }; class MutexLocker final { }; class ConditionVariable final { }; #endif /* __DOXYGEN__ */ } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/thread.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Thread support */ #pragma once #include <memory> #include <sys/types.h> #include <thread> #include <libcamera/base/private.h> #include <libcamera/base/message.h> #include <libcamera/base/signal.h> #include <libcamera/base/utils.h> namespace libcamera { class EventDispatcher; class Message; class Object; class ThreadData; class ThreadMain; class Thread { public: Thread(); virtual ~Thread(); void start(); void exit(int code = 0); bool wait(utils::duration duration = utils::duration::max()); bool isRunning(); Signal<> finished; static Thread *current(); static pid_t currentId(); EventDispatcher *eventDispatcher(); void dispatchMessages(Message::Type type = Message::Type::None); protected: int exec(); virtual void run(); private: void startThread(); void finishThread(); void postMessage(std::unique_ptr<Message> msg, Object *receiver); void removeMessages(Object *receiver); friend class Object; friend class ThreadData; friend class ThreadMain; void moveObject(Object *object); void moveObject(Object *object, ThreadData *currentData, ThreadData *targetData); std::thread thread_; ThreadData *data_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/private.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Private Header Validation * * A selection of internal libcamera headers are installed as part * of the libcamera package to allow sharing of a select subset of * internal functionality with IPA module only. * * This functionality is not considered part of the public libcamera * API, and can therefore potentially face ABI instabilities which * should not be exposed to applications. IPA modules however should be * versioned and more closely matched to the libcamera installation. * * Components which include this file can not be included in any file * which forms part of the libcamera API. */ #ifndef LIBCAMERA_BASE_PRIVATE #error "Private headers must not be included in the libcamera API" #endif
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/span.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * C++20 std::span<> implementation for C++11 */ #pragma once #include <array> #include <iterator> #include <limits> #include <stddef.h> #include <type_traits> namespace libcamera { static constexpr std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max(); template<typename T, std::size_t Extent = dynamic_extent> class Span; namespace details { template<typename U> struct is_array : public std::false_type { }; template<typename U, std::size_t N> struct is_array<std::array<U, N>> : public std::true_type { }; template<typename U> struct is_span : public std::false_type { }; template<typename U, std::size_t Extent> struct is_span<Span<U, Extent>> : public std::true_type { }; } /* namespace details */ namespace utils { template<typename C> constexpr auto size(const C &c) -> decltype(c.size()) { return c.size(); } template<typename C> constexpr auto data(const C &c) -> decltype(c.data()) { return c.data(); } template<typename C> constexpr auto data(C &c) -> decltype(c.data()) { return c.data(); } template<class T, std::size_t N> constexpr T *data(T (&array)[N]) noexcept { return array; } template<std::size_t I, typename T> struct tuple_element; template<std::size_t I, typename T, std::size_t N> struct tuple_element<I, Span<T, N>> { using type = T; }; template<typename T> struct tuple_size; template<typename T, std::size_t N> struct tuple_size<Span<T, N>> : public std::integral_constant<std::size_t, N> { }; template<typename T> struct tuple_size<Span<T, dynamic_extent>>; } /* namespace utils */ template<typename T, std::size_t Extent> class Span { public: using element_type = T; using value_type = typename std::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static constexpr std::size_t extent = Extent; template<bool Dependent = false, typename = std::enable_if_t<Dependent || Extent == 0>> constexpr Span() noexcept : data_(nullptr) { } explicit constexpr Span(pointer ptr, [[maybe_unused]] size_type count) : data_(ptr) { } explicit constexpr Span(pointer first, [[maybe_unused]] pointer last) : data_(first) { } template<std::size_t N> constexpr Span(element_type (&arr)[N], std::enable_if_t<std::is_convertible<std::remove_pointer_t<decltype(utils::data(arr))> (*)[], element_type (*)[]>::value && N == Extent, std::nullptr_t> = nullptr) noexcept : data_(arr) { } template<std::size_t N> constexpr Span(std::array<value_type, N> &arr, std::enable_if_t<std::is_convertible<std::remove_pointer_t<decltype(utils::data(arr))> (*)[], element_type (*)[]>::value && N == Extent, std::nullptr_t> = nullptr) noexcept : data_(arr.data()) { } template<std::size_t N> constexpr Span(const std::array<value_type, N> &arr, std::enable_if_t<std::is_convertible<std::remove_pointer_t<decltype(utils::data(arr))> (*)[], element_type (*)[]>::value && N == Extent, std::nullptr_t> = nullptr) noexcept : data_(arr.data()) { } template<class Container> explicit constexpr Span(Container &cont, std::enable_if_t<!details::is_span<Container>::value && !details::is_array<Container>::value && !std::is_array<Container>::value && std::is_convertible<std::remove_pointer_t<decltype(utils::data(cont))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) : data_(utils::data(cont)) { } template<class Container> explicit constexpr Span(const Container &cont, std::enable_if_t<!details::is_span<Container>::value && !details::is_array<Container>::value && !std::is_array<Container>::value && std::is_convertible<std::remove_pointer_t<decltype(utils::data(cont))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) : data_(utils::data(cont)) { static_assert(utils::size(cont) == Extent, "Size mismatch"); } template<class U, std::size_t N> explicit constexpr Span(const Span<U, N> &s, std::enable_if_t<std::is_convertible<U (*)[], element_type (*)[]>::value && N == Extent, std::nullptr_t> = nullptr) noexcept : data_(s.data()) { } constexpr Span(const Span &other) noexcept = default; constexpr Span &operator=(const Span &other) noexcept = default; constexpr iterator begin() const { return data(); } constexpr const_iterator cbegin() const { return begin(); } constexpr iterator end() const { return data() + size(); } constexpr const_iterator cend() const { return end(); } constexpr reverse_iterator rbegin() const { return reverse_iterator(end()); } constexpr const_reverse_iterator crbegin() const { return rbegin(); } constexpr reverse_iterator rend() const { return reverse_iterator(begin()); } constexpr const_reverse_iterator crend() const { return rend(); } constexpr reference front() const { return *data(); } constexpr reference back() const { return *(data() + size() - 1); } constexpr reference operator[](size_type idx) const { return data()[idx]; } constexpr pointer data() const noexcept { return data_; } constexpr size_type size() const noexcept { return Extent; } constexpr size_type size_bytes() const noexcept { return size() * sizeof(element_type); } constexpr bool empty() const noexcept { return size() == 0; } template<std::size_t Count> constexpr Span<element_type, Count> first() const { static_assert(Count <= Extent, "Count larger than size"); return Span<element_type, Count>{ data(), Count }; } constexpr Span<element_type, dynamic_extent> first(std::size_t Count) const { return Span<element_type, dynamic_extent>{ data(), Count }; } template<std::size_t Count> constexpr Span<element_type, Count> last() const { static_assert(Count <= Extent, "Count larger than size"); return Span<element_type, Count>{ data() + size() - Count, Count }; } constexpr Span<element_type, dynamic_extent> last(std::size_t Count) const { return Span<element_type, dynamic_extent>{ data() + size() - Count, Count }; } template<std::size_t Offset, std::size_t Count = dynamic_extent> constexpr Span<element_type, Count != dynamic_extent ? Count : Extent - Offset> subspan() const { static_assert(Offset <= Extent, "Offset larger than size"); static_assert(Count == dynamic_extent || Count + Offset <= Extent, "Offset + Count larger than size"); return Span<element_type, Count != dynamic_extent ? Count : Extent - Offset>{ data() + Offset, Count == dynamic_extent ? size() - Offset : Count }; } constexpr Span<element_type, dynamic_extent> subspan(std::size_t Offset, std::size_t Count = dynamic_extent) const { return Span<element_type, dynamic_extent>{ data() + Offset, Count == dynamic_extent ? size() - Offset : Count }; } private: pointer data_; }; template<typename T> class Span<T, dynamic_extent> { public: using element_type = T; using value_type = typename std::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using iterator = T *; using const_iterator = const T *; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static constexpr std::size_t extent = dynamic_extent; constexpr Span() noexcept : data_(nullptr), size_(0) { } constexpr Span(pointer ptr, size_type count) : data_(ptr), size_(count) { } constexpr Span(pointer first, pointer last) : data_(first), size_(last - first) { } template<std::size_t N> constexpr Span(element_type (&arr)[N], std::enable_if_t<std::is_convertible<std::remove_pointer_t<decltype(utils::data(arr))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) noexcept : data_(arr), size_(N) { } template<std::size_t N> constexpr Span(std::array<value_type, N> &arr, std::enable_if_t<std::is_convertible<std::remove_pointer_t<decltype(utils::data(arr))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) noexcept : data_(utils::data(arr)), size_(N) { } template<std::size_t N> constexpr Span(const std::array<value_type, N> &arr) noexcept : data_(utils::data(arr)), size_(N) { } template<class Container> constexpr Span(Container &cont, std::enable_if_t<!details::is_span<Container>::value && !details::is_array<Container>::value && !std::is_array<Container>::value && std::is_convertible<std::remove_pointer_t<decltype(utils::data(cont))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) : data_(utils::data(cont)), size_(utils::size(cont)) { } template<class Container> constexpr Span(const Container &cont, std::enable_if_t<!details::is_span<Container>::value && !details::is_array<Container>::value && !std::is_array<Container>::value && std::is_convertible<std::remove_pointer_t<decltype(utils::data(cont))> (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) : data_(utils::data(cont)), size_(utils::size(cont)) { } template<class U, std::size_t N> constexpr Span(const Span<U, N> &s, std::enable_if_t<std::is_convertible<U (*)[], element_type (*)[]>::value, std::nullptr_t> = nullptr) noexcept : data_(s.data()), size_(s.size()) { } constexpr Span(const Span &other) noexcept = default; constexpr Span &operator=(const Span &other) noexcept { data_ = other.data_; size_ = other.size_; return *this; } constexpr iterator begin() const { return data(); } constexpr const_iterator cbegin() const { return begin(); } constexpr iterator end() const { return data() + size(); } constexpr const_iterator cend() const { return end(); } constexpr reverse_iterator rbegin() const { return reverse_iterator(end()); } constexpr const_reverse_iterator crbegin() const { return rbegin(); } constexpr reverse_iterator rend() const { return reverse_iterator(begin()); } constexpr const_reverse_iterator crend() const { return rend(); } constexpr reference front() const { return *data(); } constexpr reference back() const { return *(data() + size() - 1); } constexpr reference operator[](size_type idx) const { return data()[idx]; } constexpr pointer data() const noexcept { return data_; } constexpr size_type size() const noexcept { return size_; } constexpr size_type size_bytes() const noexcept { return size() * sizeof(element_type); } constexpr bool empty() const noexcept { return size() == 0; } template<std::size_t Count> constexpr Span<element_type, Count> first() const { return Span<element_type, Count>{ data(), Count }; } constexpr Span<element_type, dynamic_extent> first(std::size_t Count) const { return { data(), Count }; } template<std::size_t Count> constexpr Span<element_type, Count> last() const { return Span<element_type, Count>{ data() + size() - Count, Count }; } constexpr Span<element_type, dynamic_extent> last(std::size_t Count) const { return Span<element_type, dynamic_extent>{ data() + size() - Count, Count }; } template<std::size_t Offset, std::size_t Count = dynamic_extent> constexpr Span<element_type, Count> subspan() const { return Span<element_type, Count>{ data() + Offset, Count == dynamic_extent ? size() - Offset : Count }; } constexpr Span<element_type, dynamic_extent> subspan(std::size_t Offset, std::size_t Count = dynamic_extent) const { return Span<element_type, dynamic_extent>{ data() + Offset, Count == dynamic_extent ? size() - Offset : Count }; } private: pointer data_; size_type size_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/unique_fd.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * File descriptor wrapper that owns a file descriptor. */ #pragma once #include <utility> #include <libcamera/base/class.h> #include <libcamera/base/compiler.h> namespace libcamera { class UniqueFD final { public: UniqueFD() : fd_(-1) { } explicit UniqueFD(int fd) : fd_(fd) { } UniqueFD(UniqueFD &&other) : fd_(other.release()) { } ~UniqueFD() { reset(); } UniqueFD &operator=(UniqueFD &&other) { reset(other.release()); return *this; } __nodiscard int release() { int fd = fd_; fd_ = -1; return fd; } void reset(int fd = -1); void swap(UniqueFD &other) { std::swap(fd_, other.fd_); } int get() const { return fd_; } bool isValid() const { return fd_ >= 0; } private: LIBCAMERA_DISABLE_COPY(UniqueFD) int fd_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/semaphore.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * General-purpose counting semaphore */ #pragma once #include <libcamera/base/private.h> #include <libcamera/base/mutex.h> namespace libcamera { class Semaphore { public: Semaphore(unsigned int n = 0); unsigned int available() LIBCAMERA_TSA_EXCLUDES(mutex_); void acquire(unsigned int n = 1) LIBCAMERA_TSA_EXCLUDES(mutex_); bool tryAcquire(unsigned int n = 1) LIBCAMERA_TSA_EXCLUDES(mutex_); void release(unsigned int n = 1) LIBCAMERA_TSA_EXCLUDES(mutex_); private: Mutex mutex_; ConditionVariable cv_; unsigned int available_ LIBCAMERA_TSA_GUARDED_BY(mutex_); }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/timer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Generic timer */ #pragma once #include <chrono> #include <stdint.h> #include <libcamera/base/private.h> #include <libcamera/base/object.h> #include <libcamera/base/signal.h> namespace libcamera { class Message; class Timer : public Object { public: Timer(Object *parent = nullptr); ~Timer(); void start(std::chrono::milliseconds duration); void start(std::chrono::steady_clock::time_point deadline); void stop(); bool isRunning() const; std::chrono::steady_clock::time_point deadline() const { return deadline_; } Signal<> timeout; protected: void message(Message *msg) override; private: void registerTimer(); void unregisterTimer(); bool running_; std::chrono::steady_clock::time_point deadline_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/utils.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * Miscellaneous utility functions */ #pragma once #include <algorithm> #include <chrono> #include <iterator> #include <memory> #include <ostream> #include <sstream> #include <string> #include <string.h> #include <sys/time.h> #include <type_traits> #include <utility> #include <vector> #include <libcamera/base/private.h> #ifndef __DOXYGEN__ /* uClibc and uClibc-ng don't provide O_TMPFILE */ #ifndef O_TMPFILE #define O_TMPFILE (020000000 | O_DIRECTORY) #endif #endif namespace libcamera { namespace utils { const char *basename(const char *path); char *secure_getenv(const char *name); std::string dirname(const std::string &path); template<typename T> std::vector<typename T::key_type> map_keys(const T &map) { std::vector<typename T::key_type> keys; std::transform(map.begin(), map.end(), std::back_inserter(keys), [](const auto &value) { return value.first; }); return keys; } template<class InputIt1, class InputIt2> unsigned int set_overlap(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { unsigned int count = 0; while (first1 != last1 && first2 != last2) { if (*first1 < *first2) { ++first1; } else { if (!(*first2 < *first1)) count++; ++first2; } } return count; } using clock = std::chrono::steady_clock; using duration = std::chrono::steady_clock::duration; using time_point = std::chrono::steady_clock::time_point; struct timespec duration_to_timespec(const duration &value); std::string time_point_to_string(const time_point &time); #ifndef __DOXYGEN__ struct _hex { uint64_t v; unsigned int w; }; std::basic_ostream<char, std::char_traits<char>> & operator<<(std::basic_ostream<char, std::char_traits<char>> &stream, const _hex &h); #endif template<typename T, std::enable_if_t<std::is_integral<T>::value> * = nullptr> _hex hex(T value, unsigned int width = 0); #ifndef __DOXYGEN__ template<> inline _hex hex<int32_t>(int32_t value, unsigned int width) { return { static_cast<uint64_t>(value), width ? width : 8 }; } template<> inline _hex hex<uint32_t>(uint32_t value, unsigned int width) { return { static_cast<uint64_t>(value), width ? width : 8 }; } template<> inline _hex hex<int64_t>(int64_t value, unsigned int width) { return { static_cast<uint64_t>(value), width ? width : 16 }; } template<> inline _hex hex<uint64_t>(uint64_t value, unsigned int width) { return { static_cast<uint64_t>(value), width ? width : 16 }; } #endif size_t strlcpy(char *dst, const char *src, size_t size); #ifndef __DOXYGEN__ template<typename Container, typename UnaryOp> std::string join(const Container &items, const std::string &sep, UnaryOp op) { std::ostringstream ss; bool first = true; for (typename Container::const_iterator it = std::begin(items); it != std::end(items); ++it) { if (!first) ss << sep; else first = false; ss << op(*it); } return ss.str(); } template<typename Container> std::string join(const Container &items, const std::string &sep) { std::ostringstream ss; bool first = true; for (typename Container::const_iterator it = std::begin(items); it != std::end(items); ++it) { if (!first) ss << sep; else first = false; ss << *it; } return ss.str(); } #else template<typename Container, typename UnaryOp> std::string join(const Container &items, const std::string &sep, UnaryOp op = nullptr); #endif namespace details { class StringSplitter { public: StringSplitter(const std::string &str, const std::string &delim); class iterator { public: using difference_type = std::size_t; using value_type = std::string; using pointer = value_type *; using reference = value_type &; using iterator_category = std::input_iterator_tag; iterator(const StringSplitter *ss, std::string::size_type pos); iterator &operator++(); std::string operator*() const; bool operator!=(const iterator &other) const; private: const StringSplitter *ss_; std::string::size_type pos_; std::string::size_type next_; }; iterator begin() const; iterator end() const; private: std::string str_; std::string delim_; }; } /* namespace details */ details::StringSplitter split(const std::string &str, const std::string &delim); std::string toAscii(const std::string &str); std::string libcameraBuildPath(); std::string libcameraSourcePath(); constexpr unsigned int alignDown(unsigned int value, unsigned int alignment) { return value / alignment * alignment; } constexpr unsigned int alignUp(unsigned int value, unsigned int alignment) { return (value + alignment - 1) / alignment * alignment; } namespace details { template<typename T> struct reverse_adapter { T &iterable; }; template<typename T> auto begin(reverse_adapter<T> r) { return std::rbegin(r.iterable); } template<typename T> auto end(reverse_adapter<T> r) { return std::rend(r.iterable); } } /* namespace details */ template<typename T> details::reverse_adapter<T> reverse(T &&iterable) { return { iterable }; } namespace details { template<typename Base> class enumerate_iterator { private: using base_reference = typename std::iterator_traits<Base>::reference; public: using difference_type = typename std::iterator_traits<Base>::difference_type; using value_type = std::pair<const std::size_t, base_reference>; using pointer = value_type *; using reference = value_type &; using iterator_category = std::input_iterator_tag; explicit enumerate_iterator(Base iter) : current_(iter), pos_(0) { } enumerate_iterator &operator++() { ++current_; ++pos_; return *this; } bool operator!=(const enumerate_iterator &other) const { return current_ != other.current_; } value_type operator*() const { return { pos_, *current_ }; } private: Base current_; std::size_t pos_; }; template<typename Base> class enumerate_adapter { public: using iterator = enumerate_iterator<Base>; enumerate_adapter(Base begin, Base end) : begin_(begin), end_(end) { } iterator begin() const { return iterator{ begin_ }; } iterator end() const { return iterator{ end_ }; } private: const Base begin_; const Base end_; }; } /* namespace details */ template<typename T> auto enumerate(T &iterable) -> details::enumerate_adapter<decltype(iterable.begin())> { return { std::begin(iterable), std::end(iterable) }; } #ifndef __DOXYGEN__ template<typename T, size_t N> auto enumerate(T (&iterable)[N]) -> details::enumerate_adapter<T *> { return { std::begin(iterable), std::end(iterable) }; } #endif class Duration : public std::chrono::duration<double, std::nano> { using BaseDuration = std::chrono::duration<double, std::nano>; public: Duration() = default; template<typename Rep> constexpr explicit Duration(const Rep &r) : BaseDuration(r) { } template<typename Rep, typename Period> constexpr Duration(const std::chrono::duration<Rep, Period> &d) : BaseDuration(d) { } template<typename Period> double get() const { auto const c = std::chrono::duration_cast<std::chrono::duration<double, Period>>(*this); return c.count(); } explicit constexpr operator bool() const { return *this != BaseDuration::zero(); } }; template<typename T> decltype(auto) abs_diff(const T &a, const T &b) { if (a < b) return b - a; else return a - b; } double strtod(const char *__restrict nptr, char **__restrict endptr); template<class Enum> constexpr std::underlying_type_t<Enum> to_underlying(Enum e) noexcept { return static_cast<std::underlying_type_t<Enum>>(e); } } /* namespace utils */ #ifndef __DOXYGEN__ template<class CharT, class Traits> std::basic_ostream<CharT, Traits> &operator<<(std::basic_ostream<CharT, Traits> &os, const utils::Duration &d); #endif } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/flags.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Type-safe enum-based bitfields */ #pragma once #include <type_traits> namespace libcamera { template<typename E> class Flags { public: static_assert(std::is_enum<E>::value, "Flags<> template parameter must be an enum"); using Type = std::underlying_type_t<E>; constexpr Flags() : value_(0) { } constexpr Flags(E flag) : value_(static_cast<Type>(flag)) { } constexpr Flags &operator&=(E flag) { value_ &= static_cast<Type>(flag); return *this; } constexpr Flags &operator&=(Flags other) { value_ &= other.value_; return *this; } constexpr Flags &operator|=(E flag) { value_ |= static_cast<Type>(flag); return *this; } constexpr Flags &operator|=(Flags other) { value_ |= other.value_; return *this; } constexpr Flags &operator^=(E flag) { value_ ^= static_cast<Type>(flag); return *this; } constexpr Flags &operator^=(Flags other) { value_ ^= other.value_; return *this; } constexpr bool operator==(E flag) { return value_ == static_cast<Type>(flag); } constexpr bool operator==(Flags other) { return value_ == static_cast<Type>(other); } constexpr bool operator!=(E flag) { return value_ != static_cast<Type>(flag); } constexpr bool operator!=(Flags other) { return value_ != static_cast<Type>(other); } constexpr explicit operator Type() const { return value_; } constexpr explicit operator bool() const { return !!value_; } constexpr Flags operator&(E flag) const { return Flags(static_cast<E>(value_ & static_cast<Type>(flag))); } constexpr Flags operator&(Flags other) const { return Flags(static_cast<E>(value_ & other.value_)); } constexpr Flags operator|(E flag) const { return Flags(static_cast<E>(value_ | static_cast<Type>(flag))); } constexpr Flags operator|(Flags other) const { return Flags(static_cast<E>(value_ | other.value_)); } constexpr Flags operator^(E flag) const { return Flags(static_cast<E>(value_ ^ static_cast<Type>(flag))); } constexpr Flags operator^(Flags other) const { return Flags(static_cast<E>(value_ ^ other.value_)); } constexpr Flags operator~() const { return Flags(static_cast<E>(~value_)); } constexpr bool operator!() const { return !value_; } private: Type value_; }; #ifndef __DOXYGEN__ template<typename E> struct flags_enable_operators { static const bool enable = false; }; template<typename E> std::enable_if_t<flags_enable_operators<E>::enable, Flags<E>> operator|(E lhs, E rhs) { using type = std::underlying_type_t<E>; return Flags<E>(static_cast<E>(static_cast<type>(lhs) | static_cast<type>(rhs))); } template<typename E> std::enable_if_t<flags_enable_operators<E>::enable, Flags<E>> operator&(E lhs, E rhs) { using type = std::underlying_type_t<E>; return Flags<E>(static_cast<E>(static_cast<type>(lhs) & static_cast<type>(rhs))); } template<typename E> std::enable_if_t<flags_enable_operators<E>::enable, Flags<E>> operator^(E lhs, E rhs) { using type = std::underlying_type_t<E>; return Flags<E>(static_cast<E>(static_cast<type>(lhs) ^ static_cast<type>(rhs))); } template<typename E> std::enable_if_t<flags_enable_operators<E>::enable, Flags<E>> operator~(E rhs) { using type = std::underlying_type_t<E>; return Flags<E>(static_cast<E>(~static_cast<type>(rhs))); } #define LIBCAMERA_FLAGS_ENABLE_OPERATORS(_enum) \ template<> \ struct flags_enable_operators<_enum> { \ static const bool enable = true; \ }; #else /* __DOXYGEN__ */ #define LIBCAMERA_FLAGS_ENABLE_OPERATORS(_enum) #endif /* __DOXYGEN__ */ } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/event_notifier.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * File descriptor event notifier */ #pragma once #include <libcamera/base/private.h> #include <libcamera/base/object.h> #include <libcamera/base/signal.h> namespace libcamera { class Message; class EventNotifier : public Object { public: enum Type { Read, Write, Exception, }; EventNotifier(int fd, Type type, Object *parent = nullptr); virtual ~EventNotifier(); Type type() const { return type_; } int fd() const { return fd_; } bool enabled() const { return enabled_; } void setEnabled(bool enable); Signal<> activated; protected: void message(Message *msg) override; private: int fd_; Type type_; bool enabled_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/backtrace.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Ideas on Board Oy * * Call stack backtraces */ #pragma once #include <string> #include <vector> #include <libcamera/base/private.h> #include <libcamera/base/class.h> namespace libcamera { class Backtrace { public: Backtrace(); std::string toString(unsigned int skipLevels = 0) const; private: LIBCAMERA_DISABLE_COPY(Backtrace) bool backtraceTrace(); bool unwindTrace(); std::vector<void *> backtrace_; std::vector<std::string> backtraceText_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/shared_fd.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * File descriptor wrapper with shared ownership */ #pragma once #include <memory> namespace libcamera { class UniqueFD; class SharedFD final { public: explicit SharedFD(const int &fd = -1); explicit SharedFD(int &&fd); explicit SharedFD(UniqueFD fd); SharedFD(const SharedFD &other); SharedFD(SharedFD &&other); ~SharedFD(); SharedFD &operator=(const SharedFD &other); SharedFD &operator=(SharedFD &&other); bool isValid() const { return fd_ != nullptr; } int get() const { return fd_ ? fd_->fd() : -1; } UniqueFD dup() const; private: class Descriptor { public: Descriptor(int fd, bool duplicate); ~Descriptor(); int fd() const { return fd_; } private: int fd_; }; std::shared_ptr<Descriptor> fd_; }; static inline bool operator==(const SharedFD &lhs, const SharedFD &rhs) { return lhs.get() == rhs.get(); } static inline bool operator!=(const SharedFD &lhs, const SharedFD &rhs) { return !(lhs == rhs); } } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/bound_method.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Method bind and invocation */ #pragma once #include <memory> #include <tuple> #include <type_traits> #include <utility> namespace libcamera { class Object; enum ConnectionType { ConnectionTypeAuto, ConnectionTypeDirect, ConnectionTypeQueued, ConnectionTypeBlocking, }; class BoundMethodPackBase { public: virtual ~BoundMethodPackBase() = default; }; template<typename R, typename... Args> class BoundMethodPack : public BoundMethodPackBase { public: BoundMethodPack(const Args &... args) : args_(args...) { } R returnValue() { return ret_; } std::tuple<typename std::remove_reference_t<Args>...> args_; R ret_; }; template<typename... Args> class BoundMethodPack<void, Args...> : public BoundMethodPackBase { public: BoundMethodPack(const Args &... args) : args_(args...) { } void returnValue() { } std::tuple<typename std::remove_reference_t<Args>...> args_; }; class BoundMethodBase { public: BoundMethodBase(void *obj, Object *object, ConnectionType type) : obj_(obj), object_(object), connectionType_(type) { } virtual ~BoundMethodBase() = default; template<typename T, std::enable_if_t<!std::is_same<Object, T>::value> * = nullptr> bool match(T *obj) { return obj == obj_; } bool match(Object *object) { return object == object_; } Object *object() const { return object_; } virtual void invokePack(BoundMethodPackBase *pack) = 0; protected: bool activatePack(std::shared_ptr<BoundMethodPackBase> pack, bool deleteMethod); void *obj_; Object *object_; private: ConnectionType connectionType_; }; template<typename R, typename... Args> class BoundMethodArgs : public BoundMethodBase { public: using PackType = BoundMethodPack<R, Args...>; private: template<std::size_t... I, typename T = R> std::enable_if_t<!std::is_void<T>::value, void> invokePack(BoundMethodPackBase *pack, std::index_sequence<I...>) { PackType *args = static_cast<PackType *>(pack); args->ret_ = invoke(std::get<I>(args->args_)...); } template<std::size_t... I, typename T = R> std::enable_if_t<std::is_void<T>::value, void> invokePack(BoundMethodPackBase *pack, std::index_sequence<I...>) { /* args is effectively unused when the sequence I is empty. */ PackType *args [[gnu::unused]] = static_cast<PackType *>(pack); invoke(std::get<I>(args->args_)...); } public: BoundMethodArgs(void *obj, Object *object, ConnectionType type) : BoundMethodBase(obj, object, type) {} void invokePack(BoundMethodPackBase *pack) override { invokePack(pack, std::make_index_sequence<sizeof...(Args)>{}); } virtual R activate(Args... args, bool deleteMethod = false) = 0; virtual R invoke(Args... args) = 0; }; template<typename T, typename R, typename Func, typename... Args> class BoundMethodFunctor : public BoundMethodArgs<R, Args...> { public: using PackType = typename BoundMethodArgs<R, Args...>::PackType; BoundMethodFunctor(T *obj, Object *object, Func func, ConnectionType type = ConnectionTypeAuto) : BoundMethodArgs<R, Args...>(obj, object, type), func_(func) { } R activate(Args... args, bool deleteMethod = false) override { if (!this->object_) return func_(args...); auto pack = std::make_shared<PackType>(args...); bool sync = BoundMethodBase::activatePack(pack, deleteMethod); return sync ? pack->returnValue() : R(); } R invoke(Args... args) override { return func_(args...); } private: Func func_; }; template<typename T, typename R, typename... Args> class BoundMethodMember : public BoundMethodArgs<R, Args...> { public: using PackType = typename BoundMethodArgs<R, Args...>::PackType; BoundMethodMember(T *obj, Object *object, R (T::*func)(Args...), ConnectionType type = ConnectionTypeAuto) : BoundMethodArgs<R, Args...>(obj, object, type), func_(func) { } bool match(R (T::*func)(Args...)) const { return func == func_; } R activate(Args... args, bool deleteMethod = false) override { if (!this->object_) { T *obj = static_cast<T *>(this->obj_); return (obj->*func_)(args...); } auto pack = std::make_shared<PackType>(args...); bool sync = BoundMethodBase::activatePack(pack, deleteMethod); return sync ? pack->returnValue() : R(); } R invoke(Args... args) override { T *obj = static_cast<T *>(this->obj_); return (obj->*func_)(args...); } private: R (T::*func_)(Args...); }; template<typename R, typename... Args> class BoundMethodStatic : public BoundMethodArgs<R, Args...> { public: BoundMethodStatic(R (*func)(Args...)) : BoundMethodArgs<R, Args...>(nullptr, nullptr, ConnectionTypeAuto), func_(func) { } bool match(R (*func)(Args...)) const { return func == func_; } R activate(Args... args, [[maybe_unused]] bool deleteMethod = false) override { return (*func_)(args...); } R invoke(Args...) override { return R(); } private: R (*func_)(Args...); }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/event_dispatcher_poll.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Poll-based event dispatcher */ #pragma once #include <list> #include <map> #include <vector> #include <libcamera/base/private.h> #include <libcamera/base/event_dispatcher.h> #include <libcamera/base/unique_fd.h> struct pollfd; namespace libcamera { class EventNotifier; class Timer; class EventDispatcherPoll final : public EventDispatcher { public: EventDispatcherPoll(); ~EventDispatcherPoll(); void registerEventNotifier(EventNotifier *notifier); void unregisterEventNotifier(EventNotifier *notifier); void registerTimer(Timer *timer); void unregisterTimer(Timer *timer); void processEvents(); void interrupt(); private: struct EventNotifierSetPoll { short events() const; EventNotifier *notifiers[3]; }; int poll(std::vector<struct pollfd> *pollfds); void processInterrupt(const struct pollfd &pfd); void processNotifiers(const std::vector<struct pollfd> &pollfds); void processTimers(); std::map<int, EventNotifierSetPoll> notifiers_; std::list<Timer *> timers_; UniqueFD eventfd_; bool processingEvents_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/log.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * Logging infrastructure */ #pragma once #include <chrono> #include <sstream> #include <libcamera/base/private.h> #include <libcamera/base/class.h> #include <libcamera/base/utils.h> namespace libcamera { enum LogSeverity { LogInvalid = -1, LogDebug = 0, LogInfo, LogWarning, LogError, LogFatal, }; class LogCategory { public: static LogCategory *create(const char *name); const std::string &name() const { return name_; } LogSeverity severity() const { return severity_; } void setSeverity(LogSeverity severity); static const LogCategory &defaultCategory(); private: explicit LogCategory(const char *name); const std::string name_; LogSeverity severity_; }; #define LOG_DECLARE_CATEGORY(name) \ extern const LogCategory &_LOG_CATEGORY(name)(); #define LOG_DEFINE_CATEGORY(name) \ const LogCategory &_LOG_CATEGORY(name)() \ { \ /* The instance will be deleted by the Logger destructor. */ \ static LogCategory *category = LogCategory::create(#name); \ return *category; \ } class LogMessage { public: LogMessage(const char *fileName, unsigned int line, const LogCategory &category, LogSeverity severity, const std::string &prefix = std::string()); LogMessage(LogMessage &&); ~LogMessage(); std::ostream &stream() { return msgStream_; } const utils::time_point &timestamp() const { return timestamp_; } LogSeverity severity() const { return severity_; } const LogCategory &category() const { return category_; } const std::string &fileInfo() const { return fileInfo_; } const std::string &prefix() const { return prefix_; } const std::string msg() const { return msgStream_.str(); } private: LIBCAMERA_DISABLE_COPY(LogMessage) void init(const char *fileName, unsigned int line); std::ostringstream msgStream_; const LogCategory &category_; LogSeverity severity_; utils::time_point timestamp_; std::string fileInfo_; std::string prefix_; }; class Loggable { public: virtual ~Loggable(); protected: virtual std::string logPrefix() const = 0; LogMessage _log(const LogCategory *category, LogSeverity severity, const char *fileName = __builtin_FILE(), unsigned int line = __builtin_LINE()) const; }; LogMessage _log(const LogCategory *category, LogSeverity severity, const char *fileName = __builtin_FILE(), unsigned int line = __builtin_LINE()); #ifndef __DOXYGEN__ #define _LOG_CATEGORY(name) logCategory##name #define _LOG1(severity) \ _log(nullptr, Log##severity).stream() #define _LOG2(category, severity) \ _log(&_LOG_CATEGORY(category)(), Log##severity).stream() /* * Expand the LOG() macro to _LOG1() or _LOG2() based on the number of * arguments. */ #define _LOG_MACRO(_1, _2, NAME, ...) NAME #define LOG(...) _LOG_MACRO(__VA_ARGS__, _LOG2, _LOG1)(__VA_ARGS__) #else /* __DOXYGEN___ */ #define LOG(category, severity) #endif /* __DOXYGEN__ */ #ifndef NDEBUG #define ASSERT(condition) static_cast<void>(({ \ if (!(condition)) \ LOG(Fatal) << "assertion \"" #condition "\" failed in " \ << __func__ << "()"; \ })) #else #define ASSERT(condition) static_cast<void>(false && (condition)) #endif } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/file.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * File I/O operations */ #pragma once #include <sys/types.h> #include <map> #include <string> #include <libcamera/base/private.h> #include <libcamera/base/class.h> #include <libcamera/base/flags.h> #include <libcamera/base/span.h> #include <libcamera/base/unique_fd.h> namespace libcamera { class File { public: enum class MapFlag { NoOption = 0, Private = (1 << 0), }; using MapFlags = Flags<MapFlag>; enum class OpenModeFlag { NotOpen = 0, ReadOnly = (1 << 0), WriteOnly = (1 << 1), ReadWrite = ReadOnly | WriteOnly, }; using OpenMode = Flags<OpenModeFlag>; File(const std::string &name); File(); ~File(); const std::string &fileName() const { return name_; } void setFileName(const std::string &name); bool exists() const; bool open(OpenMode mode); bool isOpen() const { return fd_.isValid(); } OpenMode openMode() const { return mode_; } void close(); int error() const { return error_; } ssize_t size() const; off_t pos() const; off_t seek(off_t pos); ssize_t read(const Span<uint8_t> &data); ssize_t write(const Span<const uint8_t> &data); Span<uint8_t> map(off_t offset = 0, ssize_t size = -1, MapFlags flags = MapFlag::NoOption); bool unmap(uint8_t *addr); static bool exists(const std::string &name); private: LIBCAMERA_DISABLE_COPY(File) void unmapAll(); std::string name_; UniqueFD fd_; OpenMode mode_; int error_; std::map<void *, size_t> maps_; }; LIBCAMERA_FLAGS_ENABLE_OPERATORS(File::MapFlag) LIBCAMERA_FLAGS_ENABLE_OPERATORS(File::OpenModeFlag) } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/message.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Message queue support */ #pragma once #include <atomic> #include <libcamera/base/private.h> #include <libcamera/base/bound_method.h> namespace libcamera { class BoundMethodBase; class Object; class Semaphore; class Thread; class Message { public: enum Type { None = 0, InvokeMessage = 1, ThreadMoveMessage = 2, DeferredDelete = 3, UserMessage = 1000, }; Message(Type type); virtual ~Message(); Type type() const { return type_; } Object *receiver() const { return receiver_; } static Type registerMessageType(); private: friend class Thread; Type type_; Object *receiver_; static std::atomic_uint nextUserType_; }; class InvokeMessage : public Message { public: InvokeMessage(BoundMethodBase *method, std::shared_ptr<BoundMethodPackBase> pack, Semaphore *semaphore = nullptr, bool deleteMethod = false); ~InvokeMessage(); Semaphore *semaphore() const { return semaphore_; } void invoke(); private: BoundMethodBase *method_; std::shared_ptr<BoundMethodPackBase> pack_; Semaphore *semaphore_; bool deleteMethod_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/class.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Utilities and helpers for classes */ #pragma once #include <memory> namespace libcamera { #ifndef __DOXYGEN__ #define LIBCAMERA_DISABLE_COPY(klass) \ klass(const klass &) = delete; \ klass &operator=(const klass &) = delete; #define LIBCAMERA_DISABLE_MOVE(klass) \ klass(klass &&) = delete; \ klass &operator=(klass &&) = delete; #define LIBCAMERA_DISABLE_COPY_AND_MOVE(klass) \ LIBCAMERA_DISABLE_COPY(klass) \ LIBCAMERA_DISABLE_MOVE(klass) #else #define LIBCAMERA_DISABLE_COPY(klass) #define LIBCAMERA_DISABLE_MOVE(klass) #define LIBCAMERA_DISABLE_COPY_AND_MOVE(klass) #endif #ifndef __DOXYGEN__ #define LIBCAMERA_DECLARE_PRIVATE() \ public: \ class Private; \ friend class Private; \ template <bool B = true> \ const Private *_d() const \ { \ return Extensible::_d<Private>(); \ } \ template <bool B = true> \ Private *_d() \ { \ return Extensible::_d<Private>(); \ } #define LIBCAMERA_DECLARE_PUBLIC(klass) \ friend class klass; \ using Public = klass; #define LIBCAMERA_O_PTR() \ _o<Public>() #else #define LIBCAMERA_DECLARE_PRIVATE() #define LIBCAMERA_DECLARE_PUBLIC(klass) #define LIBCAMERA_O_PTR() #endif class Extensible { public: class Private { public: Private(); virtual ~Private(); #ifndef __DOXYGEN__ template<typename T> const T *_o() const { return static_cast<const T *>(o_); } template<typename T> T *_o() { return static_cast<T *>(o_); } #endif private: /* To initialize o_ from Extensible. */ friend class Extensible; Extensible *const o_; }; Extensible(std::unique_ptr<Private> d); protected: template<typename T> const T *_d() const { return static_cast<const T *>(d_.get()); } template<typename T> T *_d() { return static_cast<T *>(d_.get()); } private: const std::unique_ptr<Private> d_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/compiler.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Compiler support */ #pragma once #if __cplusplus >= 201703L #define __nodiscard [[nodiscard]] #else #define __nodiscard #endif
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/object.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Base object */ #pragma once #include <list> #include <memory> #include <vector> #include <libcamera/base/bound_method.h> namespace libcamera { class Message; template<typename... Args> class Signal; class SignalBase; class Thread; class Object { public: Object(Object *parent = nullptr); virtual ~Object(); void deleteLater(); void postMessage(std::unique_ptr<Message> msg); template<typename T, typename R, typename... FuncArgs, typename... Args, std::enable_if_t<std::is_base_of<Object, T>::value> * = nullptr> R invokeMethod(R (T::*func)(FuncArgs...), ConnectionType type, Args&&... args) { T *obj = static_cast<T *>(this); auto *method = new BoundMethodMember<T, R, FuncArgs...>(obj, this, func, type); return method->activate(args..., true); } Thread *thread() const { return thread_; } void moveToThread(Thread *thread); Object *parent() const { return parent_; } protected: virtual void message(Message *msg); bool assertThreadBound(const char *message); private: friend class SignalBase; friend class Thread; void notifyThreadMove(); void connect(SignalBase *signal); void disconnect(SignalBase *signal); Object *parent_; std::vector<Object *> children_; Thread *thread_; std::list<SignalBase *> signals_; unsigned int pendingMessages_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/base/event_dispatcher.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Event dispatcher */ #pragma once #include <vector> #include <libcamera/base/private.h> namespace libcamera { class EventNotifier; class Timer; class EventDispatcher { public: virtual ~EventDispatcher(); virtual void registerEventNotifier(EventNotifier *notifier) = 0; virtual void unregisterEventNotifier(EventNotifier *notifier) = 0; virtual void registerTimer(Timer *timer) = 0; virtual void unregisterTimer(Timer *timer) = 0; virtual void processEvents() = 0; virtual void interrupt() = 0; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/media_object.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * Media Device objects: entities, pads and links. */ #pragma once #include <string> #include <vector> #include <linux/media.h> #include <libcamera/base/class.h> namespace libcamera { class MediaDevice; class MediaEntity; class MediaPad; class MediaObject { public: MediaDevice *device() { return dev_; } const MediaDevice *device() const { return dev_; } unsigned int id() const { return id_; } protected: friend class MediaDevice; MediaObject(MediaDevice *dev, unsigned int id) : dev_(dev), id_(id) { } virtual ~MediaObject() = default; MediaDevice *dev_; unsigned int id_; }; class MediaLink : public MediaObject { public: MediaPad *source() const { return source_; } MediaPad *sink() const { return sink_; } unsigned int flags() const { return flags_; } int setEnabled(bool enable); private: LIBCAMERA_DISABLE_COPY_AND_MOVE(MediaLink) friend class MediaDevice; MediaLink(const struct media_v2_link *link, MediaPad *source, MediaPad *sink); MediaPad *source_; MediaPad *sink_; unsigned int flags_; }; class MediaPad : public MediaObject { public: unsigned int index() const { return index_; } MediaEntity *entity() const { return entity_; } unsigned int flags() const { return flags_; } const std::vector<MediaLink *> &links() const { return links_; } void addLink(MediaLink *link); private: LIBCAMERA_DISABLE_COPY_AND_MOVE(MediaPad) friend class MediaDevice; MediaPad(const struct media_v2_pad *pad, MediaEntity *entity); unsigned int index_; MediaEntity *entity_; unsigned int flags_; std::vector<MediaLink *> links_; }; class MediaEntity : public MediaObject { public: enum class Type { Invalid, MediaEntity, V4L2Subdevice, V4L2VideoDevice, }; const std::string &name() const { return name_; } unsigned int function() const { return function_; } unsigned int flags() const { return flags_; } Type type() const { return type_; } const std::string &deviceNode() const { return deviceNode_; } unsigned int deviceMajor() const { return major_; } unsigned int deviceMinor() const { return minor_; } const std::vector<MediaPad *> &pads() const { return pads_; } const std::vector<MediaEntity *> ancillaryEntities() const { return ancillaryEntities_; } const MediaPad *getPadByIndex(unsigned int index) const; const MediaPad *getPadById(unsigned int id) const; int setDeviceNode(const std::string &deviceNode); private: LIBCAMERA_DISABLE_COPY_AND_MOVE(MediaEntity) friend class MediaDevice; MediaEntity(MediaDevice *dev, const struct media_v2_entity *entity, const struct media_v2_interface *iface); void addPad(MediaPad *pad); void addAncillaryEntity(MediaEntity *ancillaryEntity); std::string name_; unsigned int function_; unsigned int flags_; Type type_; std::string deviceNode_; unsigned int major_; unsigned int minor_; std::vector<MediaPad *> pads_; std::vector<MediaEntity *> ancillaryEntities_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/tracepoints.h.in
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) {{year}}, Google Inc. * * Tracepoints with lttng * * This file is auto-generated. Do not edit. */ #ifndef __LIBCAMERA_INTERNAL_TRACEPOINTS_H__ #define __LIBCAMERA_INTERNAL_TRACEPOINTS_H__ #if HAVE_TRACING #define LIBCAMERA_TRACEPOINT(...) tracepoint(libcamera, __VA_ARGS__) #define LIBCAMERA_TRACEPOINT_IPA_BEGIN(pipe, func) \ tracepoint(libcamera, ipa_call_begin, #pipe, #func) #define LIBCAMERA_TRACEPOINT_IPA_END(pipe, func) \ tracepoint(libcamera, ipa_call_end, #pipe, #func) #else namespace { template <typename ...Args> inline void unused([[maybe_unused]] Args&& ...args) { } } /* namespace */ #define LIBCAMERA_TRACEPOINT(category, ...) unused(__VA_ARGS__) #define LIBCAMERA_TRACEPOINT_IPA_BEGIN(pipe, func) #define LIBCAMERA_TRACEPOINT_IPA_END(pipe, func) #endif /* HAVE_TRACING */ #endif /* __LIBCAMERA_INTERNAL_TRACEPOINTS_H__ */ #if HAVE_TRACING #undef TRACEPOINT_PROVIDER #define TRACEPOINT_PROVIDER libcamera #undef TRACEPOINT_INCLUDE #define TRACEPOINT_INCLUDE "{{path}}" #if !defined(INCLUDE_LIBCAMERA_INTERNAL_TRACEPOINTS_TP_H) || defined(TRACEPOINT_HEADER_MULTI_READ) #define INCLUDE_LIBCAMERA_INTERNAL_TRACEPOINTS_TP_H #include <lttng/tracepoint.h> {{source}} #endif /* INCLUDE_LIBCAMERA_INTERNAL_TRACEPOINTS_TP_H */ #include <lttng/tracepoint-event.h> #endif /* HAVE_TRACING */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/byte_stream_buffer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Byte stream buffer */ #pragma once #include <stddef.h> #include <stdint.h> #include <type_traits> #include <libcamera/base/class.h> #include <libcamera/base/span.h> namespace libcamera { class ByteStreamBuffer { public: ByteStreamBuffer(const uint8_t *base, size_t size); ByteStreamBuffer(uint8_t *base, size_t size); ByteStreamBuffer(ByteStreamBuffer &&other); ByteStreamBuffer &operator=(ByteStreamBuffer &&other); const uint8_t *base() const { return base_; } uint32_t offset() const { return (write_ ? write_ : read_) - base_; } size_t size() const { return size_; } bool overflow() const { return overflow_; } ByteStreamBuffer carveOut(size_t size); int skip(size_t size); template<typename T> int read(T *t) { return read(reinterpret_cast<uint8_t *>(t), sizeof(*t)); } template<typename T> int read(const Span<T> &data) { return read(reinterpret_cast<uint8_t *>(data.data()), data.size_bytes()); } template<typename T> const std::remove_reference_t<T> *read(size_t count = 1) { using return_type = const std::remove_reference_t<T> *; return reinterpret_cast<return_type>(read(sizeof(T), count)); } template<typename T> int write(const T *t) { return write(reinterpret_cast<const uint8_t *>(t), sizeof(*t)); } template<typename T> int write(const Span<T> &data) { return write(reinterpret_cast<const uint8_t *>(data.data()), data.size_bytes()); } private: LIBCAMERA_DISABLE_COPY(ByteStreamBuffer) void setOverflow(); int read(uint8_t *data, size_t size); const uint8_t *read(size_t size, size_t count); int write(const uint8_t *data, size_t size); ByteStreamBuffer *parent_; const uint8_t *base_; size_t size_; bool overflow_; const uint8_t *read_; uint8_t *write_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/device_enumerator_sysfs.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * sysfs-based device enumerator */ #pragma once #include <memory> #include <string> #include "libcamera/internal/device_enumerator.h" class MediaDevice; namespace libcamera { class DeviceEnumeratorSysfs final : public DeviceEnumerator { public: int init(); int enumerate(); private: int populateMediaDevice(MediaDevice *media); std::string lookupDeviceNode(int major, int minor); }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipa_proxy.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Image Processing Algorithm proxy */ #pragma once #include <memory> #include <string> #include <vector> #include <libcamera/ipa/ipa_interface.h> namespace libcamera { class IPAModule; class IPAProxy : public IPAInterface { public: enum ProxyState { ProxyStopped, ProxyStopping, ProxyRunning, }; IPAProxy(IPAModule *ipam); ~IPAProxy(); bool isValid() const { return valid_; } std::string configurationFile(const std::string &file) const; protected: std::string resolvePath(const std::string &file) const; bool valid_; ProxyState state_; private: IPAModule *ipam_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/pub_key.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Public key signature verification */ #pragma once #include <stdint.h> #include <libcamera/base/span.h> #if HAVE_CRYPTO struct evp_pkey_st; #elif HAVE_GNUTLS struct gnutls_pubkey_st; #endif namespace libcamera { class PubKey { public: PubKey(Span<const uint8_t> key); ~PubKey(); bool isValid() const { return valid_; } bool verify(Span<const uint8_t> data, Span<const uint8_t> sig) const; private: bool valid_; #if HAVE_CRYPTO struct evp_pkey_st *pubkey_; #elif HAVE_GNUTLS struct gnutls_pubkey_st *pubkey_; #endif }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Camera private data */ #pragma once #include <atomic> #include <list> #include <memory> #include <set> #include <string> #include <libcamera/base/class.h> #include <libcamera/camera.h> namespace libcamera { class CameraControlValidator; class PipelineHandler; class Stream; class Camera::Private : public Extensible::Private { LIBCAMERA_DECLARE_PUBLIC(Camera) public: Private(PipelineHandler *pipe); ~Private(); PipelineHandler *pipe() { return pipe_.get(); } std::list<Request *> queuedRequests_; ControlInfoMap controlInfo_; ControlList properties_; uint32_t requestSequence_; const CameraControlValidator *validator() const { return validator_.get(); } private: enum State { CameraAvailable, CameraAcquired, CameraConfigured, CameraStopping, CameraRunning, }; bool isAcquired() const; bool isRunning() const; int isAccessAllowed(State state, bool allowDisconnected = false, const char *from = __builtin_FUNCTION()) const; int isAccessAllowed(State low, State high, bool allowDisconnected = false, const char *from = __builtin_FUNCTION()) const; void disconnect(); void setState(State state); std::shared_ptr<PipelineHandler> pipe_; std::string id_; std::set<Stream *> streams_; std::set<const Stream *> activeStreams_; bool disconnected_; std::atomic<State> state_; std::unique_ptr<CameraControlValidator> validator_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/v4l2_device.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Common base for V4L2 video devices and subdevices */ #pragma once #include <map> #include <memory> #include <optional> #include <vector> #include <linux/videodev2.h> #include <libcamera/base/log.h> #include <libcamera/base/signal.h> #include <libcamera/base/span.h> #include <libcamera/base/unique_fd.h> #include <libcamera/color_space.h> #include <libcamera/controls.h> #include "libcamera/internal/formats.h" namespace libcamera { class EventNotifier; class V4L2Device : protected Loggable { public: void close(); bool isOpen() const { return fd_.isValid(); } const ControlInfoMap &controls() const { return controls_; } ControlList getControls(const std::vector<uint32_t> &ids); int setControls(ControlList *ctrls); const struct v4l2_query_ext_ctrl *controlInfo(uint32_t id) const; const std::string &deviceNode() const { return deviceNode_; } std::string devicePath() const; int setFrameStartEnabled(bool enable); Signal<uint32_t> frameStart; void updateControlInfo(); protected: V4L2Device(const std::string &deviceNode); ~V4L2Device(); int open(unsigned int flags); int setFd(UniqueFD fd); int ioctl(unsigned long request, void *argp); int fd() const { return fd_.get(); } template<typename T> static std::optional<ColorSpace> toColorSpace(const T &v4l2Format, PixelFormatInfo::ColourEncoding colourEncoding); template<typename T> static int fromColorSpace(const std::optional<ColorSpace> &colorSpace, T &v4l2Format); private: static ControlType v4l2CtrlType(uint32_t ctrlType); static std::unique_ptr<ControlId> v4l2ControlId(const v4l2_query_ext_ctrl &ctrl); std::optional<ControlInfo> v4l2ControlInfo(const v4l2_query_ext_ctrl &ctrl); std::optional<ControlInfo> v4l2MenuControlInfo(const v4l2_query_ext_ctrl &ctrl); void listControls(); void updateControls(ControlList *ctrls, Span<const v4l2_ext_control> v4l2Ctrls); void eventAvailable(); std::map<unsigned int, struct v4l2_query_ext_ctrl> controlInfo_; std::vector<std::unique_ptr<ControlId>> controlIds_; ControlIdMap controlIdMap_; ControlInfoMap controls_; std::string deviceNode_; UniqueFD fd_; EventNotifier *fdEventNotifier_; bool frameStartEnabled_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipa_manager.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Image Processing Algorithm module manager */ #pragma once #include <stdint.h> #include <vector> #include <libcamera/base/log.h> #include <libcamera/ipa/ipa_interface.h> #include <libcamera/ipa/ipa_module_info.h> #include "libcamera/internal/ipa_module.h" #include "libcamera/internal/pipeline_handler.h" #include "libcamera/internal/pub_key.h" namespace libcamera { LOG_DECLARE_CATEGORY(IPAManager) class IPAManager { public: IPAManager(); ~IPAManager(); template<typename T> static std::unique_ptr<T> createIPA(PipelineHandler *pipe, uint32_t minVersion, uint32_t maxVersion) { IPAModule *m = self_->module(pipe, minVersion, maxVersion); if (!m) return nullptr; std::unique_ptr<T> proxy = std::make_unique<T>(m, !self_->isSignatureValid(m)); if (!proxy->isValid()) { LOG(IPAManager, Error) << "Failed to load proxy"; return nullptr; } return proxy; } #if HAVE_IPA_PUBKEY static const PubKey &pubKey() { return pubKey_; } #endif private: static IPAManager *self_; void parseDir(const char *libDir, unsigned int maxDepth, std::vector<std::string> &files); unsigned int addDir(const char *libDir, unsigned int maxDepth = 0); IPAModule *module(PipelineHandler *pipe, uint32_t minVersion, uint32_t maxVersion); bool isSignatureValid(IPAModule *ipa) const; std::vector<IPAModule *> modules_; #if HAVE_IPA_PUBKEY static const uint8_t publicKeyData_[]; static const PubKey pubKey_; #endif }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/control_validator.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Control validator */ #pragma once #include <string> namespace libcamera { class ControlId; class ControlValidator { public: virtual ~ControlValidator() = default; virtual const std::string &name() const = 0; virtual bool validate(unsigned int id) const = 0; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera_lens.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * A camera lens controller */ #pragma once #include <memory> #include <string> #include <libcamera/base/class.h> #include <libcamera/base/log.h> #include <libcamera/controls.h> namespace libcamera { class MediaEntity; class V4L2Subdevice; class CameraLens : protected Loggable { public: explicit CameraLens(const MediaEntity *entity); ~CameraLens(); int init(); int setFocusPosition(int32_t position); const std::string &model() const { return model_; } const ControlInfoMap &controls() const; protected: std::string logPrefix() const override; private: LIBCAMERA_DISABLE_COPY_AND_MOVE(CameraLens) int validateLensDriver(); const MediaEntity *entity_; std::unique_ptr<V4L2Subdevice> subdev_; std::string model_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/pipeline_handler.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * Pipeline handler infrastructure */ #pragma once #include <memory> #include <queue> #include <set> #include <string> #include <sys/types.h> #include <vector> #include <libcamera/base/mutex.h> #include <libcamera/base/object.h> #include <libcamera/controls.h> #include <libcamera/stream.h> #include "libcamera/internal/ipa_proxy.h" namespace libcamera { class Camera; class CameraConfiguration; class CameraManager; class DeviceEnumerator; class DeviceMatch; class FrameBuffer; class MediaDevice; class PipelineHandler; class Request; class PipelineHandler : public std::enable_shared_from_this<PipelineHandler>, public Object { public: PipelineHandler(CameraManager *manager); virtual ~PipelineHandler(); virtual bool match(DeviceEnumerator *enumerator) = 0; MediaDevice *acquireMediaDevice(DeviceEnumerator *enumerator, const DeviceMatch &dm); bool acquire(); void release(Camera *camera); virtual std::unique_ptr<CameraConfiguration> generateConfiguration(Camera *camera, Span<const StreamRole> roles) = 0; virtual int configure(Camera *camera, CameraConfiguration *config) = 0; virtual int exportFrameBuffers(Camera *camera, Stream *stream, std::vector<std::unique_ptr<FrameBuffer>> *buffers) = 0; virtual int start(Camera *camera, const ControlList *controls) = 0; void stop(Camera *camera); bool hasPendingRequests(const Camera *camera) const; void registerRequest(Request *request); void queueRequest(Request *request); bool completeBuffer(Request *request, FrameBuffer *buffer); void completeRequest(Request *request); std::string configurationFile(const std::string &subdir, const std::string &name) const; const char *name() const { return name_; } protected: void registerCamera(std::shared_ptr<Camera> camera); void hotplugMediaDevice(MediaDevice *media); virtual int queueRequestDevice(Camera *camera, Request *request) = 0; virtual void stopDevice(Camera *camera) = 0; virtual void releaseDevice(Camera *camera); CameraManager *manager_; private: void unlockMediaDevices(); void mediaDeviceDisconnected(MediaDevice *media); virtual void disconnect(); void doQueueRequest(Request *request); void doQueueRequests(); std::vector<std::shared_ptr<MediaDevice>> mediaDevices_; std::vector<std::weak_ptr<Camera>> cameras_; std::queue<Request *> waitingRequests_; const char *name_; Mutex lock_; unsigned int useCount_ LIBCAMERA_TSA_GUARDED_BY(lock_); friend class PipelineHandlerFactoryBase; }; class PipelineHandlerFactoryBase { public: PipelineHandlerFactoryBase(const char *name); virtual ~PipelineHandlerFactoryBase() = default; std::shared_ptr<PipelineHandler> create(CameraManager *manager) const; const std::string &name() const { return name_; } static std::vector<PipelineHandlerFactoryBase *> &factories(); static const PipelineHandlerFactoryBase *getFactoryByName(const std::string &name); private: static void registerType(PipelineHandlerFactoryBase *factory); virtual std::unique_ptr<PipelineHandler> createInstance(CameraManager *manager) const = 0; std::string name_; }; template<typename _PipelineHandler> class PipelineHandlerFactory final : public PipelineHandlerFactoryBase { public: PipelineHandlerFactory(const char *name) : PipelineHandlerFactoryBase(name) { } std::unique_ptr<PipelineHandler> createInstance(CameraManager *manager) const override { return std::make_unique<_PipelineHandler>(manager); } }; #define REGISTER_PIPELINE_HANDLER(handler, name) \ static PipelineHandlerFactory<handler> global_##handler##Factory(name); } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/mapped_framebuffer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Frame buffer memory mapping support */ #pragma once #include <stdint.h> #include <vector> #include <libcamera/base/class.h> #include <libcamera/base/flags.h> #include <libcamera/base/span.h> #include <libcamera/framebuffer.h> namespace libcamera { class MappedBuffer { public: using Plane = Span<uint8_t>; ~MappedBuffer(); MappedBuffer(MappedBuffer &&other); MappedBuffer &operator=(MappedBuffer &&other); bool isValid() const { return error_ == 0; } int error() const { return error_; } const std::vector<Plane> &planes() const { return planes_; } protected: MappedBuffer(); int error_; std::vector<Plane> planes_; std::vector<Plane> maps_; private: LIBCAMERA_DISABLE_COPY(MappedBuffer) }; class MappedFrameBuffer : public MappedBuffer { public: enum class MapFlag { Read = 1 << 0, Write = 1 << 1, ReadWrite = Read | Write, }; using MapFlags = Flags<MapFlag>; MappedFrameBuffer(const FrameBuffer *buffer, MapFlags flags); }; LIBCAMERA_FLAGS_ENABLE_OPERATORS(MappedFrameBuffer::MapFlag) } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/framebuffer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Internal frame buffer handling */ #pragma once #include <memory> #include <utility> #include <libcamera/base/class.h> #include <libcamera/fence.h> #include <libcamera/framebuffer.h> namespace libcamera { class FrameBuffer::Private : public Extensible::Private { LIBCAMERA_DECLARE_PUBLIC(FrameBuffer) public: Private(const std::vector<Plane> &planes, uint64_t cookie = 0); virtual ~Private(); void setRequest(Request *request) { request_ = request; } bool isContiguous() const { return isContiguous_; } Fence *fence() const { return fence_.get(); } void setFence(std::unique_ptr<Fence> fence) { fence_ = std::move(fence); } void cancel() { metadata_.status = FrameMetadata::FrameCancelled; } FrameMetadata &metadata() { return metadata_; } private: std::vector<Plane> planes_; FrameMetadata metadata_; uint64_t cookie_; std::unique_ptr<Fence> fence_; Request *request_; bool isContiguous_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipc_pipe.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Image Processing Algorithm IPC module for IPA proxies */ #pragma once #include <vector> #include <libcamera/base/shared_fd.h> #include <libcamera/base/signal.h> #include "libcamera/internal/ipc_unixsocket.h" namespace libcamera { class IPCMessage { public: struct Header { uint32_t cmd; uint32_t cookie; }; IPCMessage(); IPCMessage(uint32_t cmd); IPCMessage(const Header &header); IPCMessage(IPCUnixSocket::Payload &payload); IPCUnixSocket::Payload payload() const; Header &header() { return header_; } std::vector<uint8_t> &data() { return data_; } std::vector<SharedFD> &fds() { return fds_; } const Header &header() const { return header_; } const std::vector<uint8_t> &data() const { return data_; } const std::vector<SharedFD> &fds() const { return fds_; } private: Header header_; std::vector<uint8_t> data_; std::vector<SharedFD> fds_; }; class IPCPipe { public: IPCPipe(); virtual ~IPCPipe(); bool isConnected() const { return connected_; } virtual int sendSync(const IPCMessage &in, IPCMessage *out) = 0; virtual int sendAsync(const IPCMessage &data) = 0; Signal<const IPCMessage &> recv; protected: bool connected_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera_sensor.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * A camera sensor */ #pragma once #include <memory> #include <string> #include <vector> #include <libcamera/base/class.h> #include <libcamera/base/log.h> #include <libcamera/control_ids.h> #include <libcamera/controls.h> #include <libcamera/geometry.h> #include <libcamera/orientation.h> #include <libcamera/transform.h> #include <libcamera/ipa/core_ipa_interface.h> #include "libcamera/internal/bayer_format.h" #include "libcamera/internal/formats.h" #include "libcamera/internal/v4l2_subdevice.h" namespace libcamera { class CameraLens; class MediaEntity; class SensorConfiguration; struct CameraSensorProperties; enum class Orientation; class CameraSensor : protected Loggable { public: explicit CameraSensor(const MediaEntity *entity); ~CameraSensor(); int init(); const std::string &model() const { return model_; } const std::string &id() const { return id_; } const MediaEntity *entity() const { return entity_; } V4L2Subdevice *device() { return subdev_.get(); } CameraLens *focusLens() { return focusLens_.get(); } const std::vector<unsigned int> &mbusCodes() const { return mbusCodes_; } std::vector<Size> sizes(unsigned int mbusCode) const; Size resolution() const; V4L2SubdeviceFormat getFormat(const std::vector<unsigned int> &mbusCodes, const Size &size) const; int setFormat(V4L2SubdeviceFormat *format, Transform transform = Transform::Identity); int tryFormat(V4L2SubdeviceFormat *format) const; int applyConfiguration(const SensorConfiguration &config, Transform transform = Transform::Identity, V4L2SubdeviceFormat *sensorFormat = nullptr); const ControlList &properties() const { return properties_; } int sensorInfo(IPACameraSensorInfo *info) const; Transform computeTransform(Orientation *orientation) const; BayerFormat::Order bayerOrder(Transform t) const; const ControlInfoMap &controls() const; ControlList getControls(const std::vector<uint32_t> &ids); int setControls(ControlList *ctrls); const std::vector<controls::draft::TestPatternModeEnum> &testPatternModes() const { return testPatternModes_; } int setTestPatternMode(controls::draft::TestPatternModeEnum mode); protected: std::string logPrefix() const override; private: LIBCAMERA_DISABLE_COPY(CameraSensor) int generateId(); int validateSensorDriver(); void initVimcDefaultProperties(); void initStaticProperties(); void initTestPatternModes(); int initProperties(); int discoverAncillaryDevices(); int applyTestPatternMode(controls::draft::TestPatternModeEnum mode); const MediaEntity *entity_; std::unique_ptr<V4L2Subdevice> subdev_; unsigned int pad_; const CameraSensorProperties *staticProps_; std::string model_; std::string id_; V4L2Subdevice::Formats formats_; std::vector<unsigned int> mbusCodes_; std::vector<Size> sizes_; std::vector<controls::draft::TestPatternModeEnum> testPatternModes_; controls::draft::TestPatternModeEnum testPatternMode_; Size pixelArraySize_; Rectangle activeArea_; const BayerFormat *bayerFormat_; bool supportFlips_; bool flipsAlterBayerOrder_; Orientation mountingOrientation_; ControlList properties_; std::unique_ptr<CameraLens> focusLens_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/shared_mem_object.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2023 Raspberry Pi Ltd * Copyright (C) 2024 Andrei Konovalov * Copyright (C) 2024 Dennis Bonke * * Helpers for shared memory allocations */ #pragma once #include <stddef.h> #include <stdint.h> #include <string> #include <sys/mman.h> #include <type_traits> #include <utility> #include <libcamera/base/class.h> #include <libcamera/base/shared_fd.h> #include <libcamera/base/span.h> namespace libcamera { class SharedMem { public: SharedMem(); SharedMem(const std::string &name, std::size_t size); SharedMem(SharedMem &&rhs); virtual ~SharedMem(); SharedMem &operator=(SharedMem &&rhs); const SharedFD &fd() const { return fd_; } Span<uint8_t> mem() const { return mem_; } explicit operator bool() const { return !mem_.empty(); } private: LIBCAMERA_DISABLE_COPY(SharedMem) SharedFD fd_; Span<uint8_t> mem_; }; template<class T, typename = std::enable_if_t<std::is_standard_layout<T>::value>> class SharedMemObject : public SharedMem { public: static constexpr std::size_t kSize = sizeof(T); SharedMemObject() : SharedMem(), obj_(nullptr) { } template<class... Args> SharedMemObject(const std::string &name, Args &&...args) : SharedMem(name, kSize), obj_(nullptr) { if (mem().empty()) return; obj_ = new (mem().data()) T(std::forward<Args>(args)...); } SharedMemObject(SharedMemObject<T> &&rhs) : SharedMem(std::move(rhs)) { this->obj_ = rhs.obj_; rhs.obj_ = nullptr; } ~SharedMemObject() { if (obj_) obj_->~T(); } SharedMemObject<T> &operator=(SharedMemObject<T> &&rhs) { SharedMem::operator=(std::move(rhs)); this->obj_ = rhs.obj_; rhs.obj_ = nullptr; return *this; } T *operator->() { return obj_; } const T *operator->() const { return obj_; } T &operator*() { return *obj_; } const T &operator*() const { return *obj_; } private: LIBCAMERA_DISABLE_COPY(SharedMemObject) T *obj_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/media_device.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * Media device handler */ #pragma once #include <map> #include <sstream> #include <string> #include <vector> #include <linux/media.h> #include <libcamera/base/log.h> #include <libcamera/base/signal.h> #include <libcamera/base/unique_fd.h> #include "libcamera/internal/media_object.h" namespace libcamera { class MediaDevice : protected Loggable { public: MediaDevice(const std::string &deviceNode); ~MediaDevice(); bool acquire(); void release(); bool busy() const { return acquired_; } bool lock(); void unlock(); int populate(); bool isValid() const { return valid_; } const std::string &driver() const { return driver_; } const std::string &deviceNode() const { return deviceNode_; } const std::string &model() const { return model_; } unsigned int version() const { return version_; } unsigned int hwRevision() const { return hwRevision_; } const std::vector<MediaEntity *> &entities() const { return entities_; } MediaEntity *getEntityByName(const std::string &name) const; MediaLink *link(const std::string &sourceName, unsigned int sourceIdx, const std::string &sinkName, unsigned int sinkIdx); MediaLink *link(const MediaEntity *source, unsigned int sourceIdx, const MediaEntity *sink, unsigned int sinkIdx); MediaLink *link(const MediaPad *source, const MediaPad *sink); int disableLinks(); Signal<> disconnected; protected: std::string logPrefix() const override; private: int open(); void close(); MediaObject *object(unsigned int id); bool addObject(MediaObject *object); void clear(); struct media_v2_interface *findInterface(const struct media_v2_topology &topology, unsigned int entityId); bool populateEntities(const struct media_v2_topology &topology); bool populatePads(const struct media_v2_topology &topology); bool populateLinks(const struct media_v2_topology &topology); void fixupEntityFlags(struct media_v2_entity *entity); friend int MediaLink::setEnabled(bool enable); int setupLink(const MediaLink *link, unsigned int flags); std::string driver_; std::string deviceNode_; std::string model_; unsigned int version_; unsigned int hwRevision_; UniqueFD fd_; bool valid_; bool acquired_; std::map<unsigned int, MediaObject *> objects_; std::vector<MediaEntity *> entities_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/device_enumerator_udev.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018-2019, Google Inc. * * udev-based device enumerator */ #pragma once #include <list> #include <map> #include <memory> #include <set> #include <string> #include <sys/types.h> #include "libcamera/internal/device_enumerator.h" struct udev; struct udev_device; struct udev_monitor; namespace libcamera { class EventNotifier; class MediaDevice; class MediaEntity; class DeviceEnumeratorUdev final : public DeviceEnumerator { public: DeviceEnumeratorUdev(); ~DeviceEnumeratorUdev(); int init(); int enumerate(); private: using DependencyMap = std::map<dev_t, std::list<MediaEntity *>>; struct MediaDeviceDeps { MediaDeviceDeps(std::unique_ptr<MediaDevice> media, DependencyMap deps) : media_(std::move(media)), deps_(std::move(deps)) { } bool operator==(const MediaDeviceDeps &other) const { return media_ == other.media_; } std::unique_ptr<MediaDevice> media_; DependencyMap deps_; }; int addUdevDevice(struct udev_device *dev); int populateMediaDevice(MediaDevice *media, DependencyMap *deps); std::string lookupDeviceNode(dev_t devnum); int addV4L2Device(dev_t devnum); void udevNotify(); struct udev *udev_; struct udev_monitor *monitor_; EventNotifier *notifier_; std::set<dev_t> orphans_; std::list<MediaDeviceDeps> pending_; std::map<dev_t, MediaDeviceDeps *> devMap_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/v4l2_videodevice.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * V4L2 Video Device */ #pragma once #include <array> #include <atomic> #include <memory> #include <optional> #include <ostream> #include <stdint.h> #include <string> #include <unordered_set> #include <vector> #include <linux/videodev2.h> #include <libcamera/base/class.h> #include <libcamera/base/log.h> #include <libcamera/base/signal.h> #include <libcamera/base/timer.h> #include <libcamera/base/unique_fd.h> #include <libcamera/base/utils.h> #include <libcamera/color_space.h> #include <libcamera/framebuffer.h> #include <libcamera/geometry.h> #include <libcamera/pixel_format.h> #include "libcamera/internal/formats.h" #include "libcamera/internal/v4l2_device.h" #include "libcamera/internal/v4l2_pixelformat.h" namespace libcamera { class EventNotifier; class MediaDevice; class MediaEntity; struct V4L2Capability final : v4l2_capability { const char *driver() const { return reinterpret_cast<const char *>(v4l2_capability::driver); } const char *card() const { return reinterpret_cast<const char *>(v4l2_capability::card); } const char *bus_info() const { return reinterpret_cast<const char *>(v4l2_capability::bus_info); } unsigned int device_caps() const { return capabilities & V4L2_CAP_DEVICE_CAPS ? v4l2_capability::device_caps : v4l2_capability::capabilities; } bool isMultiplanar() const { return device_caps() & (V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_VIDEO_M2M_MPLANE); } bool isCapture() const { return device_caps() & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_META_CAPTURE); } bool isOutput() const { return device_caps() & (V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_META_OUTPUT); } bool isVideo() const { return device_caps() & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OUTPUT_MPLANE); } bool isM2M() const { return device_caps() & (V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE); } bool isMeta() const { return device_caps() & (V4L2_CAP_META_CAPTURE | V4L2_CAP_META_OUTPUT); } bool isVideoCapture() const { return isVideo() && isCapture(); } bool isVideoOutput() const { return isVideo() && isOutput(); } bool isMetaCapture() const { return isMeta() && isCapture(); } bool isMetaOutput() const { return isMeta() && isOutput(); } bool hasStreaming() const { return device_caps() & V4L2_CAP_STREAMING; } bool hasMediaController() const { return device_caps() & V4L2_CAP_IO_MC; } }; class V4L2BufferCache { public: V4L2BufferCache(unsigned int numEntries); V4L2BufferCache(const std::vector<std::unique_ptr<FrameBuffer>> &buffers); ~V4L2BufferCache(); bool isEmpty() const; int get(const FrameBuffer &buffer); void put(unsigned int index); private: class Entry { public: Entry(); Entry(bool free, uint64_t lastUsed, const FrameBuffer &buffer); bool operator==(const FrameBuffer &buffer) const; bool free_; uint64_t lastUsed_; private: struct Plane { Plane(const FrameBuffer::Plane &plane) : fd(plane.fd.get()), length(plane.length) { } int fd; unsigned int length; }; std::vector<Plane> planes_; }; std::atomic<uint64_t> lastUsedCounter_; std::vector<Entry> cache_; /* \todo Expose the miss counter through an instrumentation API. */ unsigned int missCounter_; }; class V4L2DeviceFormat { public: struct Plane { uint32_t size = 0; uint32_t bpl = 0; }; V4L2PixelFormat fourcc; Size size; std::optional<ColorSpace> colorSpace; std::array<Plane, 3> planes; unsigned int planesCount = 0; const std::string toString() const; }; std::ostream &operator<<(std::ostream &out, const V4L2DeviceFormat &f); class V4L2VideoDevice : public V4L2Device { public: using Formats = std::map<V4L2PixelFormat, std::vector<SizeRange>>; explicit V4L2VideoDevice(const std::string &deviceNode); explicit V4L2VideoDevice(const MediaEntity *entity); ~V4L2VideoDevice(); int open(); int open(SharedFD handle, enum v4l2_buf_type type); void close(); const char *driverName() const { return caps_.driver(); } const char *deviceName() const { return caps_.card(); } const char *busName() const { return caps_.bus_info(); } const V4L2Capability &caps() const { return caps_; } int getFormat(V4L2DeviceFormat *format); int tryFormat(V4L2DeviceFormat *format); int setFormat(V4L2DeviceFormat *format); Formats formats(uint32_t code = 0); int setSelection(unsigned int target, Rectangle *rect); int allocateBuffers(unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); int exportBuffers(unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); int importBuffers(unsigned int count); int releaseBuffers(); int queueBuffer(FrameBuffer *buffer); Signal<FrameBuffer *> bufferReady; int streamOn(); int streamOff(); void setDequeueTimeout(utils::Duration timeout); Signal<> dequeueTimeout; static std::unique_ptr<V4L2VideoDevice> fromEntityName(const MediaDevice *media, const std::string &entity); V4L2PixelFormat toV4L2PixelFormat(const PixelFormat &pixelFormat) const; protected: std::string logPrefix() const override; private: LIBCAMERA_DISABLE_COPY(V4L2VideoDevice) enum class State { Streaming, Stopping, Stopped, }; int initFormats(); int getFormatMeta(V4L2DeviceFormat *format); int trySetFormatMeta(V4L2DeviceFormat *format, bool set); int getFormatMultiplane(V4L2DeviceFormat *format); int trySetFormatMultiplane(V4L2DeviceFormat *format, bool set); int getFormatSingleplane(V4L2DeviceFormat *format); int trySetFormatSingleplane(V4L2DeviceFormat *format, bool set); std::vector<V4L2PixelFormat> enumPixelformats(uint32_t code); std::vector<SizeRange> enumSizes(V4L2PixelFormat pixelFormat); int requestBuffers(unsigned int count, enum v4l2_memory memoryType); int createBuffers(unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); std::unique_ptr<FrameBuffer> createBuffer(unsigned int index); UniqueFD exportDmabufFd(unsigned int index, unsigned int plane); void bufferAvailable(); FrameBuffer *dequeueBuffer(); void watchdogExpired(); template<typename T> static std::optional<ColorSpace> toColorSpace(const T &v4l2Format); V4L2Capability caps_; V4L2DeviceFormat format_; const PixelFormatInfo *formatInfo_; std::unordered_set<V4L2PixelFormat> pixelFormats_; enum v4l2_buf_type bufferType_; enum v4l2_memory memoryType_; V4L2BufferCache *cache_; std::map<unsigned int, FrameBuffer *> queuedBuffers_; EventNotifier *fdBufferNotifier_; State state_; std::optional<unsigned int> firstFrame_; Timer watchdog_; utils::Duration watchdogDuration_; }; class V4L2M2MDevice { public: V4L2M2MDevice(const std::string &deviceNode); ~V4L2M2MDevice(); int open(); void close(); V4L2VideoDevice *output() { return output_; } V4L2VideoDevice *capture() { return capture_; } private: std::string deviceNode_; V4L2VideoDevice *output_; V4L2VideoDevice *capture_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/process.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Process object */ #pragma once #include <signal.h> #include <string> #include <vector> #include <libcamera/base/signal.h> #include <libcamera/base/unique_fd.h> namespace libcamera { class EventNotifier; class Process final { public: enum ExitStatus { NotExited, NormalExit, SignalExit, }; Process(); ~Process(); int start(const std::string &path, const std::vector<std::string> &args = std::vector<std::string>(), const std::vector<int> &fds = std::vector<int>()); ExitStatus exitStatus() const { return exitStatus_; } int exitCode() const { return exitCode_; } void kill(); Signal<enum ExitStatus, int> finished; private: void closeAllFdsExcept(const std::vector<int> &fds); int isolate(); void died(int wstatus); pid_t pid_; bool running_; enum ExitStatus exitStatus_; int exitCode_; friend class ProcessManager; }; class ProcessManager { public: ProcessManager(); ~ProcessManager(); void registerProcess(Process *proc); static ProcessManager *instance(); int writePipe() const; const struct sigaction &oldsa() const; private: static ProcessManager *self_; void sighandler(); std::list<Process *> processes_; struct sigaction oldsa_; EventNotifier *sigEvent_; UniqueFD pipe_[2]; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/converter.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Laurent Pinchart * Copyright 2022 NXP * * Generic format converter interface */ #pragma once #include <functional> #include <initializer_list> #include <map> #include <memory> #include <string> #include <tuple> #include <vector> #include <libcamera/base/class.h> #include <libcamera/base/signal.h> #include <libcamera/geometry.h> namespace libcamera { class FrameBuffer; class MediaDevice; class PixelFormat; struct StreamConfiguration; class Converter { public: Converter(MediaDevice *media); virtual ~Converter(); virtual int loadConfiguration(const std::string &filename) = 0; virtual bool isValid() const = 0; virtual std::vector<PixelFormat> formats(PixelFormat input) = 0; virtual SizeRange sizes(const Size &input) = 0; virtual std::tuple<unsigned int, unsigned int> strideAndFrameSize(const PixelFormat &pixelFormat, const Size &size) = 0; virtual int configure(const StreamConfiguration &inputCfg, const std::vector<std::reference_wrapper<StreamConfiguration>> &outputCfgs) = 0; virtual int exportBuffers(unsigned int output, unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers) = 0; virtual int start() = 0; virtual void stop() = 0; virtual int queueBuffers(FrameBuffer *input, const std::map<unsigned int, FrameBuffer *> &outputs) = 0; Signal<FrameBuffer *> inputBufferReady; Signal<FrameBuffer *> outputBufferReady; const std::string &deviceNode() const { return deviceNode_; } private: std::string deviceNode_; }; class ConverterFactoryBase { public: ConverterFactoryBase(const std::string name, std::initializer_list<std::string> compatibles); virtual ~ConverterFactoryBase() = default; const std::vector<std::string> &compatibles() const { return compatibles_; } static std::unique_ptr<Converter> create(MediaDevice *media); static std::vector<ConverterFactoryBase *> &factories(); static std::vector<std::string> names(); private: LIBCAMERA_DISABLE_COPY_AND_MOVE(ConverterFactoryBase) static void registerType(ConverterFactoryBase *factory); virtual std::unique_ptr<Converter> createInstance(MediaDevice *media) const = 0; std::string name_; std::vector<std::string> compatibles_; }; template<typename _Converter> class ConverterFactory : public ConverterFactoryBase { public: ConverterFactory(const char *name, std::initializer_list<std::string> compatibles) : ConverterFactoryBase(name, compatibles) { } std::unique_ptr<Converter> createInstance(MediaDevice *media) const override { return std::make_unique<_Converter>(media); } }; #define REGISTER_CONVERTER(name, converter, compatibles) \ static ConverterFactory<converter> global_##converter##Factory(name, compatibles); } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/sysfs.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Miscellaneous utility functions to access sysfs */ #pragma once #include <string> namespace libcamera { namespace sysfs { std::string charDevPath(const std::string &deviceNode); std::string firmwareNodePath(const std::string &device); } /* namespace sysfs */ } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/bayer_format.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Raspberry Pi Ltd * * Bayer Pixel Format */ #pragma once #include <ostream> #include <stdint.h> #include <string> #include <libcamera/pixel_format.h> #include "libcamera/internal/v4l2_pixelformat.h" namespace libcamera { enum class Transform; class BayerFormat { public: enum Order : uint8_t { BGGR = 0, GBRG = 1, GRBG = 2, RGGB = 3, MONO = 4 }; enum class Packing : uint16_t { None = 0, CSI2 = 1, IPU3 = 2, PISP1 = 3, PISP2 = 4, }; constexpr BayerFormat() : order(Order::BGGR), bitDepth(0), packing(Packing::None) { } constexpr BayerFormat(Order o, uint8_t b, Packing p) : order(o), bitDepth(b), packing(p) { } static const BayerFormat &fromMbusCode(unsigned int mbusCode); bool isValid() const { return bitDepth != 0; } std::string toString() const; V4L2PixelFormat toV4L2PixelFormat() const; static BayerFormat fromV4L2PixelFormat(V4L2PixelFormat v4l2Format); PixelFormat toPixelFormat() const; static BayerFormat fromPixelFormat(PixelFormat format); BayerFormat transform(Transform t) const; Order order; uint8_t bitDepth; Packing packing; }; bool operator==(const BayerFormat &lhs, const BayerFormat &rhs); static inline bool operator!=(const BayerFormat &lhs, const BayerFormat &rhs) { return !(lhs == rhs); } std::ostream &operator<<(std::ostream &out, const BayerFormat &f); } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/yaml_parser.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2022, Google Inc. * * libcamera YAML parsing helper */ #pragma once #include <iterator> #include <map> #include <optional> #include <string> #include <vector> #include <libcamera/base/class.h> #include <libcamera/geometry.h> namespace libcamera { class File; class YamlParserContext; class YamlObject { private: struct Value { Value(std::string &&k, std::unique_ptr<YamlObject> &&v) : key(std::move(k)), value(std::move(v)) { } std::string key; std::unique_ptr<YamlObject> value; }; using Container = std::vector<Value>; using ListContainer = std::vector<std::unique_ptr<YamlObject>>; public: #ifndef __DOXYGEN__ template<typename Derived> class Iterator { public: using difference_type = std::ptrdiff_t; using iterator_category = std::forward_iterator_tag; Iterator(typename Container::const_iterator it) : it_(it) { } Derived &operator++() { ++it_; return *static_cast<Derived *>(this); } Derived operator++(int) { Derived it = *static_cast<Derived *>(this); it_++; return it; } friend bool operator==(const Iterator &a, const Iterator &b) { return a.it_ == b.it_; } friend bool operator!=(const Iterator &a, const Iterator &b) { return a.it_ != b.it_; } protected: Container::const_iterator it_; }; template<typename Iterator> class Adapter { public: Adapter(const Container &container) : container_(container) { } Iterator begin() const { return Iterator{ container_.begin() }; } Iterator end() const { return Iterator{ container_.end() }; } protected: const Container &container_; }; class ListIterator : public Iterator<ListIterator> { public: using value_type = const YamlObject &; using pointer = const YamlObject *; using reference = value_type; value_type operator*() const { return *it_->value.get(); } pointer operator->() const { return it_->value.get(); } }; class DictIterator : public Iterator<DictIterator> { public: using value_type = std::pair<const std::string &, const YamlObject &>; using pointer = value_type *; using reference = value_type &; value_type operator*() const { return { it_->key, *it_->value.get() }; } }; class DictAdapter : public Adapter<DictIterator> { public: using key_type = std::string; }; class ListAdapter : public Adapter<ListIterator> { }; #endif /* __DOXYGEN__ */ YamlObject(); ~YamlObject(); bool isValue() const { return type_ == Type::Value; } bool isList() const { return type_ == Type::List; } bool isDictionary() const { return type_ == Type::Dictionary; } std::size_t size() const; template<typename T> std::optional<T> get() const { return Getter<T>{}.get(*this); } template<typename T, typename U> T get(U &&defaultValue) const { return get<T>().value_or(std::forward<U>(defaultValue)); } #ifndef __DOXYGEN__ template<typename T, std::enable_if_t< std::is_same_v<bool, T> || std::is_same_v<float, T> || std::is_same_v<double, T> || std::is_same_v<int8_t, T> || std::is_same_v<uint8_t, T> || std::is_same_v<int16_t, T> || std::is_same_v<uint16_t, T> || std::is_same_v<int32_t, T> || std::is_same_v<uint32_t, T> || std::is_same_v<std::string, T> || std::is_same_v<Size, T>> * = nullptr> #else template<typename T> #endif std::optional<std::vector<T>> getList() const; DictAdapter asDict() const { return DictAdapter{ list_ }; } ListAdapter asList() const { return ListAdapter{ list_ }; } const YamlObject &operator[](std::size_t index) const; bool contains(const std::string &key) const; const YamlObject &operator[](const std::string &key) const; private: LIBCAMERA_DISABLE_COPY_AND_MOVE(YamlObject) template<typename T> friend struct Getter; friend class YamlParserContext; enum class Type { Dictionary, List, Value, }; template<typename T> struct Getter { std::optional<T> get(const YamlObject &obj) const; }; Type type_; std::string value_; Container list_; std::map<std::string, YamlObject *> dictionary_; }; class YamlParser final { public: static std::unique_ptr<YamlObject> parse(File &file); }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/request.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Request class private data */ #pragma once #include <chrono> #include <map> #include <memory> #include <libcamera/base/event_notifier.h> #include <libcamera/base/timer.h> #include <libcamera/request.h> using namespace std::chrono_literals; namespace libcamera { class Camera; class FrameBuffer; class Request::Private : public Extensible::Private { LIBCAMERA_DECLARE_PUBLIC(Request) public: Private(Camera *camera); ~Private(); Camera *camera() const { return camera_; } bool hasPendingBuffers() const; bool completeBuffer(FrameBuffer *buffer); void complete(); void cancel(); void reset(); void prepare(std::chrono::milliseconds timeout = 0ms); Signal<> prepared; private: friend class PipelineHandler; friend std::ostream &operator<<(std::ostream &out, const Request &r); void doCancelRequest(); void emitPrepareCompleted(); void notifierActivated(FrameBuffer *buffer); void timeout(); Camera *camera_; bool cancelled_; uint32_t sequence_ = 0; bool prepared_ = false; std::unordered_set<FrameBuffer *> pending_; std::map<FrameBuffer *, std::unique_ptr<EventNotifier>> notifiers_; std::unique_ptr<Timer> timer_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/v4l2_subdevice.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * V4L2 Subdevice */ #pragma once #include <memory> #include <optional> #include <ostream> #include <string> #include <vector> #include <linux/v4l2-subdev.h> #include <libcamera/base/class.h> #include <libcamera/base/log.h> #include <libcamera/color_space.h> #include <libcamera/geometry.h> #include "libcamera/internal/formats.h" #include "libcamera/internal/media_object.h" #include "libcamera/internal/v4l2_device.h" namespace libcamera { class MediaDevice; class MediaBusFormatInfo { public: enum class Type { Image, Metadata, EmbeddedData, }; bool isValid() const { return code != 0; } static const MediaBusFormatInfo &info(uint32_t code); const char *name; uint32_t code; Type type; unsigned int bitsPerPixel; PixelFormatInfo::ColourEncoding colourEncoding; }; struct V4L2SubdeviceCapability final : v4l2_subdev_capability { bool isReadOnly() const { return capabilities & V4L2_SUBDEV_CAP_RO_SUBDEV; } bool hasStreams() const { return capabilities & V4L2_SUBDEV_CAP_STREAMS; } }; struct V4L2SubdeviceFormat { uint32_t code; Size size; std::optional<ColorSpace> colorSpace; const std::string toString() const; }; std::ostream &operator<<(std::ostream &out, const V4L2SubdeviceFormat &f); class V4L2Subdevice : public V4L2Device { public: using Formats = std::map<unsigned int, std::vector<SizeRange>>; enum Whence { TryFormat = V4L2_SUBDEV_FORMAT_TRY, ActiveFormat = V4L2_SUBDEV_FORMAT_ACTIVE, }; struct Stream { Stream() : pad(0), stream(0) { } Stream(unsigned int p, unsigned int s) : pad(p), stream(s) { } unsigned int pad; unsigned int stream; }; struct Route { Route() : flags(0) { } Route(const Stream &snk, const Stream &src, uint32_t f) : sink(snk), source(src), flags(f) { } Stream sink; Stream source; uint32_t flags; }; using Routing = std::vector<Route>; explicit V4L2Subdevice(const MediaEntity *entity); ~V4L2Subdevice(); int open(); const MediaEntity *entity() const { return entity_; } int getSelection(const Stream &stream, unsigned int target, Rectangle *rect); int getSelection(unsigned int pad, unsigned int target, Rectangle *rect) { return getSelection({ pad, 0 }, target, rect); } int setSelection(const Stream &stream, unsigned int target, Rectangle *rect); int setSelection(unsigned int pad, unsigned int target, Rectangle *rect) { return setSelection({ pad, 0 }, target, rect); } Formats formats(const Stream &stream); Formats formats(unsigned int pad) { return formats({ pad, 0 }); } int getFormat(const Stream &stream, V4L2SubdeviceFormat *format, Whence whence = ActiveFormat); int getFormat(unsigned int pad, V4L2SubdeviceFormat *format, Whence whence = ActiveFormat) { return getFormat({ pad, 0 }, format, whence); } int setFormat(const Stream &stream, V4L2SubdeviceFormat *format, Whence whence = ActiveFormat); int setFormat(unsigned int pad, V4L2SubdeviceFormat *format, Whence whence = ActiveFormat) { return setFormat({ pad, 0 }, format, whence); } int getRouting(Routing *routing, Whence whence = ActiveFormat); int setRouting(Routing *routing, Whence whence = ActiveFormat); const std::string &model(); const V4L2SubdeviceCapability &caps() const { return caps_; } static std::unique_ptr<V4L2Subdevice> fromEntityName(const MediaDevice *media, const std::string &entity); protected: std::string logPrefix() const override; private: LIBCAMERA_DISABLE_COPY(V4L2Subdevice) std::optional<ColorSpace> toColorSpace(const v4l2_mbus_framefmt &format) const; std::vector<unsigned int> enumPadCodes(const Stream &stream); std::vector<SizeRange> enumPadSizes(const Stream &stream, unsigned int code); int getRoutingLegacy(Routing *routing, Whence whence); int setRoutingLegacy(Routing *routing, Whence whence); const MediaEntity *entity_; std::string model_; struct V4L2SubdeviceCapability caps_; }; bool operator==(const V4L2Subdevice::Stream &lhs, const V4L2Subdevice::Stream &rhs); static inline bool operator!=(const V4L2Subdevice::Stream &lhs, const V4L2Subdevice::Stream &rhs) { return !(lhs == rhs); } std::ostream &operator<<(std::ostream &out, const V4L2Subdevice::Stream &stream); std::ostream &operator<<(std::ostream &out, const V4L2Subdevice::Route &route); std::ostream &operator<<(std::ostream &out, const V4L2Subdevice::Routing &routing); } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/device_enumerator.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2018, Google Inc. * * API to enumerate and find media devices */ #pragma once #include <memory> #include <string> #include <vector> #include <libcamera/base/signal.h> namespace libcamera { class MediaDevice; class DeviceMatch { public: DeviceMatch(const std::string &driver); void add(const std::string &entity); bool match(const MediaDevice *device) const; private: std::string driver_; std::vector<std::string> entities_; }; class DeviceEnumerator { public: static std::unique_ptr<DeviceEnumerator> create(); virtual ~DeviceEnumerator(); virtual int init() = 0; virtual int enumerate() = 0; std::shared_ptr<MediaDevice> search(const DeviceMatch &dm); Signal<> devicesAdded; protected: std::unique_ptr<MediaDevice> createDevice(const std::string &deviceNode); void addDevice(std::unique_ptr<MediaDevice> media); void removeDevice(const std::string &deviceNode); private: std::vector<std::shared_ptr<MediaDevice>> devices_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipa_data_serializer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Image Processing Algorithm data serializer */ #pragma once #include <deque> #include <iostream> #include <string.h> #include <tuple> #include <type_traits> #include <vector> #include <libcamera/base/flags.h> #include <libcamera/base/log.h> #include <libcamera/control_ids.h> #include <libcamera/framebuffer.h> #include <libcamera/geometry.h> #include <libcamera/ipa/ipa_interface.h> #include "libcamera/internal/byte_stream_buffer.h" #include "libcamera/internal/camera_sensor.h" #include "libcamera/internal/control_serializer.h" namespace libcamera { LOG_DECLARE_CATEGORY(IPADataSerializer) namespace { template<typename T, std::enable_if_t<std::is_arithmetic_v<T>> * = nullptr> void appendPOD(std::vector<uint8_t> &vec, T val) { constexpr size_t byteWidth = sizeof(val); vec.resize(vec.size() + byteWidth); memcpy(&*(vec.end() - byteWidth), &val, byteWidth); } template<typename T, std::enable_if_t<std::is_arithmetic_v<T>> * = nullptr> T readPOD(std::vector<uint8_t>::const_iterator it, size_t pos, std::vector<uint8_t>::const_iterator end) { ASSERT(pos + it < end); T ret = 0; memcpy(&ret, &(*(it + pos)), sizeof(ret)); return ret; } template<typename T, std::enable_if_t<std::is_arithmetic_v<T>> * = nullptr> T readPOD(std::vector<uint8_t> &vec, size_t pos) { return readPOD<T>(vec.cbegin(), pos, vec.end()); } } /* namespace */ template<typename T> class IPADataSerializer { public: static std::tuple<std::vector<uint8_t>, std::vector<SharedFD>> serialize(const T &data, ControlSerializer *cs = nullptr); static T deserialize(const std::vector<uint8_t> &data, ControlSerializer *cs = nullptr); static T deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, ControlSerializer *cs = nullptr); static T deserialize(const std::vector<uint8_t> &data, const std::vector<SharedFD> &fds, ControlSerializer *cs = nullptr); static T deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, std::vector<SharedFD>::const_iterator fdsBegin, std::vector<SharedFD>::const_iterator fdsEnd, ControlSerializer *cs = nullptr); }; #ifndef __DOXYGEN__ /* * Serialization format for vector of type V: * * 4 bytes - uint32_t Length of vector, in number of elements * * For every element in the vector: * * 4 bytes - uint32_t Size of element, in bytes * 4 bytes - uint32_t Number of fds for the element * X bytes - Serialized element * * \todo Support elements that are references */ template<typename V> class IPADataSerializer<std::vector<V>> { public: static std::tuple<std::vector<uint8_t>, std::vector<SharedFD>> serialize(const std::vector<V> &data, ControlSerializer *cs = nullptr) { std::vector<uint8_t> dataVec; std::vector<SharedFD> fdsVec; /* Serialize the length. */ uint32_t vecLen = data.size(); appendPOD<uint32_t>(dataVec, vecLen); /* Serialize the members. */ for (auto const &it : data) { std::vector<uint8_t> dvec; std::vector<SharedFD> fvec; std::tie(dvec, fvec) = IPADataSerializer<V>::serialize(it, cs); appendPOD<uint32_t>(dataVec, dvec.size()); appendPOD<uint32_t>(dataVec, fvec.size()); dataVec.insert(dataVec.end(), dvec.begin(), dvec.end()); fdsVec.insert(fdsVec.end(), fvec.begin(), fvec.end()); } return { dataVec, fdsVec }; } static std::vector<V> deserialize(std::vector<uint8_t> &data, ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend(), cs); } static std::vector<V> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, ControlSerializer *cs = nullptr) { std::vector<SharedFD> fds; return deserialize(dataBegin, dataEnd, fds.cbegin(), fds.cend(), cs); } static std::vector<V> deserialize(std::vector<uint8_t> &data, std::vector<SharedFD> &fds, ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend(), fds.cbegin(), fds.cend(), cs); } static std::vector<V> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, std::vector<SharedFD>::const_iterator fdsBegin, [[maybe_unused]] std::vector<SharedFD>::const_iterator fdsEnd, ControlSerializer *cs = nullptr) { uint32_t vecLen = readPOD<uint32_t>(dataBegin, 0, dataEnd); std::vector<V> ret(vecLen); std::vector<uint8_t>::const_iterator dataIter = dataBegin + 4; std::vector<SharedFD>::const_iterator fdIter = fdsBegin; for (uint32_t i = 0; i < vecLen; i++) { uint32_t sizeofData = readPOD<uint32_t>(dataIter, 0, dataEnd); uint32_t sizeofFds = readPOD<uint32_t>(dataIter, 4, dataEnd); dataIter += 8; ret[i] = IPADataSerializer<V>::deserialize(dataIter, dataIter + sizeofData, fdIter, fdIter + sizeofFds, cs); dataIter += sizeofData; fdIter += sizeofFds; } return ret; } }; /* * Serialization format for map of key type K and value type V: * * 4 bytes - uint32_t Length of map, in number of pairs * * For every pair in the map: * * 4 bytes - uint32_t Size of key, in bytes * 4 bytes - uint32_t Number of fds for the key * X bytes - Serialized key * 4 bytes - uint32_t Size of value, in bytes * 4 bytes - uint32_t Number of fds for the value * X bytes - Serialized value * * \todo Support keys or values that are references */ template<typename K, typename V> class IPADataSerializer<std::map<K, V>> { public: static std::tuple<std::vector<uint8_t>, std::vector<SharedFD>> serialize(const std::map<K, V> &data, ControlSerializer *cs = nullptr) { std::vector<uint8_t> dataVec; std::vector<SharedFD> fdsVec; /* Serialize the length. */ uint32_t mapLen = data.size(); appendPOD<uint32_t>(dataVec, mapLen); /* Serialize the members. */ for (auto const &it : data) { std::vector<uint8_t> dvec; std::vector<SharedFD> fvec; std::tie(dvec, fvec) = IPADataSerializer<K>::serialize(it.first, cs); appendPOD<uint32_t>(dataVec, dvec.size()); appendPOD<uint32_t>(dataVec, fvec.size()); dataVec.insert(dataVec.end(), dvec.begin(), dvec.end()); fdsVec.insert(fdsVec.end(), fvec.begin(), fvec.end()); std::tie(dvec, fvec) = IPADataSerializer<V>::serialize(it.second, cs); appendPOD<uint32_t>(dataVec, dvec.size()); appendPOD<uint32_t>(dataVec, fvec.size()); dataVec.insert(dataVec.end(), dvec.begin(), dvec.end()); fdsVec.insert(fdsVec.end(), fvec.begin(), fvec.end()); } return { dataVec, fdsVec }; } static std::map<K, V> deserialize(std::vector<uint8_t> &data, ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend(), cs); } static std::map<K, V> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, ControlSerializer *cs = nullptr) { std::vector<SharedFD> fds; return deserialize(dataBegin, dataEnd, fds.cbegin(), fds.cend(), cs); } static std::map<K, V> deserialize(std::vector<uint8_t> &data, std::vector<SharedFD> &fds, ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend(), fds.cbegin(), fds.cend(), cs); } static std::map<K, V> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, std::vector<SharedFD>::const_iterator fdsBegin, [[maybe_unused]] std::vector<SharedFD>::const_iterator fdsEnd, ControlSerializer *cs = nullptr) { std::map<K, V> ret; uint32_t mapLen = readPOD<uint32_t>(dataBegin, 0, dataEnd); std::vector<uint8_t>::const_iterator dataIter = dataBegin + 4; std::vector<SharedFD>::const_iterator fdIter = fdsBegin; for (uint32_t i = 0; i < mapLen; i++) { uint32_t sizeofData = readPOD<uint32_t>(dataIter, 0, dataEnd); uint32_t sizeofFds = readPOD<uint32_t>(dataIter, 4, dataEnd); dataIter += 8; K key = IPADataSerializer<K>::deserialize(dataIter, dataIter + sizeofData, fdIter, fdIter + sizeofFds, cs); dataIter += sizeofData; fdIter += sizeofFds; sizeofData = readPOD<uint32_t>(dataIter, 0, dataEnd); sizeofFds = readPOD<uint32_t>(dataIter, 4, dataEnd); dataIter += 8; const V value = IPADataSerializer<V>::deserialize(dataIter, dataIter + sizeofData, fdIter, fdIter + sizeofFds, cs); ret.insert({ key, value }); dataIter += sizeofData; fdIter += sizeofFds; } return ret; } }; /* Serialization format for Flags is same as for PODs */ template<typename E> class IPADataSerializer<Flags<E>> { public: static std::tuple<std::vector<uint8_t>, std::vector<SharedFD>> serialize(const Flags<E> &data, [[maybe_unused]] ControlSerializer *cs = nullptr) { std::vector<uint8_t> dataVec; dataVec.reserve(sizeof(Flags<E>)); appendPOD<uint32_t>(dataVec, static_cast<typename Flags<E>::Type>(data)); return { dataVec, {} }; } static Flags<E> deserialize(std::vector<uint8_t> &data, [[maybe_unused]] ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend()); } static Flags<E> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, [[maybe_unused]] ControlSerializer *cs = nullptr) { return Flags<E>{ static_cast<E>(readPOD<uint32_t>(dataBegin, 0, dataEnd)) }; } static Flags<E> deserialize(std::vector<uint8_t> &data, [[maybe_unused]] std::vector<SharedFD> &fds, [[maybe_unused]] ControlSerializer *cs = nullptr) { return deserialize(data.cbegin(), data.cend()); } static Flags<E> deserialize(std::vector<uint8_t>::const_iterator dataBegin, std::vector<uint8_t>::const_iterator dataEnd, [[maybe_unused]] std::vector<SharedFD>::const_iterator fdsBegin, [[maybe_unused]] std::vector<SharedFD>::const_iterator fdsEnd, [[maybe_unused]] ControlSerializer *cs = nullptr) { return deserialize(dataBegin, dataEnd); } }; #endif /* __DOXYGEN__ */ } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera_controls.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Camera controls */ #pragma once #include "libcamera/internal/control_validator.h" namespace libcamera { class Camera; class CameraControlValidator final : public ControlValidator { public: CameraControlValidator(Camera *camera); const std::string &name() const override; bool validate(unsigned int id) const override; private: Camera *camera_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/dma_buf_allocator.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Raspberry Pi Ltd * * Helper class for dma-buf allocations. */ #pragma once #include <stddef.h> #include <libcamera/base/flags.h> #include <libcamera/base/unique_fd.h> namespace libcamera { class DmaBufAllocator { public: enum class DmaBufAllocatorFlag { CmaHeap = 1 << 0, SystemHeap = 1 << 1, UDmaBuf = 1 << 2, }; using DmaBufAllocatorFlags = Flags<DmaBufAllocatorFlag>; DmaBufAllocator(DmaBufAllocatorFlags flags = DmaBufAllocatorFlag::CmaHeap); ~DmaBufAllocator(); bool isValid() const { return providerHandle_.isValid(); } UniqueFD alloc(const char *name, std::size_t size); private: UniqueFD allocFromHeap(const char *name, std::size_t size); UniqueFD allocFromUDmaBuf(const char *name, std::size_t size); UniqueFD providerHandle_; DmaBufAllocatorFlag type_; }; LIBCAMERA_FLAGS_ENABLE_OPERATORS(DmaBufAllocator::DmaBufAllocatorFlag) } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/control_serializer.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Control (de)serializer */ #pragma once #include <map> #include <memory> #include <vector> #include <libcamera/controls.h> namespace libcamera { class ByteStreamBuffer; class ControlSerializer { public: enum class Role { Proxy, Worker }; ControlSerializer(Role role); void reset(); static size_t binarySize(const ControlInfoMap &infoMap); static size_t binarySize(const ControlList &list); int serialize(const ControlInfoMap &infoMap, ByteStreamBuffer &buffer); int serialize(const ControlList &list, ByteStreamBuffer &buffer); template<typename T> T deserialize(ByteStreamBuffer &buffer); bool isCached(const ControlInfoMap &infoMap); private: static size_t binarySize(const ControlValue &value); static size_t binarySize(const ControlInfo &info); static void store(const ControlValue &value, ByteStreamBuffer &buffer); static void store(const ControlInfo &info, ByteStreamBuffer &buffer); ControlValue loadControlValue(ByteStreamBuffer &buffer, bool isArray = false, unsigned int count = 1); ControlInfo loadControlInfo(ByteStreamBuffer &buffer); unsigned int serial_; unsigned int serialSeed_; std::vector<std::unique_ptr<ControlId>> controlIds_; std::vector<std::unique_ptr<ControlIdMap>> controlIdMaps_; std::map<unsigned int, ControlInfoMap> infoMaps_; std::map<const ControlInfoMap *, unsigned int> infoMapHandles_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/delayed_controls.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Raspberry Pi Ltd * * Helper to deal with controls that take effect with a delay */ #pragma once #include <stdint.h> #include <unordered_map> #include <libcamera/controls.h> namespace libcamera { class V4L2Device; class DelayedControls { public: struct ControlParams { unsigned int delay; bool priorityWrite; }; DelayedControls(V4L2Device *device, const std::unordered_map<uint32_t, ControlParams> &controlParams); void reset(); bool push(const ControlList &controls); ControlList get(uint32_t sequence); void applyControls(uint32_t sequence); private: class Info : public ControlValue { public: Info() : updated(false) { } Info(const ControlValue &v, bool updated_ = true) : ControlValue(v), updated(updated_) { } bool updated; }; /* \todo Make the listSize configurable at instance creation time. */ static constexpr int listSize = 16; class ControlRingBuffer : public std::array<Info, listSize> { public: Info &operator[](unsigned int index) { return std::array<Info, listSize>::operator[](index % listSize); } const Info &operator[](unsigned int index) const { return std::array<Info, listSize>::operator[](index % listSize); } }; V4L2Device *device_; /* \todo Evaluate if we should index on ControlId * or unsigned int */ std::unordered_map<const ControlId *, ControlParams> controlParams_; unsigned int maxDelay_; uint32_t queueCount_; uint32_t writeCount_; /* \todo Evaluate if we should index on ControlId * or unsigned int */ std::unordered_map<const ControlId *, ControlRingBuffer> values_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipa_module.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * Image Processing Algorithm module */ #pragma once #include <stdint.h> #include <string> #include <vector> #include <libcamera/base/log.h> #include <libcamera/ipa/ipa_interface.h> #include <libcamera/ipa/ipa_module_info.h> #include "libcamera/internal/pipeline_handler.h" namespace libcamera { class IPAModule : public Loggable { public: explicit IPAModule(const std::string &libPath); ~IPAModule(); bool isValid() const; const struct IPAModuleInfo &info() const; const std::vector<uint8_t> signature() const; const std::string &path() const; bool load(); IPAInterface *createInterface(); bool match(PipelineHandler *pipe, uint32_t minVersion, uint32_t maxVersion) const; protected: std::string logPrefix() const override; private: int loadIPAModuleInfo(); struct IPAModuleInfo info_; std::vector<uint8_t> signature_; std::string libPath_; bool valid_; bool loaded_; void *dlHandle_; typedef IPAInterface *(*IPAIntfFactory)(void); IPAIntfFactory ipaCreate_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/source_paths.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Identify libcamera source and build paths */ #pragma once #include <string> namespace libcamera::utils { std::string libcameraBuildPath(); std::string libcameraSourcePath(); } /* namespace libcamera::utils */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipc_unixsocket.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * IPC mechanism based on Unix sockets */ #pragma once #include <stdint.h> #include <sys/types.h> #include <vector> #include <libcamera/base/signal.h> #include <libcamera/base/unique_fd.h> namespace libcamera { class EventNotifier; class IPCUnixSocket { public: struct Payload { std::vector<uint8_t> data; std::vector<int32_t> fds; }; IPCUnixSocket(); ~IPCUnixSocket(); UniqueFD create(); int bind(UniqueFD fd); void close(); bool isBound() const; int send(const Payload &payload); int receive(Payload *payload); Signal<> readyRead; private: struct Header { uint32_t data; uint8_t fds; }; int sendData(const void *buffer, size_t length, const int32_t *fds, unsigned int num); int recvData(void *buffer, size_t length, int32_t *fds, unsigned int num); void dataNotifier(); UniqueFD fd_; bool headerReceived_; struct Header header_; EventNotifier *notifier_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/formats.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * * libcamera image formats */ #pragma once #include <array> #include <map> #include <vector> #include <libcamera/geometry.h> #include <libcamera/pixel_format.h> #include "libcamera/internal/v4l2_pixelformat.h" namespace libcamera { class PixelFormatInfo { public: enum ColourEncoding { ColourEncodingRGB, ColourEncodingYUV, ColourEncodingRAW, }; struct Plane { unsigned int bytesPerGroup; unsigned int verticalSubSampling; }; bool isValid() const { return format.isValid(); } static const PixelFormatInfo &info(const PixelFormat &format); static const PixelFormatInfo &info(const V4L2PixelFormat &format); static const PixelFormatInfo &info(const std::string &name); unsigned int stride(unsigned int width, unsigned int plane, unsigned int align = 1) const; unsigned int planeSize(const Size &size, unsigned int plane, unsigned int align = 1) const; unsigned int planeSize(unsigned int height, unsigned int plane, unsigned int stride) const; unsigned int frameSize(const Size &size, unsigned int align = 1) const; unsigned int frameSize(const Size &size, const std::array<unsigned int, 3> &strides) const; unsigned int numPlanes() const; /* \todo Add support for non-contiguous memory planes */ const char *name; PixelFormat format; std::vector<V4L2PixelFormat> v4l2Formats; unsigned int bitsPerPixel; enum ColourEncoding colourEncoding; bool packed; unsigned int pixelsPerGroup; std::array<Plane, 3> planes; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera_manager.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2023, Ideas on Board Oy. * * Camera manager private data */ #pragma once #include <libcamera/camera_manager.h> #include <map> #include <memory> #include <sys/types.h> #include <vector> #include <libcamera/base/class.h> #include <libcamera/base/mutex.h> #include <libcamera/base/thread.h> #include <libcamera/base/thread_annotations.h> #include "libcamera/internal/ipa_manager.h" #include "libcamera/internal/process.h" namespace libcamera { class Camera; class DeviceEnumerator; class CameraManager::Private : public Extensible::Private, public Thread { LIBCAMERA_DECLARE_PUBLIC(CameraManager) public: Private(); int start(); void addCamera(std::shared_ptr<Camera> camera) LIBCAMERA_TSA_EXCLUDES(mutex_); void removeCamera(std::shared_ptr<Camera> camera) LIBCAMERA_TSA_EXCLUDES(mutex_); protected: void run() override; private: int init(); void createPipelineHandlers(); void pipelineFactoryMatch(const PipelineHandlerFactoryBase *factory); void cleanup() LIBCAMERA_TSA_EXCLUDES(mutex_); /* * This mutex protects * * - initialized_ and status_ during initialization * - cameras_ after initialization */ mutable Mutex mutex_; std::vector<std::shared_ptr<Camera>> cameras_ LIBCAMERA_TSA_GUARDED_BY(mutex_); ConditionVariable cv_; bool initialized_ LIBCAMERA_TSA_GUARDED_BY(mutex_); int status_ LIBCAMERA_TSA_GUARDED_BY(mutex_); std::unique_ptr<DeviceEnumerator> enumerator_; IPAManager ipaManager_; ProcessManager processManager_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/ipc_pipe_unixsocket.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Google Inc. * * Image Processing Algorithm IPC module using unix socket */ #pragma once #include <map> #include <memory> #include <vector> #include "libcamera/internal/ipc_pipe.h" #include "libcamera/internal/ipc_unixsocket.h" namespace libcamera { class Process; class IPCPipeUnixSocket : public IPCPipe { public: IPCPipeUnixSocket(const char *ipaModulePath, const char *ipaProxyWorkerPath); ~IPCPipeUnixSocket(); int sendSync(const IPCMessage &in, IPCMessage *out = nullptr) override; int sendAsync(const IPCMessage &data) override; private: struct CallData { IPCUnixSocket::Payload *response; bool done; }; void readyRead(); int call(const IPCUnixSocket::Payload &message, IPCUnixSocket::Payload *response, uint32_t seq); std::unique_ptr<Process> proc_; std::unique_ptr<IPCUnixSocket> socket_; std::map<uint32_t, CallData> callData_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/v4l2_pixelformat.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2019, Google Inc. * Copyright (C) 2020, Raspberry Pi Ltd * * V4L2 Pixel Format */ #pragma once #include <functional> #include <ostream> #include <stdint.h> #include <string> #include <vector> #include <linux/videodev2.h> #include <libcamera/pixel_format.h> namespace libcamera { class V4L2PixelFormat { public: struct Info { PixelFormat format; const char *description; }; V4L2PixelFormat() : fourcc_(0) { } explicit V4L2PixelFormat(uint32_t fourcc) : fourcc_(fourcc) { } bool isValid() const { return fourcc_ != 0; } uint32_t fourcc() const { return fourcc_; } operator uint32_t() const { return fourcc_; } std::string toString() const; const char *description() const; PixelFormat toPixelFormat(bool warn = true) const; static const std::vector<V4L2PixelFormat> & fromPixelFormat(const PixelFormat &pixelFormat); private: uint32_t fourcc_; }; std::ostream &operator<<(std::ostream &out, const V4L2PixelFormat &f); } /* namespace libcamera */ namespace std { template<> struct hash<libcamera::V4L2PixelFormat> { size_t operator()(libcamera::V4L2PixelFormat const &format) const noexcept { return format.fourcc(); } }; } /* namespace std */
0
repos/libcamera/include/libcamera
repos/libcamera/include/libcamera/internal/camera_sensor_properties.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2021, Google Inc. * * Database of camera sensor properties */ #pragma once #include <map> #include <string> #include <libcamera/control_ids.h> #include <libcamera/geometry.h> namespace libcamera { struct CameraSensorProperties { static const CameraSensorProperties *get(const std::string &sensor); Size unitCellSize; std::map<controls::draft::TestPatternModeEnum, int32_t> testPatternModes; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera/internal
repos/libcamera/include/libcamera/internal/software_isp/debayer_params.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2023, 2024 Red Hat Inc. * * Authors: * Hans de Goede <[email protected]> * * DebayerParams header */ #pragma once #include <array> #include <stdint.h> namespace libcamera { struct DebayerParams { static constexpr unsigned int kRGBLookupSize = 256; using ColorLookupTable = std::array<uint8_t, kRGBLookupSize>; ColorLookupTable red; ColorLookupTable green; ColorLookupTable blue; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera/internal
repos/libcamera/include/libcamera/internal/software_isp/swisp_stats.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2023, Linaro Ltd * * Statistics data format used by the software ISP and software IPA */ #pragma once #include <array> #include <stdint.h> namespace libcamera { /** * \brief Struct that holds the statistics for the Software ISP * * The struct value types are large enough to not overflow. * Should they still overflow for some reason, no check is performed and they * wrap around. */ struct SwIspStats { /** * \brief Holds the sum of all sampled red pixels */ uint64_t sumR_; /** * \brief Holds the sum of all sampled green pixels */ uint64_t sumG_; /** * \brief Holds the sum of all sampled blue pixels */ uint64_t sumB_; /** * \brief Number of bins in the yHistogram */ static constexpr unsigned int kYHistogramSize = 64; /** * \brief Type of the histogram. */ using Histogram = std::array<uint32_t, kYHistogramSize>; /** * \brief A histogram of luminance values */ Histogram yHistogram; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera/internal
repos/libcamera/include/libcamera/internal/software_isp/software_isp.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2023, Linaro Ltd * * Simple software ISP implementation */ #pragma once #include <functional> #include <initializer_list> #include <map> #include <memory> #include <string> #include <tuple> #include <vector> #include <libcamera/base/class.h> #include <libcamera/base/log.h> #include <libcamera/base/signal.h> #include <libcamera/base/thread.h> #include <libcamera/geometry.h> #include <libcamera/pixel_format.h> #include <libcamera/ipa/soft_ipa_interface.h> #include <libcamera/ipa/soft_ipa_proxy.h> #include "libcamera/internal/camera_sensor.h" #include "libcamera/internal/dma_buf_allocator.h" #include "libcamera/internal/pipeline_handler.h" #include "libcamera/internal/shared_mem_object.h" #include "libcamera/internal/software_isp/debayer_params.h" namespace libcamera { class DebayerCpu; class FrameBuffer; class PixelFormat; struct StreamConfiguration; LOG_DECLARE_CATEGORY(SoftwareIsp) class SoftwareIsp { public: SoftwareIsp(PipelineHandler *pipe, const CameraSensor *sensor); ~SoftwareIsp(); int loadConfiguration([[maybe_unused]] const std::string &filename) { return 0; } bool isValid() const; std::vector<PixelFormat> formats(PixelFormat input); SizeRange sizes(PixelFormat inputFormat, const Size &inputSize); std::tuple<unsigned int, unsigned int> strideAndFrameSize(const PixelFormat &outputFormat, const Size &size); int configure(const StreamConfiguration &inputCfg, const std::vector<std::reference_wrapper<StreamConfiguration>> &outputCfgs, const ControlInfoMap &sensorControls); int exportBuffers(unsigned int output, unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); void processStats(const ControlList &sensorControls); int start(); void stop(); int queueBuffers(FrameBuffer *input, const std::map<unsigned int, FrameBuffer *> &outputs); void process(FrameBuffer *input, FrameBuffer *output); Signal<FrameBuffer *> inputBufferReady; Signal<FrameBuffer *> outputBufferReady; Signal<> ispStatsReady; Signal<const ControlList &> setSensorControls; private: void saveIspParams(); void setSensorCtrls(const ControlList &sensorControls); void statsReady(); void inputReady(FrameBuffer *input); void outputReady(FrameBuffer *output); std::unique_ptr<DebayerCpu> debayer_; Thread ispWorkerThread_; SharedMemObject<DebayerParams> sharedParams_; DebayerParams debayerParams_; DmaBufAllocator dmaHeap_; std::unique_ptr<ipa::soft::IPAProxySoft> ipa_; }; } /* namespace libcamera */
0
repos/libcamera/include/libcamera/internal
repos/libcamera/include/libcamera/internal/converter/converter_v4l2_m2m.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Laurent Pinchart * Copyright 2022 NXP * * V4l2 M2M Format converter interface */ #pragma once #include <functional> #include <map> #include <memory> #include <string> #include <tuple> #include <vector> #include <libcamera/base/log.h> #include <libcamera/base/signal.h> #include <libcamera/pixel_format.h> #include "libcamera/internal/converter.h" namespace libcamera { class FrameBuffer; class MediaDevice; class Size; class SizeRange; struct StreamConfiguration; class V4L2M2MDevice; class V4L2M2MConverter : public Converter { public: V4L2M2MConverter(MediaDevice *media); int loadConfiguration([[maybe_unused]] const std::string &filename) { return 0; } bool isValid() const { return m2m_ != nullptr; } std::vector<PixelFormat> formats(PixelFormat input); SizeRange sizes(const Size &input); std::tuple<unsigned int, unsigned int> strideAndFrameSize(const PixelFormat &pixelFormat, const Size &size); int configure(const StreamConfiguration &inputCfg, const std::vector<std::reference_wrapper<StreamConfiguration>> &outputCfg); int exportBuffers(unsigned int output, unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); int start(); void stop(); int queueBuffers(FrameBuffer *input, const std::map<unsigned int, FrameBuffer *> &outputs); private: class Stream : protected Loggable { public: Stream(V4L2M2MConverter *converter, unsigned int index); bool isValid() const { return m2m_ != nullptr; } int configure(const StreamConfiguration &inputCfg, const StreamConfiguration &outputCfg); int exportBuffers(unsigned int count, std::vector<std::unique_ptr<FrameBuffer>> *buffers); int start(); void stop(); int queueBuffers(FrameBuffer *input, FrameBuffer *output); protected: std::string logPrefix() const override; private: void captureBufferReady(FrameBuffer *buffer); void outputBufferReady(FrameBuffer *buffer); V4L2M2MConverter *converter_; unsigned int index_; std::unique_ptr<V4L2M2MDevice> m2m_; unsigned int inputBufferCount_; unsigned int outputBufferCount_; }; std::unique_ptr<V4L2M2MDevice> m2m_; std::vector<Stream> streams_; std::map<FrameBuffer *, unsigned int> queue_; }; } /* namespace libcamera */
0
repos/libcamera
repos/libcamera/LICENSES/Apache-2.0.txt
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
repos/libcamera
repos/libcamera/LICENSES/GPL-2.0-or-later.txt
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and an idea of what it does.> Copyright (C) <yyyy> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
0
repos/libcamera
repos/libcamera/LICENSES/Linux-syscall-note.txt
NOTE! This copyright does *not* cover user programs that use kernel services by normal system calls - this is merely considered normal use of the kernel, and does *not* fall under the heading of "derived work". Also note that the GPL below is copyrighted by the Free Software Foundation, but the instance of code that it refers to (the Linux kernel) is copyrighted by me and others who actually wrote it. Also note that the only valid version of the GPL as far as the kernel is concerned is _this_ particular version of the license (ie v2, not v2.2 or v3.x or whatever), unless explicitly otherwise stated. Linus Torvalds
0
repos/libcamera
repos/libcamera/LICENSES/CC-BY-SA-4.0.txt
Attribution-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org.
0
repos/libcamera
repos/libcamera/LICENSES/GPL-2.0.txt
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
0
repos/libcamera
repos/libcamera/LICENSES/GPL-2.0-only.txt
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
0
repos/libcamera
repos/libcamera/LICENSES/BSD-2-Clause.txt
Copyright (c) <year> <owner>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0
repos/libcamera
repos/libcamera/LICENSES/CC0-1.0.txt
Creative Commons Legal Code CC0 1.0 Universal CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
0
repos/libcamera
repos/libcamera/LICENSES/MIT.txt
MIT License Copyright (c) <year> <copyright holders> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
repos/libcamera
repos/libcamera/LICENSES/LGPL-2.1-or-later.txt
GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and an idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. < signature of Ty Coon > , 1 April 1990 Ty Coon, President of Vice That's all there is to it!
0
repos/libcamera
repos/libcamera/LICENSES/BSD-3-Clause.txt
Copyright (c) <year> <owner>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0
repos/libcamera
repos/libcamera/LICENSES/CC-BY-4.0.txt
Creative Commons Attribution 4.0 International Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 – Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 – Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: A. reproduce and Share the Licensed Material, in whole or in part; and B. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 5. Downstream recipients. A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 – License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: A. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 – Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 – Disclaimer of Warranties and Limitation of Liability. a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 – Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 – Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 – Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org.
0
repos/libcamera
repos/libcamera/LICENSES/GPL-2.0+.txt
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and an idea of what it does.> Copyright (C) <yyyy> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
0
repos/libcamera/src/apps
repos/libcamera/src/apps/ipa-verify/main.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2023, Ideas on Board Oy * * Verify signature on an IPA module */ #include <iostream> #include <libgen.h> #include <libcamera/base/file.h> #include <libcamera/base/span.h> #include "libcamera/internal/ipa_manager.h" #include "libcamera/internal/ipa_module.h" using namespace libcamera; namespace { bool isSignatureValid(IPAModule *ipa) { File file{ ipa->path() }; if (!file.open(File::OpenModeFlag::ReadOnly)) return false; Span<uint8_t> data = file.map(); if (data.empty()) return false; return IPAManager::pubKey().verify(data, ipa->signature()); } void usage(char *argv0) { std::cout << "Usage: " << basename(argv0) << " ipa_name.so" << std::endl; std::cout << std::endl; std::cout << "Verify the signature of an IPA module. The signature file ipa_name.so.sign is" << std::endl; std::cout << "expected to be in the same directory as the IPA module." << std::endl; } } /* namespace */ int main(int argc, char **argv) { if (argc != 2) { usage(argv[0]); return EXIT_FAILURE; } IPAModule module{ argv[1] }; if (!module.isValid()) { std::cout << "Invalid IPA module " << argv[1] << std::endl; return EXIT_FAILURE; } if (!isSignatureValid(&module)) { std::cout << "IPA module signature is invalid" << std::endl; return EXIT_FAILURE; } std::cout << "IPA module signature is valid" << std::endl; return 0; }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/main_window.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - Main application window */ #include "main_window.h" #include <assert.h> #include <iomanip> #include <string> #include <libcamera/camera_manager.h> #include <libcamera/version.h> #include <QCoreApplication> #include <QFileDialog> #include <QImage> #include <QImageWriter> #include <QMutexLocker> #include <QStandardPaths> #include <QStringList> #include <QTimer> #include <QToolBar> #include <QToolButton> #include <QtDebug> #include "../common/dng_writer.h" #include "../common/image.h" #include "cam_select_dialog.h" #ifndef QT_NO_OPENGL #include "viewfinder_gl.h" #endif #include "viewfinder_qt.h" using namespace libcamera; #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) /* * Qt::fixed was introduced in v5.14, and ::fixed deprecated in v5.15. Allow * usage of Qt::fixed unconditionally. */ namespace Qt { constexpr auto fixed = ::fixed; } /* namespace Qt */ #endif /** * \brief Custom QEvent to signal capture completion */ class CaptureEvent : public QEvent { public: CaptureEvent() : QEvent(type()) { } static Type type() { static int type = QEvent::registerEventType(); return static_cast<Type>(type); } }; /** * \brief Custom QEvent to signal hotplug or unplug */ class HotplugEvent : public QEvent { public: enum PlugEvent { HotPlug, HotUnplug }; HotplugEvent(std::shared_ptr<Camera> camera, PlugEvent event) : QEvent(type()), camera_(std::move(camera)), plugEvent_(event) { } static Type type() { static int type = QEvent::registerEventType(); return static_cast<Type>(type); } PlugEvent hotplugEvent() const { return plugEvent_; } Camera *camera() const { return camera_.get(); } private: std::shared_ptr<Camera> camera_; PlugEvent plugEvent_; }; MainWindow::MainWindow(CameraManager *cm, const OptionsParser::Options &options) : saveRaw_(nullptr), options_(options), cm_(cm), allocator_(nullptr), isCapturing_(false), captureRaw_(false) { int ret; /* * Initialize the UI: Create the toolbar, set the window title and * create the viewfinder widget. */ createToolbars(); title_ = "QCam " + QString::fromStdString(CameraManager::version()); setWindowTitle(title_); connect(&titleTimer_, SIGNAL(timeout()), this, SLOT(updateTitle())); /* Renderer type Qt or GLES, select Qt by default. */ std::string renderType = "qt"; if (options_.isSet(OptRenderer)) renderType = options_[OptRenderer].toString(); if (renderType == "qt") { ViewFinderQt *viewfinder = new ViewFinderQt(this); connect(viewfinder, &ViewFinderQt::renderComplete, this, &MainWindow::renderComplete); viewfinder_ = viewfinder; setCentralWidget(viewfinder); #ifndef QT_NO_OPENGL } else if (renderType == "gles") { ViewFinderGL *viewfinder = new ViewFinderGL(this); connect(viewfinder, &ViewFinderGL::renderComplete, this, &MainWindow::renderComplete); viewfinder_ = viewfinder; setCentralWidget(viewfinder); #endif } else { qWarning() << "Invalid render type" << QString::fromStdString(renderType); quit(); return; } adjustSize(); /* Hotplug/unplug support */ cm_->cameraAdded.connect(this, &MainWindow::addCamera); cm_->cameraRemoved.connect(this, &MainWindow::removeCamera); cameraSelectorDialog_ = new CameraSelectorDialog(cm_, this); /* Open the camera and start capture. */ ret = openCamera(); if (ret < 0) { quit(); return; } startStopAction_->setChecked(true); } MainWindow::~MainWindow() { if (camera_) { stopCapture(); camera_->release(); camera_.reset(); } } bool MainWindow::event(QEvent *e) { if (e->type() == CaptureEvent::type()) { processCapture(); return true; } else if (e->type() == HotplugEvent::type()) { processHotplug(static_cast<HotplugEvent *>(e)); return true; } return QMainWindow::event(e); } int MainWindow::createToolbars() { QAction *action; toolbar_ = addToolBar("Main"); /* Disable right click context menu. */ toolbar_->setContextMenuPolicy(Qt::PreventContextMenu); /* Quit action. */ action = toolbar_->addAction(QIcon::fromTheme("application-exit", QIcon(":x-circle.svg")), "Quit"); action->setShortcut(QKeySequence::Quit); connect(action, &QAction::triggered, this, &MainWindow::quit); /* Camera selector. */ cameraSelectButton_ = new QPushButton; connect(cameraSelectButton_, &QPushButton::clicked, this, &MainWindow::switchCamera); toolbar_->addWidget(cameraSelectButton_); toolbar_->addSeparator(); /* Start/Stop action. */ iconPlay_ = QIcon::fromTheme("media-playback-start", QIcon(":play-circle.svg")); iconStop_ = QIcon::fromTheme("media-playback-stop", QIcon(":stop-circle.svg")); action = toolbar_->addAction(iconPlay_, "Start Capture"); action->setCheckable(true); action->setShortcut(Qt::Key_Space); connect(action, &QAction::toggled, this, &MainWindow::toggleCapture); startStopAction_ = action; /* Save As... action. */ action = toolbar_->addAction(QIcon::fromTheme("document-save-as", QIcon(":save.svg")), "Save As..."); action->setShortcut(QKeySequence::SaveAs); connect(action, &QAction::triggered, this, &MainWindow::saveImageAs); #ifdef HAVE_DNG /* Save Raw action. */ action = toolbar_->addAction(QIcon::fromTheme("camera-photo", QIcon(":aperture.svg")), "Save Raw"); action->setEnabled(false); connect(action, &QAction::triggered, this, &MainWindow::captureRaw); saveRaw_ = action; #endif return 0; } void MainWindow::quit() { QTimer::singleShot(0, QCoreApplication::instance(), &QCoreApplication::quit); } void MainWindow::updateTitle() { /* Calculate the average frame rate over the last period. */ unsigned int duration = frameRateInterval_.elapsed(); unsigned int frames = framesCaptured_ - previousFrames_; double fps = frames * 1000.0 / duration; /* Restart counters. */ frameRateInterval_.start(); previousFrames_ = framesCaptured_; setWindowTitle(title_ + " : " + QString::number(fps, 'f', 2) + " fps"); } /* ----------------------------------------------------------------------------- * Camera Selection */ void MainWindow::switchCamera() { /* Get and acquire the new camera. */ std::string newCameraId = chooseCamera(); if (newCameraId.empty()) return; if (camera_ && newCameraId == camera_->id()) return; const std::shared_ptr<Camera> &cam = cm_->get(newCameraId); if (cam->acquire()) { qInfo() << "Failed to acquire camera" << cam->id().c_str(); return; } qInfo() << "Switching to camera" << cam->id().c_str(); /* * Stop the capture session, release the current camera, replace it with * the new camera and start a new capture session. */ startStopAction_->setChecked(false); if (camera_) camera_->release(); camera_ = cam; startStopAction_->setChecked(true); /* Display the current cameraId in the toolbar .*/ cameraSelectButton_->setText(QString::fromStdString(newCameraId)); } std::string MainWindow::chooseCamera() { if (cameraSelectorDialog_->exec() != QDialog::Accepted) return std::string(); return cameraSelectorDialog_->getCameraId(); } int MainWindow::openCamera() { std::string cameraName; /* * Use the camera specified on the command line, if any, or display the * camera selection dialog box otherwise. */ if (options_.isSet(OptCamera)) cameraName = static_cast<std::string>(options_[OptCamera]); else cameraName = chooseCamera(); if (cameraName == "") return -EINVAL; /* Get and acquire the camera. */ camera_ = cm_->get(cameraName); if (!camera_) { qInfo() << "Camera" << cameraName.c_str() << "not found"; return -ENODEV; } if (camera_->acquire()) { qInfo() << "Failed to acquire camera"; camera_.reset(); return -EBUSY; } /* Set the camera switch button with the currently selected Camera id. */ cameraSelectButton_->setText(QString::fromStdString(cameraName)); return 0; } /* ----------------------------------------------------------------------------- * Capture Start & Stop */ void MainWindow::toggleCapture(bool start) { if (start) { startCapture(); startStopAction_->setIcon(iconStop_); startStopAction_->setText("Stop Capture"); } else { stopCapture(); startStopAction_->setIcon(iconPlay_); startStopAction_->setText("Start Capture"); } } /** * \brief Start capture with the current camera * * This function shall not be called directly, use toggleCapture() instead. */ int MainWindow::startCapture() { std::vector<StreamRole> roles = StreamKeyValueParser::roles(options_[OptStream]); int ret; /* Verify roles are supported. */ switch (roles.size()) { case 1: if (roles[0] != StreamRole::Viewfinder) { qWarning() << "Only viewfinder supported for single stream"; return -EINVAL; } break; case 2: if (roles[0] != StreamRole::Viewfinder || roles[1] != StreamRole::Raw) { qWarning() << "Only viewfinder + raw supported for dual streams"; return -EINVAL; } break; default: qWarning() << "Unsupported stream configuration"; return -EINVAL; } /* Configure the camera. */ config_ = camera_->generateConfiguration(roles); if (!config_) { qWarning() << "Failed to generate configuration from roles"; return -EINVAL; } StreamConfiguration &vfConfig = config_->at(0); /* Use a format supported by the viewfinder if available. */ std::vector<PixelFormat> formats = vfConfig.formats().pixelformats(); for (const PixelFormat &format : viewfinder_->nativeFormats()) { auto match = std::find_if(formats.begin(), formats.end(), [&](const PixelFormat &f) { return f == format; }); if (match != formats.end()) { vfConfig.pixelFormat = format; break; } } /* Allow user to override configuration. */ if (StreamKeyValueParser::updateConfiguration(config_.get(), options_[OptStream])) { qWarning() << "Failed to update configuration"; return -EINVAL; } CameraConfiguration::Status validation = config_->validate(); if (validation == CameraConfiguration::Invalid) { qWarning() << "Failed to create valid camera configuration"; return -EINVAL; } if (validation == CameraConfiguration::Adjusted) qInfo() << "Stream configuration adjusted to " << vfConfig.toString().c_str(); ret = camera_->configure(config_.get()); if (ret < 0) { qInfo() << "Failed to configure camera"; return ret; } /* Store stream allocation. */ vfStream_ = config_->at(0).stream(); if (config_->size() == 2) rawStream_ = config_->at(1).stream(); else rawStream_ = nullptr; /* * Configure the viewfinder. If no color space is reported, default to * sYCC. */ ret = viewfinder_->setFormat(vfConfig.pixelFormat, QSize(vfConfig.size.width, vfConfig.size.height), vfConfig.colorSpace.value_or(ColorSpace::Sycc), vfConfig.stride); if (ret < 0) { qInfo() << "Failed to set viewfinder format"; return ret; } adjustSize(); /* Configure the raw capture button. */ if (saveRaw_) saveRaw_->setEnabled(config_->size() == 2); /* Allocate and map buffers. */ allocator_ = new FrameBufferAllocator(camera_); for (StreamConfiguration &config : *config_) { Stream *stream = config.stream(); ret = allocator_->allocate(stream); if (ret < 0) { qWarning() << "Failed to allocate capture buffers"; goto error; } for (const std::unique_ptr<FrameBuffer> &buffer : allocator_->buffers(stream)) { /* Map memory buffers and cache the mappings. */ std::unique_ptr<Image> image = Image::fromFrameBuffer(buffer.get(), Image::MapMode::ReadOnly); assert(image != nullptr); mappedBuffers_[buffer.get()] = std::move(image); /* Store buffers on the free list. */ freeBuffers_[stream].enqueue(buffer.get()); } } /* Create requests and fill them with buffers from the viewfinder. */ while (!freeBuffers_[vfStream_].isEmpty()) { FrameBuffer *buffer = freeBuffers_[vfStream_].dequeue(); std::unique_ptr<Request> request = camera_->createRequest(); if (!request) { qWarning() << "Can't create request"; ret = -ENOMEM; goto error; } ret = request->addBuffer(vfStream_, buffer); if (ret < 0) { qWarning() << "Can't set buffer for request"; goto error; } requests_.push_back(std::move(request)); } /* Start the title timer and the camera. */ titleTimer_.start(2000); frameRateInterval_.start(); previousFrames_ = 0; framesCaptured_ = 0; lastBufferTime_ = 0; ret = camera_->start(); if (ret) { qInfo() << "Failed to start capture"; goto error; } camera_->requestCompleted.connect(this, &MainWindow::requestComplete); /* Queue all requests. */ for (std::unique_ptr<Request> &request : requests_) { ret = queueRequest(request.get()); if (ret < 0) { qWarning() << "Can't queue request"; goto error_disconnect; } } isCapturing_ = true; return 0; error_disconnect: camera_->requestCompleted.disconnect(this); camera_->stop(); error: requests_.clear(); mappedBuffers_.clear(); freeBuffers_.clear(); delete allocator_; allocator_ = nullptr; return ret; } /** * \brief Stop ongoing capture * * This function may be called directly when tearing down the MainWindow. Use * toggleCapture() instead in all other cases. */ void MainWindow::stopCapture() { if (!isCapturing_) return; viewfinder_->stop(); if (saveRaw_) saveRaw_->setEnabled(false); captureRaw_ = false; int ret = camera_->stop(); if (ret) qInfo() << "Failed to stop capture"; camera_->requestCompleted.disconnect(this); mappedBuffers_.clear(); requests_.clear(); freeQueue_.clear(); delete allocator_; isCapturing_ = false; config_.reset(); /* * A CaptureEvent may have been posted before we stopped the camera, * but not processed yet. Clear the queue of done buffers to avoid * racing with the event handler. */ freeBuffers_.clear(); doneQueue_.clear(); titleTimer_.stop(); setWindowTitle(title_); } /* ----------------------------------------------------------------------------- * Camera hotplugging support */ void MainWindow::processHotplug(HotplugEvent *e) { Camera *camera = e->camera(); QString cameraId = QString::fromStdString(camera->id()); HotplugEvent::PlugEvent event = e->hotplugEvent(); if (event == HotplugEvent::HotPlug) { cameraSelectorDialog_->addCamera(cameraId); } else if (event == HotplugEvent::HotUnplug) { /* Check if the currently-streaming camera is removed. */ if (camera == camera_.get()) { toggleCapture(false); camera_->release(); camera_.reset(); } cameraSelectorDialog_->removeCamera(cameraId); } } void MainWindow::addCamera(std::shared_ptr<Camera> camera) { qInfo() << "Adding new camera:" << camera->id().c_str(); QCoreApplication::postEvent(this, new HotplugEvent(std::move(camera), HotplugEvent::HotPlug)); } void MainWindow::removeCamera(std::shared_ptr<Camera> camera) { qInfo() << "Removing camera:" << camera->id().c_str(); QCoreApplication::postEvent(this, new HotplugEvent(std::move(camera), HotplugEvent::HotUnplug)); } /* ----------------------------------------------------------------------------- * Image Save */ void MainWindow::saveImageAs() { QImage image = viewfinder_->getCurrentImage(); QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); QString filename = QFileDialog::getSaveFileName(this, "Save Image", defaultPath, "Image Files (*.png *.jpg *.jpeg)"); if (filename.isEmpty()) return; QImageWriter writer(filename); writer.setQuality(95); writer.write(image); } void MainWindow::captureRaw() { captureRaw_ = true; } void MainWindow::processRaw(FrameBuffer *buffer, [[maybe_unused]] const ControlList &metadata) { #ifdef HAVE_DNG QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); QString filename = QFileDialog::getSaveFileName(this, "Save DNG", defaultPath, "DNG Files (*.dng)"); if (!filename.isEmpty()) { uint8_t *memory = mappedBuffers_[buffer]->data(0).data(); DNGWriter::write(filename.toStdString().c_str(), camera_.get(), rawStream_->configuration(), metadata, buffer, memory); } #endif { QMutexLocker locker(&mutex_); freeBuffers_[rawStream_].enqueue(buffer); } } /* ----------------------------------------------------------------------------- * Request Completion Handling */ void MainWindow::requestComplete(Request *request) { if (request->status() == Request::RequestCancelled) return; /* * We're running in the libcamera thread context, expensive operations * are not allowed. Add the buffer to the done queue and post a * CaptureEvent for the application thread to handle. */ { QMutexLocker locker(&mutex_); doneQueue_.enqueue(request); } QCoreApplication::postEvent(this, new CaptureEvent); } void MainWindow::processCapture() { /* * Retrieve the next buffer from the done queue. The queue may be empty * if stopCapture() has been called while a CaptureEvent was posted but * not processed yet. Return immediately in that case. */ Request *request; { QMutexLocker locker(&mutex_); if (doneQueue_.isEmpty()) return; request = doneQueue_.dequeue(); } /* Process buffers. */ if (request->buffers().count(vfStream_)) processViewfinder(request->buffers().at(vfStream_)); if (request->buffers().count(rawStream_)) processRaw(request->buffers().at(rawStream_), request->metadata()); request->reuse(); QMutexLocker locker(&mutex_); freeQueue_.enqueue(request); } void MainWindow::processViewfinder(FrameBuffer *buffer) { framesCaptured_++; const FrameMetadata &metadata = buffer->metadata(); double fps = metadata.timestamp - lastBufferTime_; fps = lastBufferTime_ && fps ? 1000000000.0 / fps : 0.0; lastBufferTime_ = metadata.timestamp; QStringList bytesused; for (const FrameMetadata::Plane &plane : metadata.planes()) bytesused << QString::number(plane.bytesused); qDebug().noquote() << QString("seq: %1").arg(metadata.sequence, 6, 10, QLatin1Char('0')) << "bytesused: {" << bytesused.join(", ") << "} timestamp:" << metadata.timestamp << "fps:" << Qt::fixed << qSetRealNumberPrecision(2) << fps; /* Render the frame on the viewfinder. */ viewfinder_->render(buffer, mappedBuffers_[buffer].get()); } void MainWindow::renderComplete(FrameBuffer *buffer) { Request *request; { QMutexLocker locker(&mutex_); if (freeQueue_.isEmpty()) return; request = freeQueue_.dequeue(); } request->addBuffer(vfStream_, buffer); if (captureRaw_) { FrameBuffer *rawBuffer = nullptr; { QMutexLocker locker(&mutex_); if (!freeBuffers_[rawStream_].isEmpty()) rawBuffer = freeBuffers_[rawStream_].dequeue(); } if (rawBuffer) { request->addBuffer(rawStream_, rawBuffer); captureRaw_ = false; } else { qWarning() << "No free buffer available for RAW capture"; } } queueRequest(request); } int MainWindow::queueRequest(Request *request) { return camera_->queueRequest(request); }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/viewfinder.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - Viewfinder base class */ #pragma once #include <QImage> #include <QList> #include <QSize> #include <libcamera/color_space.h> #include <libcamera/formats.h> #include <libcamera/framebuffer.h> class Image; class ViewFinder { public: virtual ~ViewFinder() = default; virtual const QList<libcamera::PixelFormat> &nativeFormats() const = 0; virtual int setFormat(const libcamera::PixelFormat &format, const QSize &size, const libcamera::ColorSpace &colorSpace, unsigned int stride) = 0; virtual void render(libcamera::FrameBuffer *buffer, Image *image) = 0; virtual void stop() = 0; virtual QImage getCurrentImage() = 0; };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/viewfinder_qt.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - QPainter-based ViewFinder */ #include "viewfinder_qt.h" #include <assert.h> #include <stdint.h> #include <utility> #include <libcamera/formats.h> #include <QImage> #include <QImageWriter> #include <QMap> #include <QMutexLocker> #include <QPainter> #include <QtDebug> #include "../common/image.h" #include "format_converter.h" static const QMap<libcamera::PixelFormat, QImage::Format> nativeFormats { #if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) { libcamera::formats::ABGR8888, QImage::Format_RGBX8888 }, { libcamera::formats::XBGR8888, QImage::Format_RGBX8888 }, #endif { libcamera::formats::ARGB8888, QImage::Format_RGB32 }, { libcamera::formats::XRGB8888, QImage::Format_RGB32 }, #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) { libcamera::formats::RGB888, QImage::Format_BGR888 }, #endif { libcamera::formats::BGR888, QImage::Format_RGB888 }, { libcamera::formats::RGB565, QImage::Format_RGB16 }, }; ViewFinderQt::ViewFinderQt(QWidget *parent) : QWidget(parent), buffer_(nullptr) { icon_ = QIcon(":camera-off.svg"); } ViewFinderQt::~ViewFinderQt() { } const QList<libcamera::PixelFormat> &ViewFinderQt::nativeFormats() const { static const QList<libcamera::PixelFormat> formats = ::nativeFormats.keys(); return formats; } int ViewFinderQt::setFormat(const libcamera::PixelFormat &format, const QSize &size, [[maybe_unused]] const libcamera::ColorSpace &colorSpace, unsigned int stride) { image_ = QImage(); /* * If format conversion is needed, configure the converter and allocate * the destination image. */ if (!::nativeFormats.contains(format)) { int ret = converter_.configure(format, size, stride); if (ret < 0) return ret; image_ = QImage(size, QImage::Format_RGB32); qInfo() << "Using software format conversion from" << format.toString().c_str(); } else { qInfo() << "Zero-copy enabled"; } format_ = format; size_ = size; updateGeometry(); return 0; } void ViewFinderQt::render(libcamera::FrameBuffer *buffer, Image *image) { size_t size = buffer->metadata().planes()[0].bytesused; { QMutexLocker locker(&mutex_); if (::nativeFormats.contains(format_)) { /* * If the frame format is identical to the display * format, create a QImage that references the frame * and store a reference to the frame buffer. The * previously stored frame buffer, if any, will be * released. * * \todo Get the stride from the buffer instead of * computing it naively */ assert(buffer->planes().size() == 1); image_ = QImage(image->data(0).data(), size_.width(), size_.height(), size / size_.height(), ::nativeFormats[format_]); std::swap(buffer, buffer_); } else { /* * Otherwise, convert the format and release the frame * buffer immediately. */ converter_.convert(image, size, &image_); } } update(); if (buffer) renderComplete(buffer); } void ViewFinderQt::stop() { image_ = QImage(); if (buffer_) { renderComplete(buffer_); buffer_ = nullptr; } update(); } QImage ViewFinderQt::getCurrentImage() { QMutexLocker locker(&mutex_); return image_.copy(); } void ViewFinderQt::paintEvent(QPaintEvent *) { QPainter painter(this); /* If we have an image, draw it. */ if (!image_.isNull()) { painter.drawImage(rect(), image_, image_.rect()); return; } /* * Otherwise, draw the camera stopped icon. Render it to the pixmap if * the size has changed. */ constexpr int margin = 20; if (vfSize_ != size() || pixmap_.isNull()) { QSize vfSize = size() - QSize{ 2 * margin, 2 * margin }; QSize pixmapSize{ 1, 1 }; pixmapSize.scale(vfSize, Qt::KeepAspectRatio); pixmap_ = icon_.pixmap(pixmapSize); vfSize_ = size(); } QPoint point{ margin, margin }; if (pixmap_.width() < width() - 2 * margin) point.setX((width() - pixmap_.width()) / 2); else point.setY((height() - pixmap_.height()) / 2); painter.setBackgroundMode(Qt::OpaqueMode); painter.drawPixmap(point, pixmap_); } QSize ViewFinderQt::sizeHint() const { return size_.isValid() ? size_ : QSize(640, 480); }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/message_handler.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2020, Laurent Pinchart <[email protected]> * * Log message handling */ #pragma once #include <QtGlobal> class MessageHandler { public: MessageHandler(bool verbose); private: static void handleMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); static QtMessageHandler handler_; static bool verbose_; };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/format_converter.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * Convert buffer to RGB */ #include "format_converter.h" #include <errno.h> #include <utility> #include <QImage> #include <libcamera/formats.h> #include "../common/image.h" #define RGBSHIFT 8 #ifndef MAX #define MAX(a,b) ((a)>(b)?(a):(b)) #endif #ifndef MIN #define MIN(a,b) ((a)<(b)?(a):(b)) #endif #ifndef CLAMP #define CLAMP(a,low,high) MAX((low),MIN((high),(a))) #endif #ifndef CLIP #define CLIP(x) CLAMP(x,0,255) #endif int FormatConverter::configure(const libcamera::PixelFormat &format, const QSize &size, unsigned int stride) { switch (format) { case libcamera::formats::NV12: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 2; vertSubSample_ = 2; nvSwap_ = false; break; case libcamera::formats::NV21: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 2; vertSubSample_ = 2; nvSwap_ = true; break; case libcamera::formats::NV16: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 2; vertSubSample_ = 1; nvSwap_ = false; break; case libcamera::formats::NV61: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 2; vertSubSample_ = 1; nvSwap_ = true; break; case libcamera::formats::NV24: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 1; vertSubSample_ = 1; nvSwap_ = false; break; case libcamera::formats::NV42: formatFamily_ = YUVSemiPlanar; horzSubSample_ = 1; vertSubSample_ = 1; nvSwap_ = true; break; case libcamera::formats::R8: formatFamily_ = RGB; r_pos_ = 0; g_pos_ = 0; b_pos_ = 0; bpp_ = 1; break; case libcamera::formats::RGB888: formatFamily_ = RGB; r_pos_ = 2; g_pos_ = 1; b_pos_ = 0; bpp_ = 3; break; case libcamera::formats::BGR888: formatFamily_ = RGB; r_pos_ = 0; g_pos_ = 1; b_pos_ = 2; bpp_ = 3; break; case libcamera::formats::ARGB8888: case libcamera::formats::XRGB8888: formatFamily_ = RGB; r_pos_ = 2; g_pos_ = 1; b_pos_ = 0; bpp_ = 4; break; case libcamera::formats::RGBA8888: case libcamera::formats::RGBX8888: formatFamily_ = RGB; r_pos_ = 3; g_pos_ = 2; b_pos_ = 1; bpp_ = 4; break; case libcamera::formats::ABGR8888: case libcamera::formats::XBGR8888: formatFamily_ = RGB; r_pos_ = 0; g_pos_ = 1; b_pos_ = 2; bpp_ = 4; break; case libcamera::formats::BGRA8888: case libcamera::formats::BGRX8888: formatFamily_ = RGB; r_pos_ = 1; g_pos_ = 2; b_pos_ = 3; bpp_ = 4; break; case libcamera::formats::VYUY: formatFamily_ = YUVPacked; y_pos_ = 1; cb_pos_ = 2; break; case libcamera::formats::YVYU: formatFamily_ = YUVPacked; y_pos_ = 0; cb_pos_ = 3; break; case libcamera::formats::UYVY: formatFamily_ = YUVPacked; y_pos_ = 1; cb_pos_ = 0; break; case libcamera::formats::YUYV: formatFamily_ = YUVPacked; y_pos_ = 0; cb_pos_ = 1; break; case libcamera::formats::YUV420: formatFamily_ = YUVPlanar; horzSubSample_ = 2; vertSubSample_ = 2; nvSwap_ = false; break; case libcamera::formats::YVU420: formatFamily_ = YUVPlanar; horzSubSample_ = 2; vertSubSample_ = 2; nvSwap_ = true; break; case libcamera::formats::YUV422: formatFamily_ = YUVPlanar; horzSubSample_ = 2; vertSubSample_ = 1; nvSwap_ = false; break; case libcamera::formats::MJPEG: formatFamily_ = MJPEG; break; default: return -EINVAL; }; format_ = format; width_ = size.width(); height_ = size.height(); stride_ = stride; return 0; } void FormatConverter::convert(const Image *src, size_t size, QImage *dst) { switch (formatFamily_) { case MJPEG: dst->loadFromData(src->data(0).data(), size, "JPEG"); break; case RGB: convertRGB(src, dst->bits()); break; case YUVPacked: convertYUVPacked(src, dst->bits()); break; case YUVSemiPlanar: convertYUVSemiPlanar(src, dst->bits()); break; case YUVPlanar: convertYUVPlanar(src, dst->bits()); break; }; } static void yuv_to_rgb(int y, int u, int v, int *r, int *g, int *b) { int c = y - 16; int d = u - 128; int e = v - 128; *r = CLIP(( 298 * c + 409 * e + 128) >> RGBSHIFT); *g = CLIP(( 298 * c - 100 * d - 208 * e + 128) >> RGBSHIFT); *b = CLIP(( 298 * c + 516 * d + 128) >> RGBSHIFT); } void FormatConverter::convertRGB(const Image *srcImage, unsigned char *dst) { const unsigned char *src = srcImage->data(0).data(); unsigned int x, y; int r, g, b; for (y = 0; y < height_; y++) { for (x = 0; x < width_; x++) { r = src[bpp_ * x + r_pos_]; g = src[bpp_ * x + g_pos_]; b = src[bpp_ * x + b_pos_]; dst[4 * x + 0] = b; dst[4 * x + 1] = g; dst[4 * x + 2] = r; dst[4 * x + 3] = 0xff; } src += stride_; dst += width_ * 4; } } void FormatConverter::convertYUVPacked(const Image *srcImage, unsigned char *dst) { const unsigned char *src = srcImage->data(0).data(); unsigned int src_x, src_y, dst_x, dst_y; unsigned int src_stride; unsigned int dst_stride; unsigned int cr_pos; int r, g, b, y, cr, cb; cr_pos = (cb_pos_ + 2) % 4; src_stride = stride_; dst_stride = width_ * 4; for (src_y = 0, dst_y = 0; dst_y < height_; src_y++, dst_y++) { for (src_x = 0, dst_x = 0; dst_x < width_; ) { cb = src[src_y * src_stride + src_x * 4 + cb_pos_]; cr = src[src_y * src_stride + src_x * 4 + cr_pos]; y = src[src_y * src_stride + src_x * 4 + y_pos_]; yuv_to_rgb(y, cb, cr, &r, &g, &b); dst[dst_y * dst_stride + 4 * dst_x + 0] = b; dst[dst_y * dst_stride + 4 * dst_x + 1] = g; dst[dst_y * dst_stride + 4 * dst_x + 2] = r; dst[dst_y * dst_stride + 4 * dst_x + 3] = 0xff; dst_x++; y = src[src_y * src_stride + src_x * 4 + y_pos_ + 2]; yuv_to_rgb(y, cb, cr, &r, &g, &b); dst[dst_y * dst_stride + 4 * dst_x + 0] = b; dst[dst_y * dst_stride + 4 * dst_x + 1] = g; dst[dst_y * dst_stride + 4 * dst_x + 2] = r; dst[dst_y * dst_stride + 4 * dst_x + 3] = 0xff; dst_x++; src_x++; } } } void FormatConverter::convertYUVPlanar(const Image *srcImage, unsigned char *dst) { unsigned int c_stride = stride_ / horzSubSample_; unsigned int c_inc = horzSubSample_ == 1 ? 1 : 0; const unsigned char *src_y = srcImage->data(0).data(); const unsigned char *src_cb = srcImage->data(1).data(); const unsigned char *src_cr = srcImage->data(2).data(); int r, g, b; if (nvSwap_) std::swap(src_cb, src_cr); for (unsigned int y = 0; y < height_; y++) { const unsigned char *line_y = src_y + y * stride_; const unsigned char *line_cb = src_cb + (y / vertSubSample_) * c_stride; const unsigned char *line_cr = src_cr + (y / vertSubSample_) * c_stride; for (unsigned int x = 0; x < width_; x += 2) { yuv_to_rgb(*line_y, *line_cb, *line_cr, &r, &g, &b); dst[0] = b; dst[1] = g; dst[2] = r; dst[3] = 0xff; line_y++; line_cb += c_inc; line_cr += c_inc; dst += 4; yuv_to_rgb(*line_y, *line_cb, *line_cr, &r, &g, &b); dst[0] = b; dst[1] = g; dst[2] = r; dst[3] = 0xff; line_y++; line_cb += 1; line_cr += 1; dst += 4; } } } void FormatConverter::convertYUVSemiPlanar(const Image *srcImage, unsigned char *dst) { unsigned int c_stride = stride_ * (2 / horzSubSample_); 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 = srcImage->data(0).data(); const unsigned char *src_c = srcImage->data(1).data(); int r, g, b; for (unsigned int y = 0; y < height_; y++) { const unsigned char *src_y = src + y * stride_; 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 < width_; x += 2) { yuv_to_rgb(*src_y, *src_cb, *src_cr, &r, &g, &b); dst[0] = b; dst[1] = g; dst[2] = r; dst[3] = 0xff; src_y++; src_cb += c_inc; src_cr += c_inc; dst += 4; yuv_to_rgb(*src_y, *src_cb, *src_cr, &r, &g, &b); dst[0] = b; dst[1] = g; dst[2] = r; dst[3] = 0xff; src_y++; src_cb += 2; src_cr += 2; dst += 4; } } }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/viewfinder_gl.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Linaro * * OpenGL Viewfinder for rendering by OpenGL shader */ #pragma once #include <array> #include <memory> #include <QImage> #include <QMutex> #include <QOpenGLBuffer> #include <QOpenGLFunctions> #include <QOpenGLShader> #include <QOpenGLShaderProgram> #include <QOpenGLTexture> #include <QOpenGLWidget> #include <QSize> #include <libcamera/formats.h> #include <libcamera/framebuffer.h> #include "viewfinder.h" class ViewFinderGL : public QOpenGLWidget, public ViewFinder, protected QOpenGLFunctions { Q_OBJECT public: ViewFinderGL(QWidget *parent = nullptr); ~ViewFinderGL(); const QList<libcamera::PixelFormat> &nativeFormats() const override; int setFormat(const libcamera::PixelFormat &format, const QSize &size, const libcamera::ColorSpace &colorSpace, unsigned int stride) override; void render(libcamera::FrameBuffer *buffer, Image *image) override; void stop() override; QImage getCurrentImage() override; Q_SIGNALS: void renderComplete(libcamera::FrameBuffer *buffer); protected: void initializeGL() override; void paintGL() override; void resizeGL(int w, int h) override; QSize sizeHint() const override; private: bool selectFormat(const libcamera::PixelFormat &format); void selectColorSpace(const libcamera::ColorSpace &colorSpace); void configureTexture(QOpenGLTexture &texture); bool createFragmentShader(); bool createVertexShader(); void removeShader(); void doRender(); /* Captured image size, format and buffer */ libcamera::FrameBuffer *buffer_; libcamera::PixelFormat format_; libcamera::ColorSpace colorSpace_; QSize size_; unsigned int stride_; Image *image_; /* Shaders */ QOpenGLShaderProgram shaderProgram_; std::unique_ptr<QOpenGLShader> vertexShader_; std::unique_ptr<QOpenGLShader> fragmentShader_; QString vertexShaderFile_; QString fragmentShaderFile_; QStringList fragmentShaderDefines_; /* Vertex buffer */ QOpenGLBuffer vertexBuffer_; /* Textures */ std::array<std::unique_ptr<QOpenGLTexture>, 3> textures_; /* Common texture parameters */ GLuint textureMinMagFilters_; /* YUV texture parameters */ GLuint textureUniformU_; GLuint textureUniformV_; GLuint textureUniformY_; GLuint textureUniformStep_; unsigned int horzSubSample_; unsigned int vertSubSample_; /* Raw Bayer texture parameters */ GLuint textureUniformSize_; GLuint textureUniformStrideFactor_; GLuint textureUniformBayerFirstRed_; QPointF firstRed_; QMutex mutex_; /* Prevent concurrent access to image_ */ };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/cam_select_dialog.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2022, Utkarsh Tiwari <[email protected]> * * qcam - Camera Selection dialog */ #pragma once #include <string> #include <libcamera/camera.h> #include <libcamera/camera_manager.h> #include <libcamera/controls.h> #include <libcamera/property_ids.h> #include <QDialog> #include <QString> class QComboBox; class QLabel; class CameraSelectorDialog : public QDialog { Q_OBJECT public: CameraSelectorDialog(libcamera::CameraManager *cameraManager, QWidget *parent); ~CameraSelectorDialog(); std::string getCameraId(); /* Hotplug / Unplug Support. */ void addCamera(QString cameraId); void removeCamera(QString cameraId); /* Camera Information */ void updateCameraInfo(QString cameraId); private: libcamera::CameraManager *cm_; /* UI elements. */ QComboBox *cameraIdComboBox_; QLabel *cameraLocation_; QLabel *cameraModel_; };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/main_window.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - Main application window */ #pragma once #include <memory> #include <vector> #include <libcamera/camera.h> #include <libcamera/camera_manager.h> #include <libcamera/controls.h> #include <libcamera/framebuffer.h> #include <libcamera/framebuffer_allocator.h> #include <libcamera/request.h> #include <libcamera/stream.h> #include <QElapsedTimer> #include <QIcon> #include <QMainWindow> #include <QMutex> #include <QObject> #include <QPushButton> #include <QQueue> #include <QTimer> #include "../common/stream_options.h" #include "viewfinder.h" class QAction; class CameraSelectorDialog; class Image; class HotplugEvent; enum { OptCamera = 'c', OptHelp = 'h', OptRenderer = 'r', OptStream = 's', OptVerbose = 'v', }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(libcamera::CameraManager *cm, const OptionsParser::Options &options); ~MainWindow(); bool event(QEvent *e) override; private Q_SLOTS: void quit(); void updateTitle(); void switchCamera(); void toggleCapture(bool start); void saveImageAs(); void captureRaw(); void processRaw(libcamera::FrameBuffer *buffer, const libcamera::ControlList &metadata); void renderComplete(libcamera::FrameBuffer *buffer); private: int createToolbars(); std::string chooseCamera(); int openCamera(); int startCapture(); void stopCapture(); void addCamera(std::shared_ptr<libcamera::Camera> camera); void removeCamera(std::shared_ptr<libcamera::Camera> camera); int queueRequest(libcamera::Request *request); void requestComplete(libcamera::Request *request); void processCapture(); void processHotplug(HotplugEvent *e); void processViewfinder(libcamera::FrameBuffer *buffer); /* UI elements */ QToolBar *toolbar_; QAction *startStopAction_; QPushButton *cameraSelectButton_; QAction *saveRaw_; ViewFinder *viewfinder_; QIcon iconPlay_; QIcon iconStop_; QString title_; QTimer titleTimer_; CameraSelectorDialog *cameraSelectorDialog_; /* Options */ const OptionsParser::Options &options_; /* Camera manager, camera, configuration and buffers */ libcamera::CameraManager *cm_; std::shared_ptr<libcamera::Camera> camera_; libcamera::FrameBufferAllocator *allocator_; std::unique_ptr<libcamera::CameraConfiguration> config_; std::map<libcamera::FrameBuffer *, std::unique_ptr<Image>> mappedBuffers_; /* Capture state, buffers queue and statistics */ bool isCapturing_; bool captureRaw_; libcamera::Stream *vfStream_; libcamera::Stream *rawStream_; std::map<const libcamera::Stream *, QQueue<libcamera::FrameBuffer *>> freeBuffers_; QQueue<libcamera::Request *> doneQueue_; QQueue<libcamera::Request *> freeQueue_; QMutex mutex_; /* Protects freeBuffers_, doneQueue_, and freeQueue_ */ uint64_t lastBufferTime_; QElapsedTimer frameRateInterval_; uint32_t previousFrames_; uint32_t framesCaptured_; std::vector<std::unique_ptr<libcamera::Request>> requests_; };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/main.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - The libcamera GUI test application */ #include <signal.h> #include <string.h> #include <QApplication> #include <QtDebug> #include <libcamera/camera_manager.h> #include "../common/options.h" #include "../common/stream_options.h" #include "main_window.h" #include "message_handler.h" using namespace libcamera; void signalHandler([[maybe_unused]] int signal) { qInfo() << "Exiting"; qApp->quit(); } OptionsParser::Options parseOptions(int argc, char *argv[]) { StreamKeyValueParser streamKeyValue; OptionsParser parser; parser.addOption(OptCamera, OptionString, "Specify which camera to operate on", "camera", ArgumentRequired, "camera"); parser.addOption(OptHelp, OptionNone, "Display this help message", "help"); parser.addOption(OptRenderer, OptionString, "Choose the renderer type {qt,gles} (default: qt)", "renderer", ArgumentRequired, "renderer"); parser.addOption(OptStream, &streamKeyValue, "Set configuration of a camera stream", "stream", true); parser.addOption(OptVerbose, OptionNone, "Print verbose log messages", "verbose"); OptionsParser::Options options = parser.parse(argc, argv); if (options.isSet(OptHelp)) parser.usage(); return options; } int main(int argc, char **argv) { QApplication app(argc, argv); int ret; OptionsParser::Options options = parseOptions(argc, argv); if (!options.valid()) return EXIT_FAILURE; if (options.isSet(OptHelp)) return 0; MessageHandler msgHandler(options.isSet(OptVerbose)); struct sigaction sa = {}; sa.sa_handler = &signalHandler; sigaction(SIGINT, &sa, nullptr); CameraManager *cm = new libcamera::CameraManager(); ret = cm->start(); if (ret) { qInfo() << "Failed to start camera manager:" << strerror(-ret); return EXIT_FAILURE; } MainWindow *mainWindow = new MainWindow(cm, options); mainWindow->show(); ret = app.exec(); delete mainWindow; cm->stop(); delete cm; return ret; }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/viewfinder_qt.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * qcam - QPainter-based ViewFinder */ #pragma once #include <QIcon> #include <QImage> #include <QList> #include <QMutex> #include <QSize> #include <QWidget> #include <libcamera/formats.h> #include <libcamera/framebuffer.h> #include <libcamera/pixel_format.h> #include "format_converter.h" #include "viewfinder.h" class ViewFinderQt : public QWidget, public ViewFinder { Q_OBJECT public: ViewFinderQt(QWidget *parent); ~ViewFinderQt(); const QList<libcamera::PixelFormat> &nativeFormats() const override; int setFormat(const libcamera::PixelFormat &format, const QSize &size, const libcamera::ColorSpace &colorSpace, unsigned int stride) override; void render(libcamera::FrameBuffer *buffer, Image *image) override; void stop() override; QImage getCurrentImage() override; Q_SIGNALS: void renderComplete(libcamera::FrameBuffer *buffer); protected: void paintEvent(QPaintEvent *) override; QSize sizeHint() const override; private: FormatConverter converter_; libcamera::PixelFormat format_; QSize size_; /* Camera stopped icon */ QSize vfSize_; QIcon icon_; QPixmap pixmap_; /* Buffer and render image */ libcamera::FrameBuffer *buffer_; QImage image_; QMutex mutex_; /* Prevent concurrent access to image_ */ };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/format_converter.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2019, Google Inc. * * Convert buffer to RGB */ #pragma once #include <stddef.h> #include <QSize> #include <libcamera/pixel_format.h> class Image; class QImage; class FormatConverter { public: int configure(const libcamera::PixelFormat &format, const QSize &size, unsigned int stride); void convert(const Image *src, size_t size, QImage *dst); private: enum FormatFamily { MJPEG, RGB, YUVPacked, YUVPlanar, YUVSemiPlanar, }; void convertRGB(const Image *src, unsigned char *dst); void convertYUVPacked(const Image *src, unsigned char *dst); void convertYUVPlanar(const Image *src, unsigned char *dst); void convertYUVSemiPlanar(const Image *src, unsigned char *dst); libcamera::PixelFormat format_; unsigned int width_; unsigned int height_; unsigned int stride_; enum FormatFamily formatFamily_; /* NV parameters */ unsigned int horzSubSample_; unsigned int vertSubSample_; bool nvSwap_; /* RGB parameters */ unsigned int bpp_; unsigned int r_pos_; unsigned int g_pos_; unsigned int b_pos_; /* YUV parameters */ unsigned int y_pos_; unsigned int cb_pos_; };
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/cam_select_dialog.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2022, Utkarsh Tiwari <[email protected]> * * qcam - Camera Selection dialog */ #include "cam_select_dialog.h" #include <memory> #include <libcamera/camera.h> #include <libcamera/camera_manager.h> #include <QComboBox> #include <QDialogButtonBox> #include <QFormLayout> #include <QLabel> #include <QString> CameraSelectorDialog::CameraSelectorDialog(libcamera::CameraManager *cameraManager, QWidget *parent) : QDialog(parent), cm_(cameraManager) { /* Use a QFormLayout for the dialog. */ QFormLayout *layout = new QFormLayout(this); /* Setup the camera id combo-box. */ cameraIdComboBox_ = new QComboBox; for (const auto &cam : cm_->cameras()) cameraIdComboBox_->addItem(QString::fromStdString(cam->id())); /* Set camera information labels. */ cameraLocation_ = new QLabel; cameraModel_ = new QLabel; updateCameraInfo(cameraIdComboBox_->currentText()); connect(cameraIdComboBox_, &QComboBox::currentTextChanged, this, &CameraSelectorDialog::updateCameraInfo); /* Setup the QDialogButton Box */ QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); /* Set the layout. */ layout->addRow("Camera:", cameraIdComboBox_); layout->addRow("Location:", cameraLocation_); layout->addRow("Model:", cameraModel_); layout->addWidget(buttonBox); } CameraSelectorDialog::~CameraSelectorDialog() = default; std::string CameraSelectorDialog::getCameraId() { return cameraIdComboBox_->currentText().toStdString(); } /* Hotplug / Unplug Support. */ void CameraSelectorDialog::addCamera(QString cameraId) { cameraIdComboBox_->addItem(cameraId); } void CameraSelectorDialog::removeCamera(QString cameraId) { int cameraIndex = cameraIdComboBox_->findText(cameraId); cameraIdComboBox_->removeItem(cameraIndex); } /* Camera Information */ void CameraSelectorDialog::updateCameraInfo(QString cameraId) { const std::shared_ptr<libcamera::Camera> &camera = cm_->get(cameraId.toStdString()); if (!camera) return; const libcamera::ControlList &properties = camera->properties(); const auto &location = properties.get(libcamera::properties::Location); if (location) { switch (*location) { case libcamera::properties::CameraLocationFront: cameraLocation_->setText("Internal front camera"); break; case libcamera::properties::CameraLocationBack: cameraLocation_->setText("Internal back camera"); break; case libcamera::properties::CameraLocationExternal: cameraLocation_->setText("External camera"); break; default: cameraLocation_->setText("Unknown"); } } else { cameraLocation_->setText("Unknown"); } const auto &model = properties.get(libcamera::properties::Model) .value_or("Unknown"); cameraModel_->setText(QString::fromStdString(model)); }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/message_handler.cpp
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2020, Laurent Pinchart <[email protected]> * * qcam - Log message handling */ #include "message_handler.h" QtMessageHandler MessageHandler::handler_ = nullptr; bool MessageHandler::verbose_ = false; MessageHandler::MessageHandler(bool verbose) { verbose_ = verbose; handler_ = qInstallMessageHandler(&MessageHandler::handleMessage); } void MessageHandler::handleMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) { if (type == QtDebugMsg && !verbose_) return; handler_(type, context, msg); }
0
repos/libcamera/src/apps
repos/libcamera/src/apps/qcam/viewfinder_gl.cpp
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright (C) 2020, Linaro * * OpenGL Viewfinder for rendering by OpenGL shader */ #include "viewfinder_gl.h" #include <array> #include <QByteArray> #include <QFile> #include <QImage> #include <QStringList> #include <libcamera/formats.h> #include "../common/image.h" static const QList<libcamera::PixelFormat> supportedFormats{ /* YUV - packed (single plane) */ libcamera::formats::UYVY, libcamera::formats::VYUY, libcamera::formats::YUYV, libcamera::formats::YVYU, /* YUV - semi planar (two planes) */ libcamera::formats::NV12, libcamera::formats::NV21, libcamera::formats::NV16, libcamera::formats::NV61, libcamera::formats::NV24, libcamera::formats::NV42, /* YUV - fully planar (three planes) */ libcamera::formats::YUV420, libcamera::formats::YVU420, /* RGB */ libcamera::formats::ABGR8888, libcamera::formats::ARGB8888, libcamera::formats::BGRA8888, libcamera::formats::RGBA8888, libcamera::formats::BGR888, libcamera::formats::RGB888, /* Raw Bayer 8-bit */ libcamera::formats::SBGGR8, libcamera::formats::SGBRG8, libcamera::formats::SGRBG8, libcamera::formats::SRGGB8, /* Raw Bayer 10-bit packed */ libcamera::formats::SBGGR10_CSI2P, libcamera::formats::SGBRG10_CSI2P, libcamera::formats::SGRBG10_CSI2P, libcamera::formats::SRGGB10_CSI2P, /* Raw Bayer 12-bit packed */ libcamera::formats::SBGGR12_CSI2P, libcamera::formats::SGBRG12_CSI2P, libcamera::formats::SGRBG12_CSI2P, libcamera::formats::SRGGB12_CSI2P, }; ViewFinderGL::ViewFinderGL(QWidget *parent) : QOpenGLWidget(parent), buffer_(nullptr), colorSpace_(libcamera::ColorSpace::Raw), image_(nullptr), vertexBuffer_(QOpenGLBuffer::VertexBuffer) { } ViewFinderGL::~ViewFinderGL() { removeShader(); } const QList<libcamera::PixelFormat> &ViewFinderGL::nativeFormats() const { return supportedFormats; } int ViewFinderGL::setFormat(const libcamera::PixelFormat &format, const QSize &size, const libcamera::ColorSpace &colorSpace, unsigned int stride) { if (format != format_ || colorSpace != colorSpace_) { /* * If the fragment already exists, remove it and create a new * one for the new format. */ if (shaderProgram_.isLinked()) { shaderProgram_.release(); shaderProgram_.removeShader(fragmentShader_.get()); fragmentShader_.reset(); } if (!selectFormat(format)) return -1; selectColorSpace(colorSpace); format_ = format; colorSpace_ = colorSpace; } size_ = size; stride_ = stride; updateGeometry(); return 0; } void ViewFinderGL::stop() { if (buffer_) { renderComplete(buffer_); buffer_ = nullptr; image_ = nullptr; } } QImage ViewFinderGL::getCurrentImage() { QMutexLocker locker(&mutex_); return grabFramebuffer(); } void ViewFinderGL::render(libcamera::FrameBuffer *buffer, Image *image) { if (buffer_) renderComplete(buffer_); image_ = image; update(); buffer_ = buffer; } bool ViewFinderGL::selectFormat(const libcamera::PixelFormat &format) { bool ret = true; /* Set min/mag filters to GL_LINEAR by default. */ textureMinMagFilters_ = GL_LINEAR; /* Use identity.vert as the default vertex shader. */ vertexShaderFile_ = ":identity.vert"; fragmentShaderDefines_.clear(); switch (format) { case libcamera::formats::NV12: horzSubSample_ = 2; vertSubSample_ = 2; fragmentShaderDefines_.append("#define YUV_PATTERN_UV"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::NV21: horzSubSample_ = 2; vertSubSample_ = 2; fragmentShaderDefines_.append("#define YUV_PATTERN_VU"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::NV16: horzSubSample_ = 2; vertSubSample_ = 1; fragmentShaderDefines_.append("#define YUV_PATTERN_UV"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::NV61: horzSubSample_ = 2; vertSubSample_ = 1; fragmentShaderDefines_.append("#define YUV_PATTERN_VU"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::NV24: horzSubSample_ = 1; vertSubSample_ = 1; fragmentShaderDefines_.append("#define YUV_PATTERN_UV"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::NV42: horzSubSample_ = 1; vertSubSample_ = 1; fragmentShaderDefines_.append("#define YUV_PATTERN_VU"); fragmentShaderFile_ = ":YUV_2_planes.frag"; break; case libcamera::formats::YUV420: horzSubSample_ = 2; vertSubSample_ = 2; fragmentShaderFile_ = ":YUV_3_planes.frag"; break; case libcamera::formats::YVU420: horzSubSample_ = 2; vertSubSample_ = 2; fragmentShaderFile_ = ":YUV_3_planes.frag"; break; case libcamera::formats::UYVY: fragmentShaderDefines_.append("#define YUV_PATTERN_UYVY"); fragmentShaderFile_ = ":YUV_packed.frag"; break; case libcamera::formats::VYUY: fragmentShaderDefines_.append("#define YUV_PATTERN_VYUY"); fragmentShaderFile_ = ":YUV_packed.frag"; break; case libcamera::formats::YUYV: fragmentShaderDefines_.append("#define YUV_PATTERN_YUYV"); fragmentShaderFile_ = ":YUV_packed.frag"; break; case libcamera::formats::YVYU: fragmentShaderDefines_.append("#define YUV_PATTERN_YVYU"); fragmentShaderFile_ = ":YUV_packed.frag"; break; case libcamera::formats::ABGR8888: fragmentShaderDefines_.append("#define RGB_PATTERN rgb"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::ARGB8888: fragmentShaderDefines_.append("#define RGB_PATTERN bgr"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::BGRA8888: fragmentShaderDefines_.append("#define RGB_PATTERN gba"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::RGBA8888: fragmentShaderDefines_.append("#define RGB_PATTERN abg"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::BGR888: fragmentShaderDefines_.append("#define RGB_PATTERN rgb"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::RGB888: fragmentShaderDefines_.append("#define RGB_PATTERN bgr"); fragmentShaderFile_ = ":RGB.frag"; break; case libcamera::formats::SBGGR8: firstRed_.setX(1.0); firstRed_.setY(1.0); vertexShaderFile_ = ":bayer_8.vert"; fragmentShaderFile_ = ":bayer_8.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGBRG8: firstRed_.setX(0.0); firstRed_.setY(1.0); vertexShaderFile_ = ":bayer_8.vert"; fragmentShaderFile_ = ":bayer_8.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGRBG8: firstRed_.setX(1.0); firstRed_.setY(0.0); vertexShaderFile_ = ":bayer_8.vert"; fragmentShaderFile_ = ":bayer_8.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SRGGB8: firstRed_.setX(0.0); firstRed_.setY(0.0); vertexShaderFile_ = ":bayer_8.vert"; fragmentShaderFile_ = ":bayer_8.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SBGGR10_CSI2P: firstRed_.setX(1.0); firstRed_.setY(1.0); fragmentShaderDefines_.append("#define RAW10P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGBRG10_CSI2P: firstRed_.setX(0.0); firstRed_.setY(1.0); fragmentShaderDefines_.append("#define RAW10P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGRBG10_CSI2P: firstRed_.setX(1.0); firstRed_.setY(0.0); fragmentShaderDefines_.append("#define RAW10P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SRGGB10_CSI2P: firstRed_.setX(0.0); firstRed_.setY(0.0); fragmentShaderDefines_.append("#define RAW10P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SBGGR12_CSI2P: firstRed_.setX(1.0); firstRed_.setY(1.0); fragmentShaderDefines_.append("#define RAW12P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGBRG12_CSI2P: firstRed_.setX(0.0); firstRed_.setY(1.0); fragmentShaderDefines_.append("#define RAW12P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SGRBG12_CSI2P: firstRed_.setX(1.0); firstRed_.setY(0.0); fragmentShaderDefines_.append("#define RAW12P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; case libcamera::formats::SRGGB12_CSI2P: firstRed_.setX(0.0); firstRed_.setY(0.0); fragmentShaderDefines_.append("#define RAW12P"); fragmentShaderFile_ = ":bayer_1x_packed.frag"; textureMinMagFilters_ = GL_NEAREST; break; default: ret = false; qWarning() << "[ViewFinderGL]:" << "format not supported."; break; }; return ret; } void ViewFinderGL::selectColorSpace(const libcamera::ColorSpace &colorSpace) { std::array<double, 9> yuv2rgb; /* OpenGL stores arrays in column-major order. */ switch (colorSpace.ycbcrEncoding) { case libcamera::ColorSpace::YcbcrEncoding::None: default: yuv2rgb = { 1.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 1.0000, }; break; case libcamera::ColorSpace::YcbcrEncoding::Rec601: yuv2rgb = { 1.0000, 1.0000, 1.0000, 0.0000, -0.3441, 1.7720, 1.4020, -0.7141, 0.0000, }; break; case libcamera::ColorSpace::YcbcrEncoding::Rec709: yuv2rgb = { 1.0000, 1.0000, 1.0000, 0.0000, -0.1873, 1.8856, 1.5748, -0.4681, 0.0000, }; break; case libcamera::ColorSpace::YcbcrEncoding::Rec2020: yuv2rgb = { 1.0000, 1.0000, 1.0000, 0.0000, -0.1646, 1.8814, 1.4746, -0.5714, 0.0000, }; break; } double offset; switch (colorSpace.range) { case libcamera::ColorSpace::Range::Full: default: offset = 0.0; break; case libcamera::ColorSpace::Range::Limited: offset = 16.0; for (unsigned int i = 0; i < 3; ++i) yuv2rgb[i] *= 255.0 / 219.0; for (unsigned int i = 4; i < 9; ++i) yuv2rgb[i] *= 255.0 / 224.0; break; } QStringList matrix; for (double coeff : yuv2rgb) matrix.append(QString::number(coeff, 'f')); fragmentShaderDefines_.append("#define YUV2RGB_MATRIX " + matrix.join(", ")); fragmentShaderDefines_.append(QString("#define YUV2RGB_Y_OFFSET %1") .arg(offset, 0, 'f', 1)); } bool ViewFinderGL::createVertexShader() { /* Create Vertex Shader */ vertexShader_ = std::make_unique<QOpenGLShader>(QOpenGLShader::Vertex, this); /* Compile the vertex shader */ if (!vertexShader_->compileSourceFile(vertexShaderFile_)) { qWarning() << "[ViewFinderGL]:" << vertexShader_->log(); return false; } shaderProgram_.addShader(vertexShader_.get()); return true; } bool ViewFinderGL::createFragmentShader() { int attributeVertex; int attributeTexture; /* * Create the fragment shader, compile it, and add it to the shader * program. The #define macros stored in fragmentShaderDefines_, if * any, are prepended to the source code. */ fragmentShader_ = std::make_unique<QOpenGLShader>(QOpenGLShader::Fragment, this); QFile file(fragmentShaderFile_); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Shader" << fragmentShaderFile_ << "not found"; return false; } QString defines = fragmentShaderDefines_.join('\n') + "\n"; QByteArray src = file.readAll(); src.prepend(defines.toUtf8()); if (!fragmentShader_->compileSourceCode(src)) { qWarning() << "[ViewFinderGL]:" << fragmentShader_->log(); return false; } shaderProgram_.addShader(fragmentShader_.get()); /* Link shader pipeline */ if (!shaderProgram_.link()) { qWarning() << "[ViewFinderGL]:" << shaderProgram_.log(); close(); } /* Bind shader pipeline for use */ if (!shaderProgram_.bind()) { qWarning() << "[ViewFinderGL]:" << shaderProgram_.log(); close(); } attributeVertex = shaderProgram_.attributeLocation("vertexIn"); attributeTexture = shaderProgram_.attributeLocation("textureIn"); shaderProgram_.enableAttributeArray(attributeVertex); shaderProgram_.setAttributeBuffer(attributeVertex, GL_FLOAT, 0, 2, 2 * sizeof(GLfloat)); shaderProgram_.enableAttributeArray(attributeTexture); shaderProgram_.setAttributeBuffer(attributeTexture, GL_FLOAT, 8 * sizeof(GLfloat), 2, 2 * sizeof(GLfloat)); textureUniformY_ = shaderProgram_.uniformLocation("tex_y"); textureUniformU_ = shaderProgram_.uniformLocation("tex_u"); textureUniformV_ = shaderProgram_.uniformLocation("tex_v"); textureUniformStep_ = shaderProgram_.uniformLocation("tex_step"); textureUniformSize_ = shaderProgram_.uniformLocation("tex_size"); textureUniformStrideFactor_ = shaderProgram_.uniformLocation("stride_factor"); textureUniformBayerFirstRed_ = shaderProgram_.uniformLocation("tex_bayer_first_red"); /* Create the textures. */ for (std::unique_ptr<QOpenGLTexture> &texture : textures_) { if (texture) continue; texture = std::make_unique<QOpenGLTexture>(QOpenGLTexture::Target2D); texture->create(); } return true; } void ViewFinderGL::configureTexture(QOpenGLTexture &texture) { glBindTexture(GL_TEXTURE_2D, texture.textureId()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, textureMinMagFilters_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, textureMinMagFilters_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } void ViewFinderGL::removeShader() { if (shaderProgram_.isLinked()) { shaderProgram_.release(); shaderProgram_.removeAllShaders(); } } void ViewFinderGL::initializeGL() { initializeOpenGLFunctions(); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); static const GLfloat coordinates[2][4][2]{ { /* Vertex coordinates */ { -1.0f, -1.0f }, { -1.0f, +1.0f }, { +1.0f, +1.0f }, { +1.0f, -1.0f }, }, { /* Texture coordinates */ { 0.0f, 1.0f }, { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, }, }; vertexBuffer_.create(); vertexBuffer_.bind(); vertexBuffer_.allocate(coordinates, sizeof(coordinates)); /* Create Vertex Shader */ if (!createVertexShader()) qWarning() << "[ViewFinderGL]: create vertex shader failed."; glClearColor(1.0f, 1.0f, 1.0f, 0.0f); } void ViewFinderGL::doRender() { /* Stride of the first plane, in pixels. */ unsigned int stridePixels; switch (format_) { case libcamera::formats::NV12: case libcamera::formats::NV21: case libcamera::formats::NV16: case libcamera::formats::NV61: case libcamera::formats::NV24: case libcamera::formats::NV42: /* Activate texture Y */ glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_, size_.height(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); /* Activate texture UV/VU */ glActiveTexture(GL_TEXTURE1); configureTexture(*textures_[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, stride_ / horzSubSample_, size_.height() / vertSubSample_, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, image_->data(1).data()); shaderProgram_.setUniformValue(textureUniformU_, 1); stridePixels = stride_; break; case libcamera::formats::YUV420: /* Activate texture Y */ glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_, size_.height(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); /* Activate texture U */ glActiveTexture(GL_TEXTURE1); configureTexture(*textures_[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_ / horzSubSample_, size_.height() / vertSubSample_, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(1).data()); shaderProgram_.setUniformValue(textureUniformU_, 1); /* Activate texture V */ glActiveTexture(GL_TEXTURE2); configureTexture(*textures_[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_ / horzSubSample_, size_.height() / vertSubSample_, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(2).data()); shaderProgram_.setUniformValue(textureUniformV_, 2); stridePixels = stride_; break; case libcamera::formats::YVU420: /* Activate texture Y */ glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_, size_.height(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); /* Activate texture V */ glActiveTexture(GL_TEXTURE2); configureTexture(*textures_[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_ / horzSubSample_, size_.height() / vertSubSample_, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(1).data()); shaderProgram_.setUniformValue(textureUniformV_, 2); /* Activate texture U */ glActiveTexture(GL_TEXTURE1); configureTexture(*textures_[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_ / horzSubSample_, size_.height() / vertSubSample_, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(2).data()); shaderProgram_.setUniformValue(textureUniformU_, 1); stridePixels = stride_; break; case libcamera::formats::UYVY: case libcamera::formats::VYUY: case libcamera::formats::YUYV: case libcamera::formats::YVYU: /* * Packed YUV formats are stored in a RGBA texture to match the * OpenGL texel size with the 4 bytes repeating pattern in YUV. * The texture width is thus half of the image_ with. */ glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, stride_ / 4, size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); /* * The shader needs the step between two texture pixels in the * horizontal direction, expressed in texture coordinate units * ([0, 1]). There are exactly width - 1 steps between the * leftmost and rightmost texels. */ shaderProgram_.setUniformValue(textureUniformStep_, 1.0f / (size_.width() / 2 - 1), 1.0f /* not used */); stridePixels = stride_ / 2; break; case libcamera::formats::ABGR8888: case libcamera::formats::ARGB8888: case libcamera::formats::BGRA8888: case libcamera::formats::RGBA8888: glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, stride_ / 4, size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); stridePixels = stride_ / 4; break; case libcamera::formats::BGR888: case libcamera::formats::RGB888: glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, stride_ / 3, size_.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); stridePixels = stride_ / 3; break; case libcamera::formats::SBGGR8: case libcamera::formats::SGBRG8: case libcamera::formats::SGRBG8: case libcamera::formats::SRGGB8: case libcamera::formats::SBGGR10_CSI2P: case libcamera::formats::SGBRG10_CSI2P: case libcamera::formats::SGRBG10_CSI2P: case libcamera::formats::SRGGB10_CSI2P: case libcamera::formats::SBGGR12_CSI2P: case libcamera::formats::SGBRG12_CSI2P: case libcamera::formats::SGRBG12_CSI2P: case libcamera::formats::SRGGB12_CSI2P: /* * Raw Bayer 8-bit, and packed raw Bayer 10-bit/12-bit formats * are stored in a GL_LUMINANCE texture. The texture width is * equal to the stride. */ glActiveTexture(GL_TEXTURE0); configureTexture(*textures_[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, stride_, size_.height(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image_->data(0).data()); shaderProgram_.setUniformValue(textureUniformY_, 0); shaderProgram_.setUniformValue(textureUniformBayerFirstRed_, firstRed_); shaderProgram_.setUniformValue(textureUniformSize_, size_.width(), /* in pixels */ size_.height()); shaderProgram_.setUniformValue(textureUniformStep_, 1.0f / (stride_ - 1), 1.0f / (size_.height() - 1)); /* * The stride is already taken into account in the shaders, set * the generic stride factor to 1.0. */ stridePixels = size_.width(); break; default: stridePixels = size_.width(); break; }; /* * Compute the stride factor for the vertex shader, to map the * horizontal texture coordinate range [0.0, 1.0] to the active portion * of the image. */ shaderProgram_.setUniformValue(textureUniformStrideFactor_, static_cast<float>(size_.width() - 1) / (stridePixels - 1)); } void ViewFinderGL::paintGL() { if (!fragmentShader_) if (!createFragmentShader()) { qWarning() << "[ViewFinderGL]:" << "create fragment shader failed."; } if (image_) { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); doRender(); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } } void ViewFinderGL::resizeGL(int w, int h) { glViewport(0, 0, w, h); } QSize ViewFinderGL::sizeHint() const { return size_.isValid() ? size_ : QSize(640, 480); }
0
repos/libcamera/src/apps/qcam/assets
repos/libcamera/src/apps/qcam/assets/shader/bayer_8.frag
/* SPDX-License-Identifier: BSD-2-Clause */ /* From http://jgt.akpeters.com/papers/McGuire08/ Efficient, High-Quality Bayer Demosaic Filtering on GPUs Morgan McGuire This paper appears in issue Volume 13, Number 4. --------------------------------------------------------- Copyright (c) 2008, Morgan McGuire. All rights reserved. Modified by Linaro Ltd to integrate it into libcamera. Copyright (C) 2021, Linaro */ //Pixel Shader #ifdef GL_ES precision mediump float; #endif /** Monochrome RGBA or GL_LUMINANCE Bayer encoded texture.*/ uniform sampler2D tex_y; varying vec4 center; varying vec4 yCoord; varying vec4 xCoord; void main(void) { #define fetch(x, y) texture2D(tex_y, vec2(x, y)).r float C = texture2D(tex_y, center.xy).r; // ( 0, 0) const vec4 kC = vec4( 4.0, 6.0, 5.0, 5.0) / 8.0; // Determine which of four types of pixels we are on. vec2 alternate = mod(floor(center.zw), 2.0); vec4 Dvec = vec4( fetch(xCoord[1], yCoord[1]), // (-1,-1) fetch(xCoord[1], yCoord[2]), // (-1, 1) fetch(xCoord[2], yCoord[1]), // ( 1,-1) fetch(xCoord[2], yCoord[2])); // ( 1, 1) vec4 PATTERN = (kC.xyz * C).xyzz; // Can also be a dot product with (1,1,1,1) on hardware where that is // specially optimized. // Equivalent to: D = Dvec[0] + Dvec[1] + Dvec[2] + Dvec[3]; Dvec.xy += Dvec.zw; Dvec.x += Dvec.y; vec4 value = vec4( fetch(center.x, yCoord[0]), // ( 0,-2) fetch(center.x, yCoord[1]), // ( 0,-1) fetch(xCoord[0], center.y), // (-2, 0) fetch(xCoord[1], center.y)); // (-1, 0) vec4 temp = vec4( fetch(center.x, yCoord[3]), // ( 0, 2) fetch(center.x, yCoord[2]), // ( 0, 1) fetch(xCoord[3], center.y), // ( 2, 0) fetch(xCoord[2], center.y)); // ( 1, 0) // Even the simplest compilers should be able to constant-fold these to // avoid the division. // Note that on scalar processors these constants force computation of some // identical products twice. const vec4 kA = vec4(-1.0, -1.5, 0.5, -1.0) / 8.0; const vec4 kB = vec4( 2.0, 0.0, 0.0, 4.0) / 8.0; const vec4 kD = vec4( 0.0, 2.0, -1.0, -1.0) / 8.0; // Conserve constant registers and take advantage of free swizzle on load #define kE (kA.xywz) #define kF (kB.xywz) value += temp; // There are five filter patterns (identity, cross, checker, // theta, phi). Precompute the terms from all of them and then // use swizzles to assign to color channels. // // Channel Matches // x cross (e.g., EE G) // y checker (e.g., EE B) // z theta (e.g., EO R) // w phi (e.g., EO R) #define A (value[0]) #define B (value[1]) #define D (Dvec.x) #define E (value[2]) #define F (value[3]) // Avoid zero elements. On a scalar processor this saves two MADDs // and it has no effect on a vector processor. PATTERN.yzw += (kD.yz * D).xyy; PATTERN += (kA.xyz * A).xyzx + (kE.xyw * E).xyxz; PATTERN.xw += kB.xw * B; PATTERN.xz += kF.xz * F; gl_FragColor.rgb = (alternate.y == 0.0) ? ((alternate.x == 0.0) ? vec3(C, PATTERN.xy) : vec3(PATTERN.z, C, PATTERN.w)) : ((alternate.x == 0.0) ? vec3(PATTERN.w, C, PATTERN.z) : vec3(PATTERN.yx, C)); }