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/common_macro.h"
18 #include "common/sharing_log.h"
19
20 namespace OHOS {
21 namespace Sharing {
PrefixSize(const char * ptr,size_t len)22 size_t PrefixSize(const char *ptr, size_t len)
23 {
24 if (ptr == nullptr) {
25 return 0;
26 }
27
28 if (len < 4) { // 4:byte offset
29 return 0;
30 }
31 if (ptr[0] != 0x00 || ptr[1] != 0x00) {
32 return 0;
33 }
34 if (ptr[2] == 0x00 && ptr[3] == 0x01) { // 2:byte offset, 3:byte offset
35 return 4; // 4:prefix size
36 }
37 if (ptr[2] == 0x01) { // 2:byte offset
38 return 3; // 3:prefix size
39 }
40
41 return 0;
42 }
43
MemFind(const char * buf,ssize_t len,const char * subBuf,ssize_t subLen)44 static const char *MemFind(const char *buf, ssize_t len, const char *subBuf, ssize_t subLen)
45 {
46 if (buf == nullptr || subBuf == nullptr) {
47 return NULL;
48 }
49
50 for (auto i = 0; i < len - subLen; ++i) {
51 if (memcmp(buf + i, subBuf, subLen) == 0) {
52 return buf + i;
53 }
54 }
55
56 return NULL;
57 }
58
SplitH264(const char * ptr,size_t len,size_t prefix,const std::function<void (const char *,size_t,size_t)> & cb)59 void SplitH264(const char *ptr, size_t len, size_t prefix, const std::function<void(const char *, size_t, size_t)> &cb)
60 {
61 RETURN_IF_NULL(ptr);
62 if (prefix <= 0) {
63 prefix = PrefixSize(ptr, len);
64 }
65 auto start = ptr + prefix;
66 auto end = ptr + len;
67 size_t nextPrefix;
68 while (true) {
69 auto nextStart = MemFind(start, end - start, "\x00\x00\x01", 3);
70 if (nextStart) {
71 if (*(nextStart - 1) == 0x00) {
72 nextStart -= 1;
73 nextPrefix = 4; // 4:prefix size
74 } else {
75 nextPrefix = 3; // 3:prefix size
76 }
77
78 cb(start - prefix, nextStart - start + prefix, prefix);
79
80 start = nextStart + nextPrefix;
81
82 prefix = nextPrefix;
83 continue;
84 }
85
86 cb(start - prefix, end - start + prefix, prefix);
87 break;
88 }
89 }
90 } // namespace Sharing
91 } // namespace OHOS