Home | History | Annotate | Download | only in tests
      1 /*
      2  * Copyright (C) 2014 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.media.tests;
     18 
     19 import com.android.ddmlib.testrunner.TestIdentifier;
     20 import com.android.tradefed.config.Option;
     21 import com.android.tradefed.config.Option.Importance;
     22 import com.android.tradefed.device.CollectingOutputReceiver;
     23 import com.android.tradefed.device.DeviceNotAvailableException;
     24 import com.android.tradefed.device.ITestDevice;
     25 import com.android.tradefed.log.LogUtil.CLog;
     26 import com.android.tradefed.result.ByteArrayInputStreamSource;
     27 import com.android.tradefed.result.ITestInvocationListener;
     28 import com.android.tradefed.result.LogDataType;
     29 import com.android.tradefed.testtype.IDeviceTest;
     30 import com.android.tradefed.testtype.IRemoteTest;
     31 import com.android.tradefed.util.CommandResult;
     32 import com.android.tradefed.util.IRunUtil;
     33 import com.android.tradefed.util.RunUtil;
     34 
     35 import org.junit.Assert;
     36 
     37 import java.util.ArrayList;
     38 import java.util.Collection;
     39 import java.util.Collections;
     40 import java.util.Date;
     41 import java.util.HashMap;
     42 import java.util.Map;
     43 import java.util.concurrent.TimeUnit;
     44 import java.util.regex.Matcher;
     45 import java.util.regex.Pattern;
     46 
     47 /**
     48  * A harness that test video playback and reports result.
     49  */
     50 public class VideoMultimeterTest implements IDeviceTest, IRemoteTest {
     51 
     52     static final String RUN_KEY = "video_multimeter";
     53 
     54     @Option(name = "multimeter-util-path", description = "path for multimeter control util",
     55             importance = Importance.ALWAYS)
     56     String mMeterUtilPath = "/tmp/util.sh";
     57 
     58     @Option(name = "start-video-cmd", description = "adb shell command to start video playback; " +
     59         "use '%s' as placeholder for media source filename", importance = Importance.ALWAYS)
     60     String mCmdStartVideo = "am instrument -w -r -e media-file"
     61             + " \"%s\" -e class com.android.mediaframeworktest.stress.MediaPlayerStressTest"
     62             + " com.android.mediaframeworktest/.MediaPlayerStressTestRunner";
     63 
     64     @Option(name = "stop-video-cmd", description = "adb shell command to stop video playback",
     65             importance = Importance.ALWAYS)
     66     String mCmdStopVideo = "am force-stop com.android.mediaframeworktest";
     67 
     68     @Option(name="video-spec", description=
     69             "Comma deliminated information for test video files with the following format: " +
     70             "video_filename, reporting_key_prefix, fps, duration(in sec) " +
     71             "May be repeated for test with multiple files.")
     72     private Collection<String> mVideoSpecs = new ArrayList<>();
     73 
     74     @Option(name="wait-time-between-runs", description=
     75         "wait time between two test video measurements, in millisecond")
     76     private long mWaitTimeBetweenRuns = 3 * 60 * 1000;
     77 
     78     @Option(name="calibration-video", description=
     79         "filename of calibration video")
     80     private String mCaliVideoDevicePath = "video_cali.mp4";
     81 
     82     static final String ROTATE_LANDSCAPE = "content insert --uri content://settings/system"
     83             + " --bind name:s:user_rotation --bind value:i:1";
     84 
     85     // Max number of trailing frames to trim
     86     static final int TRAILING_FRAMES_MAX = 3;
     87     // Min threshold for duration of trailing frames
     88     static final long FRAME_DURATION_THRESHOLD_US = 500 * 1000; // 0.5s
     89 
     90     static final String CMD_GET_FRAMERATE_STATE = "GETF";
     91     static final String CMD_START_CALIBRATION = "STAC";
     92     static final String CMD_SET_CALIBRATION_VALS = "SETCAL";
     93     static final String CMD_STOP_CALIBRATION = "STOC";
     94     static final String CMD_START_MEASUREMENT = "STAM";
     95     static final String CMD_STOP_MEASUREMENT = "STOM";
     96     static final String CMD_GET_NUM_FRAMES = "GETN";
     97     static final String CMD_GET_ALL_DATA = "GETD";
     98 
     99     static final long DEVICE_SYNC_TIME_MS = 30 * 1000;
    100     static final long CALIBRATION_TIMEOUT_MS = 30 * 1000;
    101     static final long COMMAND_TIMEOUT_MS = 5 * 1000;
    102     static final long GETDATA_TIMEOUT_MS = 10 * 60 * 1000;
    103 
    104     // Regex for: "OK (time); (frame duration); (marker color); (total dropped frames)"
    105     static final String VIDEO_FRAME_DATA_PATTERN = "OK\\s+\\d+;\\s*(-?\\d+);\\s*[a-z]+;\\s*(\\d+)";
    106 
    107     // Regex for: "OK (time); (frame duration); (marker color); (total dropped frames); (lipsync)"
    108     static final String LIPSYNC_DATA_PATTERN =
    109         "OK\\s+\\d+;\\s*\\d+;\\s*[a-z]+;\\s*\\d+;\\s*(-?\\d+)";
    110 
    111     ITestDevice mDevice;
    112 
    113     /**
    114      * {@inheritDoc}
    115      */
    116     @Override
    117     public void setDevice(ITestDevice device) {
    118         mDevice = device;
    119     }
    120 
    121     /**
    122      * {@inheritDoc}
    123      */
    124     @Override
    125     public ITestDevice getDevice() {
    126         return mDevice;
    127     }
    128 
    129     private void rotateScreen() throws DeviceNotAvailableException {
    130         // rotate to landscape mode, except for manta
    131         if (!getDevice().getProductType().contains("manta")) {
    132             getDevice().executeShellCommand(ROTATE_LANDSCAPE);
    133         }
    134     }
    135 
    136     protected boolean setupTestEnv() throws DeviceNotAvailableException {
    137         return setupTestEnv(null);
    138     }
    139 
    140     protected void startPlayback(final String videoPath) {
    141         new Thread() {
    142             @Override
    143             public void run() {
    144                 try {
    145                     CollectingOutputReceiver receiver = new CollectingOutputReceiver();
    146                     getDevice().executeShellCommand(String.format(
    147                             mCmdStartVideo, videoPath),
    148                             receiver, 1L, TimeUnit.SECONDS, 0);
    149                 } catch (DeviceNotAvailableException e) {
    150                     CLog.e(e.getMessage());
    151                 }
    152             }
    153         }.start();
    154     }
    155 
    156     /**
    157      * Perform calibration process for video multimeter
    158      *
    159      * @return boolean whether calibration succeeds
    160      * @throws DeviceNotAvailableException
    161      */
    162     protected boolean doCalibration() throws DeviceNotAvailableException {
    163         // play calibration video
    164         startPlayback(mCaliVideoDevicePath);
    165         getRunUtil().sleep(3 * 1000);
    166         rotateScreen();
    167         getRunUtil().sleep(1 * 1000);
    168         CommandResult cr = getRunUtil().runTimedCmd(
    169                 COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_START_CALIBRATION);
    170         CLog.i("Starting calibration: " + cr.getStdout());
    171         // check whether multimeter is calibrated
    172         boolean isCalibrated = false;
    173         long calibrationStartTime = System.currentTimeMillis();
    174         while (!isCalibrated &&
    175                 System.currentTimeMillis() - calibrationStartTime <= CALIBRATION_TIMEOUT_MS) {
    176             getRunUtil().sleep(1 * 1000);
    177             cr = getRunUtil().runTimedCmd(2 * 1000, mMeterUtilPath, CMD_GET_FRAMERATE_STATE);
    178             if (cr.getStdout().contains("calib0")) {
    179                 isCalibrated = true;
    180             }
    181         }
    182         if (!isCalibrated) {
    183             // stop calibration if time out
    184             cr = getRunUtil().runTimedCmd(
    185                         COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_STOP_CALIBRATION);
    186             CLog.e("Calibration timed out.");
    187         } else {
    188             CLog.i("Calibration succeeds.");
    189         }
    190         getDevice().executeShellCommand(mCmdStopVideo);
    191         return isCalibrated;
    192     }
    193 
    194     protected boolean setupTestEnv(String caliValues) throws DeviceNotAvailableException {
    195         getRunUtil().sleep(DEVICE_SYNC_TIME_MS);
    196         CommandResult cr = getRunUtil().runTimedCmd(
    197                 COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_STOP_MEASUREMENT);
    198 
    199         getDevice().setDate(new Date());
    200         CLog.i("syncing device time to host time");
    201         getRunUtil().sleep(3 * 1000);
    202 
    203         // TODO: need a better way to clear old data
    204         // start and stop to clear old data
    205         cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_START_MEASUREMENT);
    206         getRunUtil().sleep(3 * 1000);
    207         cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_STOP_MEASUREMENT);
    208         getRunUtil().sleep(3 * 1000);
    209         CLog.i("Stopping measurement: " + cr.getStdout());
    210         getDevice().unlockDevice();
    211         getRunUtil().sleep(3 * 1000);
    212 
    213         if (caliValues == null) {
    214             return doCalibration();
    215         } else {
    216             CLog.i("Setting calibration values: " + caliValues);
    217             cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath,
    218                     CMD_SET_CALIBRATION_VALS + " " +  caliValues);
    219             if (cr.getStdout().contains("OK")) {
    220                 CLog.i("Calibration values are set to: " + caliValues);
    221                 return true;
    222             } else {
    223                 CLog.e("Failed to set calibration values: " + cr.getStdout());
    224                 return false;
    225             }
    226         }
    227     }
    228 
    229     private void doMeasurement(final String testVideoPath, long durationSecond)
    230             throws DeviceNotAvailableException {
    231         CommandResult cr;
    232         getDevice().clearErrorDialogs();
    233         getDevice().unlockDevice();
    234         getRunUtil().sleep(mWaitTimeBetweenRuns);
    235 
    236         // play test video
    237         startPlayback(testVideoPath);
    238 
    239         getRunUtil().sleep(3 * 1000);
    240 
    241         rotateScreen();
    242         getRunUtil().sleep(1 * 1000);
    243         cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_START_MEASUREMENT);
    244         CLog.i("Starting measurement: " + cr.getStdout());
    245 
    246         // end measurement
    247         getRunUtil().sleep(durationSecond * 1000);
    248 
    249         cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_STOP_MEASUREMENT);
    250         CLog.i("Stopping measurement: " + cr.getStdout());
    251         if (cr == null || !cr.getStdout().contains("OK")) {
    252             cr = getRunUtil().runTimedCmd(
    253                     COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_STOP_MEASUREMENT);
    254             CLog.i("Retry - Stopping measurement: " + cr.getStdout());
    255         }
    256 
    257         getDevice().executeShellCommand(mCmdStopVideo);
    258         getDevice().clearErrorDialogs();
    259     }
    260 
    261     private Map<String, String> getResult(ITestInvocationListener listener,
    262             Map<String, String> metrics, String keyprefix, float fps, boolean lipsync) {
    263         CommandResult cr;
    264 
    265         // get number of results
    266         getRunUtil().sleep(5 * 1000);
    267         cr = getRunUtil().runTimedCmd(COMMAND_TIMEOUT_MS, mMeterUtilPath, CMD_GET_NUM_FRAMES);
    268         String frameNum = cr.getStdout();
    269 
    270         CLog.i("== Video Multimeter Result '%s' ==", keyprefix);
    271         CLog.i("Number of results: " + frameNum);
    272 
    273         String nrOfDataPointsStr = extractNumberOfCollectedDataPoints(frameNum);
    274         metrics.put(keyprefix + "frame_captured", nrOfDataPointsStr);
    275 
    276         long nrOfDataPoints = Long.parseLong(nrOfDataPointsStr);
    277 
    278         Assert.assertTrue("Multimeter did not collect any data for " + keyprefix,
    279                           nrOfDataPoints > 0);
    280 
    281         CLog.i("Captured frames: " + nrOfDataPointsStr);
    282 
    283         // get all results from multimeter and write to output file
    284         cr = getRunUtil().runTimedCmd(GETDATA_TIMEOUT_MS, mMeterUtilPath, CMD_GET_ALL_DATA);
    285         String allData = cr.getStdout();
    286         listener.testLog(
    287                 keyprefix, LogDataType.TEXT, new ByteArrayInputStreamSource(allData.getBytes()));
    288 
    289         // parse results
    290         return parseResult(metrics, nrOfDataPoints, allData, keyprefix, fps, lipsync);
    291     }
    292 
    293     private String extractNumberOfCollectedDataPoints(String numFrames) {
    294         // Create pattern that matches string like "OK 14132" capturing the
    295         // number of data points.
    296         Pattern p = Pattern.compile("OK\\s+(\\d+)$");
    297         Matcher m = p.matcher(numFrames.trim());
    298 
    299         String frameCapturedStr = "0";
    300         if (m.matches()) {
    301             frameCapturedStr = m.group(1);
    302         }
    303 
    304         return frameCapturedStr;
    305     }
    306 
    307     protected void runMultimeterTest(ITestInvocationListener listener,
    308             Map<String,String> metrics) throws DeviceNotAvailableException {
    309         for (String videoSpec : mVideoSpecs) {
    310             String[] videoInfo = videoSpec.split(",");
    311             String filename = videoInfo[0].trim();
    312             String keyPrefix = videoInfo[1].trim();
    313             float fps = Float.parseFloat(videoInfo[2].trim());
    314             long duration = Long.parseLong(videoInfo[3].trim());
    315             doMeasurement(filename, duration);
    316             metrics = getResult(listener, metrics, keyPrefix, fps, true);
    317         }
    318     }
    319 
    320     /**
    321      * {@inheritDoc}
    322      */
    323     @Override
    324     public void run(ITestInvocationListener listener)
    325             throws DeviceNotAvailableException {
    326         TestIdentifier testId = new TestIdentifier(getClass()
    327                 .getCanonicalName(), RUN_KEY);
    328 
    329         listener.testRunStarted(RUN_KEY, 0);
    330         listener.testStarted(testId);
    331 
    332         long testStartTime = System.currentTimeMillis();
    333         Map<String, String> metrics = new HashMap<>();
    334 
    335         if (setupTestEnv()) {
    336             runMultimeterTest(listener, metrics);
    337         }
    338 
    339         long durationMs = System.currentTimeMillis() - testStartTime;
    340         listener.testEnded(testId, metrics);
    341         listener.testRunEnded(durationMs, metrics);
    342     }
    343 
    344     /**
    345      * Parse Multimeter result.
    346      *
    347      * @param result
    348      * @return a {@link HashMap} that contains metrics keys and results
    349      */
    350     private Map<String, String> parseResult(Map<String, String> metrics,
    351             long frameCaptured, String result, String keyprefix, float fps,
    352             boolean lipsync) {
    353         final int MISSING_FRAME_CEILING = 5; //5+ frames missing count the same
    354         final double[] MISSING_FRAME_WEIGHT = {0.0, 1.0, 2.5, 5.0, 6.25, 8.0};
    355 
    356         // Get total captured frames and calculate smoothness and freezing score
    357         // format: "OK (time); (frame duration); (marker color); (total dropped frames)"
    358         Pattern p = Pattern.compile(VIDEO_FRAME_DATA_PATTERN);
    359         Matcher m = null;
    360         String[] lines = result.split(System.getProperty("line.separator"));
    361         String totalDropFrame = "-1";
    362         String lastDropFrame = "0";
    363         long frameCount = 0;
    364         long consecutiveDropFrame = 0;
    365         double freezingPenalty = 0.0;
    366         long frameDuration = 0;
    367         double offByOne = 0;
    368         double offByMultiple = 0;
    369         double expectedFrameDurationInUs = 1000000.0 / fps;
    370         for (int i = 0; i < lines.length; i++) {
    371             m = p.matcher(lines[i].trim());
    372             if (m.matches()) {
    373                 frameDuration = Long.parseLong(m.group(1));
    374                 // frameDuration = -1 indicates dropped frame
    375                 if (frameDuration > 0) {
    376                     frameCount++;
    377                 }
    378                 totalDropFrame = m.group(2);
    379                 // trim the last few data points if needed
    380                 if (frameCount >= frameCaptured - TRAILING_FRAMES_MAX - 1 &&
    381                         frameDuration > FRAME_DURATION_THRESHOLD_US) {
    382                     metrics.put(keyprefix + "frame_captured", String.valueOf(frameCount));
    383                     break;
    384                 }
    385                 if (lastDropFrame.equals(totalDropFrame)) {
    386                     if (consecutiveDropFrame > 0) {
    387                       freezingPenalty += MISSING_FRAME_WEIGHT[(int) (Math.min(consecutiveDropFrame,
    388                               MISSING_FRAME_CEILING))] * consecutiveDropFrame;
    389                       consecutiveDropFrame = 0;
    390                     }
    391                 } else {
    392                     consecutiveDropFrame++;
    393                 }
    394                 lastDropFrame = totalDropFrame;
    395 
    396                 if (frameDuration < expectedFrameDurationInUs * 0.5) {
    397                     offByOne++;
    398                 } else if (frameDuration > expectedFrameDurationInUs * 1.5) {
    399                     if (frameDuration < expectedFrameDurationInUs * 2.5) {
    400                         offByOne++;
    401                     } else {
    402                         offByMultiple++;
    403                     }
    404                 }
    405             }
    406         }
    407         if (totalDropFrame.equals("-1")) {
    408             // no matching result found
    409             CLog.w("No result found for " + keyprefix);
    410             return metrics;
    411         } else {
    412             metrics.put(keyprefix + "frame_drop", totalDropFrame);
    413             CLog.i("Dropped frames: " + totalDropFrame);
    414         }
    415         double smoothnessScore = 100.0 - (offByOne / frameCaptured) * 100.0 -
    416                 (offByMultiple / frameCaptured) * 300.0;
    417         metrics.put(keyprefix + "smoothness", String.valueOf(smoothnessScore));
    418         CLog.i("Off by one frame: " + offByOne);
    419         CLog.i("Off by multiple frames: " + offByMultiple);
    420         CLog.i("Smoothness score: " + smoothnessScore);
    421 
    422         double freezingScore = 100.0 - 100.0 * freezingPenalty / frameCaptured;
    423         metrics.put(keyprefix + "freezing", String.valueOf(freezingScore));
    424         CLog.i("Freezing score: " + freezingScore);
    425 
    426         // parse lipsync results (the audio and video synchronization offset)
    427         // format: "OK (time); (frame duration); (marker color); (total dropped frames); (lipsync)"
    428         p = Pattern.compile(LIPSYNC_DATA_PATTERN);
    429         if (lipsync) {
    430             ArrayList<Integer> lipsyncVals = new ArrayList<>();
    431             StringBuilder lipsyncValsStr = new StringBuilder("[");
    432             long lipsyncSum = 0;
    433             for (int i = 0; i < lines.length; i++) {
    434                 m = p.matcher(lines[i].trim());
    435                 if (m.matches()) {
    436                     int lipSyncVal = Integer.parseInt(m.group(1));
    437                     lipsyncVals.add(lipSyncVal);
    438                     lipsyncValsStr.append(lipSyncVal);
    439                     lipsyncValsStr.append(", ");
    440                     lipsyncSum += lipSyncVal;
    441                 }
    442             }
    443             if (lipsyncVals.size() > 0) {
    444                 lipsyncValsStr.append("]");
    445                 CLog.i("Lipsync values: " + lipsyncValsStr);
    446                 Collections.sort(lipsyncVals);
    447                 int lipsyncCount = lipsyncVals.size();
    448                 int minLipsync = lipsyncVals.get(0);
    449                 int maxLipsync = lipsyncVals.get(lipsyncCount - 1);
    450                 metrics.put(keyprefix + "lipsync_count", String.valueOf(lipsyncCount));
    451                 CLog.i("Lipsync Count: " + lipsyncCount);
    452                 metrics.put(keyprefix + "lipsync_min", String.valueOf(lipsyncVals.get(0)));
    453                 CLog.i("Lipsync Min: " + minLipsync);
    454                 metrics.put(keyprefix + "lipsync_max", String.valueOf(maxLipsync));
    455                 CLog.i("Lipsync Max: " + maxLipsync);
    456                 double meanLipSync = (double) lipsyncSum / lipsyncCount;
    457                 metrics.put(keyprefix + "lipsync_mean", String.valueOf(meanLipSync));
    458                 CLog.i("Lipsync Mean: " + meanLipSync);
    459             } else {
    460                 CLog.w("Lipsync value not found in result.");
    461             }
    462         }
    463         CLog.i("== End ==", keyprefix);
    464         return metrics;
    465     }
    466 
    467     protected IRunUtil getRunUtil() {
    468         return RunUtil.getDefault();
    469     }
    470 }
    471