#!/usr/bin/env python3
"""Summarise GPU frequency, load, memory and frame jank from a Perfetto trace.

    pip install perfetto
    python analyze_gpu_trace.py gpu.pftrace --pkg com.example.game
    python analyze_gpu_trace.py gpu.pftrace --pkg com.example.game --tp path/to/trace_processor_shell

Sections the trace has no data for say "no data" (for example kgsl_* on a Mali
phone). With -v every SQL query is printed, so the same rows can be looked at in
ui.perfetto.dev (Query (SQL) page).

Where the numbers come from (trace processor tables, Perfetto v50+):
  frequency   counter tracks of type 'gpu_frequency'   <- power/gpu_frequency
  app GPU time slices on tracks 'android_gpu_work_period', uid in the track
              dimensions, thread_dur = active ns        <- power/gpu_work_period
  Adreno load ftrace kgsl_pwrstats busy_time/total_time  (one DCVS window each)
  memory      counter tracks 'gpu_memory' (global) / 'process_gpu_memory'
  frames      actual_frame_timeline_slice               <- SurfaceFlinger FrameTimeline
"""
import argparse
import sys

from perfetto.trace_processor import TraceProcessor, TraceProcessorConfig

NS = 1e9


def rows(tp, sql, verbose=False):
    if verbose:
        print('  sql>', ' '.join(sql.split()))
    try:
        return list(tp.query(sql))
    except Exception as e:  # table or column missing in this trace processor version
        if verbose:
            print('  (query failed: %s)' % str(e).splitlines()[0][:160])
        return None


def section(title):
    print('\n== ' + title)


def bounds(tp):
    r = rows(tp, 'select start_ts, end_ts from trace_bounds')
    return (r[0].start_ts, r[0].end_ts) if r else (0, 0)


def bar(frac, width=30):
    return '#' * int(round(width * max(0.0, min(1.0, frac))))


def gpu_frequency(tp, v):
    section('GPU frequency residency (power/gpu_frequency)')
    t0, t1 = bounds(tp)
    # power/gpu_frequency reports kHz (state=191000 is 191 MHz); kgsl_pwrlevel below reports Hz
    r = rows(tp, f'''
        with f as (
          select c.ts, c.value as khz,
                 lead(c.ts, 1, {t1}) over (partition by c.track_id order by c.ts) - c.ts as dur
          from counter c join counter_track t on c.track_id = t.id
          where t.type = 'gpu_frequency')
        select cast(khz / 1e3 as int) as mhz, sum(dur) as dur, count(*) as changes
        from f group by mhz order by mhz''', v)
    if not r:
        # Adreno also reports every power level change on its own
        r = rows(tp, f'''
            with f as (
              select ts, extract_arg(arg_set_id, 'freq') as hz,
                     lead(ts, 1, {t1}) over (order by ts) - ts as dur
              from ftrace_event where name = 'kgsl_pwrlevel')
            select cast(hz / 1e6 as int) as mhz, sum(dur) as dur, count(*) as changes
            from f group by mhz order by mhz''', v)
        if r:
            print('  (from kgsl/kgsl_pwrlevel)')
    if not r:
        print('  no data: the frequency did not change during the capture, or the event is not enabled')
        return
    total = sum(x.dur for x in r) or 1
    for x in r:
        print('  %5d MHz  %5.1f %%  %s' % (x.mhz, 100 * x.dur / total, bar(x.dur / total)))
    w = sum(x.mhz * x.dur for x in r) / total
    n = sum(x.changes for x in r)
    print('  time-weighted mean %.0f MHz, %d changes (time before the first change is not counted)' % (w, n))


def adreno_load(tp, v):
    section('Adreno load per DCVS window (kgsl/kgsl_pwrstats)')
    r = rows(tp, '''
        select extract_arg(arg_set_id, 'busy_time') as busy,
               extract_arg(arg_set_id, 'total_time') as total
        from ftrace_event where name = 'kgsl_pwrstats' ''', v)
    r = [x for x in (r or []) if x.total]
    if not r:
        print('  no data (not an Adreno device, or the event is not enabled)')
        return
    loads = sorted(x.busy / x.total for x in r)
    n = len(loads)
    win = sum(x.total for x in r) / n
    pct = lambda p: loads[min(n - 1, int(p * n))]
    print('  %d windows of about %.1f ms' % (n, win / 1000))
    print('  busy  mean %4.0f %%   p50 %4.0f %%   p90 %4.0f %%   max %4.0f %%' % (
        100 * sum(loads) / n, 100 * pct(0.5), 100 * pct(0.9), 100 * loads[-1]))
    full = sum(1 for x in loads if x >= 0.98)
    print('  windows at >= 98 %% busy: %d (%.0f %%)  <- the GPU had no idle time at all' % (full, 100 * full / n))


def gpu_work(tp, pkg, v):
    section('GPU active time per app (power/gpu_work_period)')
    r = rows(tp, '''
        with t as (
          select id, extract_arg(dimension_arg_set_id, 'uid') as uid
          from track where type = 'android_gpu_work_period')
        select t.uid as uid, count(*) as periods, sum(s.thread_dur) as active, sum(s.dur) as span
        from slice s join t on s.track_id = t.id
        group by t.uid order by active desc limit 10''', v)
    if not r:
        print('  no data (the kernel does not emit gpu_work_period, or the event is not enabled)')
        return
    names = {x.uid: x.package_name for x in (rows(tp, 'select uid, package_name from package_list') or [])}
    _, t1 = bounds(tp)
    for x in r:
        name = names.get(x.uid) or ('uid %s' % x.uid)
        if x.uid is not None and x.uid < 10000 and x.uid not in names:
            name += ' (system)'
        mark = '  <-' if pkg and name == pkg else ''
        print('  %-40s GPU active %8.1f ms in %6.2f s of periods  (%4.1f %%)%s' % (
            name[:40], (x.active or 0) / 1e6, (x.span or 0) / NS, 100 * (x.active or 0) / max(x.span or 1, 1), mark))


def gpu_memory(tp, pkg, v):
    section('GPU memory (gpu_mem/gpu_mem_total)')
    r = rows(tp, '''
        select coalesce(p.name, case when t.type = 'gpu_memory' then 'all processes' end, 'pid ?') as who,
               max(c.value) as peak, min(c.value) as low
        from counter c join counter_track t on c.track_id = t.id
        left join process_counter_track pt on pt.id = t.id
        left join process p using (upid)
        where t.type in ('gpu_memory', 'process_gpu_memory')
        group by t.id order by peak desc limit 8''', v)
    if not r:
        print('  no data')
        return
    for x in r:
        mark = '  <-' if pkg and x.who == pkg else ''
        print('  %-40s peak %7.1f MB  low %7.1f MB%s' % (x.who[:40], x.peak / 2**20, x.low / 2**20, mark))


def frames(tp, pkg, v):
    section('Frames (android.surfaceflinger.frametimeline)')
    where = "where p.name = '%s'" % pkg.replace("'", "''") if pkg else ''
    r = rows(tp, f'''
        select a.jank_type as jank, count(*) as n, cast(avg(a.dur) as int) as avg_dur, max(a.dur) as max_dur
        from actual_frame_timeline_slice a left join process p using (upid)
        {where} group by a.jank_type order by n desc''', v)
    if not r:
        print('  no data (no frames from %s in the trace)' % (pkg or 'any app'))
        return
    total = sum(x.n for x in r)
    for x in r:
        print('  %-36s %5d (%5.1f %%)  avg %6.1f ms  max %6.1f ms' % (
            x.jank[:36], x.n, 100 * x.n / total, x.avg_dur / 1e6, x.max_dur / 1e6))
    t0, _ = bounds(tp)
    worst = rows(tp, f'''
        select a.ts, a.dur, a.jank_type from actual_frame_timeline_slice a left join process p using (upid)
        {where + (' and' if where else 'where')} a.jank_type != 'None'
        order by a.dur desc limit 5''', v)
    if worst:
        print('  longest janky frames (seconds from trace start, open them in ui.perfetto.dev):')
        for x in worst:
            print('    t=%8.3f s  %6.1f ms  %s' % ((x.ts - t0) / NS, x.dur / 1e6, x.jank_type))


def adreno_batches(tp, v):
    section('Adreno submit -> retire per command batch (kgsl/adreno_cmdbatch_*, usually root only)')
    r = rows(tp, '''
        with s as (select ts, extract_arg(arg_set_id, 'id') as ctx, extract_arg(arg_set_id, 'timestamp') as stamp
                   from ftrace_event where name = 'adreno_cmdbatch_submitted'),
             d as (select ts, extract_arg(arg_set_id, 'id') as ctx, extract_arg(arg_set_id, 'timestamp') as stamp
                   from ftrace_event where name = 'adreno_cmdbatch_retired')
        select s.ctx as ctx, count(*) as n, cast(avg(d.ts - s.ts) as int) as avg_ns, max(d.ts - s.ts) as max_ns
        from s join d on s.ctx = d.ctx and s.stamp = d.stamp and d.ts >= s.ts
        group by s.ctx order by n desc limit 8''', v)
    if not r:
        print('  no data (production builds refuse these events to the shell user)')
        return
    for x in r:
        print('  context %-6s %6d batches  avg %6.2f ms  max %7.2f ms' % (x.ctx, x.n, x.avg_ns / 1e6, x.max_ns / 1e6))


def setup(tp, v):
    r = rows(tp, "select coalesce(sum(value), 0) as v from stats where name = 'ftrace_setup_errors'", v)
    if r and r[0].v:
        print('note: %d ftrace setup errors; some requested events were refused (normal on user builds)' % r[0].v)


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('trace')
    ap.add_argument('--pkg', help='process name of the app to highlight')
    ap.add_argument('--tp', help='path to trace_processor_shell (otherwise the perfetto package downloads it)')
    ap.add_argument('-v', '--verbose', action='store_true', help='print every SQL query')
    a = ap.parse_args()
    tp = TraceProcessor(trace=a.trace, config=TraceProcessorConfig(bin_path=a.tp)) if a.tp else TraceProcessor(trace=a.trace)
    try:
        setup(tp, a.verbose)
        gpu_frequency(tp, a.verbose)
        adreno_load(tp, a.verbose)
        gpu_work(tp, a.pkg, a.verbose)
        gpu_memory(tp, a.pkg, a.verbose)
        frames(tp, a.pkg, a.verbose)
        adreno_batches(tp, a.verbose)
    finally:
        tp.close()


if __name__ == '__main__':
    sys.exit(main())
