1// Copyright (c) 2024 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 { type DmaFenceStruct } from '../ui-worker/ProcedureWorkerDmaFence';
15import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum';
16import { threadPool } from '../SqlLite';
17import { TraceRow } from '../../component/trace/base/TraceRow';
18
19export function dmaFenceSender(
20  dmaFenceInit: String, 
21  dmaFenceName: String, 
22  row: TraceRow<DmaFenceStruct>
23  ): Promise<DmaFenceStruct[]> {
24  let trafic: number = TraficEnum.Memory;
25  let width = row.clientWidth - CHART_OFFSET_LEFT;
26  if ((trafic === TraficEnum.SharedArrayBuffer || trafic === TraficEnum.Memory) && !row.sharedArrayBuffers) {
27    row.sharedArrayBuffers = {
28      dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
29      startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
30      presentId: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
31    };
32  }
33  return new Promise((resolve): void => {
34    threadPool.submitProto(
35      QueryEnum.dmaFenceData, 
36      {
37      dmaFenceInit: dmaFenceInit,
38      dmaFenceName: dmaFenceName,
39      startNS: TraceRow.range?.startNS || 0,
40      endNS: TraceRow.range?.endNS || 0,
41      recordStartNS: window.recordStartNS,
42      recordEndNS: window.recordEndNS,
43      width: width,
44      trafic: trafic,
45      sharedArrayBuffers: row.sharedArrayBuffers,
46    }, 
47    (res: unknown, len: number, transfer: boolean): void => {
48      resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len));
49    });
50  });
51}
52
53function arrayBufferHandler(res: unknown, len: number): DmaFenceStruct[] {
54  let outArr: DmaFenceStruct[] = [];
55  //@ts-ignore
56  let startTime = new Float64Array(res.startTime);
57  //@ts-ignore
58  let dur = new Float64Array(res.dur);
59  //@ts-ignore
60  let id = new Uint16Array(res.id);
61  for (let i = 0; i < len; i++) {
62    outArr.push({
63      id: id[i],
64      dur: dur[i],
65      startTime: startTime[i],
66    } as unknown as DmaFenceStruct);
67  }
68  return outArr;
69}
70