Vuo  2.0.2
VuoImage.c
Go to the documentation of this file.
1 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "type.h"
14 #include "node.h"
15 #include "VuoImage.h"
16 #include "VuoImageRenderer.h"
17 #include "VuoGlContext.h"
18 #include "VuoGlPool.h"
19 
20 #include <CoreFoundation/CoreFoundation.h>
21 
22 #include <IOSurface/IOSurfaceAPI.h>
23 
24 #include <OpenGL/OpenGL.h>
25 #include <OpenGL/CGLMacro.h>
27 void glBindVertexArray(GLuint array);
28 void glDeleteVertexArrays(GLsizei n, const GLuint *arrays);
29 void glGenVertexArrays(GLsizei n, GLuint *arrays);
31 
32 
34 #ifdef VUO_COMPILER
36  "title" : "Image",
37  "description" : "An image residing in GPU memory (GL Texture Object).",
38  "keywords" : [ ],
39  "version" : "1.0.0",
40  "dependencies" : [
41  "VuoBoolean",
42  "VuoColor",
43  "VuoImageColorDepth",
44  "VuoImageWrapMode",
45  "VuoPoint2d",
46  "VuoGlContext",
47  "VuoGlPool",
48  "VuoImageRenderer",
49  "VuoImageBlur",
50  "VuoImageMapColors",
51  "CoreFoundation.framework",
52  "IOSurface.framework"
53  ]
54  });
55 #endif
56 
58 
66 void VuoImage_free(void *texture)
67 {
68  VuoImage t = (VuoImage)texture;
69 // VLog("Freeing image %p %s",t,VuoImage_getSummary(t));
70 
71  // Detach the CPU memory from the GL texture before recycling.
72  if (t->cpuQueueInitialized && json_object_object_length(t->cpuData))
73  {
74  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
75  glBindTexture(t->glTextureTarget, t->glTextureName);
76  GLenum format = GL_BGRA;
77  if (t->glInternalFormat == GL_DEPTH_COMPONENT)
78  format = GL_DEPTH_COMPONENT;
79  GLenum type = VuoGlTexture_getType(format);
80 // VLog("glTexImage2D(%s, 0, %s, %ld, %ld, 0, %s, %s, NULL);", VuoGl_stringForConstant(t->glTextureTarget), VuoGl_stringForConstant(t->glInternalFormat), t->pixelsWide, t->pixelsHigh, VuoGl_stringForConstant(format), VuoGl_stringForConstant(type));
81  glTexImage2D(t->glTextureTarget, 0, t->glInternalFormat, t->pixelsWide, t->pixelsHigh, 0, format, type, NULL);
82  glBindTexture(t->glTextureTarget, 0);
83  });
84  }
85 
86  VuoGlTexture_release(VuoGlTexturePool_Allocate, t->glTextureTarget, t->glInternalFormat, t->pixelsWide, t->pixelsHigh, t->glTextureName);
87 
88  if (t->cpuQueueInitialized)
89  {
90  dispatch_release(t->cpuQueue);
91 
92  json_object_object_foreach(t->cpuData, key, value)
93  {
94 // VLog("%p: freeing %s",t,key);
95  json_object *o;
96  json_object_object_get_ex(value, "buffer", &o);
97  void *buffer = (void *)json_object_get_int64(o);
98 
99  json_object_object_get_ex(value, "freeCallback", &o);
100  void (^freeCallback)(void *) = (void (^)(void *))json_object_get_int64(o);
101 
102  freeCallback(buffer);
103 
104  Block_release(freeCallback);
105  }
106 
107  json_object_put(t->cpuData);
108  }
109 
110  free(t);
111 }
112 
116 static VuoImage VuoImage_make_internal(unsigned int glTextureName, unsigned int glInternalFormat, unsigned long int pixelsWide, unsigned long int pixelsHigh, VuoImage_freeCallback freeCallback, void *freeCallbackContext)
117 {
118  VuoImage t = (VuoImage)malloc(sizeof(struct _VuoImage));
120 
121  t->glTextureName = glTextureName;
122  t->glTextureTarget = GL_TEXTURE_2D;
123  t->glInternalFormat = glInternalFormat;
124  t->pixelsWide = pixelsWide;
125  t->pixelsHigh = pixelsHigh;
126  t->scaleFactor = 1;
127 
128  t->freeCallbackContext = freeCallbackContext;
129 
130  VuoGlTexture_retain(glTextureName, freeCallback, freeCallbackContext);
131 
132  t->cpuQueueInitialized = 0;
133 
134 // VLog("Made image %p %s",t,VuoImage_getSummary(t));
135  return t;
136 }
137 
156 VuoImage VuoImage_make(unsigned int glTextureName, unsigned int glInternalFormat, unsigned long int pixelsWide, unsigned long int pixelsHigh)
157 {
158  if (!glTextureName || !pixelsWide || !pixelsHigh)
159  return NULL;
160 
161  VuoImage t = VuoImage_make_internal(glTextureName, glInternalFormat, pixelsWide, pixelsHigh, NULL, NULL);
162  return t;
163 }
164 
187 VuoImage VuoImage_makeClientOwned(unsigned int glTextureName, unsigned int glInternalFormat, unsigned long int pixelsWide, unsigned long int pixelsHigh, VuoImage_freeCallback freeCallback, void *freeCallbackContext)
188 {
189  if (!freeCallback)
190  {
191  VUserLog("Error: freeCallback may not be NULL.");
192  return NULL;
193  }
194 
195  if (!glTextureName || !pixelsWide || !pixelsHigh)
196  return NULL;
197 
198  return VuoImage_make_internal(glTextureName, glInternalFormat, pixelsWide, pixelsHigh, freeCallback, freeCallbackContext);
199 }
200 
225 VuoImage VuoImage_makeClientOwnedGlTextureRectangle(unsigned int glTextureName, unsigned int glInternalFormat, unsigned long int pixelsWide, unsigned long int pixelsHigh, VuoImage_freeCallback freeCallback, void *freeCallbackContext)
226 {
227  VuoImage t = VuoImage_makeClientOwned(glTextureName, glInternalFormat, pixelsWide, pixelsHigh, freeCallback, freeCallbackContext);
228  if (!t)
229  return NULL;
230 
231  t->glTextureTarget = GL_TEXTURE_RECTANGLE_ARB;
232 
233  return t;
234 }
235 
259 VuoImage VuoImage_makeFromBuffer(const void *pixels, unsigned int format, unsigned int pixelsWide, unsigned int pixelsHigh, VuoImageColorDepth colorDepth, void (^freeCallback)(void *pixels))
260 {
261  return VuoImage_makeFromBufferWithStride(pixels, format, pixelsWide, pixelsHigh, 0, colorDepth, freeCallback);
262 }
263 
267 VuoImage VuoImage_makeFromBufferWithStride(const void *pixels, unsigned int format, unsigned int pixelsWide, unsigned int pixelsHigh, unsigned int bytesPerRow, VuoImageColorDepth colorDepth, void (^freeCallback)(void *pixels))
268 {
269  if (!pixels || !pixelsWide || !pixelsHigh)
270  return NULL;
271 
272  if (!freeCallback)
273  {
274  static bool freeCallbackWarningEmitted = false;
275  if (!freeCallbackWarningEmitted)
276  {
277  freeCallbackWarningEmitted = true;
278  VUserLog("VuoImage_makeFromBuffer() and VuoImage_makeFromBufferWithStride() now take ownership of `pixels`, and therefore `freeCallback` is required. Since there's no `freeCallback`, I'm giving up and outputting an empty image. Please update the plugin listed in the backtrace below.");
280  }
281  return NULL;
282  }
283 
284  __block GLenum internalformat;
285  __block GLuint glTextureName;
286  __block int alignment = 1;
287  __block bool customRowLength = false;
288  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
289 
290  internalformat = VuoImageColorDepth_getGlInternalFormat(format, colorDepth);
291 // VLog("Using format=%s -> internalformat=%s", VuoGl_stringForConstant(format), VuoGl_stringForConstant(internalformat));
292  glTextureName = VuoGlTexturePool_use(cgl_ctx, VuoGlTexturePool_Allocate, GL_TEXTURE_2D, internalformat, pixelsWide, pixelsHigh, format, NULL);
293  if (!glTextureName)
294  return;
295 
296  int bytesPerPixel = VuoGlTexture_getChannelCount(format);
297  GLuint glType;
298  if (colorDepth == VuoImageColorDepth_8)
299  glType = VuoGlTexture_getType(format);
300  else if (colorDepth == VuoImageColorDepth_16)
301  {
302  glType = GL_HALF_FLOAT_ARB;
303  bytesPerPixel *= 2;
304  }
305  else // if (colorDepth == VuoImageColorDepth_32)
306  {
307  glType = GL_FLOAT;
308  bytesPerPixel *= 4;
309  }
310 
311  if (!bytesPerRow
312  || bytesPerRow == bytesPerPixel * pixelsWide)
313  // Tightly-packed.
314  alignment = 1;
315  else
316  {
317  if (bytesPerRow % 4 == 0)
318  alignment = 4;
319  else if (bytesPerRow % 8 == 0)
320  alignment = 8;
321  else if (bytesPerRow % 2 == 0)
322  alignment = 2;
323  else if (bytesPerRow % bytesPerPixel == 0)
324  {
325  GLuint rowPixels = bytesPerRow / bytesPerPixel;
326  glPixelStorei(GL_UNPACK_ROW_LENGTH, rowPixels);
327  customRowLength = true;
328  }
329  else
330  {
331  VUserLog("Not sure how to handle this stride:");
332  VUserLog(" %dx%d",pixelsWide,pixelsHigh);
333  VUserLog(" bytesPerRow = %d",bytesPerRow);
334  VUserLog(" bytesPerPixel = %d",bytesPerPixel);
335  GLint leftoverBytes = bytesPerRow - bytesPerPixel*pixelsWide;
336  VUserLog(" leftoverBytes = %d",leftoverBytes);
337  return;
338  }
339  }
340  if (alignment != 4)
341  glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
342 
343  glBindTexture(GL_TEXTURE_2D, glTextureName);
344  glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
345 // VLog("glTexImage2D(GL_TEXTURE_2D, 0, %s, %d, %d, 0, %s, %s, %p);", VuoGl_stringForConstant(internalformat), pixelsWide, pixelsHigh, VuoGl_stringForConstant(format), VuoGl_stringForConstant(glType), pixels);
346  glTexImage2D(GL_TEXTURE_2D, 0, internalformat, pixelsWide, pixelsHigh, 0, format, glType, (GLvoid *)pixels);
347  glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
348  glBindTexture(GL_TEXTURE_2D, 0);
349 
350  if (alignment != 4)
351  glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
352  if (customRowLength)
353  glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
354 
355  // Since returning from this function implies that the texture is ready to use,
356  // flush before returning, to ensure that the enqueued commands to create the texture actually get executed
357  // before it gets used on a different context.
358  glFlushRenderAPPLE();
359 // glFinish();
360 
361  });
362  if (!glTextureName)
363  return NULL;
364 
365  VuoImage image = VuoImage_make(glTextureName, internalformat, pixelsWide, pixelsHigh);
366 
367  dispatch_once(&image->cpuQueueInitialized, ^{});
368  image->cpuQueue = dispatch_queue_create("org.vuo.image.cpu", NULL);
369  image->cpuData = json_object_new_object();
370  char *key = VuoGl_stringForConstant(format);
371  if (alignment != 1)
372  {
373  char *keyWithAlignment;
374  asprintf(&keyWithAlignment, "%s alignment=%d", key, alignment);
375  free(key);
376  key = keyWithAlignment;
377  }
378  if (customRowLength)
379  {
380  char *keyWithRowLength;
381  asprintf(&keyWithRowLength, "%s rowLength=%d", key, bytesPerRow);
382  free(key);
383  key = keyWithRowLength;
384  }
385  json_object *cpuEntry = json_object_new_object();
386  json_object_object_add(cpuEntry, "buffer", json_object_new_int64((long long)pixels));
387  json_object_object_add(cpuEntry, "freeCallback", json_object_new_int64((long long)Block_copy(freeCallback)));
388  json_object_object_add(image->cpuData, key, cpuEntry);
389 // VLog("%p: populated %s",image,key);
390  free(key);
391 
392  return image;
393 }
394 
419 const unsigned char *VuoImage_getBuffer(VuoImage image, unsigned int requestedFormat)
420 {
421  if (!image)
422  return NULL;
423 
424  if (image->glInternalFormat == GL_DEPTH_COMPONENT && requestedFormat != GL_DEPTH_COMPONENT16)
425  {
426  VUserLog("Error: Image has format GL_DEPTH_COMPONENT, which must be fetched as GL_DEPTH_COMPONENT16.");
427  return NULL;
428  }
429 
430  dispatch_once(&image->cpuQueueInitialized, ^{
431  image->cpuQueue = dispatch_queue_create("org.vuo.image.cpu", NULL);
432  image->cpuData = json_object_new_object();
433  });
434 
435  __block unsigned char *pixels = NULL;
436  dispatch_sync(image->cpuQueue, ^{
437  char *key = VuoGl_stringForConstant(requestedFormat);
438  struct json_object *value;
439  if (json_object_object_get_ex(image->cpuData, key, &value))
440  {
441  json_object *o;
442  json_object_object_get_ex(value, "buffer", &o);
443  pixels = (unsigned char *)json_object_get_int64(o);
444  }
445  else
446  {
447  unsigned int channels;
448  if (requestedFormat == GL_LUMINANCE
449  || requestedFormat == GL_R16
450  || requestedFormat == GL_DEPTH_COMPONENT16)
451  channels = 1;
452  else if (requestedFormat == GL_LUMINANCE_ALPHA)
453  channels = 2;
454  else if (requestedFormat == GL_RGB
455  || requestedFormat == GL_BGR)
456  channels = 3;
457  else if (requestedFormat == GL_RGBA
458  || requestedFormat == GL_BGRA
459  || requestedFormat == GL_RGBA16I_EXT
460  || requestedFormat == GL_RGBA16F_ARB
461  || requestedFormat == GL_RGBA32F_ARB)
462  channels = 4;
463  else
464  {
465  VUserLog("Error: Unknown format %s.", VuoGl_stringForConstant(requestedFormat));
466  return;
467  }
468 
469  unsigned int bytesPerChannel = 1;
470  GLuint type = GL_UNSIGNED_BYTE;
471  if (requestedFormat == GL_RGBA16I_EXT
472  || requestedFormat == GL_R16
473  || requestedFormat == GL_DEPTH_COMPONENT16)
474  {
475  bytesPerChannel = 2;
476  type = GL_UNSIGNED_SHORT;
477  }
478  else if (requestedFormat == GL_RGBA16F_ARB)
479  {
480  bytesPerChannel = 2;
481  type = GL_HALF_FLOAT_ARB;
482  }
483  else if (requestedFormat == GL_RGBA32F_ARB)
484  {
485  bytesPerChannel = 4;
486  type = GL_FLOAT;
487  }
488 
489  GLuint actualFormat = requestedFormat;
490  if (requestedFormat == GL_RGBA16I_EXT
491  || requestedFormat == GL_RGBA16F_ARB
492  || requestedFormat == GL_RGBA32F_ARB)
493  actualFormat = GL_BGRA;
494  else if (requestedFormat == GL_DEPTH_COMPONENT16)
495  actualFormat = GL_DEPTH_COMPONENT;
496  else if (requestedFormat == GL_R16)
497  actualFormat = GL_RED;
498 
499  size_t pixelBufferSize = image->pixelsWide * image->pixelsHigh * channels * bytesPerChannel;
500  pixels = (unsigned char *)malloc(pixelBufferSize);
501 
502  // In the seal, use zeroes for the alpha channel,
503  // to lessen the chance that we collide with valid image data.
504  const char *tamperEvidentSeal = "Vuo\0Ima\0ge_\0get\0Buf\0fer\0()\0";
505  int tamperEvidentSealLength = strlen(tamperEvidentSeal);
506  if (pixelBufferSize > tamperEvidentSealLength)
507  strlcpy((char *)pixels, tamperEvidentSeal, pixelBufferSize);
508 
509  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
510 
511  // If each row is quad-aligned, OpenGL doesn't add any padding (good).
512  bool openGLAddsPadding = ((image->pixelsWide * channels * bytesPerChannel) % 4 != 0);
513  if (openGLAddsPadding)
514  // Remove the padding, since VuoImage_getBuffer promises tightly-packed buffers.
515  glPixelStorei(GL_PACK_ALIGNMENT, 1);
516 
517  glBindTexture(image->glTextureTarget, image->glTextureName);
518 // VLog("glGetTexImage(%s, 0, %s, %s, …); on texture internalformat %s", VuoGl_stringForConstant(image->glTextureTarget), VuoGl_stringForConstant(actualFormat), VuoGl_stringForConstant(type), VuoGl_stringForConstant(image->glInternalFormat));
519  glGetTexImage(image->glTextureTarget, 0, actualFormat, type, (GLvoid *)pixels);
520  glBindTexture(image->glTextureTarget, 0);
521 
522  if (openGLAddsPadding)
523  // Restore the default.
524  glPixelStorei(GL_PACK_ALIGNMENT, 4);
525 
526  if (pixelBufferSize > tamperEvidentSealLength && strncmp((char *)pixels, tamperEvidentSeal, strlen(tamperEvidentSeal)) == 0)
527  {
528  GLenum error = glGetError();
529  if (error == GL_NO_ERROR)
530  // But as of macOS 10.14.4, calling glGetTexImage on an IOSurface
531  // now fills the buffer with garbage (instead of leaving the buffer unmodified),
532  // and still doesn't return an error, so we no longer have a way to detect this situation.
533  VUserLog("Warning: glGetTexImage() says it was successful, but it didn't actually copy any data. This might happen if the input texture has an IOSurface bound to it.");
534  else
535  VUserLog("OpenGL Error: %d", error);
536  free(pixels);
537  pixels = NULL;
538  return;
539  }
540 
541  });
542  if (!pixels)
543  return;
544 
545  json_object *cpuEntry = json_object_new_object();
546  json_object_object_add(cpuEntry, "buffer", json_object_new_int64((long long)pixels));
547  json_object_object_add(cpuEntry, "freeCallback", json_object_new_int64((long long)Block_copy( ^(void *buffer){ free(buffer); } )));
548  json_object_object_add(image->cpuData, key, cpuEntry);
549 // VLog("%p: populated %s",image,key);
550  }
551  free(key);
552  });
553 
554  return pixels;
555 }
556 
561 {
562  __block GLint wrapModeGL;
563  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
564 
565  glBindTexture(image->glTextureTarget, image->glTextureName);
566 
567  glGetTexParameteriv(image->glTextureTarget, GL_TEXTURE_WRAP_S, &wrapModeGL);
568  // Ignore GL_TEXTURE_WRAP_T since Vuo assumes it's the same as _S.
569 
570  glBindTexture(image->glTextureTarget, 0);
571 
572  });
573 
574  if (wrapModeGL == GL_CLAMP_TO_EDGE)
575  return VuoImageWrapMode_ClampEdge;
576  else if (wrapModeGL == GL_REPEAT)
577  return VuoImageWrapMode_Repeat;
578  else if (wrapModeGL == GL_MIRRORED_REPEAT)
579  return VuoImageWrapMode_MirroredRepeat;
580 
581  return VuoImageWrapMode_None;
582 }
583 
588 {
589  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
590 
591  glBindTexture(image->glTextureTarget, image->glTextureName);
592 
593  GLint wrapModeGL = GL_CLAMP_TO_BORDER;
594  if (wrapMode == VuoImageWrapMode_ClampEdge)
595  wrapModeGL = GL_CLAMP_TO_EDGE;
596  else if (wrapMode == VuoImageWrapMode_Repeat)
597  wrapModeGL = GL_REPEAT;
598  else if (wrapMode == VuoImageWrapMode_MirroredRepeat)
599  wrapModeGL = GL_MIRRORED_REPEAT;
600 
601  glTexParameteri(image->glTextureTarget, GL_TEXTURE_WRAP_S, wrapModeGL);
602  glTexParameteri(image->glTextureTarget, GL_TEXTURE_WRAP_T, wrapModeGL);
603 
604  glBindTexture(image->glTextureTarget, 0);
605 
606  // Ensure the command queue gets executed before we return,
607  // since the VuoShader might immediately be used on another context.
608  glFlushRenderAPPLE();
609 
610  });
611 }
612 
616 VuoImage VuoImage_makeColorImage(VuoColor color, unsigned int pixelsWide, unsigned int pixelsHigh)
617 {
618  if (!pixelsWide || !pixelsHigh)
619  return NULL;
620 
622  VuoRetain(shader);
623  VuoImage image = VuoImageRenderer_render(shader, pixelsWide, pixelsHigh, VuoImageColorDepth_8);
624  VuoRelease(shader);
625  return image;
626 }
627 
639 VuoImage VuoImage_makeCopy(VuoImage image, bool flip, unsigned int forcePixelsWide, unsigned int forcePixelsHigh, bool forceAlpha)
640 {
641  VuoShader shader = NULL;
642  if (image->glTextureTarget == GL_TEXTURE_2D)
643  shader = VuoShader_makeUnlitAlphaPassthruImageShader(image, flip);
644  else if (image->glTextureTarget == GL_TEXTURE_RECTANGLE_ARB)
646  else
647  {
648  VUserLog("Error: Unknown glTextureTarget %s", VuoGl_stringForConstant(image->glTextureTarget));
649  return NULL;
650  }
651  VuoRetain(shader);
652 
653  if (forceAlpha)
654  shader->isTransparent = true;
655 
656  VuoImage img = VuoImageRenderer_render(shader,
657  forcePixelsWide ? forcePixelsWide : image->pixelsWide,
658  forcePixelsHigh ? forcePixelsHigh : image->pixelsHigh,
659  VuoImage_getColorDepth(image));
660 
661  VuoRelease(shader);
662 
663  return img;
664 }
665 
672 {
673  VuoShader frag = VuoShader_makeUnlitImageShader(image, 1);
674  VuoRetain(frag);
675 
676  GLuint textureName = VuoImageRenderer_draw_internal(frag, image->pixelsWide, image->pixelsHigh, VuoImage_getColorDepth(image), false, true, 0, NULL);
677 
678  VuoImage img = VuoImage_make_internal(textureName, image->glInternalFormat, image->pixelsWide, image->pixelsHigh, NULL, NULL);
679  img->glTextureTarget = GL_TEXTURE_RECTANGLE_ARB;
680 
681  VuoRelease(frag);
682 
683  return img;
684 }
685 
689 bool VuoImage_areEqualWithinTolerance(const VuoImage a, const VuoImage b, const unsigned char tolerance)
690 {
691  if (!a && !b)
692  return true;
693  if (!a || !b)
694  return false;
695 
696  if (a->pixelsWide != b->pixelsWide
697  || a->pixelsHigh != b->pixelsHigh)
698  return false;
699 
700  if (a->glTextureName == b->glTextureName)
701  return true;
702 
703  const unsigned char *aPixels = VuoImage_getBuffer(a, GL_BGRA);
704  const unsigned char *bPixels = VuoImage_getBuffer(b, GL_BGRA);
705 
706  unsigned char aChannels = VuoGlTexture_getChannelCount(a->glInternalFormat);
707  unsigned char bChannels = VuoGlTexture_getChannelCount(b->glInternalFormat);
708  if (aChannels == 4 && bChannels == 1)
709  {
710  // Treat 1-channel red images as equal to opaque greyscale BGRA images.
711  for (unsigned int i = 0; i < a->pixelsWide * a->pixelsHigh; ++i)
712  if (abs(aPixels[i*4+0] - bPixels[i*4+2]) > tolerance
713  || abs(aPixels[i*4+1] - bPixels[i*4+2]) > tolerance
714  || abs(aPixels[i*4+2] - bPixels[i*4+2]) > tolerance
715  || abs(aPixels[i*4+3] - bPixels[i*4+3]) > tolerance)
716  {
717  VDebugLog("Difference found at pixel coordinate (%ld,%ld): RGBA %d,%d,%d,%d vs %d,%d,%d,%d",
718  i%a->pixelsWide, i/a->pixelsWide,
719  aPixels[i*4+2],aPixels[i*4+1],aPixels[i*4+0],aPixels[i*4+3],
720  bPixels[i*4+2],bPixels[i*4+2],bPixels[i*4+2],bPixels[i*4+3]);
721  return false;
722  }
723  return true;
724  }
725  else if (aChannels == 1 && bChannels == 4)
726  {
727  // Treat 1-channel red images as equal to opaque greyscale BGRA images.
728  for (unsigned int i = 0; i < a->pixelsWide * a->pixelsHigh; ++i)
729  if (abs(aPixels[i*4+2] - bPixels[i*4+0]) > tolerance
730  || abs(aPixels[i*4+2] - bPixels[i*4+1]) > tolerance
731  || abs(aPixels[i*4+2] - bPixels[i*4+2]) > tolerance
732  || abs(aPixels[i*4+3] - bPixels[i*4+3]) > tolerance)
733  {
734  VDebugLog("Difference found at pixel coordinate (%ld,%ld): RGBA %d,%d,%d,%d vs %d,%d,%d,%d",
735  i%a->pixelsWide, i/a->pixelsWide,
736  aPixels[i*4+2],aPixels[i*4+2],aPixels[i*4+2],aPixels[i*4+3],
737  bPixels[i*4+2],bPixels[i*4+1],bPixels[i*4+0],bPixels[i*4+3]);
738  return false;
739  }
740  return true;
741  }
742 
743  for (unsigned int i = 0; i < a->pixelsWide * a->pixelsHigh * 4; ++i)
744  if (abs(aPixels[i] - bPixels[i]) > tolerance)
745  {
746  unsigned int p = (i/4)*4; // Round down to the start of this 32bit pixel.
747  VDebugLog("Difference found at pixel coordinate (%ld,%ld): abs(%d - %d) > %d (RGBA %d,%d,%d,%d vs %d,%d,%d,%d)",
748  i%a->pixelsWide, i/a->pixelsWide,
749  aPixels[i], bPixels[i], tolerance,
750  aPixels[p+2],aPixels[p+1],aPixels[p+0],aPixels[p+3],
751  bPixels[p+2],bPixels[p+1],bPixels[p+0],bPixels[p+3]);
752  return false;
753  }
754 
755  return true;
756 }
757 
769 bool VuoImage_areEqual(const VuoImage a, const VuoImage b)
770 {
771  return VuoImage_areEqualWithinTolerance(a,b,0);
772 }
773 
779 bool VuoImage_isLessThan(const VuoImage a, const VuoImage b)
780 {
781  // Treat null images as greater than non-null images,
782  // so the more useful non-null images sort to the beginning of the list.
783  if (!a || !b)
784  return a && !b;
785 
786  if (a->pixelsWide < b->pixelsWide) return true;
787  if (b->pixelsWide < a->pixelsWide) return false;
788 
789  if (a->pixelsHigh < b->pixelsHigh) return true;
790  /*if (b->pixelsHigh < a->pixelsHigh)*/ return false;
791 }
792 
798 bool VuoImage_isEmpty(const VuoImage image)
799 {
800  if (!image || image->pixelsWide == 0 || image->pixelsHigh == 0)
801  return true;
802 
803  const unsigned char *pixels = VuoImage_getBuffer(image, GL_BGRA);
804  bool foundSubstantialPixel = false;
805  for (unsigned int p = 3; p < image->pixelsWide * image->pixelsHigh * 4; p += 4)
806  if (pixels[p])
807  {
808  foundSubstantialPixel = true;
809  break;
810  }
811  return !foundSubstantialPixel;
812 }
813 
820 {
821  return (image && image->pixelsWide && image->pixelsHigh);
822 }
823 
828 {
829  return VuoRectangle_make(0, 0, 2, 2. * image->pixelsHigh / image->pixelsWide);
830 }
831 
836 {
837  if (!image)
838  return VuoImageColorDepth_8;
839 
840  if (image->glInternalFormat == GL_LUMINANCE8
841  || image->glInternalFormat == GL_LUMINANCE8_ALPHA8
842  || image->glInternalFormat == GL_RGB
843  || image->glInternalFormat == GL_RGBA
844  || image->glInternalFormat == GL_RGBA8
845  || image->glInternalFormat == GL_BGRA
846  || image->glInternalFormat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT
847  || image->glInternalFormat == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
848  return VuoImageColorDepth_8;
849  else if (image->glInternalFormat == GL_LUMINANCE16F_ARB
850  || image->glInternalFormat == GL_LUMINANCE_ALPHA16F_ARB
851  || image->glInternalFormat == GL_DEPTH_COMPONENT
852  || image->glInternalFormat == GL_RGB16
853  || image->glInternalFormat == GL_RGBA16
854  || image->glInternalFormat == GL_RGB16F_ARB
855  || image->glInternalFormat == GL_RGBA16F_ARB)
856  return VuoImageColorDepth_16;
857  else if (image->glInternalFormat == GL_LUMINANCE32F_ARB
858  || image->glInternalFormat == GL_LUMINANCE_ALPHA32F_ARB
859  || image->glInternalFormat == GL_RGB32F_ARB
860  || image->glInternalFormat == GL_RGBA32F_ARB)
861  return VuoImageColorDepth_32;
862 
863  char *formatString = VuoGl_stringForConstant(image->glInternalFormat);
864  VUserLog("Error: Unknown glInternalFormat %x (%s)", image->glInternalFormat, formatString);
865  free(formatString);
866  return VuoImageColorDepth_8;
867 }
868 
907 {
908  return VuoImage_makeFromJsonWithDimensions(js, 0, 0);
909 }
910 
915 {
916  VuoGlTexturePool_disuse(VuoGlTexturePool_AllocateIOSurface, i->glTextureTarget, i->glInternalFormat, i->pixelsWide, i->pixelsHigh, i->glTextureName);
917 }
918 
930 VuoImage VuoImage_makeFromJsonWithDimensions(struct json_object *js, unsigned int requestedPixelsWide, unsigned int requestedPixelsHigh)
931 {
932  if (!js)
933  return NULL;
934 
935  {
936  json_object * o;
937  if (json_object_object_get_ex(js, "pointer", &o))
938  {
939  VuoImage im = (VuoImage)json_object_get_int64(o);
940  if ((requestedPixelsWide == 0 && requestedPixelsHigh == 0)
941  || (im->pixelsWide == requestedPixelsWide && im->pixelsHigh == requestedPixelsHigh))
942  return im;
943  else
944  {
945  VuoImage outputImage = VuoImage_make(im->glTextureName, im->glInternalFormat, requestedPixelsWide, requestedPixelsHigh);
946  outputImage->glTextureTarget = im->glTextureTarget;
947  outputImage->scaleFactor = im->scaleFactor;
948  return outputImage;
949  }
950  }
951  }
952 
953  __block unsigned int glInternalFormat = 0;
954  unsigned long int pixelsWide;
955  unsigned long int pixelsHigh;
956  float scaleFactor = 1;
957 
958  {
959  json_object * o;
960  if (json_object_object_get_ex(js, "pixelsWide", &o))
961  pixelsWide = json_object_get_int64(o);
962  else
963  return NULL;
964  }
965  {
966  json_object * o;
967  if (json_object_object_get_ex(js, "pixelsHigh", &o))
968  pixelsHigh = json_object_get_int64(o);
969  else
970  return NULL;
971  }
972  if (pixelsWide == 0 || pixelsHigh == 0)
973  return NULL;
974 
975  {
976  json_object * o;
977  if (json_object_object_get_ex(js, "scaleFactor", &o))
978  scaleFactor = json_object_get_double(o);
979  }
980 
981  {
982  json_object * o;
983  if (json_object_object_get_ex(js, "color", &o))
984  return VuoImage_makeColorImage(VuoColor_makeFromJson(o), pixelsWide, pixelsHigh);
985  }
986 
987  {
988  json_object * o;
989  if (json_object_object_get_ex(js, "ioSurface", &o))
990  {
991  IOSurfaceID surfID = json_object_get_int(o);
992 // VLog("Converting IOSurfaceID %d",surfID);
993 
994  // Read the IOSurface into a GL_TEXTURE_RECTANGLE_ARB (the only texture type IOSurface supports).
995  __block IOSurfaceRef surf = NULL;
996  __block GLuint textureRect;
997  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
998  glInternalFormat = GL_RGBA;
999  surf = IOSurfaceLookup(surfID);
1000  if (!surf)
1001  {
1002  VUserLog("Error: IOSurfaceLookup(%d) failed.", surfID);
1003  return;
1004  }
1005  textureRect = VuoGlTexturePool_use(cgl_ctx, VuoGlTexturePool_AllocateIOSurface, GL_TEXTURE_RECTANGLE_ARB, glInternalFormat, pixelsWide, pixelsHigh, GL_BGRA, surf);
1006  glFlushRenderAPPLE();
1007  });
1008  if (!surf)
1009  return NULL;
1010 
1011  // Convert the GL_TEXTURE_RECTANGLE_ARB into GL_TEXTURE_2D.
1012  VuoImage image2d;
1013  {
1014  VuoImage imageRect = VuoImage_makeClientOwnedGlTextureRectangle(textureRect, glInternalFormat, pixelsWide, pixelsHigh, VuoImage_IOSurfaceTextureFree, NULL);
1015 
1016  imageRect->glTextureTarget = GL_TEXTURE_RECTANGLE_ARB;
1017  VuoLocal(imageRect);
1018 
1019  VuoShader shader = VuoShader_makeGlTextureRectangleShader(imageRect, 1);
1020  VuoLocal(shader);
1021 
1022  image2d = VuoImageRenderer_render(shader,
1023  requestedPixelsWide ? requestedPixelsWide : pixelsWide,
1024  requestedPixelsHigh ? requestedPixelsHigh : pixelsHigh,
1025  VuoImage_getColorDepth(imageRect));
1026  }
1027 
1029  CFRelease(surf);
1030 
1031  image2d->scaleFactor = scaleFactor;
1032 
1033  return image2d;
1034  }
1035  }
1036 
1037  return NULL;
1038 }
1039 
1060 GLuint VuoImage_resolveInterprocessJsonUsingTextureProvider(struct json_object *js, GLuint (^provider)(unsigned int pixelsWide, unsigned int pixelsHigh), unsigned int *outputPixelsWide, unsigned int *outputPixelsHigh, void *outputIOSurface)
1061 {
1062  json_object *o;
1063 
1064  if (!json_object_object_get_ex(js, "pixelsWide", &o))
1065  return 0;
1066  *outputPixelsWide = json_object_get_int64(o);
1067 
1068  if (!json_object_object_get_ex(js, "pixelsHigh", &o))
1069  return 0;
1070  *outputPixelsHigh = json_object_get_int64(o);
1071 
1072  if (!json_object_object_get_ex(js, "ioSurface", &o))
1073  return 0;
1074  IOSurfaceID surfID = json_object_get_int(o);
1075 
1076  GLuint textureRect = provider(*outputPixelsWide, *outputPixelsHigh);
1077  if (!textureRect)
1078  return 0;
1079 
1080  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
1081  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, textureRect);
1082 
1083  IOSurfaceRef *surf = outputIOSurface;
1084  *surf = IOSurfaceLookup(surfID);
1085  if (!*surf)
1086  {
1087  VUserLog("Error: IOSurfaceLookup(%d) failed.", surfID);
1088  return;
1089  }
1090 
1091  CGLError err = CGLTexImageIOSurface2D(cgl_ctx, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, (GLsizei)*outputPixelsWide, (GLsizei)*outputPixelsHigh, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, *surf, 0);
1092  if(err != kCGLNoError)
1093  {
1094  VUserLog("Error in CGLTexImageIOSurface2D(): %s", CGLErrorString(err));
1095  return;
1096  }
1097  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
1098  glFlushRenderAPPLE();
1099  });
1100 
1101  return textureRect;
1102 }
1103 
1104 static bool VuoImage_resolveInterprocessJsonOntoFramebufferInternal(IOSurfaceRef surf, VuoGlContext context, GLsizei pixelsWide, GLsizei pixelsHigh, bool flip);
1105 
1127 bool VuoImage_resolveInterprocessJsonUsingClientTexture(struct json_object *js, GLuint clientTextureName, unsigned int pixelsWide, unsigned int pixelsHigh, void *outputIOSurface)
1128 {
1129  if (!clientTextureName)
1130  return false;
1131 
1132  json_object *o;
1133 
1134  if (!json_object_object_get_ex(js, "pixelsWide", &o))
1135  return false;
1136  unsigned long inputPixelsWide = json_object_get_int64(o);
1137 
1138  if (!json_object_object_get_ex(js, "pixelsHigh", &o))
1139  return false;
1140  unsigned long inputPixelsHigh = json_object_get_int64(o);
1141 
1142  if (!json_object_object_get_ex(js, "ioSurface", &o))
1143  return false;
1144  IOSurfaceID surfID = json_object_get_int(o);
1145 
1146  __block bool success = true;
1147  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
1148  IOSurfaceRef *surf = outputIOSurface;
1149  *surf = IOSurfaceLookup(surfID);
1150  if (!*surf)
1151  {
1152  VUserLog("Error: IOSurfaceLookup(%d) failed.", surfID);
1153  success = false;
1154  return;
1155  }
1156 
1157  bool shouldResize = (inputPixelsWide != pixelsWide
1158  || inputPixelsHigh != pixelsHigh);
1159  if (shouldResize)
1160  {
1161  VuoShader_resetContext(cgl_ctx);
1162 
1163  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, clientTextureName);
1164  glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, pixelsWide, pixelsHigh, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
1165  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
1166 
1167  GLuint outputFramebuffer;
1168  glGenFramebuffers(1, &outputFramebuffer);
1169  glBindFramebuffer(GL_FRAMEBUFFER, outputFramebuffer);
1170  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, clientTextureName, 0);
1171 
1172  glViewport(0, 0, pixelsWide, pixelsHigh);
1173 
1174  success = VuoImage_resolveInterprocessJsonOntoFramebufferInternal(*surf, cgl_ctx, inputPixelsWide, inputPixelsHigh, false);
1175 
1176  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, 0, 0);
1177  glBindFramebuffer(GL_FRAMEBUFFER, 0);
1178  glDeleteFramebuffers(1, &outputFramebuffer);
1179  }
1180  else
1181  {
1182  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, clientTextureName);
1183 
1184  CGLError err = CGLTexImageIOSurface2D(cgl_ctx, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, (GLsizei)inputPixelsWide, (GLsizei)inputPixelsHigh, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, *surf, 0);
1185  if (err != kCGLNoError)
1186  {
1187  VUserLog("Error in CGLTexImageIOSurface2D(): %s", CGLErrorString(err));
1188  success = false;
1189  return;
1190  }
1191 
1192  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
1193  }
1194 
1195  glFlushRenderAPPLE();
1196  });
1197 
1198  return success;
1199 }
1200 
1214 {
1215  json_object *o;
1216  if (!json_object_object_get_ex(js, "pixelsWide", &o))
1217  return false;
1218  GLsizei pixelsWide = json_object_get_int64(o);
1219 
1220  if (!json_object_object_get_ex(js, "pixelsHigh", &o))
1221  return false;
1222  GLsizei pixelsHigh = json_object_get_int64(o);
1223 
1224  if (!json_object_object_get_ex(js, "ioSurface", &o))
1225  return false;
1226  IOSurfaceID surfID = json_object_get_int(o);
1227  IOSurfaceRef surf = IOSurfaceLookup(surfID);
1228  if (!surf)
1229  {
1230  VUserLog("Error: IOSurfaceLookup(%d) failed.", surfID);
1231  return false;
1232  }
1233 
1234  bool ret = VuoImage_resolveInterprocessJsonOntoFramebufferInternal(surf, context, pixelsWide, pixelsHigh, flip);
1235 
1237  CFRelease(surf);
1238  return ret;
1239 }
1240 
1244 static GLuint CompileShader(CGLContextObj cgl_ctx, GLenum type, const char *source)
1245 {
1246  GLint length = (GLint)strlen(source);
1247  GLuint shader = glCreateShader(type);
1248  glShaderSource(shader, 1, (const GLchar**)&source, &length);
1249  glCompileShader(shader);
1250 
1251  int infologLength = 0;
1252  glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infologLength);
1253  if (infologLength > 0)
1254  {
1255  char *infoLog = (char *)malloc(infologLength);
1256  int charsWritten = 0;
1257  glGetShaderInfoLog(shader, infologLength, &charsWritten, infoLog);
1258  VUserLog("%s", infoLog);
1259  free(infoLog);
1260  }
1261  return shader;
1262 }
1263 
1266 
1270 static bool VuoImage_resolveInterprocessJsonOntoFramebufferInternal(IOSurfaceRef surf, VuoGlContext context, GLsizei pixelsWide, GLsizei pixelsHigh, bool flip)
1271 {
1272  CGLContextObj cgl_ctx = (CGLContextObj)context;
1273 
1274  static bool openGL32Core;
1275  static GLuint vertexArray;
1276  static GLuint program;
1277  static GLuint receiveTextureOffsetAndSizeUniform;
1279  openGL32Core = VuoGlContext_isOpenGL32Core((VuoGlContext)cgl_ctx);
1280 
1281  char *vertexShaderSource;
1282  char *fragmentShaderSource;
1283  if (openGL32Core)
1284  {
1285  // The following 2 `gl*VertexArrays` calls use the thread-local context (not CGLMacro).
1286  CGLSetCurrentContext(cgl_ctx);
1287 
1288  glGenVertexArrays(1, &vertexArray);
1289  glBindVertexArray(vertexArray);
1290 
1291  vertexShaderSource = VUOSHADER_GLSL_SOURCE(150,
1292  in vec2 position;
1293  in vec2 textureCoordinate;
1294  out vec2 fragmentTextureCoordinate;
1295  void main()
1296  {
1297  fragmentTextureCoordinate = textureCoordinate;
1298  gl_Position = vec4(position.x, position.y, 0., 1.);
1299  }
1300  );
1301  fragmentShaderSource = VUOSHADER_GLSL_SOURCE(150,
1302  uniform sampler2DRect receiveTexture;
1303  uniform vec4 receiveTextureOffsetAndSize;
1304  in vec2 fragmentTextureCoordinate;
1305  out vec4 FragColor;
1306  void main()
1307  {
1308  FragColor = texture(receiveTexture, receiveTextureOffsetAndSize.xy + fragmentTextureCoordinate * receiveTextureOffsetAndSize.zw);
1309  }
1310  );
1311  }
1312  else
1313  {
1314  // OpenGL 2.1 context.
1315 
1316  glGenVertexArraysAPPLE(1, &vertexArray);
1317  glBindVertexArrayAPPLE(vertexArray);
1318 
1319  vertexShaderSource = VUOSHADER_GLSL_SOURCE(120,
1320  attribute vec2 position;
1321  attribute vec2 textureCoordinate;
1322  varying vec2 fragmentTextureCoordinate;
1323  void main()
1324  {
1325  fragmentTextureCoordinate = textureCoordinate;
1326  gl_Position = vec4(position.x, position.y, 0., 1.);
1327  }
1328  );
1329  fragmentShaderSource = VUOSHADER_GLSL_SOURCE(120,
1330  uniform sampler2DRect receiveTexture;
1331  uniform vec4 receiveTextureOffsetAndSize;
1332  varying vec2 fragmentTextureCoordinate;
1333  void main()
1334  {
1335  gl_FragColor = texture2DRect(receiveTexture, receiveTextureOffsetAndSize.xy + fragmentTextureCoordinate * receiveTextureOffsetAndSize.zw);
1336  }
1337  );
1338  }
1339 
1340 
1341  const GLfloat quadPositionsAndTextureCoordinates[] = {
1342  // X Y U V
1343  -1, -1, 0, 0,
1344  1, -1, 1, 0,
1345  -1, 1, 0, 1,
1346 
1347  1, 1, 1, 1,
1348  -1, 1, 0, 1,
1349  1, -1, 1, 0,
1350  };
1351  GLuint quadPTCBuffer;
1352  glGenBuffers(1, &quadPTCBuffer);
1353  glBindBuffer(GL_ARRAY_BUFFER, quadPTCBuffer);
1354  glBufferData(GL_ARRAY_BUFFER, sizeof(quadPositionsAndTextureCoordinates), quadPositionsAndTextureCoordinates, GL_STATIC_DRAW);
1355  VuoGlPool_logVRAMAllocated(sizeof(quadPositionsAndTextureCoordinates));
1356 
1357  GLuint vertexShader = CompileShader(context, GL_VERTEX_SHADER, vertexShaderSource);
1358  GLuint fragmentShader = CompileShader(context, GL_FRAGMENT_SHADER, fragmentShaderSource);
1359  program = glCreateProgram();
1360  glAttachShader(program, vertexShader);
1361  glAttachShader(program, fragmentShader);
1362  glLinkProgram(program);
1363  GLuint positionAttribute = glGetAttribLocation(program, "position");
1364  GLuint textureCoordinateAttribute = glGetAttribLocation(program, "textureCoordinate");
1365  GLuint receiveTextureUniform = glGetUniformLocation(program, "receiveTexture");
1366  receiveTextureOffsetAndSizeUniform = glGetUniformLocation(program, "receiveTextureOffsetAndSize");
1367 
1368  glUseProgram(program);
1369 
1370  glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, (void*)0);
1371  glEnableVertexAttribArray(positionAttribute);
1372 
1373  glVertexAttribPointer(textureCoordinateAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, (void*)(sizeof(GLfloat)*2));
1374  glEnableVertexAttribArray(textureCoordinateAttribute);
1375 
1376  glUniform1i(receiveTextureUniform, 0);
1377  });
1378 
1379 
1380  if (openGL32Core)
1381  {
1382  CGLSetCurrentContext(cgl_ctx);
1383  glBindVertexArray(vertexArray);
1384  }
1385  else
1386  glBindVertexArrayAPPLE(vertexArray);
1387 
1388  GLuint textureRect = VuoGlTexturePool_use(cgl_ctx, VuoGlTexturePool_AllocateIOSurface, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, pixelsWide, pixelsHigh, GL_BGRA, surf);
1389  if (!textureRect)
1390  {
1391  VUserLog("Error: Couldn't allocate texture.");
1392  VGL();
1393  return false;
1394  }
1395  VuoGlTexture_retain(textureRect, NULL, NULL);
1396 
1397  glActiveTexture(GL_TEXTURE0);
1398  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, textureRect);
1399 
1400  glUseProgram(program);
1401 
1402  // Center the image in the viewport.
1403  GLint viewport[4];
1404  glGetIntegerv(GL_VIEWPORT, viewport);
1405 // VLog("Resolving %dx%d image onto a %dx%d viewport.", pixelsWide, pixelsHigh, viewport[2], viewport[3]);
1406  glUniform4f(receiveTextureOffsetAndSizeUniform,
1407  ((float)pixelsWide - viewport[2]) / 2,
1408  flip ? viewport[3] : 0,
1409  viewport[2],
1410  viewport[3] * (flip ? -1 : 1));
1411 
1412  glDrawArrays(GL_TRIANGLES, 0, 6);
1413 
1414  glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
1415  VuoGlTexture_release(VuoGlTexturePool_AllocateIOSurface, GL_TEXTURE_RECTANGLE_ARB, GL_RGBA, pixelsWide, pixelsHigh, textureRect);
1416  glUseProgram(0);
1417  if (openGL32Core)
1418  glBindVertexArray(0);
1419  else
1420  glBindVertexArrayAPPLE(0);
1421 
1422  glBindBuffer(GL_ARRAY_BUFFER, 0);
1423 
1424  return true;
1425 }
1426 
1434 {
1435  if (!value)
1436  return NULL;
1437 
1438  json_object *js = json_object_new_object();
1439  json_object_object_add(js, "pointer", json_object_new_int64((int64_t)value));
1440  return js;
1441 }
1442 
1452 {
1453  if (!value)
1454  return NULL;
1455 
1456  __block VuoShader shader = NULL;
1457  __block IOSurfaceID surfID = 0;
1458  VuoGlContext_perform(^(CGLContextObj cgl_ctx){
1459 // VLog("Creating an IOSurface from glTextureName %d on target %lu",value->glTextureName,value->glTextureTarget);
1460 
1461  if (value->glTextureTarget == GL_TEXTURE_2D)
1462  shader = VuoShader_makeUnlitAlphaPassthruImageShader(value, false);
1463  else if (value->glTextureTarget == GL_TEXTURE_RECTANGLE_ARB)
1465  VuoRetain(shader);
1466 
1467  surfID = VuoImageRenderer_draw_internal(shader, value->pixelsWide, value->pixelsHigh, VuoImage_getColorDepth(value), true, true, 0, NULL);
1468 // VLog("Created IOSurfaceID %d",surfID);
1469 
1470  // Ensure the command queue gets executed before we return,
1471  // since the IOSurface might immediately be used on another context.
1472  glFlushRenderAPPLE();
1473  });
1474  if (!surfID)
1475  return NULL;
1476 
1477  json_object * js = json_object_new_object();
1478  {
1479  json_object * o = json_object_new_int(surfID);
1480  json_object_object_add(js, "ioSurface", o);
1481  }
1482 
1483  {
1484  json_object * o = json_object_new_int64(value->pixelsWide);
1485  json_object_object_add(js, "pixelsWide", o);
1486  }
1487  {
1488  json_object * o = json_object_new_int64(value->pixelsHigh);
1489  json_object_object_add(js, "pixelsHigh", o);
1490  }
1491  {
1492  json_object *o = json_object_new_double(value->scaleFactor);
1493  json_object_object_add(js, "scaleFactor", o);
1494  }
1495  // VuoShader_makeUnlitImageShader retains the image; VuoRelease(shader) then releases it.
1496  // So don't release the shader until we're done with the image, in case this release is its last.
1497  VuoRelease(shader);
1498 
1499  return js;
1500 }
1501 
1511 char * VuoImage_getSummary(const VuoImage value)
1512 {
1513  if (!value)
1514  return strdup("No image");
1515 
1516  const char *type;
1517  switch (value->glInternalFormat)
1518  {
1519  case GL_RGB: type = "RGB, each channel 8-bit unsigned integer"; break;
1520  case GL_RGB16F_ARB: type = "RGB, each channel 16-bit signed float"; break;
1521  case GL_RGB32F_ARB: type = "RGB, each channel 32-bit signed float"; break;
1522  case GL_RGBA: type = "RGBA, each channel 8-bit unsigned integer"; break;
1523  case GL_RGBA16F_ARB: type = "RGBA, each channel 16-bit signed float"; break;
1524  case GL_RGBA32F_ARB: type = "RGBA, each channel 32-bit signed float"; break;
1525  case GL_LUMINANCE8: type = "intensity, 8-bit unsigned integer"; break;
1526  case GL_LUMINANCE16F_ARB: type = "intensity, 16-bit signed float"; break;
1527  case GL_LUMINANCE32F_ARB: type = "intensity, 32-bit signed float"; break;
1528  case GL_LUMINANCE8_ALPHA8: type = "intensity+alpha, each channel 8-bit unsigned integer"; break;
1529  case GL_LUMINANCE_ALPHA16F_ARB: type = "intensity+alpha, each channel 16-bit signed float"; break;
1530  case GL_LUMINANCE_ALPHA32F_ARB: type = "intensity+alpha, each channel 32-bit signed float"; break;
1531  case GL_DEPTH_COMPONENT: type = "intensity, 16-bit signed float"; break;
1532  default: type = "(unknown)";
1533  }
1534 
1535  char *target = VuoGl_stringForConstant(value->glTextureTarget);
1536  char *internalformat = VuoGl_stringForConstant(value->glInternalFormat);
1537 
1538  char *summary = VuoText_format("<div>%luĂ—%lu pixels @ %gx</div><div>%s</div><div>OpenGL: %s, %s, ID %u</div>",
1539  value->pixelsWide, value->pixelsHigh,
1540  value->scaleFactor,
1541  type,
1542  target,
1543  internalformat,
1544  value->glTextureName);
1545 
1546  free(internalformat);
1547 
1548  return summary;
1549 }