CMVideoSampling.mm 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "CMVideoSampling.h"
  2. #include "CVTextureCache.h"
  3. #include "GlesHelper.h"
  4. #include <OpenGLES/ES3/glext.h>
  5. #include <AVFoundation/AVFoundation.h>
  6. void CMVideoSampling_Initialize(CMVideoSampling* sampling)
  7. {
  8. ::memset(sampling, 0x00, sizeof(CMVideoSampling));
  9. sampling->cvTextureCache = CreateCVTextureCache();
  10. }
  11. void CMVideoSampling_Uninitialize(CMVideoSampling* sampling)
  12. {
  13. if (sampling->cvImageBuffer)
  14. {
  15. CFRelease(sampling->cvImageBuffer);
  16. sampling->cvImageBuffer = 0;
  17. }
  18. if (sampling->cvTextureCacheTexture)
  19. {
  20. CFRelease(sampling->cvTextureCacheTexture);
  21. sampling->cvTextureCacheTexture = 0;
  22. }
  23. if (sampling->cvTextureCache)
  24. {
  25. CFRelease(sampling->cvTextureCache);
  26. sampling->cvTextureCache = 0;
  27. }
  28. }
  29. intptr_t CMVideoSampling_SampleBuffer(CMVideoSampling* sampling, void* buffer, size_t* w, size_t* h)
  30. {
  31. intptr_t retTex = 0;
  32. if (sampling->cvImageBuffer)
  33. CFRelease(sampling->cvImageBuffer);
  34. sampling->cvImageBuffer = CMSampleBufferGetImageBuffer((CMSampleBufferRef)buffer);
  35. CFRetain(sampling->cvImageBuffer);
  36. *w = CVPixelBufferGetWidth((CVImageBufferRef)sampling->cvImageBuffer);
  37. *h = CVPixelBufferGetHeight((CVImageBufferRef)sampling->cvImageBuffer);
  38. if (sampling->cvTextureCacheTexture)
  39. {
  40. CFRelease(sampling->cvTextureCacheTexture);
  41. FlushCVTextureCache(sampling->cvTextureCache);
  42. }
  43. sampling->cvTextureCacheTexture = CreateTextureFromCVTextureCache(sampling->cvTextureCache, sampling->cvImageBuffer, *w, *h);
  44. if (sampling->cvTextureCacheTexture)
  45. retTex = GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
  46. if (UnitySelectedRenderingAPI() == apiOpenGLES2 || UnitySelectedRenderingAPI() == apiOpenGLES3)
  47. {
  48. GLint oldTexBinding = 0;
  49. glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTexBinding);
  50. glBindTexture(GL_TEXTURE_2D, (GLuint)retTex);
  51. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  52. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  53. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  54. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  55. glBindTexture(GL_TEXTURE_2D, oldTexBinding);
  56. }
  57. return retTex;
  58. }
  59. intptr_t CMVideoSampling_LastSampledTexture(CMVideoSampling* sampling)
  60. {
  61. return GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
  62. }