title: Android Camera2 preview occasionally rotated by 90 degrees
body: <p>I'm working on some app using Android's Camera2 API. So far I've been able to get a preview displayed within a <code>TextureView</code>. The app is by default in landscape mode. When using the emulator the preview will appear upside-down. On my physical Nexus 5 the preview is <em>usually</em> displayed correctly (landscape, not upside-down), but occasionally it is rotated by 90 degrees, yet stretched to the dimensions of the screen.
  I thought that should be easy and thought the following code would return the necessary information on the current orientation:</p>
  
  <pre><code>// display rotation
  getActivity().getWindowManager().getDefaultDisplay().getRotation();
  // sensor orientation
  mManager.getCameraCharacteristics(mCameraId).get(CameraCharacteristics.SENSOR_ORIENTATION);
  </code></pre>
  
  <p>... I was pretty surprised when I saw that above code <strong>always</strong> returned <code>1</code> for the display rotation and <code>90</code> for the sensor orientation, <em>regardless</em> of the preview being rotated by 90 degree or not. (Within the emulator sensor orientation is always 270 which kinda makes sense if I assume 90 to be the correct orientation).
  I also checked the width and height within <code>onMeasure</code> within <a href="https://github.com/googlesamples/android-Camera2Basic/blob/master/Application/src/main/java/com/example/android/camera2basic/AutoFitTextureView.java" rel="nofollow noreferrer">AutoMeasureTextureView</a> (adopted from <a href="https://github.com/googlesamples/android-Camera2Basic/blob/master/Application/src/main/java/com/example/android/camera2basic/Camera2BasicFragment.java" rel="nofollow noreferrer">Android's Camera2 example</a>) that I'm using to create my TextureView. But no luck either - width and height reported from within <code>onMeasure</code> are always the same regardless of the preview rotation.
  So I'm clueless on how to tackle this issue. Does anyone have an idea what could be the reason for the occasional hickups in my preview orientation?</p>
  
  <p>[Edit]
  A detail I just found out: Whenever the preview appears rotated <code>onSurfaceTextureSizeChanged</code> in the <code>TextureView.SurfaceTextureListener</code> seems not to get called. In the documentation for <code>onSurfaceTextureSizeChanged</code> it is said that this method is called whenever the <code>SurfaceTexture</code>'s buffers size is changed. I have a method <code>createCameraPreviewSession</code> (copied from Android's Camera2 example) in which I set the default buffer size of my texture like</p>
  
  <pre><code>texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  </code></pre>
  
  <p>From my logging output I can tell that <code>onSurfaceTextureSizeChanged</code> is called exactly after that - however, not always... (or setting the default buffer size sometimes silently fails?).</p>