1 /*
<lambda>null2  * Copyright (C) 2023 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 android.tools.traces.parsers.perfetto
18 
19 fun queryRealToMonotonicTimeOffsetNs(session: TraceProcessorSession, tableName: String): Long {
20     val elapsed = queryLastEntryTimestamp(session, tableName)
21     if (elapsed == null) {
22         return 0L
23     }
24     val monotonic = queryToMonotonic(session, elapsed)
25     val real = queryToRealtime(session, elapsed)
26     return real - monotonic
27 }
28 
queryLastEntryTimestampnull29 fun queryLastEntryTimestamp(session: TraceProcessorSession, tableName: String): Long? {
30     val sql =
31         """
32                 SELECT
33                     ts
34                 FROM $tableName
35                 WHERE
36                     id = ( SELECT MAX(id) FROM $tableName );
37             """
38             .trimIndent()
39     val value =
40         session.query(sql) { rows ->
41             if (rows.size == 1) {
42                 rows.get(0).get("ts") as Long
43             } else {
44                 null
45             }
46         }
47     return value
48 }
49 
queryToMonotonicnull50 fun queryToMonotonic(session: TraceProcessorSession, elapsedTimestamp: Long): Long {
51     val sql = "SELECT TO_MONOTONIC($elapsedTimestamp) as ts;"
52     val value =
53         session.query(sql) { rows ->
54             require(rows.size == 1)
55             rows.get(0).get("ts") as Long
56         }
57     return value
58 }
59 
queryToRealtimenull60 fun queryToRealtime(session: TraceProcessorSession, elapsedTimestamp: Long): Long {
61     val sql = "SELECT TO_REALTIME($elapsedTimestamp) as ts;"
62     val value =
63         session.query(sql) { rows ->
64             require(rows.size == 1)
65             rows.get(0).get("ts") as Long
66         }
67     return value
68 }
69