Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL
4 : * Purpose: Zarr driver, ZarrV3CodecSequence class
5 : * Author: Even Rouault <even dot rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "zarr_v3_codec.h"
14 :
15 : /************************************************************************/
16 : /* ZarrV3CodecSequence::Clone() */
17 : /************************************************************************/
18 :
19 100 : std::unique_ptr<ZarrV3CodecSequence> ZarrV3CodecSequence::Clone() const
20 : {
21 100 : auto poClone = std::make_unique<ZarrV3CodecSequence>(m_oInputArrayMetadata);
22 168 : for (const auto &poCodec : m_apoCodecs)
23 68 : poClone->m_apoCodecs.emplace_back(poCodec->Clone());
24 100 : poClone->m_oCodecArray = m_oCodecArray.Clone();
25 100 : poClone->m_bPartialDecodingPossible = m_bPartialDecodingPossible;
26 100 : return poClone;
27 : }
28 :
29 : /************************************************************************/
30 : /* ZarrV3CodecSequence::InitFromJson() */
31 : /************************************************************************/
32 :
33 3285 : bool ZarrV3CodecSequence::InitFromJson(const std::string &osArrayName,
34 : const CPLJSONObject &oCodecs,
35 : ZarrArrayMetadata &oOutputArrayMetadata)
36 : {
37 3285 : if (oCodecs.GetType() != CPLJSONObject::Type::Array)
38 : {
39 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s: codecs is not an array",
40 : osArrayName.c_str());
41 0 : return false;
42 : }
43 6570 : auto oCodecsArray = oCodecs.ToArray();
44 :
45 6570 : ZarrArrayMetadata oInputArrayMetadata = m_oInputArrayMetadata;
46 3285 : ZarrV3Codec::IOType eLastType = ZarrV3Codec::IOType::ARRAY;
47 6570 : std::string osLastCodec;
48 :
49 : const auto InsertImplicitEndianCodecIfNeeded =
50 9477 : [this, &oInputArrayMetadata, &eLastType, &osLastCodec]()
51 : {
52 4735 : CPL_IGNORE_RET_VAL(this);
53 4735 : if (eLastType == ZarrV3Codec::IOType::ARRAY &&
54 1 : oInputArrayMetadata.oElt.nativeSize > 1 &&
55 1 : oInputArrayMetadata.oElt.nativeType !=
56 1 : DtypeElt::NativeType::STRING_ASCII &&
57 1 : oInputArrayMetadata.oElt.nativeType !=
58 : DtypeElt::NativeType::STRING_UNICODE)
59 : {
60 1 : CPLError(CE_Warning, CPLE_AppDefined,
61 : "'bytes' codec missing. Assuming little-endian storage, "
62 : "but such tolerance may be removed in future versions");
63 2 : auto poEndianCodec = std::make_unique<ZarrV3CodecBytes>();
64 2 : ZarrArrayMetadata oTmpOutputArrayMetadata;
65 2 : poEndianCodec->InitFromConfiguration(
66 2 : std::string(), ZarrV3CodecBytes::GetConfiguration(true),
67 : oInputArrayMetadata, oTmpOutputArrayMetadata,
68 : /* bEmitWarnings = */ true);
69 1 : oInputArrayMetadata = std::move(oTmpOutputArrayMetadata);
70 1 : eLastType = poEndianCodec->GetOutputType();
71 1 : osLastCodec = poEndianCodec->GetName();
72 : if constexpr (!CPL_IS_LSB)
73 : {
74 : // Insert a little endian codec if we are on a big endian target
75 : m_apoCodecs.emplace_back(std::move(poEndianCodec));
76 : }
77 : }
78 4735 : };
79 :
80 3285 : bool bShardingFound = false;
81 6570 : std::vector<size_t> anBlockSizesBeforeSharding;
82 8102 : for (const auto &oCodec : oCodecsArray)
83 : {
84 4838 : if (oCodec.GetType() != CPLJSONObject::Type::Object)
85 : {
86 0 : CPLError(CE_Failure, CPLE_AppDefined, "codecs[] is not an object");
87 21 : return false;
88 : }
89 9676 : const auto osName = oCodec["name"].ToString();
90 0 : std::unique_ptr<ZarrV3Codec> poCodec;
91 4838 : if (osName == ZarrV3CodecGZip::NAME)
92 59 : poCodec = std::make_unique<ZarrV3CodecGZip>();
93 4779 : else if (osName == ZarrV3CodecBlosc::NAME)
94 32 : poCodec = std::make_unique<ZarrV3CodecBlosc>();
95 4747 : else if (osName == ZarrV3CodecZstd::NAME)
96 535 : poCodec = std::make_unique<ZarrV3CodecZstd>();
97 4212 : else if (osName == ZarrV3CodecNumcodecsZlib::NAME)
98 5 : poCodec = std::make_unique<ZarrV3CodecNumcodecsZlib>();
99 4207 : else if (osName == ZarrV3CodecNumcodecsShuffle::NAME)
100 5 : poCodec = std::make_unique<ZarrV3CodecNumcodecsShuffle>();
101 5850 : else if (osName == ZarrV3CodecBytes::NAME ||
102 1648 : osName == "endian" /* endian is the old name */)
103 2554 : poCodec = std::make_unique<ZarrV3CodecBytes>();
104 1648 : else if (osName == ZarrV3CodecTranspose::NAME)
105 83 : poCodec = std::make_unique<ZarrV3CodecTranspose>();
106 1565 : else if (osName == ZarrV3CodecCRC32C::NAME)
107 835 : poCodec = std::make_unique<ZarrV3CodecCRC32C>();
108 730 : else if (osName == ZarrV3CodecVLenUTF8::NAME)
109 14 : poCodec = std::make_unique<ZarrV3CodecVLenUTF8>();
110 716 : else if (osName == ZarrV3CodecShardingIndexed::NAME)
111 : {
112 714 : bShardingFound = true;
113 714 : poCodec = std::make_unique<ZarrV3CodecShardingIndexed>();
114 : }
115 2 : else if (osName == ZarrV3CodecPcodec::NAME)
116 : {
117 : #ifdef HAVE_PCODEC
118 : constexpr bool bHasPcodec = true;
119 : #else
120 0 : constexpr bool bHasPcodec = false;
121 : #endif
122 : if constexpr (bHasPcodec)
123 : {
124 : poCodec = std::make_unique<ZarrV3CodecPcodec>();
125 : }
126 : else
127 : {
128 0 : CPLError(
129 : CE_Failure, CPLE_NotSupported,
130 : "%s: Codec '%s' is supported by GDAL, but not in this "
131 : "particular build. Requires building GDAL with "
132 : "-DGDAL_USE_PCODEC=ON and with a Rust toolchain available",
133 : osArrayName.c_str(), osName.c_str());
134 0 : return false;
135 : }
136 : }
137 : else
138 : {
139 2 : CPLError(CE_Failure, CPLE_NotSupported, "%s: Unsupported codec: %s",
140 : osArrayName.c_str(), osName.c_str());
141 2 : return false;
142 : }
143 :
144 4836 : if (poCodec->GetInputType() == ZarrV3Codec::IOType::ARRAY)
145 : {
146 3365 : if (eLastType == ZarrV3Codec::IOType::BYTES)
147 : {
148 0 : CPLError(CE_Failure, CPLE_AppDefined,
149 : "Cannot chain codec %s with %s",
150 0 : poCodec->GetName().c_str(), osLastCodec.c_str());
151 0 : return false;
152 : }
153 : }
154 : else
155 : {
156 1471 : InsertImplicitEndianCodecIfNeeded();
157 : }
158 :
159 4836 : ZarrArrayMetadata oStepOutputArrayMetadata;
160 4836 : if (osName == ZarrV3CodecShardingIndexed::NAME)
161 : {
162 714 : anBlockSizesBeforeSharding = oInputArrayMetadata.anBlockSizes;
163 : }
164 9672 : if (!poCodec->InitFromConfiguration(
165 : osArrayName, oCodec["configuration"], oInputArrayMetadata,
166 : oStepOutputArrayMetadata,
167 4836 : /* bEmitWarnings = */ true))
168 : {
169 19 : return false;
170 : }
171 4817 : oInputArrayMetadata = std::move(oStepOutputArrayMetadata);
172 4817 : eLastType = poCodec->GetOutputType();
173 4817 : osLastCodec = poCodec->GetName();
174 :
175 4817 : if (!poCodec->IsNoOp())
176 2316 : m_apoCodecs.emplace_back(std::move(poCodec));
177 : }
178 :
179 3264 : if (bShardingFound)
180 : {
181 696 : m_bPartialDecodingPossible =
182 696 : (m_apoCodecs.back()->GetName() == ZarrV3CodecShardingIndexed::NAME);
183 696 : if (!m_bPartialDecodingPossible)
184 : {
185 139 : m_bPartialDecodingPossible = false;
186 : // This is not an implementation limitation, but the result of a
187 : // badly thought dataset. Zarr-Python also emits a similar warning.
188 139 : CPLError(
189 : CE_Warning, CPLE_AppDefined,
190 : "Sharding codec found, but not in last position. Consequently "
191 : "partial shard decoding will not be possible");
192 : oInputArrayMetadata.anBlockSizes =
193 139 : std::move(anBlockSizesBeforeSharding);
194 : }
195 : }
196 :
197 3264 : InsertImplicitEndianCodecIfNeeded();
198 :
199 3264 : m_oCodecArray = oCodecs.Clone();
200 3264 : oOutputArrayMetadata = std::move(oInputArrayMetadata);
201 3264 : return true;
202 : }
203 :
204 : /************************************************************************/
205 : /* ZarrV3CodecBytes::AllocateBuffer() */
206 : /************************************************************************/
207 :
208 45292 : bool ZarrV3CodecSequence::AllocateBuffer(ZarrByteVectorQuickResize &abyBuffer,
209 : size_t nEltCount)
210 : {
211 45292 : if (!m_apoCodecs.empty())
212 : {
213 33039 : const size_t nRawSize =
214 33039 : nEltCount * m_oInputArrayMetadata.oElt.nativeSize;
215 : // Grow the temporary buffer a bit beyond the uncompressed size
216 33039 : const size_t nMaxSize = nRawSize + nRawSize / 3 + 64;
217 : try
218 : {
219 33039 : m_abyTmp.resize(nMaxSize);
220 : }
221 0 : catch (const std::exception &e)
222 : {
223 0 : CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
224 0 : return false;
225 : }
226 33039 : m_abyTmp.resize(nRawSize);
227 :
228 : // Grow the input/output buffer too if we have several steps
229 33039 : if (m_apoCodecs.size() >= 2 && abyBuffer.capacity() < nMaxSize)
230 : {
231 227 : const size_t nSize = abyBuffer.size();
232 : try
233 : {
234 227 : abyBuffer.resize(nMaxSize);
235 : }
236 0 : catch (const std::exception &e)
237 : {
238 0 : CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
239 0 : return false;
240 : }
241 227 : abyBuffer.resize(nSize);
242 : }
243 : }
244 45292 : return true;
245 : }
246 :
247 : /************************************************************************/
248 : /* ZarrV3CodecSequence::Encode() */
249 : /************************************************************************/
250 :
251 15676 : bool ZarrV3CodecSequence::Encode(ZarrByteVectorQuickResize &abyBuffer)
252 : {
253 15676 : if (!AllocateBuffer(abyBuffer,
254 15676 : MultiplyElements(m_oInputArrayMetadata.anBlockSizes)))
255 0 : return false;
256 25422 : for (const auto &poCodec : m_apoCodecs)
257 : {
258 9746 : if (!poCodec->Encode(abyBuffer, m_abyTmp))
259 0 : return false;
260 9746 : std::swap(abyBuffer, m_abyTmp);
261 : }
262 15676 : return true;
263 : }
264 :
265 : /************************************************************************/
266 : /* ZarrV3CodecSequence::Decode() */
267 : /************************************************************************/
268 :
269 28588 : bool ZarrV3CodecSequence::Decode(ZarrByteVectorQuickResize &abyBuffer)
270 : {
271 28588 : if (!AllocateBuffer(abyBuffer,
272 28588 : MultiplyElements(m_oInputArrayMetadata.anBlockSizes)))
273 0 : return false;
274 50196 : for (auto iter = m_apoCodecs.rbegin(); iter != m_apoCodecs.rend(); ++iter)
275 : {
276 22502 : const auto &poCodec = *iter;
277 22502 : if (!poCodec->Decode(abyBuffer, m_abyTmp))
278 894 : return false;
279 21608 : std::swap(abyBuffer, m_abyTmp);
280 : }
281 27694 : return true;
282 : }
283 :
284 : /************************************************************************/
285 : /* ZarrV3CodecSequence::DecodePartial() */
286 : /************************************************************************/
287 :
288 1028 : bool ZarrV3CodecSequence::DecodePartial(VSIVirtualHandle *poFile,
289 : ZarrByteVectorQuickResize &abyBuffer,
290 : const std::vector<size_t> &anStartIdxIn,
291 : const std::vector<size_t> &anCountIn)
292 : {
293 1028 : CPLAssert(anStartIdxIn.size() == m_oInputArrayMetadata.anBlockSizes.size());
294 1028 : CPLAssert(anStartIdxIn.size() == anCountIn.size());
295 :
296 1028 : if (!AllocateBuffer(abyBuffer, MultiplyElements(anCountIn)))
297 0 : return false;
298 :
299 : // anStartIdxIn and anCountIn are expressed in the shape *before* encoding
300 : // We need to apply the potential transpositions before submitting them
301 : // to the decoder of the Array->Bytes decoder
302 2056 : std::vector<size_t> anStartIdx(anStartIdxIn);
303 2056 : std::vector<size_t> anCount(anCountIn);
304 2081 : for (auto &poCodec : m_apoCodecs)
305 : {
306 1053 : poCodec->ChangeArrayShapeForward(anStartIdx, anCount);
307 : }
308 :
309 1725 : for (auto iter = m_apoCodecs.rbegin(); iter != m_apoCodecs.rend(); ++iter)
310 : {
311 1053 : const auto &poCodec = *iter;
312 :
313 2106 : if (!poCodec->DecodePartial(poFile, abyBuffer, m_abyTmp, anStartIdx,
314 1053 : anCount))
315 356 : return false;
316 697 : std::swap(abyBuffer, m_abyTmp);
317 : }
318 672 : return true;
319 : }
320 :
321 : /************************************************************************/
322 : /* ZarrV3CodecSequence::BatchDecodePartial() */
323 : /************************************************************************/
324 :
325 4031 : bool ZarrV3CodecSequence::BatchDecodePartial(
326 : VSIVirtualHandle *poFile, const char *pszFilename,
327 : const std::vector<std::pair<std::vector<size_t>, std::vector<size_t>>>
328 : &anRequests,
329 : std::vector<ZarrByteVectorQuickResize> &aResults)
330 : {
331 : // Only batch-decode when sharding is the sole codec. If other codecs
332 : // (e.g. transpose) precede it, indices and output need codec-specific
333 : // transformations that BatchDecodePartial does not handle.
334 4031 : if (m_apoCodecs.size() == 1)
335 : {
336 4023 : auto *poSharding = dynamic_cast<ZarrV3CodecShardingIndexed *>(
337 8046 : m_apoCodecs.back().get());
338 4023 : if (poSharding)
339 : {
340 4023 : return poSharding->BatchDecodePartial(poFile, pszFilename,
341 4023 : anRequests, aResults);
342 : }
343 : }
344 :
345 : // Fallback: sequential DecodePartial for non-sharding codec chains
346 8 : aResults.resize(anRequests.size());
347 32 : for (size_t i = 0; i < anRequests.size(); ++i)
348 : {
349 24 : if (!DecodePartial(poFile, aResults[i], anRequests[i].first,
350 24 : anRequests[i].second))
351 0 : return false;
352 : }
353 8 : return true;
354 : }
355 :
356 : /************************************************************************/
357 : /* ZarrV3CodecSequence::GetInnerMostBlockSize() */
358 : /************************************************************************/
359 :
360 1848 : std::vector<size_t> ZarrV3CodecSequence::GetInnerMostBlockSize(
361 : const std::vector<size_t> &anOuterBlockSize) const
362 : {
363 1848 : auto chunkSize = anOuterBlockSize;
364 2917 : for (auto iter = m_apoCodecs.rbegin(); iter != m_apoCodecs.rend(); ++iter)
365 : {
366 1069 : const auto &poCodec = *iter;
367 1581 : if (m_bPartialDecodingPossible ||
368 512 : poCodec->GetName() != ZarrV3CodecShardingIndexed::NAME)
369 : {
370 930 : chunkSize = poCodec->GetInnerMostBlockSize(chunkSize);
371 : }
372 : }
373 1848 : return chunkSize;
374 : }
|