Debian Codegraph @

frmts/jpipkak/jpipkakdataset.cpp

raw
1 /******************************************************************************
2 *
3 * Project: jpip read driver
4 * Purpose: GDAL bindings for JPIP.
5 * Author: Norman Barker, ITT VIS, [email protected]
6 *
7 ******************************************************************************
8 * ITT Visual Information Systems grants you use of this code, under the
9 * following license:
10 *
11 * Copyright (c) 2000-2007, ITT Visual Information Solutions
12 *
13 * SPDX-License-Identifier: MIT
14 **/
15
16 #include "gdal_frmts.h"
17 #include "jpipkakdataset.h"
18
19 #include "jpipkakdrivercore.h"
20
21 #include <algorithm>
22
23 /*
24 ** The following are for testing premature stream termination support.
25 ** This is a mechanism to test handling of failed or incomplete reads
26 ** from the server, and is not normally active. For this reason we
27 ** don't worry about the non-threadsafe nature of the debug support
28 ** variables below.
29 */
30
31 #ifdef DEBUG
32 #define PST_DEBUG 1
33 #endif
34
35 #ifdef PST_DEBUG
36 static int nPSTTargetInstance = -1;
37 static int nPSTThisInstance = -1;
38 static int nPSTTargetOffset = -1;
39 #endif
40
41 static bool kakadu_initialized = false;
42
43 /************************************************************************/
44 /* ==================================================================== */
45 /* Set up messaging services */
46 /* ==================================================================== */
47 /************************************************************************/
48
49 class jpipkak_kdu_cpl_error_message final : public kdu_message
50 {
51 public: // Member classes
52 using kdu_message::put_text;
53
54 explicit jpipkak_kdu_cpl_error_message(CPLErr eErrClass)
55 : m_eErrClass(eErrClass), m_pszError(nullptr)
56 {
57 }
58
59 void put_text(const char *string) override
60 {
61 if (m_pszError == nullptr)
62 m_pszError = CPLStrdup(string);
63 else
64 {
65 m_pszError = (char *)CPLRealloc(m_pszError, strlen(m_pszError) +
66 strlen(string) + 1);
67 strcat(m_pszError, string);
68 }
69 }
70
71 class JP2KAKException
72 {
73 };
74
75 void flush(bool end_of_message = false) override
76 {
77 if (m_pszError == nullptr)
78 return;
79 if (m_pszError[strlen(m_pszError) - 1] == '\n')
80 m_pszError[strlen(m_pszError) - 1] = '\0';
81
82 CPLError(m_eErrClass, CPLE_AppDefined, "%s", m_pszError);
83 CPLFree(m_pszError);
84 m_pszError = nullptr;
85
86 if (end_of_message && m_eErrClass == CE_Failure)
87 {
88 throw new JP2KAKException();
89 }
90 }
91
92 private:
93 CPLErr m_eErrClass;
94 char *m_pszError;
95 };
96
97 /************************************************************************/
98 /* ==================================================================== */
99 /* JPIPKAKRasterBand */
100 /* ==================================================================== */
101 /************************************************************************/
102
103 /************************************************************************/
104 /* JPIPKAKRasterBand() */
105 /************************************************************************/
106
107 JPIPKAKRasterBand::JPIPKAKRasterBand(int nBandIn, int nDiscardLevelsIn,
108 kdu_codestream *oCodeStreamIn,
109 int nResCount, JPIPKAKDataset *poBaseDSIn)
110
111 {
112 this->nBand = nBandIn;
113 poBaseDS = poBaseDSIn;
114
115 eDataType = poBaseDSIn->eDT;
116
117 this->nDiscardLevels = nDiscardLevelsIn;
118 this->oCodeStream = oCodeStreamIn;
119
120 oCodeStream->apply_input_restrictions(0, 0, nDiscardLevels, 0, nullptr);
121 oCodeStream->get_dims(0, band_dims);
122
123 nRasterXSize = band_dims.size.x;
124 nRasterYSize = band_dims.size.y;
125
126 /* -------------------------------------------------------------------- */
127 /* Use a 2048x128 "virtual" block size unless the file is small. */
128 /* -------------------------------------------------------------------- */
129 if (nRasterXSize >= 2048)
130 nBlockXSize = 2048;
131 else
132 nBlockXSize = nRasterXSize;
133
134 if (nRasterYSize >= 256)
135 nBlockYSize = 128;
136 else
137 nBlockYSize = nRasterYSize;
138
139 /* -------------------------------------------------------------------- */
140 /* Figure out the color interpretation for this band. */
141 /* -------------------------------------------------------------------- */
142
143 eInterp = GCI_Undefined;
144
145 /* -------------------------------------------------------------------- */
146 /* Do we have any overviews? Only check if we are the full res */
147 /* image. */
148 /* -------------------------------------------------------------------- */
149 nOverviewCount = 0;
150 papoOverviewBand = nullptr;
151
152 if (nDiscardLevels == 0)
153 {
154 int nXSize = nRasterXSize;
155 int nYSize = nRasterYSize;
156
157 for (int nDiscard = 1; nDiscard < nResCount; nDiscard++)
158 {
159
160 nXSize = (nXSize + 1) / 2;
161 nYSize = (nYSize + 1) / 2;
162
163 if ((nXSize + nYSize) < 128 || nXSize < 4 || nYSize < 4)
164 continue; /* skip super reduced resolution layers */
165
166 oCodeStream->apply_input_restrictions(0, 0, nDiscard, 0, nullptr);
167 kdu_dims dims;
168 oCodeStream->get_dims(0, dims);
169
170 if ((dims.size.x == nXSize || dims.size.x == nXSize - 1) &&
171 (dims.size.y == nYSize || dims.size.y == nYSize - 1))
172 {
173 nOverviewCount++;
174 papoOverviewBand = (JPIPKAKRasterBand **)CPLRealloc(
175 papoOverviewBand, sizeof(void *) * nOverviewCount);
176 papoOverviewBand[nOverviewCount - 1] = new JPIPKAKRasterBand(
177 nBand, nDiscard, oCodeStream, 0, poBaseDS);
178 }
179 else
180 {
181 CPLDebug("GDAL",
182 "Discard %dx%d JPEG2000 overview layer,\n"
183 "expected %dx%d.",
184 dims.size.x, dims.size.y, nXSize, nYSize);
185 }
186 }
187 }
188 }
189
190 /************************************************************************/
191 /* ~JPIPKAKRasterBand() */
192 /************************************************************************/
193
194 JPIPKAKRasterBand::~JPIPKAKRasterBand()
195
196 {
197 for (int i = 0; i < nOverviewCount; i++)
198 delete papoOverviewBand[i];
199
200 CPLFree(papoOverviewBand);
201 }
202
203 /************************************************************************/
204 /* GetOverviewCount() */
205 /************************************************************************/
206
207 int JPIPKAKRasterBand::GetOverviewCount()
208
209 {
210 return nOverviewCount;
211 }
212
213 /************************************************************************/
214 /* GetOverview() */
215 /************************************************************************/
216
217 GDALRasterBand *JPIPKAKRasterBand::GetOverview(int iOverviewIndex)
218
219 {
220 if (iOverviewIndex < 0 || iOverviewIndex >= nOverviewCount)
221 return nullptr;
222 else
223 return papoOverviewBand[iOverviewIndex];
224 }
225
226 /************************************************************************/
227 /* IReadBlock() */
228 /************************************************************************/
229
230 CPLErr JPIPKAKRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
231 void *pImage)
232 {
233 CPLDebug("JPIPKAK", "IReadBlock(%d,%d) on band %d.", nBlockXOff, nBlockYOff,
234 nBand);
235
236 /* -------------------------------------------------------------------- */
237 /* Fix the buffer layer. */
238 /* -------------------------------------------------------------------- */
239 const int nPixelSpace = GDALGetDataTypeSizeBytes(eDataType);
240 const int nLineSpace = nPixelSpace * nBlockXSize;
241 const int nBandSpace = nLineSpace * nBlockYSize;
242
243 /* -------------------------------------------------------------------- */
244 /* Zoom up file window based on overview level so we are */
245 /* referring to the full res image. */
246 /* -------------------------------------------------------------------- */
247 int nZoom = 1 << nDiscardLevels;
248
249 int xOff = nBlockXOff * nBlockXSize * nZoom;
250 int yOff = nBlockYOff * nBlockYSize * nZoom;
251 int xSize = nBlockXSize * nZoom;
252 int ySize = nBlockYSize * nZoom;
253
254 int nBufXSize = nBlockXSize;
255 int nBufYSize = nBlockYSize;
256
257 /* -------------------------------------------------------------------- */
258 /* Make adjustments for partial blocks on right and bottom. */
259 /* -------------------------------------------------------------------- */
260 if (xOff + xSize > poBaseDS->GetRasterXSize())
261 {
262 xSize = poBaseDS->GetRasterXSize() - xOff;
263 nBufXSize = std::max(xSize / nZoom, 1);
264 }
265
266 if (yOff + ySize > poBaseDS->GetRasterYSize())
267 {
268 ySize = poBaseDS->GetRasterYSize() - yOff;
269 nBufYSize = std::max(ySize / nZoom, 1);
270 }
271
272 /* -------------------------------------------------------------------- */
273 /* Start the reader and run till complete. */
274 /* -------------------------------------------------------------------- */
275 GDALAsyncReader *ario = poBaseDS->BeginAsyncReader(
276 xOff, yOff, xSize, ySize, pImage, nBufXSize, nBufYSize, eDataType, 1,
277 &nBand, nPixelSpace, nLineSpace, nBandSpace, nullptr);
278
279 if (ario == nullptr)
280 return CE_Failure;
281
282 int nXBufOff; // absolute x image offset
283 int nYBufOff; // absolute y image offset
284 int nXBufSize;
285 int nYBufSize;
286
287 GDALAsyncStatusType status;
288
289 do
290 {
291 status = ario->GetNextUpdatedRegion(-1.0, &nXBufOff, &nYBufOff,
292 &nXBufSize, &nYBufSize);
293 } while (status != GARIO_ERROR && status != GARIO_COMPLETE);
294
295 poBaseDS->EndAsyncReader(ario);
296
297 if (status == GARIO_ERROR)
298 return CE_Failure;
299 else
300 return CE_None;
301 }
302
303 /************************************************************************/
304 /* IRasterIO() */
305 /************************************************************************/
306
307 CPLErr JPIPKAKRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
308 int nXSize, int nYSize, void *pData,
309 int nBufXSize, int nBufYSize,
310 GDALDataType eBufType, GSpacing nPixelSpace,
311 GSpacing nLineSpace,
312 GDALRasterIOExtraArg *psExtraArg)
313
314 {
315 /* -------------------------------------------------------------------- */
316 /* We need various criteria to skip out to block based methods. */
317 /* -------------------------------------------------------------------- */
318 int anBand[1] = {nBand};
319 if (poBaseDS->TestUseBlockIO(nXOff, nYOff, nXSize, nYSize, nBufXSize,
320 nBufYSize, eBufType, 1, &anBand[0]))
321 return GDALPamRasterBand::IRasterIO(
322 eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
323 eBufType, nPixelSpace, nLineSpace, psExtraArg);
324
325 /* -------------------------------------------------------------------- */
326 /* Otherwise do this as a single uncached async rasterio. */
327 /* -------------------------------------------------------------------- */
328 GDALAsyncReader *ario = poBaseDS->BeginAsyncReader(
329 nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, 1,
330 &anBand[0], static_cast<int>(nPixelSpace), static_cast<int>(nLineSpace),
331 0, nullptr);
332
333 if (ario == nullptr)
334 return CE_Failure;
335
336 GDALAsyncStatusType status;
337
338 do
339 {
340 int nXBufOff, nYBufOff, nXBufSize, nYBufSize;
341
342 status = ario->GetNextUpdatedRegion(-1.0, &nXBufOff, &nYBufOff,
343 &nXBufSize, &nYBufSize);
344 } while (status != GARIO_ERROR && status != GARIO_COMPLETE);
345
346 poBaseDS->EndAsyncReader(ario);
347
348 if (status == GARIO_ERROR)
349 return CE_Failure;
350 else
351 return CE_None;
352 }
353
354 /*****************************************/
355 /* JPIPKAKDataset() */
356 /*****************************************/
357 JPIPKAKDataset::JPIPKAKDataset()
358 {
359 pGlobalMutex = CPLCreateMutex();
360 CPLReleaseMutex(pGlobalMutex);
361 }
362
363 /*****************************************/
364 /* ~JPIPKAKDataset() */
365 /*****************************************/
366 JPIPKAKDataset::~JPIPKAKDataset()
367 {
368 char **papszOptions = nullptr;
369 papszOptions = CSLSetNameValue(papszOptions, "CLOSE_PERSISTENT",
370 CPLSPrintf("JPIPKAK:%p", this));
371 CPLHTTPDestroyResult(CPLHTTPFetch("", papszOptions));
372 CSLDestroy(papszOptions);
373
374 Deinitialize();
375
376 CPLFree(pszPath);
377
378 if (nGCPCount > 0)
379 {
380 GDALDeinitGCPs(nGCPCount, pasGCPList);
381 CPLFree(pasGCPList);
382 }
383 }
384
385 /************************************************************************/
386 /* Deinitialize() */
387 /* */
388 /* Cleanup stuff that we will rebuild during a */
389 /* reinitialization. */
390 /************************************************************************/
391
392 void JPIPKAKDataset::Deinitialize()
393
394 {
395 CPLFree(pszCid);
396 pszCid = nullptr;
397
398 // frees decompressor as well
399 if (poCodestream)
400 {
401 poCodestream->destroy();
402 delete poCodestream;
403 poCodestream = nullptr;
404 }
405
406 delete poDecompressor;
407 poDecompressor = nullptr;
408
409 delete poCache;
410 poCache = nullptr;
411
412 bNeedReinitialize = TRUE;
413 }
414
415 /************************************************************************/
416 /* KakaduInitialize() */
417 /************************************************************************/
418
419 void JPIPKAKDataset::KakaduInitialize()
420
421 {
422 /* -------------------------------------------------------------------- */
423 /* Initialize Kakadu warning/error reporting subsystem. */
424 /* -------------------------------------------------------------------- */
425 if (!kakadu_initialized)
426 {
427 kakadu_initialized = true;
428
429 jpipkak_kdu_cpl_error_message oErrHandler(CE_Failure);
430 jpipkak_kdu_cpl_error_message oWarningHandler(CE_Warning);
431 CPL_IGNORE_RET_VAL(oErrHandler);
432 CPL_IGNORE_RET_VAL(oWarningHandler);
433
434 kdu_customize_warnings(new jpipkak_kdu_cpl_error_message(CE_Warning));
435 kdu_customize_errors(new jpipkak_kdu_cpl_error_message(CE_Failure));
436 }
437 }
438
439 /*****************************************/
440 /* Initialize() */
441 /*****************************************/
442 int JPIPKAKDataset::Initialize(const char *pszDatasetName, int bReinitializing)
443 {
444 KakaduInitialize();
445
446 // create necessary http headers
447 CPLString osHeaders = "HEADERS=Accept: jpp-stream";
448 CPLString osPersistent;
449
450 osPersistent.Printf("PERSISTENT=JPIPKAK:%p", this);
451
452 char *apszOptions[] = {(char *)osHeaders.c_str(),
453 (char *)osPersistent.c_str(), nullptr};
454
455 // Setup url to have http in place of jpip protocol indicator.
456 CPLString osURL = "http";
457 osURL += (pszDatasetName + 4);
458
459 CPLAssert(STARTS_WITH(pszDatasetName, "jpip"));
460
461 // make initial request to the server for a session, we are going to
462 // assume that the jpip communication is stateful, rather than one-shot
463 // stateless requests append pszUrl with jpip request parameters for a
464 // stateful session (multi-shot communications)
465 // "cnew=http&type=jpp-stream&stream=0&tid=0&len="
466 CPLString osRequest;
467 osRequest.Printf("%s?%s%i", osURL.c_str(),
468 "cnew=http&type=jpp-stream&stream=0&tid=0&len=", 2000);
469
470 CPLHTTPResult *psResult = CPLHTTPFetch(osRequest, apszOptions);
471
472 if (psResult == nullptr)
473 return FALSE;
474
475 if (psResult->nDataLen == 0 || psResult->pabyData == nullptr)
476 {
477
478 CPLError(CE_Failure, CPLE_AppDefined,
479 "No data was returned from the given URL");
480 CPLHTTPDestroyResult(psResult);
481 return FALSE;
482 }
483
484 if (psResult->nStatus != 0)
485 {
486 CPLError(CE_Failure, CPLE_AppDefined, "Curl reports error: %d: %s",
487 psResult->nStatus, psResult->pszErrBuf);
488 CPLHTTPDestroyResult(psResult);
489 return FALSE;
490 }
491
492 // parse the response headers, and the initial data until we get to the
493 // codestream definition
494 char **pszHdrs = psResult->papszHeaders;
495 const char *pszCnew = CSLFetchNameValue(pszHdrs, "JPIP-cnew");
496
497 if (pszCnew == nullptr)
498 {
499 if (psResult->pszContentType != nullptr &&
500 STARTS_WITH_CI(psResult->pszContentType, "text/html"))
501 CPLDebug("JPIPKAK", "%s", psResult->pabyData);
502
503 CPLHTTPDestroyResult(psResult);
504 CPLError(CE_Failure, CPLE_AppDefined,
505 "Unable to parse required cnew and tid response headers");
506
507 return FALSE;
508 }
509
510 // parse cnew response
511 // JPIP-cnew:
512 // cid=DC69DF980A641A4BBDEB50E484A66578,path=MyPath,transport=http
513 char **papszTokens = CSLTokenizeString2(pszCnew, ",", CSLT_HONOURSTRINGS);
514 for (int i = 0; i < CSLCount(papszTokens); i++)
515 {
516 // looking for cid, path
517 if (STARTS_WITH_CI(papszTokens[i], "cid"))
518 {
519 char *pszKey = nullptr;
520 const char *pszValue = CPLParseNameValue(papszTokens[i], &pszKey);
521 pszCid = CPLStrdup(pszValue);
522 CPLFree(pszKey);
523 }
524
525 if (STARTS_WITH_CI(papszTokens[i], "path"))
526 {
527 char *pszKey = nullptr;
528 const char *pszValue = CPLParseNameValue(papszTokens[i], &pszKey);
529 pszPath = CPLStrdup(pszValue);
530 CPLFree(pszKey);
531 }
532 }
533
534 CSLDestroy(papszTokens);
535
536 if (pszPath == nullptr || pszCid == nullptr)
537 {
538 CPLHTTPDestroyResult(psResult);
539 CPLError(CE_Failure, CPLE_AppDefined,
540 "Error parsing path and cid from cnew - %s", pszCnew);
541 return FALSE;
542 }
543
544 // Okay, good to go with JPIP, get to the codestream before returning
545 // successful initialization of the driver
546 try
547 {
548 poCache = new kdu_cache();
549 poCodestream = new kdu_codestream();
550 poDecompressor = new kdu_region_decompressor();
551
552 int bFinished = FALSE;
553 int bError = FALSE;
554 bFinished =
555 ReadFromInput(psResult->pabyData, psResult->nDataLen, bError);
556 CPLHTTPDestroyResult(psResult);
557
558 // continue making requests in the main thread to get all the available
559 // metadata for data bin 0, and reach the codestream
560
561 // format the new request
562 // and set as pszRequestUrl;
563 // get the protocol from the original request
564 size_t found = osRequest.find_first_of("/");
565 CPLString osProtocol = osRequest.substr(0, found + 2);
566 osRequest.erase(0, found + 2);
567 // find context path
568 found = osRequest.find_first_of("/");
569 osRequest.erase(found);
570
571 osRequestUrl.Printf("%s%s/%s?cid=%s&stream=0&len=%i",
572 osProtocol.c_str(), osRequest.c_str(), pszPath,
573 pszCid, 2000);
574
575 while (!bFinished && !bError)
576 {
577 psResult = CPLHTTPFetch(osRequestUrl, apszOptions);
578 bFinished =
579 ReadFromInput(psResult->pabyData, psResult->nDataLen, bError);
580 CPLHTTPDestroyResult(psResult);
581 }
582
583 if (bError)
584 return FALSE;
585
586 // clean up osRequest, remove variable len= parameter
587 size_t pos = osRequestUrl.find_last_of("&");
588 osRequestUrl.erase(pos);
589
590 // create codestream
591 poCache->set_read_scope(KDU_MAIN_HEADER_DATABIN, 0, 0);
592 poCodestream->create(poCache);
593 poCodestream->set_persistent();
594
595 /* --------------------------------------------------------------------
596 */
597 /* If this is a reinitialization then we can hop out at this */
598 /* point. The rest of the stuff was already done, and */
599 /* hopefully the configuration is unchanged. */
600 /* --------------------------------------------------------------------
601 */
602 if (bReinitializing)
603 {
604 bNeedReinitialize = FALSE;
605 return TRUE;
606 }
607
608 /* --------------------------------------------------------------------
609 */
610 /* Collect GDAL raster configuration information. */
611 /* --------------------------------------------------------------------
612 */
613 kdu_channel_mapping oChannels;
614 oChannels.configure(*poCodestream);
615 kdu_coords *ref_expansion = new kdu_coords(1, 1);
616
617 // get available resolutions, image width / height etc.
618 kdu_dims view_dims = poDecompressor->get_rendered_image_dims(
619 *poCodestream, &oChannels, -1, 0, *ref_expansion, *ref_expansion,
620 KDU_WANT_OUTPUT_COMPONENTS);
621
622 nRasterXSize = view_dims.size.x;
623 nRasterYSize = view_dims.size.y;
624
625 // Establish the datatype - we will use the same datatype for
626 // all bands based on the first. This really doesn't do something
627 // great for >16 bit images.
628 if (poCodestream->get_bit_depth(0) > 8 && poCodestream->get_signed(0))
629 {
630 eDT = GDT_Int16;
631 }
632 else if (poCodestream->get_bit_depth(0) > 8 &&
633 !poCodestream->get_signed(0))
634 {
635 eDT = GDT_UInt16;
636 }
637 else
638 eDT = GDT_UInt8;
639
640 if ((poCodestream->get_bit_depth(0) % 8) != 0 &&
641 poCodestream->get_bit_depth(0) < 16)
642 SetMetadataItem(
643 "NBITS",
644 CPLString().Printf("%d", poCodestream->get_bit_depth(0)),
645 "IMAGE_STRUCTURE");
646
647 // TODO add color interpretation
648
649 // calculate overviews
650 siz_params *siz_in = poCodestream->access_siz();
651 kdu_params *cod_in = siz_in->access_cluster("COD");
652
653 delete ref_expansion;
654
655 siz_in->get("Scomponents", 0, 0, nComps);
656 siz_in->get("Sprecision", 0, 0, nBitDepth);
657
658 cod_in->get("Clayers", 0, 0, nQualityLayers);
659 cod_in->get("Clevels", 0, 0, nResLevels);
660
661 bYCC = TRUE;
662 cod_in->get("Cycc", 0, 0, bYCC);
663 }
664 catch (...)
665 {
666 CPLError(
667 CE_Failure, CPLE_AppDefined,
668 "Trapped Kakadu exception attempting to initialize JPIP access.");
669 return FALSE;
670 }
671
672 /* -------------------------------------------------------------------- */
673 /* YCC images are always processed as 3 bands. */
674 /* -------------------------------------------------------------------- */
675 if (bYCC)
676 nBands = 3;
677 else
678 nBands = nComps;
679
680 /* -------------------------------------------------------------------- */
681 /* Setup band objects. */
682 /* -------------------------------------------------------------------- */
683 int iBand;
684
685 for (iBand = 1; iBand <= nBands; iBand++)
686 {
687 JPIPKAKRasterBand *poBand =
688 new JPIPKAKRasterBand(iBand, 0, poCodestream, nResLevels, this);
689
690 SetBand(iBand, poBand);
691 }
692
693 // set specific metadata items
694 CPLString osNQualityLayers;
695 osNQualityLayers.Printf("%i", nQualityLayers);
696 CPLString osNResolutionLevels;
697 osNResolutionLevels.Printf("%i", nResLevels);
698 CPLString osNComps;
699 osNComps.Printf("%i", nComps);
700 CPLString osBitDepth;
701 osBitDepth.Printf("%i", nBitDepth);
702
703 SetMetadataItem("JPIP_NQUALITYLAYERS", osNQualityLayers.c_str(), "JPIP");
704 SetMetadataItem("JPIP_NRESOLUTIONLEVELS", osNResolutionLevels.c_str(),
705 "JPIP");
706 SetMetadataItem("JPIP_NCOMPS", osNComps.c_str(), "JPIP");
707 SetMetadataItem("JPIP_SPRECISION", osBitDepth.c_str(), "JPIP");
708
709 if (bYCC)
710 SetMetadataItem("JPIP_YCC", "YES", "JPIP");
711 else
712 SetMetadataItem("JPIP_YCC", "NO", "JPIP");
713
714 /* ==================================================================== */
715 /* Parse geojp2, or gmljp2, we will assume that the core */
716 /* metadata of gml or a geojp2 uuid have been sent in the */
717 /* initial metadata response. */
718 /* If the server has used placeholder boxes for this */
719 /* information then the image will be interpreted as x,y */
720 /* ==================================================================== */
721 GDALJP2Metadata oJP2Geo;
722 int nLen = poCache->get_databin_length(KDU_META_DATABIN, nCodestream, 0);
723
724 if (nLen == 0)
725 {
726 CPLError(CE_Failure, CPLE_AppDefined,
727 "Unable to open stream to parse metadata boxes");
728 return FALSE;
729 }
730
731 // create in memory file using vsimem
732 const CPLString osFileBoxName(VSIMemGenerateHiddenFilename("jpip"));
733 VSILFILE *fpLL = VSIFOpenL(osFileBoxName.c_str(), "w+");
734 poCache->set_read_scope(KDU_META_DATABIN, nCodestream, 0);
735 kdu_byte *pabyBuffer = (kdu_byte *)CPLMalloc(nLen);
736 poCache->read(pabyBuffer, nLen);
737 VSIFWriteL(pabyBuffer, nLen, 1, fpLL);
738 CPLFree(pabyBuffer);
739
740 VSIFFlushL(fpLL);
741 VSIFSeekL(fpLL, 0, SEEK_SET);
742
743 nPamFlags |= GPF_NOSAVE;
744
745 try
746 {
747 oJP2Geo.ReadBoxes(fpLL);
748 // parse gml first, followed by geojp2 as a fallback
749 if (oJP2Geo.ParseGMLCoverageDesc() || oJP2Geo.ParseJP2GeoTIFF())
750 {
751 m_oSRS = oJP2Geo.m_oSRS;
752 bGeoTransformValid = TRUE;
753
754 m_gt = oJP2Geo.m_gt;
755 nGCPCount = oJP2Geo.nGCPCount;
756 pasGCPList = oJP2Geo.pasGCPList;
757
758 oJP2Geo.pasGCPList = nullptr;
759 oJP2Geo.nGCPCount = 0;
760
761 int iBox;
762
763 for (iBox = 0; oJP2Geo.papszGMLMetadata &&
764 oJP2Geo.papszGMLMetadata[iBox] != nullptr;
765 iBox++)
766 {
767 char *pszName = nullptr;
768 const char *pszXML =
769 CPLParseNameValue(oJP2Geo.papszGMLMetadata[iBox], &pszName);
770 CPLString osDomain;
771 char *apszMDList[2];
772
773 osDomain.Printf("xml:%s", pszName);
774 apszMDList[0] = (char *)pszXML;
775 apszMDList[1] = nullptr;
776
777 GDALPamDataset::SetMetadata(apszMDList, osDomain);
778 CPLFree(pszName);
779 }
780 }
781 else
782 {
783 // treat as Cartesian, no geo metadata
784 CPLError(
785 CE_Warning, CPLE_AppDefined,
786 "Parsed metadata boxes from jpip stream, geographic metadata "
787 "not found - is the server using placeholders for this data?");
788 }
789 }
790 catch (...)
791 {
792 CPLError(CE_Failure, CPLE_AppDefined,
793 "Unable to parse geographic metadata boxes from jpip stream");
794 }
795
796 VSIFCloseL(fpLL);
797 VSIUnlink(osFileBoxName.c_str());
798
799 bNeedReinitialize = FALSE;
800
801 return TRUE;
802 }
803
804 /******************************************/
805 /* ReadVBAS() */
806 /******************************************/
807 long JPIPKAKDataset::ReadVBAS(GByte *pabyData, int nLen)
808 {
809 int c = -1;
810 long val = 0;
811 nVBASLen = 0;
812
813 while ((c & 0x80) != 0)
814 {
815 if (nVBASLen >= 9)
816 {
817 CPLError(CE_Failure, CPLE_AppDefined, "VBAS Length not supported");
818 return -1;
819 }
820
821 if (nPos > nLen)
822 {
823 CPLError(CE_Failure, CPLE_AppDefined,
824 "EOF reached before completing VBAS");
825 return -1;
826 }
827
828 #ifdef PST_DEBUG
829 if (nPSTThisInstance == nPSTTargetInstance && nPos >= nPSTTargetOffset)
830 {
831 CPLError(CE_Failure, CPLE_AppDefined,
832 "Artificial PST EOF reached before completing VBAS");
833 return -1;
834 }
835 #endif
836
837 c = pabyData[nPos];
838 nPos++;
839
840 val = (val << 7) | (long)(c & 0x7F);
841
842 if (nVBASLen == 0)
843 nVBASFirstByte = c;
844
845 nVBASLen++;
846 }
847
848 return val;
849 }
850
851 /******************************************/
852 /* ReadSegment() */
853 /******************************************/
854 JPIPDataSegment *JPIPKAKDataset::ReadSegment(GByte *pabyData, int nLen,
855 int &bError)
856 {
857 long nId = ReadVBAS(pabyData, nLen);
858 bError = FALSE;
859
860 if (nId < 0)
861 {
862 bError = TRUE;
863 return nullptr;
864 }
865 else
866 {
867 JPIPDataSegment *segment = new JPIPDataSegment();
868 segment->SetId(nId);
869
870 if (nVBASFirstByte == 0)
871 {
872 segment->SetEOR(TRUE);
873 segment->SetId(pabyData[nPos]);
874 }
875 else
876 {
877 segment->SetEOR(FALSE);
878 nId &= ~(0x70 << ((nVBASLen - 1) * 7));
879 segment->SetId(nId);
880 segment->SetFinal((nVBASFirstByte & 0x10) != 0);
881
882 int m = (nVBASFirstByte & 0x7F) >> 5;
883
884 if (m == 0)
885 {
886 CPLError(CE_Failure, CPLE_AppDefined,
887 "Invalid Bin-ID value format");
888 bError = TRUE;
889 delete segment;
890 return nullptr;
891 }
892 else if (m >= 2)
893 {
894 nClassId = static_cast<int>(ReadVBAS(pabyData, nLen));
895 if (m > 2)
896 {
897 nCodestream = static_cast<int>(ReadVBAS(pabyData, nLen));
898 if (nCodestream < 0)
899 {
900 bError = TRUE;
901 delete segment;
902 return nullptr;
903 }
904 }
905 }
906
907 long nNextVal;
908
909 segment->SetClassId(nClassId);
910 segment->SetCodestreamIdx(nCodestream);
911
912 nNextVal = ReadVBAS(pabyData, nLen);
913 if (nNextVal == -1)
914 {
915 bError = TRUE;
916 delete segment;
917 return nullptr;
918 }
919 else
920 segment->SetOffset(nNextVal);
921
922 nNextVal = ReadVBAS(pabyData, nLen);
923 if (nNextVal == -1)
924 {
925 bError = TRUE;
926 delete segment;
927 return nullptr;
928 }
929 else
930 segment->SetLen(nNextVal);
931 }
932
933 if ((segment->GetLen() > 0) && (!segment->IsEOR()))
934 {
935 GByte *pabyDataSegment = (GByte *)CPLCalloc(1, segment->GetLen());
936
937 // copy data from input array pabyData to the data segment
938 memcpy(pabyDataSegment, pabyData + nPos, segment->GetLen());
939
940 segment->SetData(pabyDataSegment);
941 }
942
943 nPos += segment->GetLen();
944
945 if (!segment->IsEOR())
946 nDatabins++;
947
948 if ((segment->GetId() == JPIPKAKDataset::JPIP_EOR_WINDOW_DONE) &&
949 (segment->IsEOR()))
950 bWindowDone = TRUE;
951
952 return segment;
953 }
954 }
955
956 /******************************************/
957 /* KakaduClassId() */
958 /******************************************/
959 int JPIPKAKDataset::KakaduClassId(int nClassIdIn)
960 {
961 if (nClassIdIn == 0)
962 return KDU_PRECINCT_DATABIN;
963 else if (nClassIdIn == 2)
964 return KDU_TILE_HEADER_DATABIN;
965 else if (nClassIdIn == 6)
966 return KDU_MAIN_HEADER_DATABIN;
967 else if (nClassIdIn == 8)
968 return KDU_META_DATABIN;
969 else if (nClassIdIn == 4)
970 return KDU_TILE_DATABIN;
971 else
972 return -1;
973 }
974
975 /******************************************/
976 /* ReadFromInput() */
977 /******************************************/
978 int JPIPKAKDataset::ReadFromInput(GByte *pabyData, int nLen, int &bError)
979 {
980 int res = FALSE;
981 bError = FALSE;
982
983 if (nLen <= 0)
984 return FALSE;
985
986 #ifdef PST_DEBUG
987 nPSTThisInstance++;
988 if (CPLGetConfigOption("PST_OFFSET", nullptr) != nullptr)
989 {
990 nPSTTargetOffset = atoi(CPLGetConfigOption("PST_OFFSET", "0"));
991 nPSTTargetInstance = 0;
992 }
993 if (CPLGetConfigOption("PST_INSTANCE", nullptr) != nullptr)
994 {
995 nPSTTargetInstance = atoi(CPLGetConfigOption("PST_INSTANCE", "0"));
996 }
997
998 if (nPSTTargetOffset != -1 && nPSTThisInstance == 0)
999 {
1000 CPLDebug("JPIPKAK",
1001 "Premature Stream Termination Activated, PST_OFFSET=%d, "
1002 "PST_INSTANCE=%d",
1003 nPSTTargetOffset, nPSTTargetInstance);
1004 }
1005 if (nPSTTargetOffset != -1 && nPSTThisInstance == nPSTTargetInstance)
1006 {
1007 CPLDebug("JPIPKAK",
1008 "Premature Stream Termination in force for this input "
1009 "instance, PST_OFFSET=%d, data length=%d",
1010 nPSTTargetOffset, nLen);
1011 }
1012 #endif // def PST_DEBUG
1013
1014 // parse the data stream, reading the vbas and adding to the kakadu cache
1015 // we could parse all the boxes by hand, and just add data to the kakadu
1016 // cache we will do it the easy way and retrieve the metadata through the
1017 // kakadu query api
1018
1019 nPos = 0;
1020 JPIPDataSegment *pSegment = nullptr;
1021
1022 while ((pSegment = ReadSegment(pabyData, nLen, bError)) != nullptr)
1023 {
1024 if (pSegment->IsEOR())
1025 {
1026 if ((pSegment->GetId() == JPIPKAKDataset::JPIP_EOR_IMAGE_DONE) ||
1027 (pSegment->GetId() == JPIPKAKDataset::JPIP_EOR_WINDOW_DONE))
1028 res = TRUE;
1029
1030 delete pSegment;
1031 break;
1032 }
1033 else
1034 {
1035 // add data to kakadu
1036 // CPLDebug("JPIPKAK", "Parsed JPIP Segment class=%i stream=%i id=%i
1037 // offset=%i len=%i isFinal=%i isEOR=%i", pSegment->GetClassId(),
1038 // pSegment->GetCodestreamIdx(), pSegment->GetId(),
1039 // pSegment->GetOffset(), pSegment->GetLen(), pSegment->IsFinal(),
1040 // pSegment->IsEOR());
1041 poCache->add_to_databin(
1042 KakaduClassId(static_cast<int>(pSegment->GetClassId())),
1043 pSegment->GetCodestreamIdx(), pSegment->GetId(),
1044 pSegment->GetData(), static_cast<int>(pSegment->GetOffset()),
1045 static_cast<int>(pSegment->GetLen()), pSegment->IsFinal());
1046
1047 delete pSegment;
1048 }
1049 }
1050
1051 return res;
1052 }
1053
1054 /************************************************************************/
1055 /* GetSpatialRef() */
1056 /************************************************************************/
1057
1058 const OGRSpatialReference *JPIPKAKDataset::GetSpatialRef() const
1059
1060 {
1061 if (!m_oSRS.IsEmpty())
1062 return &m_oSRS;
1063 else
1064 return GDALPamDataset::GetSpatialRef();
1065 }
1066
1067 /************************************************************************/
1068 /* GetGeoTransform() */
1069 /************************************************************************/
1070
1071 CPLErr JPIPKAKDataset::GetGeoTransform(GDALGeoTransform &gt) const
1072
1073 {
1074 if (bGeoTransformValid)
1075 {
1076 gt = m_gt;
1077
1078 return CE_None;
1079 }
1080 else
1081 return GDALPamDataset::GetGeoTransform(gt);
1082 }
1083
1084 /************************************************************************/
1085 /* GetGCPCount() */
1086 /************************************************************************/
1087
1088 int JPIPKAKDataset::GetGCPCount()
1089
1090 {
1091 return nGCPCount;
1092 }
1093
1094 /************************************************************************/
1095 /* GetGCPSpatialRef() */
1096 /************************************************************************/
1097
1098 const OGRSpatialReference *JPIPKAKDataset::GetGCPSpatialRef() const
1099
1100 {
1101 if (nGCPCount > 0 && !m_oSRS.IsEmpty())
1102 return &m_oSRS;
1103 else
1104 return nullptr;
1105 }
1106
1107 /************************************************************************/
1108 /* GetGCP() */
1109 /************************************************************************/
1110
1111 const GDAL_GCP *JPIPKAKDataset::GetGCPs()
1112
1113 {
1114 return pasGCPList;
1115 }
1116
1117 /************************************************************************/
1118 /* IRasterIO() */
1119 /************************************************************************/
1120
1121 CPLErr JPIPKAKDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
1122 int nXSize, int nYSize, void *pData,
1123 int nBufXSize, int nBufYSize,
1124 GDALDataType eBufType, int nBandCount,
1125 BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
1126 GSpacing nLineSpace, GSpacing nBandSpace,
1127 GDALRasterIOExtraArg *psExtraArg)
1128
1129 {
1130 /* -------------------------------------------------------------------- */
1131 /* We need various criteria to skip out to block based methods. */
1132 /* -------------------------------------------------------------------- */
1133 if (TestUseBlockIO(nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize,
1134 eBufType, nBandCount, panBandMap))
1135 return GDALPamDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
1136 pData, nBufXSize, nBufYSize, eBufType,
1137 nBandCount, panBandMap, nPixelSpace,
1138 nLineSpace, nBandSpace, psExtraArg);
1139
1140 /* -------------------------------------------------------------------- */
1141 /* Otherwise do this as a single uncached async rasterio. */
1142 /* -------------------------------------------------------------------- */
1143 GDALAsyncReader *ario = BeginAsyncReader(
1144 nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType,
1145 nBandCount, const_cast<int *>(panBandMap),
1146 static_cast<int>(nPixelSpace), static_cast<int>(nLineSpace),
1147 static_cast<int>(nBandSpace), nullptr);
1148
1149 if (ario == nullptr)
1150 return CE_Failure;
1151
1152 GDALAsyncStatusType status;
1153
1154 do
1155 {
1156 int nXBufOff, nYBufOff, nXBufSize, nYBufSize;
1157
1158 status = ario->GetNextUpdatedRegion(-1.0, &nXBufOff, &nYBufOff,
1159 &nXBufSize, &nYBufSize);
1160 } while (status != GARIO_ERROR && status != GARIO_COMPLETE);
1161
1162 EndAsyncReader(ario);
1163
1164 if (status == GARIO_ERROR)
1165 return CE_Failure;
1166 else
1167 return CE_None;
1168 }
1169
1170 /************************************************************************/
1171 /* TestUseBlockIO() */
1172 /************************************************************************/
1173
1174 int JPIPKAKDataset::TestUseBlockIO(CPL_UNUSED int nXOff, CPL_UNUSED int nYOff,
1175 int nXSize, int nYSize, int nBufXSize,
1176 int nBufYSize,
1177 CPL_UNUSED GDALDataType eDataType,
1178 int nBandCount, const int *panBandList) const
1179
1180 {
1181 /* -------------------------------------------------------------------- */
1182 /* Due to limitations in DirectRasterIO() we can only handle */
1183 /* it no duplicates in the band list. */
1184 /* -------------------------------------------------------------------- */
1185 int i, j;
1186
1187 for (i = 0; i < nBandCount; i++)
1188 {
1189 for (j = i + 1; j < nBandCount; j++)
1190 if (panBandList[j] == panBandList[i])
1191 return TRUE;
1192 }
1193
1194 /* -------------------------------------------------------------------- */
1195 /* The rest of the rules are io strategy stuff, and use */
1196 /* configuration checks. */
1197 /* -------------------------------------------------------------------- */
1198 int bUseBlockedIO = bForceCachedIO;
1199
1200 if (nYSize == 1 || nXSize * ((double)nYSize) < 100.0)
1201 bUseBlockedIO = TRUE;
1202
1203 if (nBufYSize == 1 || nBufXSize * ((double)nBufYSize) < 100.0)
1204 bUseBlockedIO = TRUE;
1205
1206 if (bUseBlockedIO &&
1207 CPLTestBool(CPLGetConfigOption("GDAL_ONE_BIG_READ", "NO")))
1208 bUseBlockedIO = FALSE;
1209
1210 return bUseBlockedIO;
1211 }
1212
1213 /************************************************************************/
1214 /* BeginAsyncReader() */
1215 /************************************************************************/
1216
1217 GDALAsyncReader *JPIPKAKDataset::BeginAsyncReader(
1218 int xOff, int yOff, int xSize, int ySize, void *pBuf, int bufXSize,
1219 int bufYSize, GDALDataType bufType, int nBandCount, int *pBandMap,
1220 int nPixelSpace, int nLineSpace, int nBandSpace, CSLConstList papszOptions)
1221 {
1222 CPLDebug("JPIP", "BeginAsyncReadeR(%d,%d,%d,%d -> %dx%d)", xOff, yOff,
1223 xSize, ySize, bufXSize, bufYSize);
1224
1225 /* -------------------------------------------------------------------- */
1226 /* Recreate the code stream access if needed. */
1227 /* -------------------------------------------------------------------- */
1228 if (bNeedReinitialize)
1229 {
1230 CPLDebug("JPIPKAK", "\n\nReinitializing after error! ******\n");
1231
1232 Deinitialize();
1233 if (!Initialize(GetDescription(), TRUE))
1234 return nullptr;
1235 }
1236
1237 /* -------------------------------------------------------------------- */
1238 /* Provide default packing if needed. */
1239 /* -------------------------------------------------------------------- */
1240 if (nPixelSpace == 0)
1241 nPixelSpace = GDALGetDataTypeSizeBytes(bufType);
1242 if (nLineSpace == 0)
1243 nLineSpace = nPixelSpace * bufXSize;
1244 if (nBandSpace == 0)
1245 nBandSpace = nLineSpace * bufYSize;
1246
1247 /* -------------------------------------------------------------------- */
1248 /* check we have sensible values for windowing. */
1249 /* -------------------------------------------------------------------- */
1250 if (xOff > GetRasterXSize() || yOff > GetRasterYSize() ||
1251 (xOff + xSize) > GetRasterXSize() || (yOff + ySize) > GetRasterYSize())
1252 {
1253 CPLError(CE_Failure, CPLE_AppDefined,
1254 "Requested window (%d,%d %dx%d) off dataset.", xOff, yOff,
1255 xSize, ySize);
1256 return nullptr;
1257 }
1258
1259 /* -------------------------------------------------------------------- */
1260 /* Record request information. */
1261 /* -------------------------------------------------------------------- */
1262 JPIPKAKAsyncReader *ario = new JPIPKAKAsyncReader();
1263 ario->poDS = this;
1264 ario->nBufXSize = bufXSize;
1265 ario->nBufYSize = bufYSize;
1266 ario->eBufType = bufType;
1267 ario->nBandCount = nBandCount;
1268 ario->nXOff = xOff;
1269 ario->nYOff = yOff;
1270 ario->nXSize = xSize;
1271 ario->nYSize = ySize;
1272
1273 ario->panBandMap = new int[nBandCount];
1274 if (pBandMap)
1275 {
1276 for (int i = 0; i < nBandCount; i++)
1277 ario->panBandMap[i] = pBandMap[i];
1278 }
1279 else
1280 {
1281 for (int i = 0; i < nBandCount; i++)
1282 ario->panBandMap[i] = i + 1;
1283 }
1284
1285 /* -------------------------------------------------------------------- */
1286 /* If the buffer type is of other than images type, we need to */
1287 /* allocate a private buffer the same type as the image which */
1288 /* will be converted later. */
1289 /* -------------------------------------------------------------------- */
1290 if (bufType != eDT)
1291 {
1292 ario->nPixelSpace = GDALGetDataTypeSizeBytes(eDT);
1293 ario->nLineSpace = ario->nPixelSpace * bufXSize;
1294 ario->nBandSpace = ario->nLineSpace * bufYSize;
1295
1296 ario->nAppPixelSpace = nPixelSpace;
1297 ario->nAppLineSpace = nLineSpace;
1298 ario->nAppBandSpace = nBandSpace;
1299
1300 ario->pBuf = VSI_MALLOC3_VERBOSE(bufXSize, bufYSize,
1301 ario->nPixelSpace * nBandCount);
1302 if (ario->pBuf == nullptr)
1303 {
1304 delete[] ario->panBandMap;
1305 ario->panBandMap = nullptr;
1306 delete ario;
1307 return nullptr;
1308 }
1309
1310 ario->pAppBuf = pBuf;
1311 }
1312 else
1313 {
1314 ario->pBuf = pBuf;
1315 ario->pAppBuf = pBuf;
1316
1317 ario->nAppPixelSpace = nPixelSpace;
1318 ario->nPixelSpace = nPixelSpace;
1319
1320 ario->nAppLineSpace = nLineSpace;
1321 ario->nLineSpace = nLineSpace;
1322
1323 ario->nAppBandSpace = nBandSpace;
1324 ario->nBandSpace = nBandSpace;
1325 }
1326
1327 // parse options
1328 const char *pszLevel = CSLFetchNameValue(papszOptions, "LEVEL");
1329 const char *pszLayers = CSLFetchNameValue(papszOptions, "LAYERS");
1330 const char *pszPriority = CSLFetchNameValue(papszOptions, "PRIORITY");
1331
1332 if (pszLayers)
1333 ario->nQualityLayers = atoi(pszLayers);
1334 else
1335 ario->nQualityLayers = nQualityLayers;
1336
1337 if (pszPriority)
1338 {
1339 if (EQUAL(pszPriority, "0"))
1340 ario->bHighPriority = 0;
1341 else
1342 ario->bHighPriority = 1;
1343 }
1344 else
1345 ario->bHighPriority = 1;
1346
1347 /* -------------------------------------------------------------------- */
1348 /* Select an appropriate level based on the ratio of buffer */
1349 /* size to full resolution image. We aim for the next */
1350 /* resolution *lower* than we might expect for the target */
1351 /* buffer unless it falls on a power of two. This is because */
1352 /* the region decompressor only seems to support upsampling */
1353 /* via the numerator/denominator magic. */
1354 /* -------------------------------------------------------------------- */
1355 if (pszLevel)
1356 ario->nLevel = atoi(pszLevel);
1357 else
1358 {
1359 int nRXSize = xSize;
1360 int nRYSize = ySize;
1361 ario->nLevel = 0;
1362
1363 while (ario->nLevel < nResLevels &&
1364 (nRXSize > bufXSize || nRYSize > bufYSize))
1365 {
1366 nRXSize = (nRXSize + 1) / 2;
1367 nRYSize = (nRYSize + 1) / 2;
1368 ario->nLevel++;
1369 }
1370 }
1371
1372 ario->Start();
1373
1374 return ario;
1375 }
1376
1377 /************************************************************************/
1378 /* EndAsyncReader() */
1379 /************************************************************************/
1380
1381 void JPIPKAKDataset::EndAsyncReader(GDALAsyncReader *poARIO)
1382 {
1383 delete poARIO;
1384 }
1385
1386 /*****************************************/
1387 /* Open() */
1388 /*****************************************/
1389 GDALDataset *JPIPKAKDataset::Open(GDALOpenInfo *poOpenInfo)
1390 {
1391 // test jpip and jpips, assuming jpip is using http as the transport layer
1392 // jpip = http, jpips = https (note SSL is allowed, but jpips is not in the
1393 // ISO spec)
1394 if (STARTS_WITH_CI(poOpenInfo->pszFilename, "jpip://") ||
1395 STARTS_WITH_CI(poOpenInfo->pszFilename, "jpips://"))
1396 {
1397 // perform the initial connection
1398 // using cpl_http for the connection
1399 if (CPLHTTPEnabled() == TRUE)
1400 {
1401 JPIPKAKDataset *poDS = new JPIPKAKDataset();
1402 if (poDS->Initialize(poOpenInfo->pszFilename, FALSE))
1403 {
1404 poDS->SetDescription(poOpenInfo->pszFilename);
1405 return poDS;
1406 }
1407 else
1408 {
1409 delete poDS;
1410 return nullptr;
1411 }
1412 }
1413 else
1414 {
1415 CPLError(CE_Failure, CPLE_OpenFailed,
1416 "Failed to open %s within JPIPKAK driver CPL HTTP not "
1417 "enabled.\n",
1418 poOpenInfo->pszFilename);
1419 return nullptr;
1420 }
1421 }
1422 else
1423 return nullptr;
1424 }
1425
1426 /************************************************************************/
1427 /* GDALRegister_JPIPKAK() */
1428 /************************************************************************/
1429
1430 void GDALRegister_JPIPKAK()
1431 {
1432 if (!GDAL_CHECK_VERSION("JPIPKAK driver"))
1433 return;
1434
1435 if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
1436 return;
1437
1438 GDALDriver *poDriver = new GDALDriver();
1439 JPIPKAKDriverSetCommonMetadata(poDriver);
1440 poDriver->pfnOpen = JPIPKAKDataset::Open;
1441 GetGDALDriverManager()->RegisterDriver(poDriver);
1442 }
1443
1444 /************************************************************************/
1445 /* JPIPKAKAsyncReader */
1446 /************************************************************************/
1447 JPIPKAKAsyncReader::JPIPKAKAsyncReader()
1448 {
1449 panBandMap = nullptr;
1450 pAppBuf = nullptr;
1451 pBuf = nullptr;
1452 nDataRead = 0;
1453 nAppPixelSpace = 0;
1454 nAppLineSpace = 0;
1455 nAppBandSpace = 0;
1456 nLevel = 0;
1457 nQualityLayers = 0;
1458 bHighPriority = FALSE;
1459 bComplete = FALSE;
1460 }
1461
1462 /************************************************************************/
1463 /* ~JPIPKAKAsyncReader */
1464 /************************************************************************/
1465 JPIPKAKAsyncReader::~JPIPKAKAsyncReader()
1466 {
1467 Stop();
1468
1469 // don't own the buffer
1470 delete[] panBandMap;
1471
1472 if (pAppBuf != pBuf)
1473 CPLFree(pBuf);
1474 }
1475
1476 /************************************************************************/
1477 /* Start() */
1478 /************************************************************************/
1479
1480 void JPIPKAKAsyncReader::Start()
1481 {
1482 JPIPKAKDataset *poJDS = cpl::down_cast<JPIPKAKDataset *>(poDS);
1483
1484 // stop the currently running thread
1485 // start making requests to the server to the server
1486 nDataRead = 0;
1487 bComplete = 0;
1488
1489 // check a thread is not already running
1490 if (((bHighPriority) && (poJDS->bHighThreadRunning)) ||
1491 ((!bHighPriority) && (poJDS->bLowThreadRunning)))
1492 CPLError(CE_Failure, CPLE_AppDefined,
1493 "JPIPKAKAsyncReader supports at most two concurrent server "
1494 "communication threads");
1495 else
1496 {
1497 // Ensure we are working against full res
1498 poJDS->poCodestream->apply_input_restrictions(0, 0, 0, 0, nullptr);
1499
1500 // calculate the url the worker function is going to retrieve
1501 // calculate the kakadu adjust image size
1502 channels.configure(*(poJDS->poCodestream));
1503
1504 // find current canvas width and height in the cache and check we don't
1505 // exceed this in our process request
1506 kdu_dims view_dims;
1507 kdu_coords ref_expansion;
1508 ref_expansion.x = 1;
1509 ref_expansion.y = 1;
1510
1511 view_dims = poJDS->poDecompressor->get_rendered_image_dims(
1512 *(poJDS->poCodestream), &channels, -1, nLevel, ref_expansion);
1513
1514 kdu_coords *view_siz = view_dims.access_size();
1515
1516 // Establish the decimation implied by our resolution level.
1517 int nRes = 1;
1518 if (nLevel > 0)
1519 nRes = 2 << (nLevel - 1);
1520
1521 // setup expansion to account for the difference between
1522 // the selected level and the buffer resolution.
1523 exp_numerator.x = nBufXSize;
1524 exp_numerator.y = nBufYSize;
1525
1526 exp_denominator.x = (int)ceil(nXSize / (double)nRes);
1527 exp_denominator.y = (int)ceil(nYSize / (double)nRes);
1528
1529 // formulate jpip parameters and adjust offsets for current level
1530 int fx = view_siz->x / nRes;
1531 int fy = view_siz->y / nRes;
1532
1533 rr_win.pos.x = (int)ceil(nXOff / (1.0 * nRes)); // roffx
1534 rr_win.pos.y = (int)ceil(nYOff / (1.0 * nRes)); // roffy
1535 rr_win.size.x = (int)ceil(nXSize / (1.0 * nRes)); // rsizx
1536 rr_win.size.y = (int)ceil(nYSize / (1.0 * nRes)); // rsizy
1537
1538 if (rr_win.pos.x + rr_win.size.x > fx)
1539 rr_win.size.x = fx - rr_win.pos.x;
1540 if (rr_win.pos.y + rr_win.size.y > fy)
1541 rr_win.size.y = fy - rr_win.pos.y;
1542
1543 CPLString jpipUrl;
1544 CPLString comps;
1545
1546 if (poJDS->bYCC)
1547 {
1548 comps = "0,1,2";
1549 }
1550 else
1551 {
1552 for (int i = 0; i < nBandCount; i++)
1553 comps.Printf("%s%i,", comps.c_str(), panBandMap[i] - 1);
1554
1555 comps.erase(comps.length() - 1);
1556 }
1557
1558 jpipUrl.Printf("%s&type=jpp-stream&roff=%i,%i&rsiz=%i,%i&fsiz=%i,%i,"
1559 "closest&quality=%i&comps=%s",
1560 poJDS->osRequestUrl.c_str(), rr_win.pos.x, rr_win.pos.y,
1561 rr_win.size.x, rr_win.size.y, fx, fy, nQualityLayers,
1562 comps.c_str());
1563
1564 JPIPRequest *pRequest = new JPIPRequest();
1565 pRequest->bPriority = bHighPriority;
1566 pRequest->osRequest = jpipUrl;
1567 pRequest->poARIO = this;
1568
1569 if (bHighPriority)
1570 poJDS->bHighThreadFinished = 0;
1571 else
1572 poJDS->bLowThreadFinished = 0;
1573
1574 // CPLDebug("JPIPKAKAsyncReader", "THREADING TURNED OFF");
1575 if (CPLCreateThread(JPIPWorkerFunc, pRequest) == -1)
1576 CPLError(CE_Failure, CPLE_AppDefined,
1577 "Unable to create worker jpip thread");
1578 // run in main thread as a test
1579 // JPIPWorkerFunc(pRequest);
1580 }
1581 }
1582
1583 /************************************************************************/
1584 /* Stop() */
1585 /************************************************************************/
1586 void JPIPKAKAsyncReader::Stop()
1587 {
1588 JPIPKAKDataset *poJDS = cpl::down_cast<JPIPKAKDataset *>(poDS);
1589
1590 bComplete = 1;
1591 if (poJDS->pGlobalMutex)
1592 {
1593 if (((bHighPriority) && (!poJDS->bHighThreadFinished)) ||
1594 ((!bHighPriority) && (!poJDS->bLowThreadFinished)))
1595 {
1596 CPLDebug("JPIPKAK", "JPIPKAKAsyncReader::Stop() requested.");
1597
1598 // stop the thread
1599 if (bHighPriority)
1600 {
1601 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
1602 poJDS->bHighThreadRunning = 0;
1603 CPLReleaseMutex(poJDS->pGlobalMutex);
1604
1605 while (!poJDS->bHighThreadFinished)
1606 CPLSleep(0.1);
1607 }
1608 else
1609 {
1610 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
1611 poJDS->bLowThreadRunning = 0;
1612 CPLReleaseMutex(poJDS->pGlobalMutex);
1613
1614 while (!poJDS->bLowThreadFinished)
1615 {
1616 CPLSleep(0.1);
1617 }
1618 }
1619 CPLDebug("JPIPKAK", "JPIPKAKAsyncReader::Stop() confirmed.");
1620 }
1621 }
1622 }
1623
1624 /************************************************************************/
1625 /* GetNextUpdatedRegion() */
1626 /************************************************************************/
1627
1628 GDALAsyncStatusType JPIPKAKAsyncReader::GetNextUpdatedRegion(double dfTimeout,
1629 int *pnxbufoff,
1630 int *pnybufoff,
1631 int *pnxbufsize,
1632 int *pnybufsize)
1633 {
1634 GDALAsyncStatusType result = GARIO_ERROR;
1635 JPIPKAKDataset *poJDS = cpl::down_cast<JPIPKAKDataset *>(poDS);
1636
1637 long nSize = 0;
1638 // take a snapshot of the volatile variables
1639 if (bHighPriority)
1640 {
1641 const long s = poJDS->nHighThreadByteCount - nDataRead;
1642 nSize = s;
1643 }
1644 else
1645 {
1646 const long s = poJDS->nLowThreadByteCount - nDataRead;
1647 nSize = s;
1648 }
1649
1650 /* -------------------------------------------------------------------- */
1651 /* Wait for new data to return if required. */
1652 /* -------------------------------------------------------------------- */
1653 if ((nSize == 0) && dfTimeout != 0)
1654 {
1655 // poll for change in cache size
1656 clock_t end_wait = 0;
1657
1658 end_wait = clock() + (int)(dfTimeout * CLOCKS_PER_SEC);
1659 while ((nSize == 0) && ((bHighPriority && poJDS->bHighThreadRunning) ||
1660 (!bHighPriority && poJDS->bLowThreadRunning)))
1661 {
1662 if (end_wait)
1663 if (clock() > end_wait && dfTimeout >= 0)
1664 break;
1665
1666 CPLSleep(0.1);
1667
1668 if (bHighPriority)
1669 {
1670 const long s = poJDS->nHighThreadByteCount - nDataRead;
1671 nSize = s;
1672 }
1673 else
1674 {
1675 const long s = poJDS->nLowThreadByteCount - nDataRead;
1676 nSize = s;
1677 }
1678 }
1679 }
1680
1681 // if there is no pending data and we don't want to wait.
1682 if (nSize == 0)
1683 {
1684 *pnxbufoff = 0;
1685 *pnybufoff = 0;
1686 *pnxbufsize = 0;
1687 *pnybufsize = 0;
1688
1689 // Indicate an error if the thread finished prematurely
1690 if ((bHighPriority && !poJDS->bHighThreadRunning &&
1691 poJDS->bHighThreadFinished) ||
1692 (!bHighPriority && !poJDS->bLowThreadRunning &&
1693 poJDS->bLowThreadFinished))
1694 {
1695 if (osErrorMsg != "")
1696 CPLError(CE_Failure, CPLE_AppDefined, "%s", osErrorMsg.c_str());
1697 else
1698 CPLError(
1699 CE_Failure, CPLE_AppDefined,
1700 "Working thread failed without complete data. (%d,%d,%d)",
1701 bHighPriority, poJDS->bHighThreadRunning,
1702 poJDS->bHighThreadFinished);
1703 poJDS->bNeedReinitialize = TRUE;
1704 return GARIO_ERROR;
1705 }
1706
1707 // Otherwise there is still pending data to wait for.
1708 return GARIO_PENDING;
1709 }
1710
1711 /* -------------------------------------------------------------------- */
1712 /* Establish the canvas region with the expansion factor */
1713 /* applied, and compute region from the original window cut */
1714 /* down to the target canvas. */
1715 /* -------------------------------------------------------------------- */
1716 kdu_dims view_dims, region;
1717 int nBytesPerPixel = GDALGetDataTypeSizeBytes(poJDS->eDT);
1718 int nPrecision = 0;
1719
1720 try
1721 {
1722 // Ensure we are working against full res
1723 poJDS->poCodestream->apply_input_restrictions(0, 0, 0, 0, nullptr);
1724
1725 view_dims = poJDS->poDecompressor->get_rendered_image_dims(
1726 *poJDS->poCodestream, &channels, -1, nLevel, exp_numerator,
1727 exp_denominator);
1728
1729 double x_ratio, y_ratio;
1730 x_ratio = view_dims.size.x / (double)poDS->GetRasterXSize();
1731 y_ratio = view_dims.size.y / (double)poDS->GetRasterYSize();
1732
1733 region = rr_win;
1734
1735 region.pos.x = (int)ceil(region.pos.x * x_ratio);
1736 region.pos.y = (int)ceil(region.pos.y * y_ratio);
1737 region.size.x = (int)ceil(region.size.x * x_ratio);
1738 region.size.y = (int)ceil(region.size.y * y_ratio);
1739
1740 region.size.x = std::min(region.size.x, nBufXSize);
1741 region.size.y = std::min(region.size.y, nBufYSize);
1742
1743 if (region.pos.x + region.size.x > view_dims.size.x)
1744 region.size.x = view_dims.size.x - region.pos.x;
1745 if (region.pos.y + region.size.y > view_dims.size.y)
1746 region.size.y = view_dims.size.y - region.pos.y;
1747
1748 region.pos += view_dims.pos;
1749
1750 CPLAssert(nBytesPerPixel == 1 || nBytesPerPixel == 2);
1751
1752 if (poJDS->poCodestream->get_bit_depth(0) > 16)
1753 nPrecision = 16;
1754 }
1755 catch (...)
1756 {
1757 // The error handler should already have posted an error message.
1758 return GARIO_ERROR;
1759 }
1760
1761 /* ==================================================================== */
1762 /* Now we process the available cached jpeg2000 data into */
1763 /* imagery. The kdu_region_decompressor only seems to support */
1764 /* reading back one or three components at a time, we may need */
1765 /* to do several processing passes to get the bands we */
1766 /* want. We try to do groups of three were possible, and handle */
1767 /* the rest one band at a time. */
1768 /* ==================================================================== */
1769 int nBandsCompleted = 0;
1770
1771 while (nBandsCompleted < nBandCount)
1772 {
1773 /* --------------------------------------------------------------------
1774 */
1775 /* Set up channel list requested. */
1776 /* --------------------------------------------------------------------
1777 */
1778 std::vector<int> component_indices;
1779 unsigned int i;
1780
1781 if (nBandCount - nBandsCompleted >= 3)
1782 {
1783 CPLDebug("JPIPKAK", "process bands %d,%d,%d",
1784 panBandMap[nBandsCompleted],
1785 panBandMap[nBandsCompleted + 1],
1786 panBandMap[nBandsCompleted + 2]);
1787
1788 component_indices.push_back(panBandMap[nBandsCompleted++] - 1);
1789 component_indices.push_back(panBandMap[nBandsCompleted++] - 1);
1790 component_indices.push_back(panBandMap[nBandsCompleted++] - 1);
1791 }
1792 else
1793 {
1794 CPLDebug("JPIPKAK", "process band %d", panBandMap[nBandsCompleted]);
1795 component_indices.push_back(panBandMap[nBandsCompleted++] - 1);
1796 }
1797
1798 /* --------------------------------------------------------------------
1799 */
1800 /* Apply region, channel and overview level restrictions. */
1801 /* --------------------------------------------------------------------
1802 */
1803 kdu_dims region_pass = region;
1804
1805 poJDS->poCodestream->apply_input_restrictions(
1806 static_cast<int>(component_indices.size()), &(component_indices[0]),
1807 nLevel, nQualityLayers, &region_pass,
1808 KDU_WANT_CODESTREAM_COMPONENTS);
1809
1810 channels.configure(*(poJDS->poCodestream));
1811
1812 for (i = 0; i < component_indices.size(); i++)
1813 channels.source_components[i] = component_indices[i];
1814
1815 kdu_dims incomplete_region = region_pass;
1816 kdu_coords origin = region_pass.pos;
1817
1818 int bIsDecompressing = FALSE;
1819
1820 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
1821
1822 try
1823 {
1824
1825 bIsDecompressing = poJDS->poDecompressor->start(
1826 *(poJDS->poCodestream), &channels, -1, nLevel, nQualityLayers,
1827 region_pass, exp_numerator, exp_denominator, TRUE);
1828
1829 *pnxbufoff = 0;
1830 *pnybufoff = 0;
1831 *pnxbufsize = region_pass.access_size()->x;
1832 *pnybufsize = region_pass.access_size()->y;
1833
1834 // Setup channel buffers
1835 std::vector<kdu_byte *> channel_bufs;
1836
1837 for (i = 0; i < component_indices.size(); i++)
1838 channel_bufs.push_back(
1839 ((kdu_byte *)pBuf) +
1840 (i + nBandsCompleted - component_indices.size()) *
1841 nBandSpace);
1842
1843 int pixel_gap = nPixelSpace / nBytesPerPixel;
1844 int row_gap = nLineSpace / nBytesPerPixel;
1845
1846 while ((bIsDecompressing == 1) || (incomplete_region.area() != 0))
1847 {
1848 if (nBytesPerPixel == 1)
1849 {
1850 bIsDecompressing = poJDS->poDecompressor->process(
1851 &(channel_bufs[0]), false, pixel_gap, origin, row_gap,
1852 1000000, 0, incomplete_region, region_pass, 0, false);
1853 }
1854 else if (nBytesPerPixel == 2)
1855 {
1856 bIsDecompressing = poJDS->poDecompressor->process(
1857 reinterpret_cast<kdu_uint16 **>(&(channel_bufs[0])),
1858 false, pixel_gap, origin, row_gap, 1000000, 0,
1859 incomplete_region, region_pass, nPrecision, false);
1860 }
1861
1862 CPLDebug("JPIPKAK",
1863 "processed=%d,%d %dx%d - incomplete=%d,%d %dx%d",
1864 region_pass.pos.x, region_pass.pos.y,
1865 region_pass.size.x, region_pass.size.y,
1866 incomplete_region.pos.x, incomplete_region.pos.y,
1867 incomplete_region.size.x, incomplete_region.size.y);
1868 }
1869
1870 poJDS->poDecompressor->finish();
1871 CPLReleaseMutex(poJDS->pGlobalMutex);
1872 }
1873 catch (...)
1874 {
1875 poJDS->poDecompressor->finish();
1876 CPLReleaseMutex(poJDS->pGlobalMutex);
1877 // The error handler should already have posted an error message.
1878 return GARIO_ERROR;
1879 }
1880 } // nBandsCompleted < nBandCount
1881
1882 /* -------------------------------------------------------------------- */
1883 /* If the application buffer is of a different type than our */
1884 /* band we need to copy into the application buffer at this */
1885 /* point. */
1886 /* */
1887 /* We could optimize to only update affected area, but that is */
1888 /* always the whole area for the JPIP driver it seems. */
1889 /* -------------------------------------------------------------------- */
1890 if (pAppBuf != pBuf)
1891 {
1892 int iY, iBand;
1893 GByte *pabySrc = (GByte *)pBuf;
1894 GByte *pabyDst = (GByte *)pAppBuf;
1895
1896 for (iBand = 0; iBand < nBandCount; iBand++)
1897 {
1898 for (iY = 0; iY < nBufYSize; iY++)
1899 {
1900 GDALCopyWords(pabySrc + nLineSpace * iY + nBandSpace * iBand,
1901 poJDS->eDT, nPixelSpace,
1902 pabyDst + nAppLineSpace * iY +
1903 nAppBandSpace * iBand,
1904 eBufType, nAppPixelSpace, nBufXSize);
1905 }
1906 }
1907 }
1908
1909 /* -------------------------------------------------------------------- */
1910 /* has there been any more data read while were have been processing?*/
1911 /* -------------------------------------------------------------------- */
1912 long size = 0;
1913 if (bHighPriority)
1914 {
1915 const long x = poJDS->nHighThreadByteCount - nDataRead;
1916 size = x;
1917 }
1918 else
1919 {
1920 const long x = poJDS->nLowThreadByteCount - nDataRead;
1921 size = x;
1922 }
1923
1924 if ((bComplete) && (nSize == size))
1925 result = GARIO_COMPLETE;
1926 else
1927 result = GARIO_UPDATE;
1928
1929 nDataRead += nSize;
1930
1931 if (result == GARIO_ERROR)
1932 poJDS->bNeedReinitialize = TRUE;
1933
1934 return result;
1935 }
1936
1937 /************************************************************************/
1938 /* JPIPDataSegment() */
1939 /************************************************************************/
1940 JPIPDataSegment::JPIPDataSegment()
1941 {
1942 nId = 0;
1943 nAux = 0;
1944 nClassId = 0;
1945 nCodestream = 0;
1946 nOffset = 0;
1947 nLen = 0;
1948 pabyData = nullptr;
1949 bIsFinal = FALSE;
1950 bIsEOR = FALSE;
1951 }
1952
1953 /************************************************************************/
1954 /* ~JPIPDataSegment() */
1955 /************************************************************************/
1956 JPIPDataSegment::~JPIPDataSegment()
1957 {
1958 CPLFree(pabyData);
1959 }
1960
1961 /************************************************************************/
1962 /* JPIPWorkerFunc() */
1963 /************************************************************************/
1964 static void JPIPWorkerFunc(void *req)
1965 {
1966 int nCurrentTransmissionLength = 2000;
1967 int nMinimumTransmissionLength = 2000;
1968
1969 JPIPRequest *pRequest = (JPIPRequest *)req;
1970 JPIPKAKDataset *poJDS =
1971 cpl::down_cast<JPIPKAKDataset *>(pRequest->poARIO->GetGDALDataset());
1972
1973 int bPriority = pRequest->bPriority;
1974
1975 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
1976
1977 CPLDebug("JPIPKAK", "working thread starting.");
1978 // set the running status
1979 if (bPriority)
1980 {
1981 poJDS->bHighThreadRunning = 1;
1982 poJDS->bHighThreadFinished = 0;
1983 }
1984 else
1985 {
1986 poJDS->bLowThreadRunning = 1;
1987 poJDS->bLowThreadFinished = 0;
1988 }
1989
1990 CPLReleaseMutex(poJDS->pGlobalMutex);
1991
1992 CPLString osHeaders = "HEADERS=";
1993 osHeaders += "Accept: jpp-stream";
1994 CPLString osPersistent;
1995
1996 osPersistent.Printf("PERSISTENT=JPIPKAK:%p", poJDS);
1997
1998 char *apszOptions[] = {(char *)osHeaders.c_str(),
1999 (char *)osPersistent.c_str(), nullptr};
2000
2001 while (true)
2002 {
2003 // modulate the len= parameter to use the currently available bandwidth
2004 long nStart = clock();
2005
2006 if (((bPriority) && (!poJDS->bHighThreadRunning)) ||
2007 ((!bPriority) && (!poJDS->bLowThreadRunning)))
2008 break;
2009
2010 // make jpip requests
2011 // adjust transmission length
2012 CPLString osCurrentRequest;
2013 osCurrentRequest.Printf("%s&len=%i", pRequest->osRequest.c_str(),
2014 nCurrentTransmissionLength);
2015 CPLHTTPResult *psResult = CPLHTTPFetch(osCurrentRequest, apszOptions);
2016 if (psResult->nDataLen == 0)
2017 {
2018 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
2019 if (psResult->pszErrBuf)
2020 pRequest->poARIO->osErrorMsg.Printf(
2021 "zero data returned from server, timeout?\n%s",
2022 psResult->pszErrBuf);
2023 else
2024 pRequest->poARIO->osErrorMsg =
2025 "zero data returned from server, timeout?";
2026
2027 // status is not being set, always zero in cpl_http
2028 CPLDebug("JPIPWorkerFunc", "zero data returned from server");
2029 CPLReleaseMutex(poJDS->pGlobalMutex);
2030 CPLHTTPDestroyResult(psResult);
2031 break;
2032 }
2033
2034 if (psResult->pszContentType != nullptr)
2035 CPLDebug("JPIPKAK", "Content-type: %s", psResult->pszContentType);
2036
2037 if (psResult->pszContentType != nullptr &&
2038 strstr(psResult->pszContentType, "html") != nullptr)
2039 {
2040 CPLDebug("JPIPKAK", "%s", psResult->pabyData);
2041 }
2042
2043 int bytes = psResult->nDataLen;
2044 long nEnd = clock();
2045
2046 if ((nEnd - nStart) > 0)
2047 nCurrentTransmissionLength = (int)std::max<double>(
2048 bytes / ((1.0 * (nEnd - nStart)) / CLOCKS_PER_SEC),
2049 nMinimumTransmissionLength);
2050
2051 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
2052
2053 int bError;
2054 int bComplete =
2055 cpl::down_cast<JPIPKAKDataset *>(pRequest->poARIO->GetGDALDataset())
2056 ->ReadFromInput(psResult->pabyData, psResult->nDataLen, bError);
2057 if (bPriority)
2058 poJDS->nHighThreadByteCount += psResult->nDataLen;
2059 else
2060 poJDS->nLowThreadByteCount += psResult->nDataLen;
2061
2062 pRequest->poARIO->SetComplete(bComplete);
2063
2064 CPLReleaseMutex(poJDS->pGlobalMutex);
2065 CPLHTTPDestroyResult(psResult);
2066
2067 if (bComplete || bError)
2068 break;
2069 }
2070
2071 CPLAcquireMutex(poJDS->pGlobalMutex, 100.0);
2072
2073 CPLDebug("JPIPKAK", "Worker shutting down.");
2074
2075 if (bPriority)
2076 {
2077 poJDS->bHighThreadRunning = 0;
2078 poJDS->bHighThreadFinished = 1;
2079 }
2080 else
2081 {
2082 poJDS->bLowThreadRunning = 0;
2083 poJDS->bLowThreadFinished = 1;
2084 }
2085
2086 CPLReleaseMutex(poJDS->pGlobalMutex);
2087
2088 // end of thread
2089 delete pRequest;
2090 }