hc
2025-02-14 bbb9540dc49f70f6b703d1c8d1b85fa5f602d86e
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
/*
 * Copyright (c) 2019-2021 Rockchip Eletronics Co., Ltd.
 *
 * 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.
 */
 
#include "MessageParser.hpp"
 
#define BUFFER_MAX_SIZE (1024 * 512)
 
#ifndef LOGE
#define LOGE printf
#endif
 
// #define AIQ_MSGPARSER_CHECK_HASH
 
#define CALC_32BIT_LITTLE(array)                                               \
  ((array[0] & 0xff) | ((array[1] & 0xff) << 8) | ((array[2] & 0xff) << 16) |  \
   ((array[3] & 0xff) << 24))
 
namespace RkMSG {
 
MessageParser::MessageParser() : is_running(false) {}
 
int MessageParser::stop() {
  is_running = false;
  notify_wakeup();
  return 0;
}
 
MessageParser::~MessageParser() {
  this->stop();
  if (this->proc_thread && this->proc_thread->joinable()) {
    this->proc_thread->join();
    this->proc_thread.reset();
    this->proc_thread = nullptr;
  }
  if (raw_stream.size()) {
    raw_stream.clear();
  }
}
 
int MessageParser::notify_wakeup() {
  std::unique_lock<std::mutex> lck(this->proc_mutex);
  this->proc_cond.notify_all();
 
  return 0;
}
 
int MessageParser::freePacket(void *packet, MessageType type) {
  if (!packet) {
    return 0;
  }
 
  if (type == RKAIQ_MESSAGE_NEW) {
    RkAiqSocketPacket_t *newpkt = (RkAiqSocketPacket_t *)packet;
    if (newpkt->data) {
      free(newpkt->data);
    }
    free(newpkt);
  } else if (type == RKAIQ_MESSAGE_OLD) {
    RkAiqSocketPacket *newpkt = (RkAiqSocketPacket *)packet;
    if (newpkt->data) {
      free(newpkt->data);
    }
    free(newpkt);
  }
 
  return 0;
}
 
void *MessageParser::clonePacket(void *from, MessageType type) {
  if (type == RKAIQ_MESSAGE_NEW) {
    RkAiqSocketPacket_t *temp = (RkAiqSocketPacket_t *)from;
    RkAiqSocketPacket_t *opkt =
        (RkAiqSocketPacket_t *)malloc(sizeof(RkAiqSocketPacket_t));
    if (!opkt) {
      return nullptr;
    }
 
    memcpy(opkt, temp, sizeof(RkAiqSocketPacket_t));
    opkt->data = (uint8_t *)malloc(temp->payload_size);
 
    if (!opkt->data) {
      free(opkt);
      return nullptr;
    }
 
    memcpy(opkt->data, (uint8_t *)&(temp->data), temp->payload_size);
 
    return opkt;
  } else if (type == RKAIQ_MESSAGE_OLD) {
    RkAiqSocketPacket *temp = (RkAiqSocketPacket *)from;
    RkAiqSocketPacket *opkt =
        (RkAiqSocketPacket *)malloc(sizeof(RkAiqSocketPacket));
    if (!opkt) {
      return nullptr;
    }
 
    memcpy(opkt, temp, sizeof(RkAiqSocketPacket));
    opkt->data = (char *)malloc(temp->dataSize);
 
    if (!opkt->data) {
      free(opkt);
      return nullptr;
    }
 
    memcpy(opkt->data, temp->data, temp->dataSize);
 
    return opkt;
  }
 
  return nullptr;
}
 
void MessageParser::process() {
  while (is_running) {
    std::unique_lock<std::mutex> lck(proc_mutex);
    while (raw_stream.size() <= 0 && is_running) {
      proc_cond.wait(lck);
    }
 
    if (!is_running) {
      break;
    }
 
    // Found full packet: deal and call then erease
    // Found non full packet: wait
    // Found nothing: clear raw stream
 
    size_t start_index = 0;
    size_t end_index = 0;
 
    RkAiqSocketPacket *old_pkt = nullptr;
    RkAiqSocketPacket_t *new_pkt = nullptr;
 
    // Check if a new packet, if so, copy it and erase all ahead data
    new_pkt = findValidSection(&raw_stream[0], raw_stream.size(), &start_index,
                               &end_index);
    // if found full packet
    if (new_pkt && mCallBackFunc) {
      mCallBackFunc(pri, new_pkt, RKAIQ_MESSAGE_NEW);
    }
 
    if ((start_index >= 0) && (end_index > 0)) {
      raw_stream.erase(raw_stream.begin(), raw_stream.begin() + end_index);
    }
 
    start_index = 0;
    end_index = 0;
 
    // Check if a new packet, if so, copy it and erase all ahead data
    old_pkt = findValidSection2(&raw_stream[0], raw_stream.size(), &start_index,
                                &end_index);
    // if found full packet
    if (old_pkt && mCallBackFunc) {
      mCallBackFunc(pri, old_pkt, RKAIQ_MESSAGE_OLD);
      freePacket(old_pkt, RKAIQ_MESSAGE_OLD);
    }
 
    if ((start_index >= 0) && (end_index > 0)) {
      raw_stream.erase(raw_stream.begin(), raw_stream.begin() + end_index);
    }
 
    if (!new_pkt && !old_pkt && is_running) {
      proc_cond.wait(lck);
    }
  }
  LOGE("MessageParser %s loop exit!\n", __func__);
}
 
int MessageParser::pushRawData(const uint8_t *data, size_t size) {
  {
    int erase_section = 0;
    const std::lock_guard<std::mutex> lock(proc_mutex);
 
    // reach max buffer size, erase old
    if (size > RKAIQ_RAW_STREAM_MAX_SIZE) {
      erase_section = RKAIQ_RAW_STREAM_MAX_SIZE;
    } else {
      erase_section = size;
    }
 
    // do need erase
    if (raw_stream.size() >= RKAIQ_RAW_STREAM_MAX_SIZE) {
      raw_stream.erase(raw_stream.begin(), raw_stream.begin() + erase_section);
    }
 
    raw_stream.insert(raw_stream.end(), data, data + size);
  }
 
  notify_wakeup();
 
  return 0;
}
 
uint8_t *MessageParser::bit_stream_find(uint8_t *data, int size,
                                        const uint8_t *dst, int len) {
  int start_pos = -1;
 
  if (!data || !size || !dst || !len) {
    return NULL;
  }
 
  if (size < len) {
    return NULL;
  }
 
  for (start_pos = 0; start_pos < size - len; start_pos++) {
    if (0 == memcmp(data + start_pos, dst, len)) {
      return data + start_pos;
    }
  }
 
  return NULL;
}
 
// 1. find valid erase
// 2. find error packet
// 3. if crashed erase header then search again
// 4. erase ahead of first valid data
// 5. return null with non zero start en,then packet error
 
RkAiqSocketPacket_t *MessageParser::findValidSection(uint8_t *buffer, int len,
                                                     size_t *start_of,
                                                     size_t *end_of) {
  RkAiqSocketPacket_t *aiq_pkt;
  uint8_t *start_pos = NULL;
  size_t skip_size = 0;
  size_t remain_size = 0;
 
  *start_of = 0;
  *end_of = 0;
 
  start_pos = bit_stream_find(buffer, len, RKAIQ_SOCKET_DATA_HEADER,
                              RKAIQ_SOCKET_DATA_HEADER_LEN);
 
  // Found valid start
  if (NULL == start_pos) {
    return nullptr;
  }
 
  // Calculate data size
  skip_size = start_pos - buffer;
  remain_size = len - skip_size;
 
  // Check if contains packet information
  if (remain_size < (int)sizeof(RkAiqSocketPacket_t)) {
    LOGE("Not a complete packet [%d], wait more...\n", len);
    return nullptr;
  }
 
  /*
   * +---------------------------------------------------------------------+
   * |<--------------------------VALID DATA SIZE-------------------------->|
   * +-------------------+------------------------------+------------------+
   * |<---HEADER-SIZE--->|<--------PAYLOAD-SIZE-------->|<---HASH-SIZE---->|
   * +-------------------+------------------------------+------------------+
   * |   HEADER DATA     |      REAL DATA/CMD           |   VERIFY DATA    |
   * +-------------------+------------------------------+------------------+
   *
   * */
 
  // Found complete packet header, then parse packet info
  aiq_pkt = (RkAiqSocketPacket_t *)start_pos;
 
  // Assume Single packet, check if data all present
  if (remain_size < aiq_pkt->packet_size) {
    return nullptr;
  }
 
  *start_of = start_pos - buffer;
  *end_of = *start_of + aiq_pkt->payload_size + RKAIQ_SOCKET_DATA_EXTRA_SIZE;
 
#ifdef AIQ_MSGPARSER_CHECK_HASH
#endif
 
  return (RkAiqSocketPacket_t *)clonePacket(aiq_pkt, RKAIQ_MESSAGE_NEW);
}
 
RkAiqSocketPacket *MessageParser::findValidSection2(uint8_t *buffer, int len,
                                                    size_t *start_of,
                                                    size_t *end_of) {
  RkAiqSocketPacket *aiq_pkt;
  uint8_t *start_pos = NULL;
  size_t skip_size = 0;
  size_t remain_size = 0;
  size_t pkt_size = 0;
 
  *start_of = 0;
  *end_of = 0;
 
  start_pos = bit_stream_find(buffer, len, RKAIQ_SOCKET_OLD_HEADER,
                              RKAIQ_SOCKET_OLD_HEADER_LEN);
 
  // Found valid start
  if (NULL == start_pos) {
    return nullptr;
  }
 
  // Calculate data size
  skip_size = start_pos - buffer;
  remain_size = len - skip_size;
 
  // Check if contains packet information
  if (remain_size < (int)sizeof(RkAiqSocketPacket_t)) {
    LOGE("Not a complete packet [%d], wait more...\n", len);
    return nullptr;
  }
 
  // Found complete packet header, then parse packet info
  aiq_pkt = (RkAiqSocketPacket *)start_pos;
  pkt_size = CALC_32BIT_LITTLE(aiq_pkt->packetSize);
 
  // Assume Single packet, check if data all present
  if (remain_size < pkt_size) {
    return nullptr;
  }
 
  char *tmpArray = (char *)start_pos;
  int packetSize = (tmpArray[2] & 0xff) | ((tmpArray[3] & 0xff) << 8) |
                   ((tmpArray[4] & 0xff) << 16) | ((tmpArray[5] & 0xff) << 24);
 
  if (packetSize >= 102400) {
    LOGE("MessageParser %s: packetSize error!\n", __func__);
    return nullptr;
  }
 
  char *receivedPacket = (char *)malloc(packetSize);
  memset(receivedPacket, 0, packetSize);
  memcpy(receivedPacket, tmpArray, packetSize);
 
  // parse data
  RkAiqSocketPacket receivedData;
  int offset = 0;
  offset += 2;
 
  // packetSize
  memcpy(receivedData.packetSize, receivedPacket + offset, 4);
  offset += 4;
  // command id
  memcpy((void *)&(receivedData.commandID), receivedPacket + offset,
         sizeof(int));
  offset += sizeof(int);
  // command id
  memcpy((void *)&(receivedData.commandResult), receivedPacket + offset,
         sizeof(int));
  offset += sizeof(int);
 
  // data size
  memcpy((void *)&(receivedData.dataSize), receivedPacket + offset,
         sizeof(unsigned int));
 
  offset += sizeof(unsigned int);
  // data
  receivedData.data = (char *)start_pos + offset;
  offset += receivedData.dataSize;
  // data hash
  memcpy((void *)&(receivedData.dataHash), receivedPacket + offset,
         sizeof(unsigned int));
  free(receivedPacket);
  receivedPacket = NULL;
 
  // hash check
  unsigned int dataHash = MurMurHash(receivedData.data, receivedData.dataSize);
 
  // got wrong, discard these data
  if (dataHash != receivedData.dataHash) {
    *start_of = 0;
    *end_of = 0;
    return nullptr;
  }
 
  *start_of = start_pos - buffer;
  *end_of = *start_of + pkt_size;
 
  return (RkAiqSocketPacket *)clonePacket(&receivedData, RKAIQ_MESSAGE_OLD);
}
 
unsigned int MessageParser::MurMurHash(const void *key, int len) {
  const unsigned int m = 0x5bd1e995;
  const int r = 24;
  const int seed = 97;
  unsigned int h = seed ^ len;
  // Mix 4 bytes at a time into the hash
  const unsigned char *data = (const unsigned char *)key;
  while (len >= 4) {
    unsigned int k = *(unsigned int *)data;
    k *= m;
    k ^= k >> r;
    k *= m;
    h *= m;
    h ^= k;
    data += 4;
    len -= 4;
  }
  // Handle the last few bytes of the input array
  switch (len) {
  case 3:
    h ^= data[2] << 16;
  case 2:
    h ^= data[1] << 8;
  case 1:
    h ^= data[0];
    h *= m;
  };
  // Do a few final mixes of the hash to ensure the last few
  // bytes are well-incorporated.
  h ^= h >> 13;
  h *= m;
  h ^= h >> 15;
  return h;
}
 
int MessageParser::start() {
  const std::lock_guard<std::mutex> lock(proc_mutex);
  if (is_running) {
    return -1;
  }
 
  is_running = true;
  proc_thread =
      std::make_shared<std::thread>(&RkMSG::MessageParser::process, this);
 
  return 0;
}
 
} // namespace RkMSG