/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.exoplayer2.playbacktests.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Handler;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.Renderer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.video.MediaCodecVideoRenderer;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import java.util.ArrayList;

/**
 * A debug extension of {@link SimpleExoPlayer}. Provides video buffer timestamp assertions.
 */
@TargetApi(16)
public class DebugSimpleExoPlayer extends SimpleExoPlayer {

  public DebugSimpleExoPlayer(Context context, TrackSelector trackSelector,
      LoadControl loadControl, DrmSessionManager<FrameworkMediaCrypto> drmSessionManager) {
    super(context, trackSelector, loadControl, drmSessionManager,
        SimpleExoPlayer.EXTENSION_RENDERER_MODE_OFF, 0);
  }

  @Override
  protected void buildVideoRenderers(Context context, Handler mainHandler,
      DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
      @ExtensionRendererMode int extensionRendererMode, VideoRendererEventListener eventListener,
      long allowedVideoJoiningTimeMs, ArrayList<Renderer> out) {
    out.add(new DebugMediaCodecVideoRenderer(context, MediaCodecSelector.DEFAULT,
        allowedVideoJoiningTimeMs, mainHandler, drmSessionManager, eventListener,
        MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY));
  }

  /**
   * Decodes and renders video using {@link MediaCodecVideoRenderer}. Provides buffer timestamp
   * assertions.
   */
  private static class DebugMediaCodecVideoRenderer extends MediaCodecVideoRenderer {

    private static final int ARRAY_SIZE = 1000;

    private final long[] timestampsList = new long[ARRAY_SIZE];

    private int startIndex;
    private int queueSize;
    private int bufferCount;

    public DebugMediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
        long allowedJoiningTimeMs, Handler eventHandler,
        DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
        VideoRendererEventListener eventListener,
        int maxDroppedFrameCountToNotify) {
      super(context, mediaCodecSelector, allowedJoiningTimeMs, drmSessionManager, false,
          eventHandler, eventListener, maxDroppedFrameCountToNotify);
      startIndex = 0;
      queueSize = 0;
    }

    @Override
    protected void releaseCodec() {
      super.releaseCodec();
      clearTimestamps();
    }

    @Override
    protected void flushCodec() throws ExoPlaybackException {
      super.flushCodec();
      clearTimestamps();
    }

    @Override
    protected void onQueueInputBuffer(DecoderInputBuffer buffer) {
      insertTimestamp(buffer.timeUs);
      maybeShiftTimestampsList();
    }

    @Override
    protected void onProcessedOutputBuffer(long presentationTimeUs) {
      bufferCount++;
      long expectedTimestampUs = dequeueTimestamp();
      if (expectedTimestampUs != presentationTimeUs) {
        throw new IllegalStateException("Expected to dequeue video buffer with presentation "
            + "timestamp: " + expectedTimestampUs + ". Instead got: " + presentationTimeUs
            + " (Processed buffers since last flush: " + bufferCount + ").");
      }
    }

    private void clearTimestamps() {
      startIndex = 0;
      queueSize = 0;
      bufferCount = 0;
    }

    private void insertTimestamp(long presentationTimeUs) {
      for (int i = startIndex + queueSize - 1; i >= startIndex; i--) {
        if (presentationTimeUs >= timestampsList[i]) {
          timestampsList[i + 1] = presentationTimeUs;
          queueSize++;
          return;
        }
        timestampsList[i + 1] = timestampsList[i];
      }
      timestampsList[startIndex] = presentationTimeUs;
      queueSize++;
    }

    private void maybeShiftTimestampsList() {
      if (startIndex + queueSize == ARRAY_SIZE) {
        System.arraycopy(timestampsList, startIndex, timestampsList, 0, queueSize);
        startIndex = 0;
      }
    }

    private long dequeueTimestamp() {
      startIndex++;
      queueSize--;
      return timestampsList[startIndex - 1];
    }

  }

}

@@ -827,16 +827,61 @@
 eption;%0A
+import com.google.android.exoplayer2.Format;%0A
 import c
@@ -922,16 +922,16 @@
 ontrol;%0A
-
 import c
@@ -2931,16 +2931,52 @@
 erCount;
+%0A    private int minimumInsertIndex;
 %0A%0A    pu
@@ -3238,24 +3238,16 @@
 istener,
-%0A       
  int max
@@ -3438,51 +3438,8 @@
 y);%0A
-      startIndex = 0;%0A      queueSize = 0;%0A
     
@@ -3677,32 +3677,435 @@
 tamps();%0A    %7D%0A%0A
+    @Override%0A    protected void onInputFormatChanged(Format newFormat) throws ExoPlaybackException %7B%0A      super.onInputFormatChanged(newFormat);%0A      // Ensure timestamps of buffers queued after this format change are never inserted into the%0A      // queue of expected output timestamps before those of buffers that have already been queued.%0A      minimumInsertIndex = startIndex + queueSize;%0A    %7D%0A%0A
     @Override%0A  
@@ -4838,24 +4838,54 @@
 rCount = 0;%0A
+      minimumInsertIndex = 0;%0A
     %7D%0A%0A    p
@@ -4991,19 +4991,27 @@
 1; i %3E= 
-sta
+minimumInse
 rtIndex;
@@ -5254,27 +5254,35 @@
 estampsList%5B
-sta
+minimumInse
 rtIndex%5D = p
@@ -5506,16 +5506,58 @@
 eSize);%0A
+        minimumInsertIndex -= startIndex;%0A
         
@@ -5621,24 +5621,43 @@
 mestamp() %7B%0A
+      queueSize--;%0A
       startI
@@ -5666,35 +5666,85 @@
 ex++;%0A      
-queueSize--
+minimumInsertIndex = Math.max(minimumInsertIndex, startIndex)
 ;%0A      retu

Fix GTS playback test timestamp verifications