title: Android OpenGL - glTexImage2D causing crash using ByteBuffer wrapped over byte[] with offset
body: <p><em>Problem:</em> Passing a <code>ByteBuffer</code> wrapping a <code>byte[]</code> containing image data into <code>GLES20.glTexImage2D(...)</code> is working for me if and only if the <code>ByteBuffer</code> has <strong>no offset</strong> - otherwise (if there's an offset set) it crashes unhelpfully with something like:</p>
  <pre><code>Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x61616162636575 in tid 32016 (GLThread 4912), pid 31806
  </code></pre>
  <hr />
  <p><em>Background:</em> I have a single <code>byte[]</code> of YUV (I420) data for a 720p image - and I need to read this out as 3 separate <code>ByteBuffer</code>s to pass to an OpenGL shader which has 3 different sampler2D channels (1 channel per buffer).</p>
  <p>Ideally, since all the information is there in memory, I would create three ByteBuffers wrapping different parts of the <code>byte[]</code> like this:</p>
  <pre><code>ByteBuffer yBuffer = ByteBuffer.wrap(rawYUVData, 0, yBufferSize);
  ByteBuffer uBuffer = ByteBuffer.wrap(rawYUVData, yBufferSize, uBufferSize);
  ByteBuffer vBuffer = ByteBuffer.wrap(rawYUVData, yBufferSize+uBufferSize, uBufferSize);
  </code></pre>
  <p>And then in my renderer code, I call OpenGL <code>glTexImage2D</code> three times also:</p>
  <pre><code>GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yTexDataHandle);
  GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, imgWidth, imgHeight, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, yBuffer);
  
  GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, uTexDataHandle);
  GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, uWidth, uHeight, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, uBuffer);
  
  GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, vTexDataHandle);
  GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, uWidth, uHeight, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, vBuffer);
  </code></pre>
  <p>This is crashing. I can fix the crash just fine by copying the contents of the above <code>uBuffer</code> and <code>vBuffer</code> into new <code>byte[]</code>s, then rewrapping the <code>ByteBuffer</code>s over the new arrays.</p>
  <p>But I'm copying data needlessly, and 30x per second.</p>
  <p>Can I not wrap <code>ByteBuffer</code>s over the contiguous byte[], with offsets, and use these in OpenGL for some reason? Do I really have to copy all the time?</p>
  <ul>
  <li>I've checked it's not an issue in my shader file, by removing the calls to <code>texture2D()</code> that involve the offending samplers.</li>
  <li>Even just adding an offset of 1 to my construction of <code>yBuffer</code>, and it crashes where with 0 it works fine. (rawYUVData.length is always &gt; yBufferSize + 1)</li>
  </ul>