• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "h264_frame.h"
17 #include "common/sharing_log.h"
18 
19 namespace OHOS {
20 namespace Sharing {
PrefixSize(const char * ptr,size_t len)21 size_t PrefixSize(const char *ptr, size_t len)
22 {
23     if (len < 4) { // 4:byte offset
24         return 0;
25     }
26     if (ptr[0] != 0x00 || ptr[1] != 0x00) {
27         return 0;
28     }
29     if (ptr[2] == 0x00 && ptr[3] == 0x01) { // 2:byte offset, 3:byte offset
30         return 4;                           // 4:prefix size
31     }
32     if (ptr[2] == 0x01) { // 2:byte offset
33         return 3;         // 3:prefix size
34     }
35 
36     return 0;
37 }
38 
MemFind(const char * buf,ssize_t len,const char * subBuf,ssize_t subLen)39 static const char *MemFind(const char *buf, ssize_t len, const char *subBuf, ssize_t subLen)
40 {
41     for (auto i = 0; i < len - subLen; ++i) {
42         if (memcmp(buf + i, subBuf, subLen) == 0) {
43             return buf + i;
44         }
45     }
46 
47     return NULL;
48 }
49 
SplitH264(const char * ptr,size_t len,size_t prefix,const std::function<void (const char *,size_t,size_t)> & cb)50 void SplitH264(const char *ptr, size_t len, size_t prefix, const std::function<void(const char *, size_t, size_t)> &cb)
51 {
52     if (prefix <= 0) {
53         prefix = PrefixSize(ptr, len);
54     }
55     auto start = ptr + prefix;
56     auto end = ptr + len;
57     size_t nextPrefix;
58     while (true) {
59         auto nextStart = MemFind(start, end - start, "\x00\x00\x01", 3);
60         if (nextStart) {
61             if (*(nextStart - 1) == 0x00) {
62                 nextStart -= 1;
63                 nextPrefix = 4; // 4:prefix size
64             } else {
65                 nextPrefix = 3; // 3:prefix size
66             }
67 
68             cb(start - prefix, nextStart - start + prefix, prefix);
69 
70             start = nextStart + nextPrefix;
71 
72             prefix = nextPrefix;
73             continue;
74         }
75 
76         cb(start - prefix, end - start + prefix, prefix);
77         break;
78     }
79 }
80 } // namespace Sharing
81 } // namespace OHOS