1 /* 2 * Copyright (C) 2018 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.server.wm.flicker.monitor; 18 19 import static com.android.compatibility.common.util.SystemUtil.runShellCommand; 20 21 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; 22 23 import android.os.Environment; 24 import android.support.annotation.VisibleForTesting; 25 import android.util.Log; 26 27 import java.io.IOException; 28 import java.nio.file.Files; 29 import java.nio.file.Path; 30 import java.nio.file.Paths; 31 32 /** 33 * Captures screen contents and saves it as a mp4 video file. 34 */ 35 public class ScreenRecorder { 36 private static final String TAG = "FLICKER"; 37 private static final String OUTPUT_DIR = 38 Environment.getExternalStorageDirectory().getPath(); 39 @VisibleForTesting 40 static final Path DEFAULT_OUTPUT_PATH = Paths.get(OUTPUT_DIR , "transition.mp4"); 41 private Thread recorderThread; 42 43 @VisibleForTesting 44 static Path getPath(String testTag) { 45 return Paths.get(OUTPUT_DIR, testTag + ".mp4"); 46 } 47 48 private static Path getPath(String testTag, int iteration) { 49 return Paths.get(OUTPUT_DIR, testTag + "_" + Integer.toString(iteration) + ".mp4"); 50 } 51 52 public void start() { 53 String command = "screenrecord " + DEFAULT_OUTPUT_PATH; 54 recorderThread = new Thread(() -> { 55 try { 56 Runtime.getRuntime().exec(command); 57 } catch (IOException e) { 58 Log.e(TAG, "Error executing " + command, e); 59 } 60 }); 61 recorderThread.start(); 62 } 63 64 public void stop() { 65 runShellCommand("killall -s 2 screenrecord"); 66 try { 67 recorderThread.join(); 68 } catch (InterruptedException e) { 69 // ignore 70 } 71 } 72 73 public Path save(String testTag, int iteration) throws IOException { 74 return Files.move(DEFAULT_OUTPUT_PATH, getPath(testTag, iteration), 75 REPLACE_EXISTING); 76 } 77 78 public Path save(String testTag) throws IOException { 79 return Files.move(DEFAULT_OUTPUT_PATH, getPath(testTag), REPLACE_EXISTING); 80 } 81 } 82