aboutsummaryrefslogtreecommitdiff
path: root/ui/src/plugins/dev.perfetto.AndroidLongBatteryTracing/index.ts
blob: 414a6620e0c8f1e81566105c8dc3389a5e6d5f8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
// Copyright (C) 2023 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.

import {Plugin, PluginContextTrace, PluginDescriptor} from '../../public';
import {EngineProxy} from '../../trace_processor/engine';
import {
  SimpleSliceTrack,
  SimpleSliceTrackConfig,
} from '../../frontend/simple_slice_track';
import {CounterOptions} from '../../frontend/base_counter_track';
import {
  SimpleCounterTrack,
  SimpleCounterTrackConfig,
} from '../../frontend/simple_counter_track';

const DEFAULT_NETWORK = `
  with base as (
      select
          ts,
          substr(s.name, 6) as conn
      from track t join slice s on t.id = s.track_id
      where t.name = 'battery_stats.conn'
  ),
  diff as (
      select
          ts,
          conn,
          conn != lag(conn) over (order by ts) as keep
      from base
  )
  select
      ts,
      ifnull(lead(ts) over (order by ts), (select end_ts from trace_bounds)) - ts as dur,
      case
        when conn like '-1:%' then 'Disconnected'
        when conn like '0:%' then 'Modem'
        when conn like '1:%' then 'WiFi'
        when conn like '4:%' then 'VPN'
        else conn
      end as name
  from diff where keep is null or keep`;

const TETHERING = `
  with base as (
      select
          ts as ts_end,
          EXTRACT_ARG(arg_set_id, 'network_tethering_reported.duration_millis') * 1000000 as dur
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
        and s.name = 'network_tethering_reported'
  )
  select ts_end - dur as ts, dur, 'Tethering' as name from base`;

const NETWORK_SUMMARY = `
  drop table if exists network_summary;
  create table network_summary as
  with base as (
      select
          cast(s.ts / 5000000000 as int) * 5000000000 as ts,
          case
              when t.name glob '*wlan*' then 'wifi'
              when t.name glob '*rmnet*' then 'modem'
              else 'unknown'
          end as dev_type,
          lower(substr(t.name, instr(t.name, ' ') + 1, 1)) || 'x' as dir,
          sum(EXTRACT_ARG(arg_set_id, 'packet_length')) AS value
      from slice s join track t on s.track_id = t.id
      where (t.name glob '*Received' or t.name glob '*Transmitted')
      and (t.name glob '*wlan*' or t.name glob '*rmnet*')
      group by 1,2,3
  ),
  zeroes as (
      select
          ts,
          dev_type,
          dir,
          value
      from base
      union all
      select
          ts + 5000000000 as ts,
          dev_type,
          dir,
          0 as value
      from base
  ),
  final as (
      select
          ts,
          dev_type,
          dir,
          sum(value) as value
      from zeroes
      group by 1, 2, 3
  )
  select * from final where ts is not null`;

const MODEM_ACTIVITY_INFO = `
  drop table if exists modem_activity_info;
  create table modem_activity_info as
  with modem_raw as (
    select
      ts,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.timestamp_millis') as timestamp_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.sleep_time_millis') as sleep_time_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_idle_time_millis') as controller_idle_time_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_tx_time_pl0_millis') as controller_tx_time_pl0_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_tx_time_pl1_millis') as controller_tx_time_pl1_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_tx_time_pl2_millis') as controller_tx_time_pl2_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_tx_time_pl3_millis') as controller_tx_time_pl3_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_tx_time_pl4_millis') as controller_tx_time_pl4_millis,
      EXTRACT_ARG(arg_set_id, 'modem_activity_info.controller_rx_time_millis') as controller_rx_time_millis
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
      and s.name = 'modem_activity_info'
  ),
  deltas as (
      select
          timestamp_millis * 1000000 as ts,
          lead(timestamp_millis) over (order by ts) - timestamp_millis as dur_millis,
          lead(sleep_time_millis) over (order by ts) - sleep_time_millis as sleep_time_millis,
          lead(controller_idle_time_millis) over (order by ts) - controller_idle_time_millis as controller_idle_time_millis,
          lead(controller_tx_time_pl0_millis) over (order by ts) - controller_tx_time_pl0_millis as controller_tx_time_pl0_millis,
          lead(controller_tx_time_pl1_millis) over (order by ts) - controller_tx_time_pl1_millis as controller_tx_time_pl1_millis,
          lead(controller_tx_time_pl2_millis) over (order by ts) - controller_tx_time_pl2_millis as controller_tx_time_pl2_millis,
          lead(controller_tx_time_pl3_millis) over (order by ts) - controller_tx_time_pl3_millis as controller_tx_time_pl3_millis,
          lead(controller_tx_time_pl4_millis) over (order by ts) - controller_tx_time_pl4_millis as controller_tx_time_pl4_millis,
          lead(controller_rx_time_millis) over (order by ts) - controller_rx_time_millis as controller_rx_time_millis
      from modem_raw
  ),
  ratios as (
      select
          ts,
          100.0 * sleep_time_millis / dur_millis as sleep_time_ratio,
          100.0 * controller_idle_time_millis / dur_millis as controller_idle_time_ratio,
          100.0 * controller_tx_time_pl0_millis / dur_millis as controller_tx_time_pl0_ratio,
          100.0 * controller_tx_time_pl1_millis / dur_millis as controller_tx_time_pl1_ratio,
          100.0 * controller_tx_time_pl2_millis / dur_millis as controller_tx_time_pl2_ratio,
          100.0 * controller_tx_time_pl3_millis / dur_millis as controller_tx_time_pl3_ratio,
          100.0 * controller_tx_time_pl4_millis / dur_millis as controller_tx_time_pl4_ratio,
          100.0 * controller_rx_time_millis / dur_millis as controller_rx_time_ratio
      from deltas
  )
  select * from ratios where sleep_time_ratio is not null and sleep_time_ratio >= 0`;

const MODEM_RIL_STRENGTH = `
  DROP VIEW IF EXISTS ScreenOn;
  CREATE VIEW ScreenOn AS
  SELECT ts, dur FROM (
      SELECT
          ts, value,
          LEAD(ts, 1, TRACE_END()) OVER (ORDER BY ts)-ts AS dur
      FROM counter, track ON (counter.track_id = track.id)
      WHERE track.name = 'ScreenState'
  ) WHERE value = 2;

  DROP VIEW IF EXISTS RilSignalStrength;
  CREATE VIEW RilSignalStrength AS
  With RilMessages AS (
      SELECT
          ts, slice.name,
          LEAD(ts, 1, TRACE_END()) OVER (ORDER BY ts)-ts AS dur
      FROM slice, track
      ON (slice.track_id = track.id)
      WHERE track.name = 'RIL'
        AND slice.name GLOB 'UNSOL_SIGNAL_STRENGTH*'
  ),
  BandTypes(band_ril, band_name) AS (
      VALUES ("CellSignalStrengthLte:", "LTE"),
              ("CellSignalStrengthNr:", "NR")
  ),
  ValueTypes(value_ril, value_name) AS (
      VALUES ("rsrp=", "rsrp"),
              ("rssi=", "rssi")
  ),
  Extracted AS (
      SELECT ts, dur, band_name, value_name, (
          SELECT CAST(SUBSTR(key_str, start_idx+1, end_idx-start_idx-1) AS INT64) AS value
          FROM (
              SELECT key_str, INSTR(key_str, "=") AS start_idx, INSTR(key_str, " ") AS end_idx
              FROM (
                  SELECT SUBSTR(band_str, INSTR(band_str, value_ril)) AS key_str
                  FROM (SELECT SUBSTR(name, INSTR(name, band_ril)) AS band_str)
              )
          )
      ) AS value
      FROM RilMessages
      JOIN BandTypes
      JOIN ValueTypes
  )
  SELECT
  ts, dur, band_name, value_name, value,
  value_name || "=" || IIF(value = 2147483647, "unknown", ""||value) AS name,
  ROW_NUMBER() OVER (ORDER BY ts) as id,
  DENSE_RANK() OVER (ORDER BY band_name, value_name) AS track_id
  FROM Extracted;

  DROP TABLE IF EXISTS RilScreenOn;
  CREATE VIRTUAL TABLE RilScreenOn
  USING SPAN_JOIN(RilSignalStrength PARTITIONED track_id, ScreenOn)`;

const MODEM_RIL_CHANNELS_PREAMBLE = `
  CREATE OR REPLACE PERFETTO FUNCTION EXTRACT_KEY_VALUE(source STRING, key_name STRING) RETURNS STRING AS
  SELECT SUBSTR(trimmed, INSTR(trimmed, "=")+1, INSTR(trimmed, ",") - INSTR(trimmed, "=") - 1)
  FROM (SELECT SUBSTR($source, INSTR($source, $key_name)) AS trimmed);`;

const MODEM_RIL_CHANNELS = `
  With RawChannelConfig AS (
      SELECT ts, slice.name AS raw_config
      FROM slice, track
      ON (slice.track_id = track.id)
      WHERE track.name = 'RIL'
      AND slice.name LIKE 'UNSOL_PHYSICAL_CHANNEL_CONFIG%'
  ),
  Attributes(attribute, attrib_name) AS (
      VALUES ("mCellBandwidthDownlinkKhz", "downlink"),
          ("mCellBandwidthUplinkKhz", "uplink"),
          ("mNetworkType", "network"),
          ("mBand", "band")
  ),
  Slots(idx, slot_name) AS (
      VALUES (0, "primary"),
          (1, "secondary 1"),
          (2, "secondary 2")
  ),
  Stage1 AS (
      SELECT *, IFNULL(EXTRACT_KEY_VALUE(STR_SPLIT(raw_config, "}, {", idx), attribute), "") AS name
      FROM RawChannelConfig
      JOIN Attributes
      JOIN Slots
  ),
  Stage2 AS (
      SELECT *, LAG(name) OVER (PARTITION BY idx, attribute ORDER BY ts) AS last_name
      FROM Stage1
  ),
  Stage3 AS (
      SELECT *, LEAD(ts, 1, TRACE_END()) OVER (PARTITION BY idx, attribute ORDER BY ts) - ts AS dur
      FROM Stage2 WHERE name != last_name
  )
  SELECT ts, dur, slot_name || "-" || attrib_name || "=" || name AS name
  FROM Stage3`;

const MODEM_CELL_RESELECTION = `
  with base as (
    select
        ts,
        s.name as raw_ril,
        ifnull(str_split(str_split(s.name, 'CellIdentityLte{', 1), ', operatorNames', 0),
            str_split(str_split(s.name, 'CellIdentityNr{', 1), ', operatorNames', 0)) as cell_id
    from track t join slice s on t.id = s.track_id
    where t.name = 'RIL' and s.name like '%DATA_REGISTRATION_STATE%'
  ),
  base2 as (
    select
        ts,
        raw_ril,
        case
            when cell_id like '%earfcn%' then 'LTE ' || cell_id
            when cell_id like '%nrarfcn%' then 'NR ' || cell_id
            when cell_id is null then 'Unknown'
            else cell_id
        end as cell_id
    from base
  ),
  base3 as (
    select ts, cell_id , lag(cell_id) over (order by ts) as lag_cell_id, raw_ril
    from base2
  )
  select ts, 0 as dur, cell_id as name, raw_ril
  from base3
  where cell_id != lag_cell_id
  order by ts`;

const SUSPEND_RESUME = `
  SELECT
    ts,
    dur,
    'Suspended' AS name
  FROM android_suspend_state
  WHERE power_state = 'suspended'`;

const SCREEN_STATE = `
  WITH _counter AS (
    SELECT counter.id, ts, 0 AS track_id, value
    FROM counter
    JOIN counter_track ON counter_track.id = counter.track_id
    WHERE name = 'ScreenState'
  )
  SELECT
    ts,
    dur,
    CASE value
      WHEN 1 THEN 'Screen off'
      WHEN 2 THEN 'Screen on'
      WHEN 3 THEN 'Always-on display (doze)'
      ELSE 'unknown'
    END AS name
  FROM counter_leading_intervals!(_counter)`;

// See DeviceIdleController.java for where these states come from and how
// they transition.
const DOZE_LIGHT = `
  WITH _counter AS (
    SELECT counter.id, ts, 0 AS track_id, value
    FROM counter
    JOIN counter_track ON counter_track.id = counter.track_id
    WHERE name = 'DozeLightState'
  )
  SELECT
    ts,
    dur,
    CASE value
      WHEN 0 THEN 'active'
      WHEN 1 THEN 'inactive'
      WHEN 4 THEN 'idle'
      WHEN 5 THEN 'waiting_for_network'
      WHEN 6 THEN 'idle_maintenance'
      WHEN 7 THEN 'override'
      ELSE 'unknown'
    END AS name
  FROM counter_leading_intervals!(_counter)`;

const DOZE_DEEP = `
  WITH _counter AS (
    SELECT counter.id, ts, 0 AS track_id, value
    FROM counter
    JOIN counter_track ON counter_track.id = counter.track_id
    WHERE name = 'DozeDeepState'
  )
  SELECT
    ts,
    dur,
    CASE value
      WHEN 0 THEN 'active'
      WHEN 1 THEN 'inactive'
      WHEN 2 THEN 'idle_pending'
      WHEN 3 THEN 'sensing'
      WHEN 4 THEN 'locating'
      WHEN 5 THEN 'idle'
      WHEN 6 THEN 'idle_maintenance'
      WHEN 7 THEN 'quick_doze_delay'
      ELSE 'unknown'
    END AS name
  FROM counter_leading_intervals!(_counter)`;

const CHARGING = `
  WITH _counter AS (
    SELECT counter.id, ts, 0 AS track_id, value
    FROM counter
    JOIN counter_track ON counter_track.id = counter.track_id
    WHERE name = 'BatteryStatus'
  )
  SELECT
    ts,
    dur,
    CASE value
      -- 0 and 1 are both unknown
      WHEN 2 THEN 'Charging'
      WHEN 3 THEN 'Discharging'
      -- special case when charger is present but battery isn't charging
      WHEN 4 THEN 'Not charging'
      WHEN 5 THEN 'Full'
      ELSE 'unknown'
    END AS name
  FROM counter_leading_intervals!(_counter)`;

const THERMAL_THROTTLING = `
  with step1 as (
      select
          ts,
          EXTRACT_ARG(arg_set_id, 'thermal_throttling_severity_state_changed.sensor_type') as sensor_type,
          EXTRACT_ARG(arg_set_id, 'thermal_throttling_severity_state_changed.sensor_name') as sensor_name,
          EXTRACT_ARG(arg_set_id, 'thermal_throttling_severity_state_changed.temperature_deci_celsius') / 10.0 as temperature_celcius,
          EXTRACT_ARG(arg_set_id, 'thermal_throttling_severity_state_changed.severity') as severity
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
      and s.name = 'thermal_throttling_severity_state_changed'
  ),
  step2 as (
      select
          ts,
          lead(ts) over (partition by sensor_type, sensor_name order by ts) - ts as dur,
          sensor_type,
          sensor_name,
          temperature_celcius,
          severity
      from step1
      where sensor_type not like 'TEMPERATURE_TYPE_BCL_%'
  )
  select
    ts,
    dur,
    case sensor_name
        when 'VIRTUAL-SKIN' then ''
        else sensor_name || ' is '
    end || severity || ' (' || temperature_celcius || 'C)' as name
  from step2
  where severity != 'NONE'`;

const KERNEL_WAKELOCKS = `
  drop table if exists kernel_wakelocks;
  create table kernel_wakelocks as
  with step1 as (
    select
      ts,
      EXTRACT_ARG(arg_set_id, 'kernel_wakelock.name') as wakelock_name,
      EXTRACT_ARG(arg_set_id, 'kernel_wakelock.count') as count,
      EXTRACT_ARG(arg_set_id, 'kernel_wakelock.time_micros') as time_micros
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
      and s.name = 'kernel_wakelock'
  ),
  step2 as (
    select
      ts,
      wakelock_name,
      lead(ts) over (partition by wakelock_name order by ts) as ts_end,
      lead(count) over (partition by wakelock_name order by ts) - count as count,
      (lead(time_micros) over (partition by wakelock_name order by ts) - time_micros) * 1000 as wakelock_dur
    from step1
  ),
  step3 as (
    select
      ts,
      ts_end,
      ifnull((select sum(dur) from android_suspend_state s
              where power_state = 'suspended'
                and s.ts > step2.ts
                and s.ts < step2.ts_end), 0) as suspended_dur,
      wakelock_name,
      count,
      wakelock_dur
    from step2
    where wakelock_dur is not null
      and wakelock_dur >= 0
  )
  select
    ts,
    ts_end - ts as dur,
    wakelock_name,
    min(100.0 * wakelock_dur / (ts_end - ts - suspended_dur), 100) as value
  from step3`;

const KERNEL_WAKELOCKS_SUMMARY = `
  select wakelock_name, max(value) as max_value
  from kernel_wakelocks
  where wakelock_name not in ('PowerManager.SuspendLockout', 'PowerManagerService.Display')
  group by 1
  having max_value > 1
  order by 1;`;

const HIGH_CPU = `
  drop table if exists high_cpu;
  create table high_cpu as
  with base as (
    select
      ts,
      EXTRACT_ARG(arg_set_id, 'cpu_cycles_per_uid_cluster.uid') as uid,
      EXTRACT_ARG(arg_set_id, 'cpu_cycles_per_uid_cluster.cluster') as cluster,
      sum(EXTRACT_ARG(arg_set_id, 'cpu_cycles_per_uid_cluster.time_millis')) as time_millis
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
      and s.name = 'cpu_cycles_per_uid_cluster'
    group by 1, 2, 3
  ),
  with_windows as (
    select
      ts,
      uid,
      cluster,
      lead(ts) over (partition by uid, cluster order by ts) - ts as dur,
      (lead(time_millis) over (partition by uid, cluster order by ts) - time_millis) * 1000000.0 as cpu_dur
    from base
  ),
  app_package_list as (
    select
      uid,
      group_concat(package_name) as package_name
    from package_list
    where uid >= 10000
    group by 1
  ),
  with_ratio as (
    select
      ts,
      100.0 * cpu_dur / dur as value,
      dur,
      case cluster when 0 then 'little' when 1 then 'mid' when 2 then 'big' else 'cl-' || cluster end as cluster,
      case
          when uid = 0 then 'AID_ROOT'
          when uid = 1000 then 'AID_SYSTEM_USER'
          when uid = 1001 then 'AID_RADIO'
          when uid = 1082 then 'AID_ARTD'
          when pl.package_name is null then 'uid=' || uid
          else pl.package_name
      end as pkg
    from with_windows left join app_package_list pl using(uid)
    where cpu_dur is not null
  ),
  with_zeros as (
      select ts, value, cluster, pkg
      from with_ratio
      union all
      select ts + dur as ts, 0 as value, cluster, pkg
      from with_ratio
  )
  select ts, sum(value) as value, cluster, pkg
  from with_zeros
  group by 1, 3, 4`;

const WAKEUPS = `
  drop table if exists wakeups;
  create table wakeups as
  with wakeup_reason as (
      select
      ts,
      substr(i.name, 0, instr(i.name, ' ')) as id_timestamp,
      substr(i.name, instr(i.name, ' ') + 1) as raw_wakeup
      from track t join instant i on t.id = i.track_id
      where t.name = 'wakeup_reason'
  ),
  wakeup_attribution as (
      select
      substr(i.name, 0, instr(i.name, ' ')) as id_timestamp,
      substr(i.name, instr(i.name, ' ') + 1) as attribution
      from track t join instant i on t.id = i.track_id
      where t.name = 'wakeup_attribution'
  ),
  step1 as(
    select
      ts,
      raw_wakeup,
      attribution,
      null as raw_backoff
    from wakeup_reason r
      left outer join wakeup_attribution using(id_timestamp)
    union all
    select
      ts,
      null as raw_wakeup,
      null as attribution,
      i.name as raw_backoff
    from track t join instant i on t.id = i.track_id
    where t.name = 'suspend_backoff'
  ),
  step2 as (
    select
      ts,
      raw_wakeup,
      attribution,
      lag(raw_backoff) over (order by ts) as raw_backoff
    from step1
  ),
  step3 as (
    select
      ts,
      raw_wakeup,
      attribution,
      str_split(raw_backoff, ' ', 0) as suspend_quality,
      str_split(raw_backoff, ' ', 1) as backoff_state,
      str_split(raw_backoff, ' ', 2) as backoff_reason,
      cast(str_split(raw_backoff, ' ', 3) as int) as backoff_count,
      cast(str_split(raw_backoff, ' ', 4) as int) as backoff_millis,
      false as suspend_end
    from step2
    where raw_wakeup is not null
    union all
    select
      ts,
      null as raw_wakeup,
      null as attribution,
      null as suspend_quality,
      null as backoff_state,
      null as backoff_reason,
      null as backoff_count,
      null as backoff_millis,
      true as suspend_end
    from android_suspend_state
    where power_state = 'suspended'
  ),
  step4 as (
    select
      ts,
      case suspend_quality
        when 'good' then
          min(
            lead(ts, 1, ts + 5e9) over (order by ts) - ts,
            5e9
          )
        when 'bad' then backoff_millis * 1000000
        else 0
      end as dur,
      raw_wakeup,
      attribution,
      suspend_quality,
      backoff_state,
      backoff_reason,
      backoff_count,
      backoff_millis,
      suspend_end
    from step3
  ),
  step5 as (
    select
      ts,
      dur,
      raw_wakeup,
      attribution,
      suspend_quality,
      backoff_state,
      backoff_reason,
      backoff_count,
      backoff_millis
    from step4
    where not suspend_end
  ),
  step6 as (
    select
      ts,
      dur,
      raw_wakeup,
      attribution,
      suspend_quality,
      backoff_state,
      backoff_reason,
      backoff_count,
      backoff_millis,
      case
        when raw_wakeup like 'Abort: Pending Wakeup Sources: %' then 'abort_pending'
        when raw_wakeup like 'Abort: Last active Wakeup Source: %' then 'abort_last_active'
        when raw_wakeup like 'Abort: %' then 'abort_other'
        else 'normal'
      end as type,
      case
        when raw_wakeup like 'Abort: Pending Wakeup Sources: %' then substr(raw_wakeup, 32)
        when raw_wakeup like 'Abort: Last active Wakeup Source: %' then substr(raw_wakeup, 35)
        when raw_wakeup like 'Abort: %' then substr(raw_wakeup, 8)
        else raw_wakeup
      end as main,
      case
        when raw_wakeup like 'Abort: Pending Wakeup Sources: %' then ' '
        when raw_wakeup like 'Abort: %' then 'no delimiter needed'
        else ':'
      end as delimiter
    from step5
  ),
  step7 as (
    select
      ts,
      dur,
      raw_wakeup,
      attribution,
      suspend_quality,
      backoff_state,
      backoff_reason,
      backoff_count,
      backoff_millis,
      type,
      str_split(main, delimiter, 0) as item_0,
      str_split(main, delimiter, 1) as item_1,
      str_split(main, delimiter, 2) as item_2,
      str_split(main, delimiter, 3) as item_3
    from step6
  ),
  step8 as (
    select ts, dur, raw_wakeup, attribution, suspend_quality, backoff_state, backoff_reason, backoff_count, backoff_millis, type, item_0 as item from step7
    union all
    select ts, dur, raw_wakeup, attribution, suspend_quality, backoff_state, backoff_reason, backoff_count, backoff_millis, type, item_1 as item from step7 where item_1 is not null
    union all
    select ts, dur, raw_wakeup, attribution, suspend_quality, backoff_state, backoff_reason, backoff_count, backoff_millis, type, item_2 as item from step7 where item_2 is not null
    union all
    select ts, dur, raw_wakeup, attribution, suspend_quality, backoff_state, backoff_reason, backoff_count, backoff_millis, type, item_3 as item from step7 where item_3 is not null
  )
  select
    ts,
    dur,
    ts + dur as ts_end,
    raw_wakeup,
    attribution,
    suspend_quality,
    backoff_state,
    ifnull(backoff_reason, 'none') as backoff_reason,
    backoff_count,
    backoff_millis,
    type,
    case when type = 'normal' then ifnull(str_split(item, ' ', 1), item) else item end as item
  from step8`;

const WAKEUPS_COLUMNS = [
  'item',
  'type',
  'raw_wakeup',
  'attribution',
  'suspend_quality',
  'backoff_state',
  'backoff_reason',
  'backoff_count',
  'backoff_millis',
];

function bleScanQuery(condition: string) {
  return `
  with step1 as (
      select
          ts,
          extract_arg(arg_set_id, 'ble_scan_state_changed.attribution_node[0].tag') as name,
          extract_arg(arg_set_id, 'ble_scan_state_changed.is_opportunistic') as opportunistic,
          extract_arg(arg_set_id, 'ble_scan_state_changed.is_filtered') as filtered,
          extract_arg(arg_set_id, 'ble_scan_state_changed.state') as state
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
      and s.name = 'ble_scan_state_changed'
  ),
  step2 as (
      select
          ts,
          name,
          state,
          opportunistic,
          filtered,
          lead(ts) over (partition by name order by ts) - ts as dur
      from step1
  )
  select ts, dur, name from step2 where state = 'ON' and ${condition} and dur is not null`;
}

const BLE_RESULTS = `
  with step1 as (
      select
          ts,
          extract_arg(arg_set_id, 'ble_scan_result_received.attribution_node[0].tag') as name,
          extract_arg(arg_set_id, 'ble_scan_result_received.num_results') as num_results
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
      and s.name = 'ble_scan_result_received'
  )
  select
      ts,
      0 as dur,
      name || ' (' || num_results || ' results)' as name
  from step1`;

const BT_A2DP_AUDIO = `
  with step1 as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_a2dp_playback_state_changed.playback_state') as playback_state,
        EXTRACT_ARG(arg_set_id, 'bluetooth_a2dp_playback_state_changed.audio_coding_mode') as audio_coding_mode,
        EXTRACT_ARG(arg_set_id, 'bluetooth_a2dp_playback_state_changed.metric_id') as metric_id
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_a2dp_playback_state_changed'
  ),
  step2 as (
    select
        ts,
        lead(ts) over (partition by metric_id order by ts) - ts as dur,
        playback_state,
        audio_coding_mode,
        metric_id
    from step1
  )
  select
    ts,
    dur,
    audio_coding_mode as name
  from step2
  where playback_state = 'PLAYBACK_STATE_PLAYING'`;

const BT_CONNS_ACL = `
    with acl1 as (
        select
            ts,
            EXTRACT_ARG(arg_set_id, 'bluetooth_acl_connection_state_changed.state') as state,
            EXTRACT_ARG(arg_set_id, 'bluetooth_acl_connection_state_changed.transport') as transport,
            EXTRACT_ARG(arg_set_id, 'bluetooth_acl_connection_state_changed.metric_id') as metric_id
        from track t join slice s on t.id = s.track_id
        where t.name = 'Statsd Atoms'
        and s.name = 'bluetooth_acl_connection_state_changed'
    ),
    acl2 as (
        select
            ts,
            lead(ts) over (partition by metric_id, transport order by ts) - ts as dur,
            state,
            transport,
            metric_id
        from acl1
    )
    select
        ts,
        dur,
        'Device ' || metric_id ||
          ' (' || case transport when 'TRANSPORT_TYPE_BREDR' then 'Classic' when 'TRANSPORT_TYPE_LE' then 'BLE' end || ')' as name
    from acl2
    where state != 'CONNECTION_STATE_DISCONNECTED' and dur is not null`;

const BT_CONNS_SCO = `
  with sco1 as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_sco_connection_state_changed.state') as state,
        EXTRACT_ARG(arg_set_id, 'bluetooth_sco_connection_state_changed.codec') as codec,
        EXTRACT_ARG(arg_set_id, 'bluetooth_sco_connection_state_changed.metric_id') as metric_id
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_sco_connection_state_changed'
  ),
  sco2 as (
    select
        ts,
        lead(ts) over (partition by metric_id, codec order by ts) - ts as dur,
        state,
        codec,
        metric_id
    from sco1
  )
  select
    ts,
    dur,
    case state when 'CONNECTION_STATE_CONNECTED' then '' when 'CONNECTION_STATE_CONNECTING' then 'Connecting ' when 'CONNECTION_STATE_DISCONNECTING' then 'Disconnecting ' else 'unknown ' end ||
      'Device ' || metric_id || ' (' ||
      case codec when 'SCO_CODEC_CVSD' then 'CVSD' when 'SCO_CODEC_MSBC' then 'MSBC' end || ')' as name
  from sco2
  where state != 'CONNECTION_STATE_DISCONNECTED' and dur is not null`;

const BT_LINK_LEVEL_EVENTS = `
  with base as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.direction') as direction,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.type') as type,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.hci_cmd') as hci_cmd,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.hci_event') as hci_event,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.hci_ble_event') as hci_ble_event,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.cmd_status') as cmd_status,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.reason_code') as reason_code,
        EXTRACT_ARG(arg_set_id, 'bluetooth_link_layer_connection_event.metric_id') as metric_id
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_link_layer_connection_event'
  )
  select
    *,
    0 as dur,
    'Device '|| metric_id as name
  from base`;

const BT_LINK_LEVEL_EVENTS_COLUMNS = [
  'direction',
  'type',
  'hci_cmd',
  'hci_event',
  'hci_ble_event',
  'cmd_status',
  'reason_code',
  'metric_id',
];

const BT_QUALITY_REPORTS = `
  with base as (
      select
          ts,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.quality_report_id') as quality_report_id,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.packet_types') as packet_types,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.connection_handle') as connection_handle,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.connection_role') as connection_role,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.tx_power_level') as tx_power_level,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.rssi') as rssi,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.snr') as snr,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.unused_afh_channel_count') as unused_afh_channel_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.afh_select_unideal_channel_count') as afh_select_unideal_channel_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.lsto') as lsto,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.connection_piconet_clock') as connection_piconet_clock,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.retransmission_count') as retransmission_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.no_rx_count') as no_rx_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.nak_count') as nak_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.flow_off_count') as flow_off_count,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.buffer_overflow_bytes') as buffer_overflow_bytes,
          EXTRACT_ARG(arg_set_id, 'bluetooth_quality_report_reported.buffer_underflow_bytes') as buffer_underflow_bytes
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
      and s.name = 'bluetooth_quality_report_reported'
  )
  select
      *,
      0 as dur,
      'Connection '|| connection_handle as name
  from base`;

const BT_QUALITY_REPORTS_COLUMNS = [
  'quality_report_id',
  'packet_types',
  'connection_handle',
  'connection_role',
  'tx_power_level',
  'rssi',
  'snr',
  'unused_afh_channel_count',
  'afh_select_unideal_channel_count',
  'lsto',
  'connection_piconet_clock',
  'retransmission_count',
  'no_rx_count',
  'nak_count',
  'flow_off_count',
  'buffer_overflow_bytes',
  'buffer_underflow_bytes',
];

const BT_RSSI_REPORTS = `
  with base as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_device_rssi_reported.connection_handle') as connection_handle,
        EXTRACT_ARG(arg_set_id, 'bluetooth_device_rssi_reported.hci_status') as hci_status,
        EXTRACT_ARG(arg_set_id, 'bluetooth_device_rssi_reported.rssi') as rssi,
        EXTRACT_ARG(arg_set_id, 'bluetooth_device_rssi_reported.metric_id') as metric_id
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_device_rssi_reported'
  )
  select
    *,
    0 as dur,
    'Connection '|| connection_handle as name
  from base`;

const BT_RSSI_REPORTS_COLUMNS = [
  'connection_handle',
  'hci_status',
  'rssi',
  'metric_id',
];

const BT_CODE_PATH_COUNTER = `
  with base as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_code_path_counter.key') as key,
        EXTRACT_ARG(arg_set_id, 'bluetooth_code_path_counter.number') as number
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_code_path_counter'
  )
  select
    *,
    0 as dur,
    key as name
  from base`;

const BT_CODE_PATH_COUNTER_COLUMNS = ['key', 'number'];

const BT_HAL_CRASHES = `
  with base as (
      select
          ts,
          EXTRACT_ARG(arg_set_id, 'bluetooth_hal_crash_reason_reported.metric_id') as metric_id,
          EXTRACT_ARG(arg_set_id, 'bluetooth_hal_crash_reason_reported.error_code') as error_code,
          EXTRACT_ARG(arg_set_id, 'bluetooth_hal_crash_reason_reported.vendor_error_code') as vendor_error_code
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'
      and s.name = 'bluetooth_hal_crash_reason_reported'
  )
  select
      *,
      0 as dur,
      'Device ' || metric_id as name
  from base`;

const BT_HAL_CRASHES_COLUMNS = ['metric_id', 'error_code', 'vendor_error_code'];

const BT_BYTES = `
  with step1 as (
    select
        ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_bytes_transfer.uid') as uid,
        EXTRACT_ARG(arg_set_id, 'bluetooth_bytes_transfer.tx_bytes') as tx_bytes,
        EXTRACT_ARG(arg_set_id, 'bluetooth_bytes_transfer.rx_bytes') as rx_bytes
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_bytes_transfer'
  ),
  step2 as (
    select
        ts,
        lead(ts) over (partition by uid order by ts) - ts as dur,
        uid,
        lead(tx_bytes) over (partition by uid order by ts) - tx_bytes as tx_bytes,
        lead(rx_bytes) over (partition by uid order by ts) - rx_bytes as rx_bytes
    from step1
  ),
  step3 as (
    select
        ts,
        dur,
        uid % 100000 as uid,
        sum(tx_bytes) as tx_bytes,
        sum(rx_bytes) as rx_bytes
    from step2
    where tx_bytes >=0 and rx_bytes >=0
    group by 1,2,3
    having tx_bytes > 0 or rx_bytes > 0
  ),
  app_package_list as (
  select
    uid,
    group_concat(package_name) as package_name
  from package_list
  where uid >= 10000
  group by 1
  )
    select
        ts,
        dur,
        case
            when pl.package_name is null then 'uid=' || uid
            else pl.package_name
        end || ' TX ' || tx_bytes || ' bytes / RX ' || rx_bytes || ' bytes' as name
    from step3 left join app_package_list pl using(uid)
`;

// See go/bt_system_context_report for reference on the bit-twiddling.
const BT_ACTIVITY = `
  create perfetto table bt_activity as
  with step1 as (
    select
        EXTRACT_ARG(arg_set_id, 'bluetooth_activity_info.timestamp_millis') * 1000000 as ts,
        EXTRACT_ARG(arg_set_id, 'bluetooth_activity_info.bluetooth_stack_state') as bluetooth_stack_state,
        EXTRACT_ARG(arg_set_id, 'bluetooth_activity_info.controller_idle_time_millis') * 1000000 as controller_idle_dur,
        EXTRACT_ARG(arg_set_id, 'bluetooth_activity_info.controller_tx_time_millis') * 1000000 as controller_tx_dur,
        EXTRACT_ARG(arg_set_id, 'bluetooth_activity_info.controller_rx_time_millis') * 1000000 as controller_rx_dur
    from track t join slice s on t.id = s.track_id
    where t.name = 'Statsd Atoms'
    and s.name = 'bluetooth_activity_info'
  ),
  step2 as (
    select
        ts,
        lead(ts) over (order by ts) - ts as dur,
        bluetooth_stack_state,
        lead(controller_idle_dur) over (order by ts) - controller_idle_dur as controller_idle_dur,
        lead(controller_tx_dur) over (order by ts) - controller_tx_dur as controller_tx_dur,
        lead(controller_rx_dur) over (order by ts) - controller_rx_dur as controller_rx_dur
    from step1
  )
  select
    ts,
    dur,
    bluetooth_stack_state & 0x0000000F as acl_active_count,
    bluetooth_stack_state & 0x000000F0 >> 4 as acl_sniff_count,
    bluetooth_stack_state & 0x00000F00 >> 8 as acl_ble_count,
    bluetooth_stack_state & 0x0000F000 >> 12 as advertising_count,
    case bluetooth_stack_state & 0x000F0000 >> 16
      when 0 then 0
      when 1 then 5
      when 2 then 10
      when 3 then 25
      when 4 then 100
      else -1
    end as le_scan_duty_cycle,
    bluetooth_stack_state & 0x00100000 >> 20 as inquiry_active,
    bluetooth_stack_state & 0x00200000 >> 21 as sco_active,
    bluetooth_stack_state & 0x00400000 >> 22 as a2dp_active,
    bluetooth_stack_state & 0x00800000 >> 23 as le_audio_active,
    max(0, 100.0 * controller_idle_dur / dur) as controller_idle_pct,
    max(0, 100.0 * controller_tx_dur / dur) as controller_tx_pct,
    max(0, 100.0 * controller_rx_dur / dur) as controller_rx_pct
  from step2
`;

class AndroidLongBatteryTracing implements Plugin {
  addSliceTrack(
    ctx: PluginContextTrace,
    name: string,
    query: string,
    groupName?: string,
    columns: string[] = [],
  ): void {
    const config: SimpleSliceTrackConfig = {
      data: {
        sqlSource: query,
        columns: ['ts', 'dur', 'name', ...columns],
      },
      columns: {ts: 'ts', dur: 'dur', name: 'name'},
      argColumns: columns,
    };
    ctx.registerStaticTrack({
      uri: `dev.perfetto.AndroidLongBatteryTracing#${name}`,
      displayName: name,
      trackFactory: (trackCtx) => {
        return new SimpleSliceTrack(ctx.engine, trackCtx, config);
      },
      groupName,
    });
  }

  addCounterTrack(
    ctx: PluginContextTrace,
    name: string,
    query: string,
    groupName: string,
    options?: Partial<CounterOptions>,
  ): void {
    const config: SimpleCounterTrackConfig = {
      data: {
        sqlSource: query,
        columns: ['ts', 'value'],
      },
      columns: {ts: 'ts', value: 'value'},
      options,
    };
    ctx.registerStaticTrack({
      uri: `dev.perfetto.AndroidLongBatteryTracing#${name}`,
      displayName: name,
      trackFactory: (trackCtx) => {
        return new SimpleCounterTrack(ctx.engine, trackCtx, config);
      },
      groupName,
    });
  }

  addBatteryStatsState(
    ctx: PluginContextTrace,
    name: string,
    track: string,
    groupName: string,
    features: Set<string>,
  ): void {
    if (!features.has(`track.${track}`)) {
      return;
    }
    this.addSliceTrack(
      ctx,
      name,
      `SELECT ts, dur, value_name AS name
    FROM android_battery_stats_state
    WHERE track_name = "${track}"`,
      groupName,
    );
  }

  addBatteryStatsEvent(
    ctx: PluginContextTrace,
    name: string,
    track: string,
    groupName: string | undefined,
    features: Set<string>,
  ): void {
    if (!features.has(`track.${track}`)) {
      return;
    }

    this.addSliceTrack(
      ctx,
      name,
      `SELECT ts, dur, str_value AS name
    FROM android_battery_stats_event_slices
    WHERE track_name = "${track}"`,
      groupName,
    );
  }

  async addDeviceState(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('track.battery_stats.*')) {
      return;
    }

    const query = (name: string, track: string) =>
      this.addBatteryStatsEvent(ctx, name, track, undefined, features);

    const e = ctx.engine;
    await e.query(`INCLUDE PERFETTO MODULE android.battery_stats;`);
    await e.query(`INCLUDE PERFETTO MODULE android.suspend;`);
    await e.query(`INCLUDE PERFETTO MODULE counters.intervals;`);

    this.addSliceTrack(ctx, 'Device State: Screen state', SCREEN_STATE);
    this.addSliceTrack(ctx, 'Device State: Charging', CHARGING);
    this.addSliceTrack(ctx, 'Device State: Suspend / resume', SUSPEND_RESUME);
    this.addSliceTrack(ctx, 'Device State: Doze light state', DOZE_LIGHT);
    this.addSliceTrack(ctx, 'Device State: Doze deep state', DOZE_DEEP);

    query('Device State: Top app', 'battery_stats.top');

    this.addSliceTrack(
      ctx,
      'Device State: Long wakelocks',
      `SELECT
            ts - 60000000000 as ts,
            dur + 60000000000 as dur,
            str_value AS name,
            ifnull(
            (select package_name from package_list where uid = int_value % 100000),
            int_value) as package
        FROM android_battery_stats_event_slices
        WHERE track_name = "battery_stats.longwake"`,
      undefined,
      ['package'],
    );

    query('Device State: Foreground apps', 'battery_stats.fg');
    query('Device State: Jobs', 'battery_stats.job');

    if (features.has('atom.thermal_throttling_severity_state_changed')) {
      this.addSliceTrack(
        ctx,
        'Device State: Thermal throttling',
        THERMAL_THROTTLING,
      );
    }
  }

  async addNetworkSummary(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('net.modem') && !features.has('net.wifi')) {
      return;
    }

    const groupName = 'Network Summary';

    const e = ctx.engine;
    await e.query(NETWORK_SUMMARY);

    this.addSliceTrack(ctx, 'Default network', DEFAULT_NETWORK, groupName);

    if (features.has('atom.network_tethering_reported')) {
      this.addSliceTrack(ctx, 'Tethering', TETHERING, groupName);
    }
    if (features.has('net.wifi')) {
      this.addCounterTrack(
        ctx,
        'Wifi bytes',
        `select ts, sum(value) as value from network_summary where dev_type = 'wifi' group by 1`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
      this.addCounterTrack(
        ctx,
        'Wifi TX bytes',
        `select ts, value from network_summary where dev_type = 'wifi' and dir = 'tx'`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
      this.addCounterTrack(
        ctx,
        'Wifi RX bytes',
        `select ts, value from network_summary where dev_type = 'wifi' and dir = 'rx'`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
    }
    if (features.has('net.modem')) {
      this.addCounterTrack(
        ctx,
        'Modem bytes',
        `select ts, sum(value) as value from network_summary where dev_type = 'modem' group by 1`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
      this.addCounterTrack(
        ctx,
        'Modem TX bytes',
        `select ts, value from network_summary where dev_type = 'modem' and dir = 'tx'`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
      this.addCounterTrack(
        ctx,
        'Modem RX bytes',
        `select ts, value from network_summary where dev_type = 'modem' and dir = 'rx'`,
        groupName,
        {yDisplay: 'log', yRangeSharingKey: 'net_bytes', unit: 'byte'},
      );
    }
    this.addBatteryStatsState(
      ctx,
      'Cellular interface',
      'battery_stats.mobile_radio',
      groupName,
      features,
    );
    this.addBatteryStatsState(
      ctx,
      'Cellular connection',
      'battery_stats.data_conn',
      groupName,
      features,
    );
    this.addBatteryStatsState(
      ctx,
      'Cellular strength',
      'battery_stats.phone_signal_strength',
      groupName,
      features,
    );
    this.addBatteryStatsState(
      ctx,
      'Wifi interface',
      'battery_stats.wifi_radio',
      groupName,
      features,
    );
    this.addBatteryStatsState(
      ctx,
      'Wifi supplicant state',
      'battery_stats.wifi_suppl',
      groupName,
      features,
    );
    this.addBatteryStatsState(
      ctx,
      'Wifi strength',
      'battery_stats.wifi_signal_strength',
      groupName,
      features,
    );
  }

  async addModemDetail(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('atom.modem_activity_info')) {
      return;
    }
    const groupName = 'Modem Detail';
    await this.addModemActivityInfo(ctx, groupName);
    if (features.has('track.ril')) {
      await this.addModemRil(ctx, groupName);
    }
  }

  async addModemActivityInfo(
    ctx: PluginContextTrace,
    groupName: string,
  ): Promise<void> {
    const query = (name: string, col: string): void =>
      this.addCounterTrack(
        ctx,
        name,
        `select ts, ${col}_ratio as value from modem_activity_info`,
        groupName,
      );

    await ctx.engine.query(MODEM_ACTIVITY_INFO);
    query('Modem sleep', 'sleep_time');
    query('Modem controller idle', 'controller_idle_time');
    query('Modem RX time', 'controller_rx_time');
    query('Modem TX time power 0', 'controller_tx_time_pl0');
    query('Modem TX time power 1', 'controller_tx_time_pl1');
    query('Modem TX time power 2', 'controller_tx_time_pl2');
    query('Modem TX time power 3', 'controller_tx_time_pl3');
    query('Modem TX time power 4', 'controller_tx_time_pl4');
  }

  async addModemRil(ctx: PluginContextTrace, groupName: string): Promise<void> {
    const rilStrength = (band: string, value: string): void =>
      this.addSliceTrack(
        ctx,
        `Modem signal strength ${band} ${value}`,
        `SELECT ts, dur, name FROM RilScreenOn WHERE band_name = '${band}' AND value_name = '${value}'`,
        groupName,
      );

    const e = ctx.engine;
    await e.query(MODEM_RIL_STRENGTH);
    await e.query(MODEM_RIL_CHANNELS_PREAMBLE);

    rilStrength('LTE', 'rsrp');
    rilStrength('LTE', 'rssi');
    rilStrength('NR', 'rsrp');
    rilStrength('NR', 'rssi');

    this.addSliceTrack(
      ctx,
      'Modem channel config',
      MODEM_RIL_CHANNELS,
      groupName,
    );

    this.addSliceTrack(
      ctx,
      'Modem cell reselection',
      MODEM_CELL_RESELECTION,
      groupName,
      ['raw_ril'],
    );
  }

  async addKernelWakelocks(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('atom.kernel_wakelock')) {
      return;
    }
    const groupName = 'Kernel Wakelock Summary';

    const e = ctx.engine;
    await e.query(`INCLUDE PERFETTO MODULE android.suspend;`);
    await e.query(KERNEL_WAKELOCKS);
    const result = await e.query(KERNEL_WAKELOCKS_SUMMARY);
    const it = result.iter({wakelock_name: 'str'});
    for (; it.valid(); it.next()) {
      this.addCounterTrack(
        ctx,
        it.wakelock_name,
        `select ts, dur, value from kernel_wakelocks where wakelock_name = "${it.wakelock_name}"`,
        groupName,
        {yRangeSharingKey: 'kernel_wakelock', unit: '%'},
      );
    }
  }

  async addWakeups(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('track.suspend_backoff')) {
      return;
    }

    const e = ctx.engine;
    const groupName = 'Wakeups';
    await e.query(`INCLUDE PERFETTO MODULE android.suspend;`);
    await e.query(WAKEUPS);
    const result = await e.query(`select
          item,
          sum(dur) as sum_dur
      from wakeups
      group by 1
      having sum_dur > 600e9`);
    const it = result.iter({item: 'str'});
    const sqlPrefix = `select
                ts,
                dur,
                item || case backoff_reason
                  when 'short' then ' (Short suspend backoff)'
                  when 'failed' then ' (Failed suspend backoff)'
                  else ''
                end as name,
                item,
                type,
                raw_wakeup,
                attribution,
                suspend_quality,
                backoff_state,
                backoff_reason,
                backoff_count,
                backoff_millis
            from wakeups`;
    const items = [];
    let labelOther = false;
    for (; it.valid(); it.next()) {
      labelOther = true;
      this.addSliceTrack(
        ctx,
        `Wakeup ${it.item}`,
        `${sqlPrefix} where item="${it.item}"`,
        groupName,
        WAKEUPS_COLUMNS,
      );
      items.push(it.item);
    }
    this.addSliceTrack(
      ctx,
      labelOther ? 'Other wakeups' : 'Wakeups',
      `${sqlPrefix} where item not in ('${items.join("','")}')`,
      groupName,
      WAKEUPS_COLUMNS,
    );
  }

  async addHighCpu(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (!features.has('atom.cpu_cycles_per_uid_cluster')) {
      return;
    }
    const groupName = 'CPU per UID (major users)';

    const e = ctx.engine;

    await e.query(HIGH_CPU);
    const result = await e.query(
      `select distinct pkg, cluster from high_cpu where value > 10 order by 1, 2`,
    );
    const it = result.iter({pkg: 'str', cluster: 'str'});
    for (; it.valid(); it.next()) {
      this.addCounterTrack(
        ctx,
        `CPU (${it.cluster}): ${it.pkg}`,
        `select ts, value from high_cpu where pkg = "${it.pkg}" and cluster="${it.cluster}"`,
        groupName,
      );
    }
  }

  async addBluetooth(
    ctx: PluginContextTrace,
    features: Set<string>,
  ): Promise<void> {
    if (
      !Array.from(features.values()).some(
        (f) => f.startsWith('atom.bluetooth_') || f.startsWith('atom.ble_'),
      )
    ) {
      return;
    }
    const groupName = 'Bluetooth';
    this.addSliceTrack(
      ctx,
      'BLE Scans (opportunistic)',
      bleScanQuery('opportunistic'),
      groupName,
    );
    this.addSliceTrack(
      ctx,
      'BLE Scans (filtered)',
      bleScanQuery('filtered'),
      groupName,
    );
    this.addSliceTrack(
      ctx,
      'BLE Scans (unfiltered)',
      bleScanQuery('not filtered'),
      groupName,
    );
    this.addSliceTrack(ctx, 'BLE Scan Results', BLE_RESULTS, groupName);
    this.addSliceTrack(ctx, 'Connections (ACL)', BT_CONNS_ACL, groupName);
    this.addSliceTrack(ctx, 'Connections (SCO)', BT_CONNS_SCO, groupName);
    this.addSliceTrack(
      ctx,
      'Link-level Events',
      BT_LINK_LEVEL_EVENTS,
      groupName,
      BT_LINK_LEVEL_EVENTS_COLUMNS,
    );
    this.addSliceTrack(ctx, 'A2DP Audio', BT_A2DP_AUDIO, groupName);
    this.addSliceTrack(
      ctx,
      'Bytes Transferred (L2CAP/RFCOMM)',
      BT_BYTES,
      groupName,
    );
    await ctx.engine.query(BT_ACTIVITY);
    this.addCounterTrack(
      ctx,
      'ACL Classic Active Count',
      'select ts, dur, acl_active_count as value from bt_activity',
      groupName,
    );
    this.addCounterTrack(
      ctx,
      'ACL Classic Sniff Count',
      'select ts, dur, acl_sniff_count as value from bt_activity',
      groupName,
    );
    this.addCounterTrack(
      ctx,
      'ACL BLE Count',
      'select ts, dur, acl_ble_count as value from bt_activity',
      groupName,
    );
    this.addCounterTrack(
      ctx,
      'Advertising Instance Count',
      'select ts, dur, advertising_count as value from bt_activity',
      groupName,
    );
    this.addCounterTrack(
      ctx,
      'LE Scan Duty Cycle Maximum',
      'select ts, dur, le_scan_duty_cycle as value from bt_activity',
      groupName,
      {unit: '%'},
    );
    this.addSliceTrack(
      ctx,
      'Inquiry Active',
      "select ts, dur, 'Active' as name from bt_activity where inquiry_active",
      groupName,
    );
    this.addSliceTrack(
      ctx,
      'SCO Active',
      "select ts, dur, 'Active' as name from bt_activity where sco_active",
      groupName,
    );
    this.addSliceTrack(
      ctx,
      'A2DP Active',
      "select ts, dur, 'Active' as name from bt_activity where a2dp_active",
      groupName,
    );
    this.addSliceTrack(
      ctx,
      'LE Audio Active',
      "select ts, dur, 'Active' as name from bt_activity where le_audio_active",
      groupName,
    );
    this.addCounterTrack(
      ctx,
      'Controller Idle Time',
      'select ts, dur, controller_idle_pct as value from bt_activity',
      groupName,
      {yRangeSharingKey: 'bt_controller_time', unit: '%'},
    );
    this.addCounterTrack(
      ctx,
      'Controller TX Time',
      'select ts, dur, controller_tx_pct as value from bt_activity',
      groupName,
      {yRangeSharingKey: 'bt_controller_time', unit: '%'},
    );
    this.addCounterTrack(
      ctx,
      'Controller RX Time',
      'select ts, dur, controller_rx_pct as value from bt_activity',
      groupName,
      {yRangeSharingKey: 'bt_controller_time', unit: '%'},
    );
    this.addSliceTrack(
      ctx,
      'Quality reports',
      BT_QUALITY_REPORTS,
      groupName,
      BT_QUALITY_REPORTS_COLUMNS,
    );
    this.addSliceTrack(
      ctx,
      'RSSI Reports',
      BT_RSSI_REPORTS,
      groupName,
      BT_RSSI_REPORTS_COLUMNS,
    );
    this.addSliceTrack(
      ctx,
      'HAL Crashes',
      BT_HAL_CRASHES,
      groupName,
      BT_HAL_CRASHES_COLUMNS,
    );
    this.addSliceTrack(
      ctx,
      'Code Path Counter',
      BT_CODE_PATH_COUNTER,
      groupName,
      BT_CODE_PATH_COUNTER_COLUMNS,
    );
  }

  async findFeatures(e: EngineProxy): Promise<Set<string>> {
    const features = new Set<string>();

    const addFeatures = async (q: string) => {
      const result = await e.query(q);
      const it = result.iter({feature: 'str'});
      for (; it.valid(); it.next()) {
        features.add(it.feature);
      }
    };

    await addFeatures(`
      select distinct 'atom.' || s.name as feature
      from track t join slice s on t.id = s.track_id
      where t.name = 'Statsd Atoms'`);

    await addFeatures(`
      select distinct
        case when name like '%wlan%' then 'net.wifi'
            when name like '%rmnet%' then 'net.modem'
            else 'net.other'
        end as feature
      from track
      where name like '%Transmitted' or name like '%Received'`);

    await addFeatures(`
      select distinct 'track.' || lower(name) as feature
      from track where name in ('RIL', 'suspend_backoff') or name like 'battery_stats.%'`);

    await addFeatures(`
      select distinct 'track.battery_stats.*' as feature
      from track where name like 'battery_stats.%'`);

    return features;
  }

  async addTracks(ctx: PluginContextTrace): Promise<void> {
    const features: Set<string> = await this.findFeatures(ctx.engine);

    await this.addNetworkSummary(ctx, features),
      await this.addModemDetail(ctx, features);
    await this.addKernelWakelocks(ctx, features);
    await this.addWakeups(ctx, features);
    await this.addDeviceState(ctx, features);
    await this.addHighCpu(ctx, features);
    await this.addBluetooth(ctx, features);
  }

  async onTraceLoad(ctx: PluginContextTrace): Promise<void> {
    await this.addTracks(ctx);
  }
}

export const plugin: PluginDescriptor = {
  pluginId: 'dev.perfetto.AndroidLongBatteryTracing',
  plugin: AndroidLongBatteryTracing,
};