from conf import LisaLogging
LisaLogging.setup()

%pylab inline

import json
import os

# Support to access the remote target
import devlib
from env import TestEnv

# Import support for Android devices
from android import System, Screen, Workload

# Support for trace events analysis
from trace import Trace

# Suport for FTrace events parsing and visualization
import trappy

import pandas as pd
import sqlite3

"""
Explanation: YouTube on Android
The goal of this experiment is to run Youtube videos on a Pixel device running Android and collect results.
End of explanation
"""


def experiment():
    
    # Configure governor
    target.cpufreq.set_all_governors('sched')

    # Get workload
    wload = Workload(te).getInstance(te, 'YouTube')
    
    # Run Youtube workload
    wload.run(te.res_dir, 'https://youtu.be/XSGBVzeBUbk?t=45s',
              video_duration_s=60, collect='ftrace')

    # Dump platform descriptor
    te.platform_dump(te.res_dir)

"""
Explanation: Support Functions
This function helps us run our experiments:
End of explanation
"""


# Setup target configuration
my_conf = {
    # Target platform and board
    "platform"     : 'android',
    "board"        : 'pixel',
    
    # Device
    #"device"       : "FA6A10306347",
    
    # Android home
    "ANDROID_HOME" : "/usr/local/google/home/kevindubois/Android/Sdk",

    # Folder where all the results will be collected
    "results_dir" : "Youtube_example",

    # Define devlib modules to load
    "modules"     : [
        'cpufreq'       # enable CPUFreq support
    ],

    # FTrace events to collect for all the tests configuration which have
    # the "ftrace" flag enabled
    "ftrace"  : {
         "events" : [
            "sched_switch",
            "sched_wakeup",
            "sched_wakeup_new",
            "sched_overutilized",
            "sched_load_avg_cpu",
            "sched_load_avg_task",
            "cpu_capacity",
            "cpu_frequency",
            "clock_enable",
            "clock_disable",
            "clock_set_rate"
         ],
         "buffsize" : 100 * 1024,
    },

    # Tools required by the experiments
    "tools"   : [ 'trace-cmd', 'taskset'],
}

# Initialize a test environment using:
te = TestEnv(my_conf, wipe=False)
target = te.target

"""
Explanation: Test environment setup
For more details on this please check out examples/utils/testenv_example.ipynb.
devlib requires the ANDROID_HOME environment variable configured to point to your local installation of the Android SDK. If you have not this variable configured in the shell used to start the notebook server, you need to run a cell to define where your Android SDK is installed or specify the ANDROID_HOME in your target configuration.
In case more than one Android device are conencted to the host, you must specify the ID of the device you want to target in my_target_conf. Run adb devices on your host to get the ID.
End of explanation
"""


# Intialize Workloads for this test environment
results = experiment()

"""
Explanation: Workloads execution
This is done using the experiment helper function defined above which is configured to run a Youtube experiment.
End of explanation
"""


# Benchmark statistics
db_file = os.path.join(te.res_dir, "framestats.txt")
!sed '/Stats since/,/99th/!d;/99th/q' {db_file}

# For all results:
# !cat {results['db_file']}

"""
Explanation: Benchmarks results
End of explanation
"""


# Parse all traces
platform_file = os.path.join(te.res_dir, 'platform.json')
with open(platform_file, 'r') as fh:
    platform = json.load(fh)
trace_file = os.path.join(te.res_dir, 'trace.dat')
trace = Trace(trace_file, my_conf['ftrace']['events'], platform)

trappy.plotter.plot_trace(trace.ftrace)

try:
    trace.analysis.frequency.plotClusterFrequencies();
    logging.info('Plotting cluster frequencies for [sched]...')
except: pass

trace.analysis.frequency.plotClusterFrequencies()


trace.analysis.frequency.plotPeripheralClock(title="Bus Clock", clk="bimc_clk")


"""
Explanation: Traces visualisation
For more information on this please check examples/trace_analysis/TraceAnalysis_TasksLatencies.ipynb.
End of explanation
"""


