@Override
 protected void onOutputFormatChanged(MediaCodec codec, android.media.MediaFormat outputFormat) {
   boolean hasCrop =
       outputFormat.containsKey(KEY_CROP_RIGHT)
           && outputFormat.containsKey(KEY_CROP_LEFT)
           && outputFormat.containsKey(KEY_CROP_BOTTOM)
           && outputFormat.containsKey(KEY_CROP_TOP);
   currentWidth =
       hasCrop
           ? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
           : outputFormat.getInteger(android.media.MediaFormat.KEY_WIDTH);
   currentHeight =
       hasCrop
           ? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
           : outputFormat.getInteger(android.media.MediaFormat.KEY_HEIGHT);
   currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
   if (Util.SDK_INT >= 21) {
     // On API level 21 and above the decoder applies the rotation when rendering to the surface.
     // Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
     // to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
     if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
       int rotatedHeight = currentWidth;
       currentWidth = currentHeight;
       currentHeight = rotatedHeight;
       currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
     }
   } else {
     // On API level 20 and below the decoder does not apply the rotation.
     currentUnappliedRotationDegrees = pendingRotationDegrees;
   }
   // Must be applied each time the output format changes.
   codec.setVideoScalingMode(videoScalingMode);
 }