1// Copyright (c) 2021 Huawei Device Co., Ltd.
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum';
15import { getThreadPool } from '../../SqlLite';
16import { TraceRow } from '../../../component/trace/base/TraceRow';
17import { CpuFreqStruct } from '../../ui-worker/ProcedureWorkerFreq';
18import { Utils } from '../../../component/trace/base/Utils';
19
20export function cpuFreqDataSender(cpu: number, row: TraceRow<CpuFreqStruct>): Promise<CpuFreqStruct[]> {
21  let trafic: number = TraficEnum.Memory;
22  let width = row.clientWidth - CHART_OFFSET_LEFT;
23  if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) {
24    row.sharedArrayBuffers = {
25      cpu: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT),
26      value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT),
27      dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
28      startNS: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
29    };
30  }
31  return new Promise((resolve): void => {
32    getThreadPool(row.traceId).submitProto(
33      QueryEnum.CpuFreqData,
34      {
35        cpu: cpu,
36        startNS: TraceRow.range?.startNS || 0,
37        endNS: TraceRow.range?.endNS || 0,
38        recordStartNS: Utils.getInstance().getRecordStartNS(row.traceId),
39        recordEndNS: Utils.getInstance().getRecordEndNS(row.traceId),
40        t: Date.now(),
41        trafic: trafic,
42        sharedArrayBuffers: row.sharedArrayBuffers,
43        width: width,
44      },
45      (res: unknown, len: number, transfer: boolean): void => {
46        resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len));
47      }
48    );
49  });
50}
51
52function arrayBufferHandler(buffers: unknown, len: number): CpuFreqStruct[] {
53  let outArr: CpuFreqStruct[] = [];
54  // @ts-ignore
55  let cpu = new Uint8Array(buffers.cpu);
56  // @ts-ignore
57  let value = new Uint32Array(buffers.value);
58  // @ts-ignore
59  let startNS = new Float64Array(buffers.startNS);
60  // @ts-ignore
61  let dur = new Float64Array(buffers.dur);
62  for (let i = 0; i < len; i++) {
63    outArr.push({
64      cpu: cpu[i],
65      value: value[i],
66      dur: dur[i],
67      startNS: startNS[i],
68    } as CpuFreqStruct);
69  }
70  return outArr;
71}
72