summaryrefslogtreecommitdiff
path: root/src/android/mm/generic_camera_buffer.cpp
blob: 0ffcb445c954af9b4c41455417c017d43f307169 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2021, Google Inc.
 *
 * Generic Android frame buffer backend
 */

#include "../camera_buffer.h"

#include <sys/mman.h>
#include <unistd.h>

#include <libcamera/base/log.h>

#include "libcamera/internal/formats.h"
#include "libcamera/internal/mapped_framebuffer.h"

using namespace libcamera;

LOG_DECLARE_CATEGORY(HAL)

class CameraBuffer::Private : public Extensible::Private,
			      public MappedBuffer
{
	LIBCAMERA_DECLARE_PUBLIC(CameraBuffer)

public:
	Private(CameraBuffer *cameraBuffer, buffer_handle_t camera3Buffer,
		PixelFormat pixelFormat, const Size &size, int flags);
	~Private();

	unsigned int numPlanes() const;

	Span<uint8_t> plane(unsigned int plane);

	unsigned int stride(unsigned int plane) const;
	unsigned int offset(unsigned int plane) const;
	unsigned int size(unsigned int plane) const;

	size_t jpegBufferSize(size_t maxJpegBufferSize) const;

private:
	struct PlaneInfo {
		unsigned int stride;
		unsigned int offset;
		unsigned int size;
	};

	void map();

	int fd_;
	int flags_;
	off_t bufferLength_;
	bool mapped_;
	std::vector<PlaneInfo> planeInfo_;
};

CameraBuffer::Private::Private([[maybe_unused]] CameraBuffer *cameraBuffer,
			       buffer_handle_t camera3Buffer,
			       PixelFormat pixelFormat,
			       const Size &size, int flags)
	: fd_(-1), flags_(flags), bufferLength_(-1), mapped_(false)
{
	error_ = 0;

	const auto &info = PixelFormatInfo::info(pixelFormat);
	if (!info.isValid()) {
		error_ = -EINVAL;
		LOG(HAL, Error) << "Invalid pixel format: " << pixelFormat;
		return;
	}

	/*
	 * As Android doesn't offer an API to query buffer layouts, assume for
	 * now that the buffer is backed by a single dmabuf, with planes being
	 * stored contiguously.
	 */
	for (int i = 0; i < camera3Buffer->numFds; i++) {
		if (camera3Buffer->data[i] == -1 || camera3Buffer->data[i] == fd_)
			continue;

		if (fd_ != -1) {
			error_ = -EINVAL;
			LOG(HAL, Error) << "Discontiguous planes are not supported";
			return;
		}

		fd_ = camera3Buffer->data[i];
	}

	if (fd_ == -1) {
		error_ = -EINVAL;
		LOG(HAL, Error) << "No valid file descriptor";
		return;
	}

	bufferLength_ = lseek(fd_, 0, SEEK_END);
	if (bufferLength_ < 0) {
		error_ = -errno;
		LOG(HAL, Error) << "Failed to get buffer length";
		return;
	}

	const unsigned int numPlanes = info.numPlanes();
	planeInfo_.resize(numPlanes);

	unsigned int offset = 0;
	for (unsigned int i = 0; i < numPlanes; ++i) {
		const unsigned int planeSize = info.planeSize(size, i);

		planeInfo_[i].stride = info.stride(size.width, i, 1u);
		planeInfo_[i].offset = offset;
		planeInfo_[i].size = planeSize;

		if (bufferLength_ < offset + planeSize) {
			LOG(HAL, Error) << "Plane " << i << " is out of buffer:"
					<< " plane offset=" << offset
					<< ", plane size=" << planeSize
					<< ", buffer length=" << bufferLength_;
			return;
		}

		offset += planeSize;
	}
}

CameraBuffer::Private::~Private()
{
}

unsigned int CameraBuffer::Private::numPlanes() const
{
	return planeInfo_.size();
}

Span<uint8_t> CameraBuffer::Private::plane(unsigned int plane)
{
	if (!mapped_)
		map();
	if (!mapped_)
		return {};

	return planes_[plane];
}

unsigned int CameraBuffer::Private::stride(unsigned int plane) const
{
	if (plane >= planeInfo_.size())
		return 0;

	return planeInfo_[plane].stride;
}

unsigned int CameraBuffer::Private::offset(unsigned int plane) const
{
	if (plane >= planeInfo_.size())
		return 0;

	return planeInfo_[plane].offset;
}

unsigned int CameraBuffer::Private::size(unsigned int plane) const
{
	if (plane >= planeInfo_.size())
		return 0;

	return planeInfo_[plane].size;
}

size_t CameraBuffer::Private::jpegBufferSize(size_t maxJpegBufferSize) const
{
	ASSERT(bufferLength_ >= 0);

	return std::min<unsigned int>(bufferLength_, maxJpegBufferSize);
}

void CameraBuffer::Private::map()
{
	ASSERT(fd_ != -1);
	ASSERT(bufferLength_ >= 0);

	void *address = mmap(nullptr, bufferLength_, flags_, MAP_SHARED, fd_, 0);
	if (address == MAP_FAILED) {
		error_ = -errno;
		LOG(HAL, Error) << "Failed to mmap plane";
		return;
	}
	maps_.emplace_back(static_cast<uint8_t *>(address), bufferLength_);

	planes_.reserve(planeInfo_.size());
	for (const auto &info : planeInfo_) {
		planes_.emplace_back(
			static_cast<uint8_t *>(address) + info.offset, info.size);
	}

	mapped_ = true;
}

PUBLIC_CAMERA_BUFFER_IMPLEMENTATION
lass="hl opt">.format(self.pattern)) print(' exposure = {}'.format(self.exposure)) print(' againQ8 = {}'.format(self.againQ8)) print(' againQ8_norm = {}'.format(self.againQ8_norm)) print(' camName = {}'.format(self.camName)) print(' blacklevel = {}'.format(self.blacklevel)) print(' blacklevel_16 = {}'.format(self.blacklevel_16)) return 1 """ get image from raw scanline data """ def get_image(self, raw): self.dptr = [] """ check if data is 10 or 12 bits """ if self.sigbits == 10: """ calc length of scanline """ lin_len = ((((((self.w+self.pad+3)>>2)) * 5)+31)>>5) * 32 """ stack scan lines into matrix """ raw = np.array(raw).reshape(-1, lin_len).astype(np.int64)[:self.h, ...] """ separate 5 bits in each package, stopping when w is satisfied """ ba0 = raw[..., 0:5*((self.w+3)>>2):5] ba1 = raw[..., 1:5*((self.w+3)>>2):5] ba2 = raw[..., 2:5*((self.w+3)>>2):5] ba3 = raw[..., 3:5*((self.w+3)>>2):5] ba4 = raw[..., 4:5*((self.w+3)>>2):5] """ assemble 10 bit numbers """ ch0 = np.left_shift((np.left_shift(ba0, 2) + (ba4 % 4)), 6) ch1 = np.left_shift((np.left_shift(ba1, 2) + (np.right_shift(ba4, 2) % 4)), 6) ch2 = np.left_shift((np.left_shift(ba2, 2) + (np.right_shift(ba4, 4) % 4)), 6) ch3 = np.left_shift((np.left_shift(ba3, 2) + (np.right_shift(ba4, 6) % 4)), 6) """ interleave bits """ mat = np.empty((self.h, self.w), dtype=ch0.dtype) mat[..., 0::4] = ch0 mat[..., 1::4] = ch1 mat[..., 2::4] = ch2 mat[..., 3::4] = ch3 """ There is som eleaking memory somewhere in the code. This code here seemed to make things good enough that the code would run for reasonable numbers of images, however this is techincally just a workaround. (sorry) """ ba0, ba1, ba2, ba3, ba4 = None, None, None, None, None del ba0, ba1, ba2, ba3, ba4 ch0, ch1, ch2, ch3 = None, None, None, None del ch0, ch1, ch2, ch3 """ same as before but 12 bit case """ elif self.sigbits == 12: lin_len = ((((((self.w+self.pad+1)>>1)) * 3)+31)>>5) * 32 raw = np.array(raw).reshape(-1, lin_len).astype(np.int64)[:self.h, ...] ba0 = raw[..., 0:3*((self.w+1)>>1):3] ba1 = raw[..., 1:3*((self.w+1)>>1):3] ba2 = raw[..., 2:3*((self.w+1)>>1):3] ch0 = np.left_shift((np.left_shift(ba0, 4) + ba2 % 16), 4) ch1 = np.left_shift((np.left_shift(ba1, 4) + (np.right_shift(ba2, 4)) % 16), 4) mat = np.empty((self.h, self.w), dtype=ch0.dtype) mat[..., 0::2] = ch0 mat[..., 1::2] = ch1 else: """ data is neither 10 nor 12 or incorrect data """ print('ERROR: wrong bit format, only 10 or 12 bit supported') return 0 """ separate bayer channels """ c0 = mat[0::2, 0::2] c1 = mat[0::2, 1::2] c2 = mat[1::2, 0::2] c3 = mat[1::2, 1::2] self.channels = [c0, c1, c2, c3] return 1 """ obtain 16x16 patch centred at macbeth square centre for each channel """ def get_patches(self, cen_coords, size=16): """ obtain channel widths and heights """ ch_w, ch_h = self.w, self.h cen_coords = list(np.array((cen_coords[0])).astype(np.int32)) self.cen_coords = cen_coords """ squares are ordered by stacking macbeth chart columns from left to right. Some useful patch indices: white = 3 black = 23 'reds' = 9, 10 'blues' = 2, 5, 8, 20, 22 'greens' = 6, 12, 17 greyscale = 3, 7, 11, 15, 19, 23 """ all_patches = [] for ch in self.channels: ch_patches = [] for cen in cen_coords: ''' macbeth centre is placed at top left of central 2x2 patch to account for rounding Patch pixels are sorted by pixel brightness so spatial information is lost. ''' patch = ch[cen[1]-7:cen[1]+9, cen[0]-7:cen[0]+9].flatten() patch.sort() if patch[-5] == (2**self.sigbits-1)*2**(16-self.sigbits): self.saturated = True ch_patches.append(patch) # print('\nNew Patch\n') all_patches.append(ch_patches) # print('\n\nNew Channel\n\n') self.patches = all_patches return 1 def brcm_load_image(Cam, im_str): """ Load image where raw data and metadata is in the BRCM format """ try: """ create byte array """ with open(im_str, 'rb') as image: f = image.read() b = bytearray(f) """ return error if incorrect image address """ except FileNotFoundError: print('\nERROR:\nInvalid image address')