VolumeDataPageAccessorImpl.cpp 9.87 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/****************************************************************************
** Copyright 2019 The Open Group
** Copyright 2019 Bluware, Inc.
**
** 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.
****************************************************************************/

#include "VolumeDataPageAccessorImpl.h"
Jørgen Lind's avatar
Jørgen Lind committed
19
#include "VolumeDataLayout.h"
20
21
#include "VolumeDataLayer.h"
#include "VolumeDataPageImpl.h"
Jørgen Lind's avatar
Jørgen Lind committed
22
#include "VolumeDataStore.h"
23
#include "MetadataManager.h"
24

Jørgen Lind's avatar
Jørgen Lind committed
25
26
27
28
29
30
#include <IO/IOManager.h>
#include "OpenVDSHandle.h"

#include "DimensionGroup.h"

#include <chrono>
31
32
33
34

namespace OpenVDS
{

35
36
37
VolumeDataPageAccessorImpl::VolumeDataPageAccessorImpl(VolumeDataAccessManagerImpl* accessManager, VolumeDataLayer* layer, int maxPages, bool isReadWrite)
  : m_accessManager(accessManager)
  , m_layer(layer)
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
  , m_maxPages(maxPages)
  , m_isReadWrite(isReadWrite)
{
}
  
VolumeDataLayout const* VolumeDataPageAccessorImpl::getLayout() const
{
  return m_layer->getLayout();
}

int VolumeDataPageAccessorImpl::getLod() const
{
  return m_layer->getLod();
}

int VolumeDataPageAccessorImpl::getChannelIndex() const
{
  return m_layer->getChannelIndex();
}

VolumeDataChannelDescriptor const& VolumeDataPageAccessorImpl::getChannelDescriptor() const
{
  return m_layer->getVolumeDataChannelDescriptor();
}

void  VolumeDataPageAccessorImpl::getNumSamples(int(&numSamples)[Dimensionality_Max]) const
{
  for (int i = 0; i < Dimensionality_Max; i++)
  {
    numSamples[i] = m_layer->getDimensionNumSamples(i);
  }
}
  
int64_t VolumeDataPageAccessorImpl::getChunkCount() const
{
  return m_layer->getTotalChunkCount();
}

void  VolumeDataPageAccessorImpl::getChunkMinMax(int64_t chunk, int(&min)[Dimensionality_Max], int(&max)[Dimensionality_Max]) const
{
  m_layer->getChunkMinMax(chunk, min, max, true);
}

void  VolumeDataPageAccessorImpl::getChunkMinMaxExcludingMargin(int64_t chunk, int(&min)[Dimensionality_Max], int(&max)[Dimensionality_Max]) const
{
  m_layer->getChunkMinMax(chunk, min, max, false);
}

int64_t VolumeDataPageAccessorImpl::getChunkIndex(const int(&position)[Dimensionality_Max]) const
{
  int32_t index_array[Dimensionality_Max];
  for (int i = 0; i < Dimensionality_Max; i++)
  {
    index_array[i] = m_layer->voxelToIndex(position[i], i);
  }
  return m_layer->indexArrayToChunkIndex(index_array); 
}

int VolumeDataPageAccessorImpl::addReference()
{
  return ++m_references;
}

int VolumeDataPageAccessorImpl::removeReference()
{
  return --m_references;
}

VolumeDataPage* VolumeDataPageAccessorImpl::readPageAtPosition(const int(&position)[Dimensionality_Max])
{
Jørgen Lind's avatar
Jørgen Lind committed
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
  std::unique_lock<std::mutex> pageMutexLocker(m_pagesMutex);

  if(!m_layer)
  {
    return NULL;
  }

  if (m_layer->getProduceStatus() == VolumeDataLayer::ProduceStatusUnavailable)
  {
    fprintf(stderr, "The accessed dimension group or channel is unavailable (check produce status on VDS before accessing data)");
    return nullptr;
  }

  int32_t indexArray[Dimensionality_Max];

  for(int32_t iDimension = 0; iDimension < Dimensionality_Max; iDimension++)
  {
    if(position[iDimension] < 0 || position[iDimension] >= m_layer->getDimensionNumSamples(iDimension))
    {
      return nullptr;
    }
    indexArray[iDimension] = m_layer->voxelToIndex(position[iDimension], iDimension);
  }

  int64_t chunk = m_layer->indexArrayToChunkIndex(indexArray);

  for(auto page_it = m_pages.begin(); page_it != m_pages.end(); ++page_it)
  {
    if((*page_it)->getChunkIndex() == chunk)
    {
      if (page_it != m_pages.begin())
      {
        m_pages.splice(m_pages.begin(), m_pages, page_it, std::next(page_it));
      }
      (*page_it)->pin();

      while((*page_it)->isEmpty())
      {
        m_pageReadCondition.wait_for(pageMutexLocker, std::chrono::milliseconds(1000));

        if(!m_layer)
        {
          (*page_it)->unPin();
          return nullptr;
        }
      }

      m_pagesFound++;
      return *page_it;
    }
  }

  // Wait for commit to finish before inserting a new page
  while(m_isCommitInProgress)
  {
    m_commitFinishedCondition.wait_for(pageMutexLocker, std::chrono::milliseconds(1000));
  }

  if(!m_layer)
  {
    return nullptr;
  }

  // Not found, we need to create a new page
  VolumeDataPageImpl *page = new VolumeDataPageImpl(this, chunk);

  m_pages.push_front(page);
  m_currentPages++;

  assert(page->isPinned());

  std::vector<uint8_t> blob;

  int32_t pitch[Dimensionality_Max];

  Error error;
Jørgen Lind's avatar
Jørgen Lind committed
184
185
  VolumeDataChunk volumeDataChunk = m_layer->getChunkFromIndex(chunk);
  if (!m_accessManager->prepareReadChunkData(volumeDataChunk, pitch, true, error))
Jørgen Lind's avatar
Jørgen Lind committed
186
  {
Jørgen Lind's avatar
Jørgen Lind committed
187
    page->unPin();
Jørgen Lind's avatar
Jørgen Lind committed
188
189
190
191
192
193
194
    fprintf(stderr, "Failed to download chunk: %s\n", error.string.c_str());
    return nullptr;
  }

  pageMutexLocker.unlock();

  std::vector<uint8_t> page_data;
Jørgen Lind's avatar
Jørgen Lind committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
  std::vector<uint8_t> metadata;
  CompressionInfo compressionInfo;
  if (!m_accessManager->readChunk(volumeDataChunk, page_data, metadata, compressionInfo, error))
  {
    pageMutexLocker.lock();
    page->unPin();
    fprintf(stderr, "Failed when waiting for chunk: %s\n", error.string.c_str());
    return nullptr;
  }

  if (!VolumeDataStore::deserializeVolumeData(volumeDataChunk, page_data, metadata, compressionInfo.GetCompressionMethod(), compressionInfo.GetAdaptiveLevel(), m_layer->getFormat(), page_data, error))
  {
    pageMutexLocker.lock();
    page->unPin();
    fprintf(stderr, "Failed when deserializing chunk: %s\n", error.string.c_str());
    return nullptr;
  }
Jørgen Lind's avatar
Jørgen Lind committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325

  pageMutexLocker.lock();
  page->setBufferData(std::move(page_data), pitch);
  m_pagesRead++;

  m_pageReadCondition.notify_all();

  if(!m_layer)
  {
    page->unPin();
    page = NULL;
  }

  limitPageListSize(m_maxPages, pageMutexLocker);

  return page;
}

void VolumeDataPageAccessorImpl::limitPageListSize(int maxPages, std::unique_lock<std::mutex>& pageListMutexLock)
{
  while(m_currentPages > m_maxPages)
  {
    // Wait for commit to finish before deleting a page
    while(m_isCommitInProgress)
    {
      m_commitFinishedCondition.wait_for(pageListMutexLock, std::chrono::milliseconds(1000));
    }

    // Find a page to evict
    auto page = m_pages.end();

    for (auto r_it = m_pages.rbegin(); r_it != m_pages.rend(); ++r_it)
    {
      if (!(*r_it)->isPinned())
      {
        page = ++r_it.base();
        break;
      }
    }

    if(page == m_pages.end())
    {
      return;
    }

    if((*page)->isWritten())
    {
      // Finish reading all pages currently being read
      while(1)
      {
        bool isReadInProgress = false;

        for(VolumeDataPageImpl *targetPage : m_pages)
        {
          if((*page)->isCopyMarginNeeded(targetPage))
          {
            if(targetPage->isEmpty())
            {
              isReadInProgress = true;
              break;
            }
          }
        }

        if(!isReadInProgress)
        {
          break;
        }

        (*page)->pin(); // Make sure this page isn't deleted by LimitPageListSize!

        // Wait for the page getting read
        m_pageReadCondition.wait_for(pageListMutexLock, std::chrono::milliseconds(1000));

        (*page)->unPin();

        // Check if the page was pinned while we released the mutex, we have to abort evicting this page
        if((*page)->isPinned())
        {
          break;
        }
      }

      // Check if the page was pinned while we released the mutex, we have to abort evicting this page
      if((*page)->isPinned())
      {
        continue;
      }

      // Copy margins
      if((*page)->isWritten())
      {
        for(VolumeDataPage *targetPage : m_pages)
        {
          if((*page)->isCopyMarginNeeded(targetPage))
          {
            (*page)->copyMargin(targetPage);
          }
        }
      }
    }

    auto page_v = *page;
    m_pages.erase(page);
    m_currentPages--;

    if(page_v->isDirty())
    {
      (*page)->writeBack(m_layer, pageListMutexLock);
      m_pagesWritten++;
    }

    delete page_v;
  }
326
327
}

Jørgen Lind's avatar
Jørgen Lind committed
328
329
330
/////////////////////////////////////////////////////////////////////////////
// Commit

331
332
void VolumeDataPageAccessorImpl::commit()
{
Jørgen Lind's avatar
Jørgen Lind committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
  std::unique_lock<std::mutex> pageListMutexLock(m_pagesMutex);

  if(m_isCommitInProgress)
  {
    return;
  }

  // Make sure we don't start reading any new pages while we're finishing up the current waiting reads
  m_isCommitInProgress = true;

  // Finish reading all pages currently being read
  for(VolumeDataPageImpl *page : m_pages)
  {
    while(page->isEmpty())
    {
      // Wait for the page getting read
      m_pageReadCondition.wait_for(pageListMutexLock, std::chrono::milliseconds(1000));
    }
  }

  // Copy all margins
  for(VolumeDataPageImpl *page : m_pages)
  {
    if(page->isWritten())
    {
      for(VolumeDataPageImpl *targetPage : m_pages)
      {
        if(page->isCopyMarginNeeded(targetPage))
        {
          page->copyMargin(targetPage);
        }
      }
    }
  }

  for(VolumeDataPageImpl *page : m_pages)
  {
    if(page->isDirty() && m_layer)
    {
      page->writeBack(m_layer, pageListMutexLock);
      m_pagesWritten++;
    }
  }

  m_isCommitInProgress = false;
  m_commitFinishedCondition.notify_all();

  // Only access the layout if there has been any write requests.
  // This allows for deleting read and interpolating accessors after their VDS has been deleted,
  // which can happen during project unload in Headwave.
  if (m_isReadWrite && m_pagesWritten > 0 && m_layer)
  {
    // FIXME: Make sure *all* invalidates are received, this is just a stop-gap measure.
    pageListMutexLock.unlock();
    m_layer->getLayout()->completePendingWriteChunkRequests(0);
  }
389
390
}
}