summaryrefslogtreecommitdiffstats
path: root/gfx/2d/DataSurfaceHelpers.cpp
blob: 0c3863b850ad3547666dd38b73b454df5d82e4d6 (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
200
201
202
203
204
205
206
207
208
209
210
211
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <cstring>

#include "2D.h"
#include "DataSurfaceHelpers.h"
#include "Logging.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/PodOperations.h"
#include "Swizzle.h"
#include "Tools.h"

namespace mozilla {
namespace gfx {

int32_t StrideForFormatAndWidth(SurfaceFormat aFormat, int32_t aWidth) {
  MOZ_ASSERT(aFormat <= SurfaceFormat::UNKNOWN);
  MOZ_ASSERT(aWidth > 0);

  // There's nothing special about this alignment, other than that it's what
  // cairo_format_stride_for_width uses.
  static const int32_t alignment = sizeof(int32_t);

  const int32_t bpp = BytesPerPixel(aFormat);

  if (aWidth >= (INT32_MAX - alignment) / bpp) {
    return -1;  // too big
  }

  return (bpp * aWidth + alignment - 1) & ~(alignment - 1);
}

already_AddRefed<DataSourceSurface> CreateDataSourceSurfaceFromData(
    const IntSize& aSize, SurfaceFormat aFormat, const uint8_t* aData,
    int32_t aDataStride) {
  RefPtr<DataSourceSurface> srcSurface =
      Factory::CreateWrappingDataSourceSurface(const_cast<uint8_t*>(aData),
                                               aDataStride, aSize, aFormat);
  RefPtr<DataSourceSurface> destSurface =
      Factory::CreateDataSourceSurface(aSize, aFormat, false);

  if (!srcSurface || !destSurface) {
    return nullptr;
  }

  if (CopyRect(srcSurface, destSurface,
               IntRect(IntPoint(), srcSurface->GetSize()), IntPoint())) {
    return destSurface.forget();
  }

  return nullptr;
}

already_AddRefed<DataSourceSurface> CreateDataSourceSurfaceWithStrideFromData(
    const IntSize& aSize, SurfaceFormat aFormat, int32_t aStride,
    const uint8_t* aData, int32_t aDataStride) {
  RefPtr<DataSourceSurface> srcSurface =
      Factory::CreateWrappingDataSourceSurface(const_cast<uint8_t*>(aData),
                                               aDataStride, aSize, aFormat);
  RefPtr<DataSourceSurface> destSurface =
      Factory::CreateDataSourceSurfaceWithStride(aSize, aFormat, aStride,
                                                 false);

  if (!srcSurface || !destSurface) {
    return nullptr;
  }

  if (CopyRect(srcSurface, destSurface,
               IntRect(IntPoint(), srcSurface->GetSize()), IntPoint())) {
    return destSurface.forget();
  }

  return nullptr;
}

uint8_t* DataAtOffset(DataSourceSurface* aSurface,
                      const DataSourceSurface::MappedSurface* aMap,
                      IntPoint aPoint) {
  if (!SurfaceContainsPoint(aSurface, aPoint)) {
    MOZ_CRASH("GFX: sample position needs to be inside surface!");
  }

  MOZ_ASSERT(Factory::CheckSurfaceSize(aSurface->GetSize()),
             "surface size overflows - this should have been prevented when "
             "the surface was created");

  uint8_t* data =
      aMap->mData + size_t(aPoint.y) * size_t(aMap->mStride) +
      size_t(aPoint.x) * size_t(BytesPerPixel(aSurface->GetFormat()));

  if (data < aMap->mData) {
    MOZ_CRASH("GFX: out-of-range data access");
  }

  return data;
}

// This check is safe against integer overflow.
bool SurfaceContainsPoint(SourceSurface* aSurface, const IntPoint& aPoint) {
  IntSize size = aSurface->GetSize();
  return aPoint.x >= 0 && aPoint.x < size.width && aPoint.y >= 0 &&
         aPoint.y < size.height;
}

void CopySurfaceDataToPackedArray(uint8_t* aSrc, uint8_t* aDst,
                                  IntSize aSrcSize, int32_t aSrcStride,
                                  int32_t aBytesPerPixel) {
  CheckedInt<size_t> packedStride(aBytesPerPixel);
  packedStride *= aSrcSize.width;
  if (!packedStride.isValid()) {
    MOZ_ASSERT(false, "Invalid stride");
    return;
  }

  CheckedInt<size_t> totalSize(aSrcStride);
  totalSize *= aSrcSize.height;
  if (!totalSize.isValid()) {
    MOZ_ASSERT(false, "Invalid surface size");
    return;
  }

  if (size_t(aSrcStride) == packedStride.value()) {
    // aSrc is already packed, so we can copy with a single memcpy.
    memcpy(aDst, aSrc, totalSize.value());
  } else {
    // memcpy one row at a time.
    for (int row = 0; row < aSrcSize.height; ++row) {
      memcpy(aDst, aSrc, packedStride.value());
      aSrc += aSrcStride;
      aDst += packedStride.value();
    }
  }
}

UniquePtr<uint8_t[]> SurfaceToPackedBGRA(DataSourceSurface* aSurface) {
  SurfaceFormat format = aSurface->GetFormat();
  if (format != SurfaceFormat::B8G8R8A8 && format != SurfaceFormat::B8G8R8X8) {
    return nullptr;
  }

  IntSize size = aSurface->GetSize();
  if (size.width < 0 || size.width >= INT32_MAX / 4) {
    return nullptr;
  }
  int32_t stride = size.width * 4;
  CheckedInt<size_t> bufferSize =
      CheckedInt<size_t>(stride) * CheckedInt<size_t>(size.height);
  if (!bufferSize.isValid()) {
    return nullptr;
  }
  UniquePtr<uint8_t[]> imageBuffer(new (std::nothrow)
                                       uint8_t[bufferSize.value()]);
  if (!imageBuffer) {
    return nullptr;
  }

  DataSourceSurface::MappedSurface map;
  if (!aSurface->Map(DataSourceSurface::MapType::READ, &map)) {
    return nullptr;
  }

  CopySurfaceDataToPackedArray(map.mData, imageBuffer.get(), size, map.mStride,
                               4);

  aSurface->Unmap();

  if (format == SurfaceFormat::B8G8R8X8) {
    // Convert BGRX to BGRA by setting a to 255.
    SwizzleData(imageBuffer.get(), stride, SurfaceFormat::X8R8G8B8_UINT32,
                imageBuffer.get(), stride, SurfaceFormat::A8R8G8B8_UINT32,
                size);
  }

  return imageBuffer;
}

uint8_t* SurfaceToPackedBGR(DataSourceSurface* aSurface) {
  SurfaceFormat format = aSurface->GetFormat();
  MOZ_ASSERT(format == SurfaceFormat::B8G8R8X8, "Format not supported");

  if (format != SurfaceFormat::B8G8R8X8) {
    // To support B8G8R8A8 we'd need to un-pre-multiply alpha
    return nullptr;
  }

  IntSize size = aSurface->GetSize();
  if (size.width < 0 || size.width >= INT32_MAX / 3) {
    return nullptr;
  }
  int32_t stride = size.width * 3;
  CheckedInt<size_t> bufferSize =
      CheckedInt<size_t>(stride) * CheckedInt<size_t>(size.height);
  if (!bufferSize.isValid()) {
    return nullptr;
  }
  uint8_t* imageBuffer = new (std::nothrow) uint8_t[bufferSize.value()];
  if (!imageBuffer) {
    return nullptr;
  }

  DataSourceSurface::MappedSurface map;
  if (!aSurface->Map(DataSourceSurface::MapType::READ, &map)) {
    delete[] imageBuffer;
    return nullptr;
  }

  SwizzleData(map.mData, map.mStride, SurfaceFormat::B8G8R8X8, imageBuffer,
              stride, SurfaceFormat::B8G8R8, size);

  aSurface->Unmap();

  return imageBuffer;
}

void ClearDataSourceSurface(DataSourceSurface* aSurface) {
  DataSourceSurface::MappedSurface map;
  if (!aSurface->Map(DataSourceSurface::MapType::WRITE, &map)) {
    MOZ_ASSERT(false, "Failed to map DataSourceSurface");
    return;
  }

  // We avoid writing into the gaps between the rows here since we can't be
  // sure that some drivers don't use those bytes.

  uint32_t width = aSurface->GetSize().width;
  uint32_t bytesPerRow = width * BytesPerPixel(aSurface->GetFormat());
  uint8_t* row = map.mData;
  // converting to size_t here because otherwise the temporaries can overflow
  // and we can end up with |end| being a bad address!
  uint8_t* end = row + size_t(map.mStride) * size_t(aSurface->GetSize().height);

  while (row != end) {
    memset(row, 0, bytesPerRow);
    row += map.mStride;
  }

  aSurface->Unmap();
}

size_t BufferSizeFromStrideAndHeight(int32_t aStride, int32_t aHeight,
                                     int32_t aExtraBytes) {
  if (MOZ_UNLIKELY(aHeight <= 0) || MOZ_UNLIKELY(aStride <= 0)) {
    return 0;
  }

  // We limit the length returned to values that can be represented by int32_t
  // because we don't want to allocate buffers any bigger than that. This
  // allows for a buffer size of over 2 GiB which is already rediculously
  // large and will make the process janky. (Note the choice of the signed type
  // is deliberate because we specifically don't want the returned value to
  // overflow if someone stores the buffer length in an int32_t variable.)

  CheckedInt32 requiredBytes =
      CheckedInt32(aStride) * CheckedInt32(aHeight) + CheckedInt32(aExtraBytes);
  if (MOZ_UNLIKELY(!requiredBytes.isValid())) {
    gfxWarning() << "Buffer size too big; returning zero " << aStride << ", "
                 << aHeight << ", " << aExtraBytes;
    return 0;
  }
  return requiredBytes.value();
}

size_t BufferSizeFromDimensions(int32_t aWidth, int32_t aHeight, int32_t aDepth,
                                int32_t aExtraBytes) {
  if (MOZ_UNLIKELY(aHeight <= 0) || MOZ_UNLIKELY(aWidth <= 0) ||
      MOZ_UNLIKELY(aDepth <= 0)) {
    return 0;
  }

  // Similar to BufferSizeFromStrideAndHeight, but with an extra parameter.

  CheckedInt32 requiredBytes =
      CheckedInt32(aWidth) * CheckedInt32(aHeight) * CheckedInt32(aDepth) +
      CheckedInt32(aExtraBytes);
  if (MOZ_UNLIKELY(!requiredBytes.isValid())) {
    gfxWarning() << "Buffer size too big; returning zero " << aWidth << ", "
                 << aHeight << ", " << aDepth << ", " << aExtraBytes;
    return 0;
  }
  return requiredBytes.value();
}

/**
 * aSrcRect: Rect relative to the aSrc surface
 * aDestPoint: Point inside aDest surface
 *
 * aSrcRect and aDestPoint are in internal local coordinates.
 * i.e. locations of pixels and not in the same coordinate space
 * as aSrc->GetRect()
 */
bool CopyRect(DataSourceSurface* aSrc, DataSourceSurface* aDest,
              IntRect aSrcRect, IntPoint aDestPoint) {
  if (aSrcRect.Overflows() ||
      IntRect(aDestPoint, aSrcRect.Size()).Overflows()) {
    MOZ_CRASH("GFX: we should never be getting invalid rects at this point");
  }

  MOZ_RELEASE_ASSERT(aSrc->GetFormat() == aDest->GetFormat(),
                     "GFX: different surface formats");
  MOZ_RELEASE_ASSERT(IntRect(IntPoint(), aSrc->GetSize()).Contains(aSrcRect),
                     "GFX: source rect too big for source surface");
  MOZ_RELEASE_ASSERT(IntRect(IntPoint(), aDest->GetSize())
                         .Contains(IntRect(aDestPoint, aSrcRect.Size())),
                     "GFX: dest surface too small");

  if (aSrcRect.IsEmpty()) {
    return false;
  }

  DataSourceSurface::ScopedMap srcMap(aSrc, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap destMap(aDest, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!srcMap.IsMapped() || !destMap.IsMapped())) {
    return false;
  }

  uint8_t* sourceData =
      DataAtOffset(aSrc, srcMap.GetMappedSurface(), aSrcRect.TopLeft());
  uint8_t* destData =
      DataAtOffset(aDest, destMap.GetMappedSurface(), aDestPoint);

  SwizzleData(sourceData, srcMap.GetStride(), aSrc->GetFormat(), destData,
              destMap.GetStride(), aDest->GetFormat(), aSrcRect.Size());

  return true;
}

already_AddRefed<DataSourceSurface> CreateDataSourceSurfaceByCloning(
    DataSourceSurface* aSource) {
  RefPtr<DataSourceSurface> copy = Factory::CreateDataSourceSurface(
      aSource->GetSize(), aSource->GetFormat(), true);
  if (copy) {
    CopyRect(aSource, copy, IntRect(IntPoint(), aSource->GetSize()),
             IntPoint());
  }
  return copy.forget();
}

}  // namespace gfx
}  // namespace mozilla