Merge "Test for issue #29422027: APR: Runtime restarts in system_server" into nyc-mr1-dev
diff --git a/apps/CameraITS/pymodules/its/caps.py b/apps/CameraITS/pymodules/its/caps.py
index a33757d..d9270f7 100644
--- a/apps/CameraITS/pymodules/its/caps.py
+++ b/apps/CameraITS/pymodules/its/caps.py
@@ -394,6 +394,59 @@
             "android.edge.availableEdgeModes") and mode \
             in props["android.edge.availableEdgeModes"];
 
+
+def lens_calibrated(props):
+    """Returns whether lens position is calibrated or not.
+
+    android.lens.info.focusDistanceCalibration has 3 modes.
+    0: Uncalibrated
+    1: Approximate
+    2: Calibrated
+
+    Args:
+        props: Camera properties objects.
+
+    Returns:
+        Boolean.
+    """
+    return props.has_key("android.lens.info.focusDistanceCalibration") and \
+         props["android.lens.info.focusDistanceCalibration"] == 2
+
+
+def lens_approx_calibrated(props):
+    """Returns whether lens position is calibrated or not.
+
+    android.lens.info.focusDistanceCalibration has 3 modes.
+    0: Uncalibrated
+    1: Approximate
+    2: Calibrated
+
+    Args:
+        props: Camera properties objects.
+
+    Returns:
+        Boolean.
+    """
+    return props.has_key("android.lens.info.focusDistanceCalibration") and \
+        (props["android.lens.info.focusDistanceCalibration"] == 1 or
+         props["android.lens.info.focusDistanceCalibration"] == 2)
+
+
+def fixed_focus(props):
+    """Returns whether a device is fixed focus.
+
+    props[android.lens.info.minimumFocusDistance] == 0 is fixed focus
+
+    Args:
+        props: Camera properties objects.
+
+    Returns:
+        Boolean.
+    """
+    return props.has_key("android.lens.info.minimumFocusDistance") and \
+        props["android.lens.info.minimumFocusDistance"] == 0
+
+
 class __UnitTest(unittest.TestCase):
     """Run a suite of unit tests on this module.
     """
diff --git a/apps/CameraITS/tests/scene1/scene1.pdf b/apps/CameraITS/tests/scene1/scene1.pdf
index e695748..7e47bcf 100644
--- a/apps/CameraITS/tests/scene1/scene1.pdf
+++ b/apps/CameraITS/tests/scene1/scene1.pdf
Binary files differ
diff --git a/apps/CameraITS/tools/load_scene.py b/apps/CameraITS/tools/load_scene.py
index ae35914..4e245f4 100644
--- a/apps/CameraITS/tools/load_scene.py
+++ b/apps/CameraITS/tools/load_scene.py
@@ -37,6 +37,10 @@
         print 'Error: need to specify which scene to load'
         assert False
 
+    if not screen_id:
+        print 'Error: need to specify screen serial'
+        assert False
+
     remote_scene_file = '/sdcard/Download/%s.pdf' % scene
     local_scene_file = os.path.join(os.environ['CAMERA_ITS_TOP'], 'tests',
                                     scene, scene+'.pdf')
diff --git a/apps/CameraITS/tools/turn_off_screen.py b/apps/CameraITS/tools/turn_off_screen.py
index 58c77c8..4163ab4 100644
--- a/apps/CameraITS/tools/turn_off_screen.py
+++ b/apps/CameraITS/tools/turn_off_screen.py
@@ -23,6 +23,11 @@
     for s in sys.argv[1:]:
         if s[:7] == 'screen=' and len(s) > 7:
             screen_id = s[7:]
+
+    if not screen_id:
+        print 'Error: need to specify screen serial'
+        assert False
+
     cmd = ('adb -s %s shell dumpsys power | egrep "Display Power"'
            % screen_id)
     process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
diff --git a/apps/CameraITS/tools/wake_up_screen.py b/apps/CameraITS/tools/wake_up_screen.py
index 2de4d22..68a974a 100644
--- a/apps/CameraITS/tools/wake_up_screen.py
+++ b/apps/CameraITS/tools/wake_up_screen.py
@@ -17,12 +17,22 @@
 import sys
 import time
 
+DISPLAY_LEVEL = 96  # [0:255] Depends on tablet model. Adjust for best result.
+DISPLAY_WAIT = 0.5  # seconds. Screen commands take time to have effect
+
+
 def main():
     """Power up and unlock screen as needed."""
     screen_id = None
     for s in sys.argv[1:]:
         if s[:7] == 'screen=' and len(s) > 7:
             screen_id = s[7:]
+
+    if not screen_id:
+        print 'Error: need to specify screen serial'
+        assert False
+
+    # turn on screen if necessary and unlock
     cmd = ('adb -s %s shell dumpsys display | egrep "mScreenState"'
            % screen_id)
     process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
@@ -32,11 +42,19 @@
         print 'Screen OFF. Turning ON.'
         wakeup = ('adb -s %s shell input keyevent POWER' % screen_id)
         subprocess.Popen(wakeup.split())
-        time.sleep(0.5)  # some screens need pause for next command
+        time.sleep(DISPLAY_WAIT)
     unlock = ('adb -s %s wait-for-device shell wm dismiss-keyguard'
               % screen_id)
     subprocess.Popen(unlock.split())
-    time.sleep(0.5)  # some screens need time for command to take effect
+    time.sleep(DISPLAY_WAIT)
+
+    # set brightness
+    print 'Tablet display brightness set to %d' % DISPLAY_LEVEL
+    bright = ('adb -s %s shell settings put system screen_brightness %d'
+              % (screen_id, DISPLAY_LEVEL))
+    subprocess.Popen(bright.split())
+    time.sleep(DISPLAY_WAIT)
+
 
 if __name__ == '__main__':
     main()
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
index 744db8f..632899d 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
@@ -39,8 +39,6 @@
             </intent-filter>
         </receiver>
         <activity
-            android:name="com.android.cts.deviceandprofileowner.ScreenCaptureDisabledActivity" />
-        <activity
             android:name="com.android.cts.deviceandprofileowner.ExampleIntentReceivingActivity1">
             <intent-filter>
                 <action android:name="com.android.cts.deviceandprofileowner.EXAMPLE_ACTION" />
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java
deleted file mode 100644
index b5b4fdc..0000000
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledActivity.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2015 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.android.cts.deviceandprofileowner;
-
-import android.app.Activity;
-import android.content.Intent;
-
-/**
- * Test activity for setScreenCaptureDisabled().
- */
-public class ScreenCaptureDisabledActivity extends Activity {
-
-    static final String ACTIVITY_RESUMED =
-            "com.android.cts.deviceandprofileowner.ACTIVITY_RESUMED";
-
-    @Override
-    protected void onResume() {
-        super.onResume();
-        sendBroadcast(new Intent(ACTIVITY_RESUMED));
-    }
-}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
index e2deaa4..b7f9066 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ScreenCaptureDisabledTest.java
@@ -16,16 +16,8 @@
 package com.android.cts.deviceandprofileowner;
 
 import android.app.admin.DevicePolicyManager;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
 import android.util.Log;
 
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
 /**
  * Tests for {@link DevicePolicyManager#setScreenCaptureDisabled} and
  * {@link DevicePolicyManager#getScreenCaptureDisabled} APIs.
@@ -34,66 +26,23 @@
 
     private static final String TAG = "ScreenCaptureDisabledTest";
 
-    private ScreenCaptureBroadcastReceiver mReceiver = new ScreenCaptureBroadcastReceiver();
-
-    protected void setUp() throws Exception {
-        super.setUp();
-        mContext.registerReceiver(mReceiver, new IntentFilter(
-                ScreenCaptureDisabledActivity.ACTIVITY_RESUMED));
-    }
-
-    protected void tearDown() throws Exception {
-        mContext.unregisterReceiver(mReceiver);
-        super.tearDown();
-    }
-
     public void testSetScreenCaptureDisabled_false() throws Exception {
         mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, false);
         assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
         assertFalse(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
-        startTestActivity();
-        assertNotNull(getInstrumentation().getUiAutomation().takeScreenshot());
     }
 
     public void testSetScreenCaptureDisabled_true() throws Exception {
         mDevicePolicyManager.setScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT, true);
         assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(ADMIN_RECEIVER_COMPONENT));
         assertTrue(mDevicePolicyManager.getScreenCaptureDisabled(null /* any admin */));
-        startTestActivity();
+    }
+
+    public void testScreenCaptureImpossible() throws Exception {
         assertNull(getInstrumentation().getUiAutomation().takeScreenshot());
     }
 
     public void testScreenCapturePossible() throws Exception {
         assertNotNull(getInstrumentation().getUiAutomation().takeScreenshot());
     }
-
-    // We need to launch an activity before trying to take a screen shot, because screenshots are
-    // only blocked on a per-user basis in the profile owner case depending on the owner of the
-    // foreground activity.
-    private void startTestActivity() throws Exception {
-        Intent launchIntent = new Intent();
-        launchIntent.setComponent(new ComponentName(PACKAGE_NAME,
-                ScreenCaptureDisabledActivity.class.getName()));
-        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        mContext.startActivity(launchIntent);
-        assertTrue(mReceiver.waitForBroadcast());
-        Thread.sleep(1000);
-    }
-
-    private class ScreenCaptureBroadcastReceiver extends BroadcastReceiver {
-        private final Semaphore mSemaphore = new Semaphore(0);
-
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            Log.d(TAG, "Broadcast received");
-            mSemaphore.release();
-        }
-
-        public boolean waitForBroadcast() throws Exception {
-            if (mSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
-                return true;
-            }
-            return false;
-        }
-    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index 8a0b57e..ca6fb62 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -106,6 +106,7 @@
             getDevice().uninstallPackage(INTENT_RECEIVER_PKG);
             getDevice().uninstallPackage(INTENT_SENDER_PKG);
             getDevice().uninstallPackage(CUSTOMIZATION_APP_PKG);
+            getDevice().uninstallPackage(TEST_APP_PKG);
 
             // Press the HOME key to close any alart dialog that may be shown.
             getDevice().executeShellCommand("input keyevent 3");
@@ -288,11 +289,9 @@
         // We need to ensure that the policy is deactivated for the device owner case, so making
         // sure the second test is run even if the first one fails
         try {
-            executeDeviceTestMethod(".ScreenCaptureDisabledTest",
-                    "testSetScreenCaptureDisabled_true");
+            setScreenCaptureDisabled(mUserId, true);
         } finally {
-            executeDeviceTestMethod(".ScreenCaptureDisabledTest",
-                    "testSetScreenCaptureDisabled_false");
+            setScreenCaptureDisabled(mUserId, false);
         }
     }
 
@@ -612,4 +611,38 @@
         assertTrue("Command was expected to succeed " + commandOutput,
                 commandOutput.contains("Status: ok"));
     }
+
+    /**
+     * Start SimpleActivity synchronously in a particular user.
+     */
+    protected void startScreenCaptureDisabledActivity(int userId) throws Exception {
+        installAppAsUser(TEST_APP_APK, userId);
+        String command = "am start -W --user " + userId + " " + TEST_APP_PKG + "/"
+                + TEST_APP_PKG + ".SimpleActivity";
+        getDevice().executeShellCommand(command);
+    }
+
+    // TODO: Remove this after investigation in b/28995242 is done
+    // So we can check which one is the top window / activity.
+    private void runDumpsysWindow() throws Exception {
+        String command = "dumpsys window displays";
+        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
+        command = "dumpsys activity a";
+        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
+    }
+
+    protected void setScreenCaptureDisabled(int userId, boolean disabled) throws Exception {
+        String testMethodName = disabled
+                ? "testSetScreenCaptureDisabled_true"
+                : "testSetScreenCaptureDisabled_false";
+        executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
+        startScreenCaptureDisabledActivity(userId);
+        // [b/28995242], dump windows to make sure the top window is
+        // ScreenCaptureDisabledActivity.
+        runDumpsysWindow();
+        testMethodName = disabled
+                ? "testScreenCaptureImpossible"
+                : "testScreenCapturePossible";
+        executeDeviceTestMethod(".ScreenCaptureDisabledTest", testMethodName);
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index 4748b35..256b03c 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -101,7 +101,7 @@
     }
 
     public void testWifi() throws Exception {
-        if (hasDeviceFeature("android.hardware.wifi")) {
+        if (!hasDeviceFeature("android.hardware.wifi")) {
             return;
         }
         executeDeviceOwnerTest("WifiTest");
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
index b467aed..afc4e34 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
@@ -73,29 +73,13 @@
         if (!mHasFeature) {
             return;
         }
-        runDumpsysWindow();
-        try {
-            executeDeviceTestMethod(".ScreenCaptureDisabledTest",
-                    "testSetScreenCaptureDisabled_true");
-            // start the ScreenCaptureDisabledActivity in the parent
-            installAppAsUser(DEVICE_ADMIN_APK, mParentUserId);
-            String command = "am start -W --user " + mParentUserId + " " + DEVICE_ADMIN_PKG + "/"
-                    + DEVICE_ADMIN_PKG + ".ScreenCaptureDisabledActivity";
-            getDevice().executeShellCommand(command);
-            executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testScreenCapturePossible");
-        } catch (AssertionError e) {
-            runDumpsysWindow();
-            CLog.e("testScreenCaptureDisabled_allowedPrimaryUser failed", e);
-            fail("testScreenCaptureDisabled_allowedPrimaryUser failed");
-        }
-    }
+        // disable screen capture in profile
+        setScreenCaptureDisabled(mUserId, true);
 
-    // TODO: Remove this after investigation in b/28995242 is done
-    private void runDumpsysWindow() throws Exception {
-        String command = "dumpsys window displays";
-        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
-        command = "dumpsys window policy";
-        CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
+        // start the ScreenCaptureDisabledActivity in the parent
+        installAppAsUser(DEVICE_ADMIN_APK, mParentUserId);
+        startScreenCaptureDisabledActivity(mParentUserId);
+        executeDeviceTestMethod(".ScreenCaptureDisabledTest", "testScreenCapturePossible");
     }
 
     @Override
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java
index 4105012..41f7010 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java
@@ -53,13 +53,6 @@
         super.tearDown();
     }
 
-    public void testWifi() throws Exception {
-        if (hasDeviceFeature("android.hardware.wifi")) {
-            return;
-        }
-        executeProfileOwnerTest("WifiTest");
-    }
-
     private void executeProfileOwnerTest(String testClassName) throws Exception {
         if (!mHasFeature) {
             return;
diff --git a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
index aec5685..2a49857 100644
--- a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
@@ -461,7 +461,13 @@
 
         for (int i = 0; i < fpsRanges.length; i += 1) {
             fpsRange = fpsRanges[i];
-            maxPreviewSz = getMaxPreviewSizeForFpsRange(fpsRange);
+            if (mStaticInfo.isHardwareLevelLegacy()) {
+                // Legacy devices don't report minimum frame duration for preview sizes. The FPS
+                // range should be valid for any supported preview size.
+                maxPreviewSz = mOrderedPreviewSizes.get(0);
+            } else {
+                maxPreviewSz = getMaxPreviewSizeForFpsRange(fpsRange);
+            }
 
             requestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
             // Turn off auto antibanding to avoid exposure time and frame duration interference
diff --git a/tests/tests/media/src/android/media/cts/VideoDecoderPerfTest.java b/tests/tests/media/src/android/media/cts/VideoDecoderPerfTest.java
index 07f00eb..c6e0578 100644
--- a/tests/tests/media/src/android/media/cts/VideoDecoderPerfTest.java
+++ b/tests/tests/media/src/android/media/cts/VideoDecoderPerfTest.java
@@ -28,6 +28,7 @@
 import android.media.MediaExtractor;
 import android.media.MediaFormat;
 import android.util.Log;
+import android.util.Pair;
 import android.view.Surface;
 
 import com.android.compatibility.common.util.DeviceReportLog;
@@ -60,7 +61,8 @@
     private static final boolean OTHER = false;
 
     private static final int MAX_SIZE_SAMPLES_IN_MEMORY_BYTES = 12 << 20;  // 12MB
-    LinkedList<ByteBuffer> mSamplesInMemory = new LinkedList<ByteBuffer>();
+    // each sample contains the buffer and the PTS offset from the frame index
+    LinkedList<Pair<ByteBuffer, Double>> mSamplesInMemory = new LinkedList<Pair<ByteBuffer, Double>>();
     private MediaFormat mDecInputFormat;
     private MediaFormat mDecOutputFormat;
     private int mBitrate;
@@ -117,6 +119,16 @@
         int trackIndex = extractor.getSampleTrackIndex();
         MediaFormat format = extractor.getTrackFormat(trackIndex);
         String mime = format.getString(MediaFormat.KEY_MIME);
+
+        // use frame rate to calculate PTS offset used for PTS scaling
+        double frameRate = 0.; // default - 0 is used for using zero PTS offset
+        if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) {
+            frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
+        } else if (!mime.equals(MediaFormat.MIMETYPE_VIDEO_VP8)
+                && !mime.equals(MediaFormat.MIMETYPE_VIDEO_VP9)) {
+            fail("need framerate info for video file");
+        }
+
         ByteBuffer[] codecInputBuffers;
         ByteBuffer[] codecOutputBuffers;
 
@@ -125,14 +137,25 @@
             ByteBuffer tmpBuf = ByteBuffer.allocate(w * h * 3 / 2);
             int sampleSize = 0;
             int index = 0;
+            long firstPTS = 0;
+            double presentationOffset = 0.;
             while ((sampleSize = extractor.readSampleData(tmpBuf, 0 /* offset */)) > 0) {
                 if (totalMemory + sampleSize > MAX_SIZE_SAMPLES_IN_MEMORY_BYTES) {
                     break;
                 }
+                if (mSamplesInMemory.size() == 0) {
+                    firstPTS = extractor.getSampleTime();
+                }
                 ByteBuffer copied = ByteBuffer.allocate(sampleSize);
                 copied.put(tmpBuf);
-                mSamplesInMemory.addLast(copied);
+                if (frameRate > 0.) {
+                    // presentation offset is an offset from the frame index
+                    presentationOffset =
+                        (extractor.getSampleTime() - firstPTS) * frameRate / 1e6 - index;
+                }
+                mSamplesInMemory.addLast(Pair.create(copied, presentationOffset));
                 totalMemory += sampleSize;
+                ++index;
                 extractor.advance();
             }
             Log.d(TAG, mSamplesInMemory.size() + " samples in memory for " +
@@ -149,7 +172,7 @@
 
         MediaCodec codec = MediaCodec.createByCodecName(name);
         VideoCapabilities cap = codec.getCodecInfo().getCapabilitiesForType(mime).getVideoCapabilities();
-        int frameRate = cap.getSupportedFrameRatesFor(w, h).getUpper().intValue();
+        frameRate = cap.getSupportedFrameRatesFor(w, h).getUpper();
         codec.configure(format, surface, null /* crypto */, 0 /* flags */);
         codec.start();
         codecInputBuffers = codec.getInputBuffers();
@@ -174,13 +197,14 @@
 
                 if (inputBufIndex >= 0) {
                     ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
-                    ByteBuffer sample =
+                    // sample contains the buffer and the PTS offset normalized to frame index
+                    Pair<ByteBuffer, Double> sample =
                             mSamplesInMemory.get(sampleIndex++ % mSamplesInMemory.size());
-                    sample.rewind();
-                    int sampleSize = sample.remaining();
-                    dstBuf.put(sample);
-                    // use 120fps to compute pts
-                    long presentationTimeUs = inputNum * 1000000L / frameRate;
+                    sample.first.rewind();
+                    int sampleSize = sample.first.remaining();
+                    dstBuf.put(sample.first);
+                    // use max supported framerate to compute pts
+                    long presentationTimeUs = (long)((inputNum + sample.second) * 1e6 / frameRate);
 
                     long elapsed = System.currentTimeMillis() - start;
                     sawInputEOS = ((++inputNum == TOTAL_FRAMES)
diff --git a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTests.java b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTests.java
index 6444713..ac21481 100644
--- a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTests.java
+++ b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTests.java
@@ -81,8 +81,8 @@
         UiSelector acceptButtonSelector = new UiSelector().resourceId("android:id/button1");
         UiObject acceptButton = uiDevice.findObject(acceptButtonSelector);
         if (acceptButton.waitForExists(PERMISSION_DIALOG_WAIT_MS)) {
-            Log.d(TAG, "found permission dialog, dismissing...");
-            assertTrue(acceptButton.click());
+            boolean success = acceptButton.click();
+            Log.d(TAG, "found permission dialog, click attempt success = " + success);
         }
     }
 
@@ -273,7 +273,8 @@
                 },
                 new FrameLayout.LayoutParams(100, 100, Gravity.LEFT | Gravity.TOP),
                 view -> makeInfinite(ObjectAnimator.ofInt(view, "offset", 10, 30)),
-                (blackishPixelCount, width, height) -> blackishPixelCount == 100));
+                (blackishPixelCount, width, height) ->
+                        blackishPixelCount >= 90 && blackishPixelCount <= 110));
     }
 
     /**