1 /* 2 * 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 @file:OptIn( 18 androidx.benchmark.perfetto.ExperimentalPerfettoCaptureApi::class, 19 androidx.benchmark.perfetto.ExperimentalPerfettoTraceProcessorApi::class 20 ) 21 22 package android.tools.traces.parsers.perfetto 23 24 import android.tools.io.TraceType 25 import android.tools.withTracing 26 import androidx.benchmark.perfetto.PerfettoTrace 27 import androidx.benchmark.perfetto.PerfettoTraceProcessor 28 import java.io.File 29 import java.io.FileOutputStream 30 31 typealias Row = Map<String, Any?> 32 33 class TraceProcessorSession(val session: PerfettoTraceProcessor.Session) { 34 querynull35 fun <T> query(sql: String, predicate: (List<Row>) -> T): T { 36 return withTracing("TraceProcessorSession#query") { 37 val rows = session.query(sql) 38 predicate(rows.toList()) 39 } 40 } 41 42 companion object { loadPerfettoTracenull43 fun <T> loadPerfettoTrace(trace: ByteArray, predicate: (TraceProcessorSession) -> T): T { 44 return withTracing("TraceProcessorSession#loadPerfettoTrace") { 45 val traceFile = File.createTempFile(TraceType.SF.fileName, "") 46 FileOutputStream(traceFile).use { it.write(trace) } 47 val result = 48 PerfettoTraceProcessor.runServer { 49 loadTrace(PerfettoTrace(traceFile.absolutePath)) { 50 predicate(TraceProcessorSession(this)) 51 } 52 } 53 result 54 } 55 } 56 } 57 } 58