blob: dc258d6064a0feea006ee2982e0037b055bba373 [file] [log] [blame]
Zeke Chin71f6f442015-06-29 14:34:58 -07001/*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 *
10 */
11
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020012#include "sdk/objc/components/video_codec/nalu_rewriter.h"
Zeke Chin71f6f442015-06-29 14:34:58 -070013
14#include <CoreFoundation/CoreFoundation.h>
kwiberg3f55dea2016-02-29 05:51:59 -080015#include <memory>
Zeke Chin71f6f442015-06-29 14:34:58 -070016#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
19#include "rtc_base/logging.h"
Zeke Chin71f6f442015-06-29 14:34:58 -070020
21namespace webrtc {
22
jianjun.zhue1b4d242016-08-15 18:56:18 -070023using H264::kAud;
24using H264::kSps;
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +010025using H264::NaluIndex;
26using H264::NaluType;
jianjun.zhue1b4d242016-08-15 18:56:18 -070027using H264::ParseNaluType;
28
Zeke Chin71f6f442015-06-29 14:34:58 -070029const char kAnnexBHeaderBytes[4] = {0, 0, 0, 1};
30const size_t kAvccHeaderByteSize = sizeof(uint32_t);
31
32bool H264CMSampleBufferToAnnexBBuffer(
33 CMSampleBufferRef avcc_sample_buffer,
34 bool is_keyframe,
35 rtc::Buffer* annexb_buffer,
Yves Gerey665174f2018-06-19 15:03:05 +020036 std::unique_ptr<RTPFragmentationHeader>* out_header) {
henrikg91d6ede2015-09-17 00:24:34 -070037 RTC_DCHECK(avcc_sample_buffer);
38 RTC_DCHECK(out_header);
kthelgasonf8084d42017-08-30 04:47:10 -070039 out_header->reset(nullptr);
Zeke Chin71f6f442015-06-29 14:34:58 -070040
41 // Get format description from the sample buffer.
42 CMVideoFormatDescriptionRef description =
43 CMSampleBufferGetFormatDescription(avcc_sample_buffer);
44 if (description == nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010045 RTC_LOG(LS_ERROR) << "Failed to get sample buffer's description.";
Zeke Chin71f6f442015-06-29 14:34:58 -070046 return false;
47 }
48
49 // Get parameter set information.
50 int nalu_header_size = 0;
51 size_t param_set_count = 0;
52 OSStatus status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
53 description, 0, nullptr, nullptr, &param_set_count, &nalu_header_size);
54 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010055 RTC_LOG(LS_ERROR) << "Failed to get parameter set.";
Zeke Chin71f6f442015-06-29 14:34:58 -070056 return false;
57 }
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +010058 RTC_CHECK_EQ(nalu_header_size, kAvccHeaderByteSize);
kwibergaf476c72016-11-28 15:21:39 -080059 RTC_DCHECK_EQ(param_set_count, 2);
Zeke Chin71f6f442015-06-29 14:34:58 -070060
61 // Truncate any previous data in the buffer without changing its capacity.
62 annexb_buffer->SetSize(0);
63
64 size_t nalu_offset = 0;
65 std::vector<size_t> frag_offsets;
66 std::vector<size_t> frag_lengths;
67
68 // Place all parameter sets at the front of buffer.
69 if (is_keyframe) {
70 size_t param_set_size = 0;
71 const uint8_t* param_set = nullptr;
72 for (size_t i = 0; i < param_set_count; ++i) {
73 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
74 description, i, &param_set, &param_set_size, nullptr, nullptr);
75 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010076 RTC_LOG(LS_ERROR) << "Failed to get parameter set.";
Zeke Chin71f6f442015-06-29 14:34:58 -070077 return false;
78 }
79 // Update buffer.
80 annexb_buffer->AppendData(kAnnexBHeaderBytes, sizeof(kAnnexBHeaderBytes));
81 annexb_buffer->AppendData(reinterpret_cast<const char*>(param_set),
82 param_set_size);
83 // Update fragmentation.
84 frag_offsets.push_back(nalu_offset + sizeof(kAnnexBHeaderBytes));
85 frag_lengths.push_back(param_set_size);
86 nalu_offset += sizeof(kAnnexBHeaderBytes) + param_set_size;
87 }
88 }
89
90 // Get block buffer from the sample buffer.
91 CMBlockBufferRef block_buffer =
92 CMSampleBufferGetDataBuffer(avcc_sample_buffer);
93 if (block_buffer == nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010094 RTC_LOG(LS_ERROR) << "Failed to get sample buffer's block buffer.";
Zeke Chin71f6f442015-06-29 14:34:58 -070095 return false;
96 }
97 CMBlockBufferRef contiguous_buffer = nullptr;
98 // Make sure block buffer is contiguous.
99 if (!CMBlockBufferIsRangeContiguous(block_buffer, 0, 0)) {
100 status = CMBlockBufferCreateContiguous(
101 nullptr, block_buffer, nullptr, nullptr, 0, 0, 0, &contiguous_buffer);
102 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100103 RTC_LOG(LS_ERROR) << "Failed to flatten non-contiguous block buffer: "
104 << status;
Zeke Chin71f6f442015-06-29 14:34:58 -0700105 return false;
106 }
107 } else {
108 contiguous_buffer = block_buffer;
109 // Retain to make cleanup easier.
110 CFRetain(contiguous_buffer);
111 block_buffer = nullptr;
112 }
113
114 // Now copy the actual data.
115 char* data_ptr = nullptr;
116 size_t block_buffer_size = CMBlockBufferGetDataLength(contiguous_buffer);
117 status = CMBlockBufferGetDataPointer(contiguous_buffer, 0, nullptr, nullptr,
118 &data_ptr);
119 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100120 RTC_LOG(LS_ERROR) << "Failed to get block buffer data.";
Zeke Chin71f6f442015-06-29 14:34:58 -0700121 CFRelease(contiguous_buffer);
122 return false;
123 }
124 size_t bytes_remaining = block_buffer_size;
125 while (bytes_remaining > 0) {
126 // The size type here must match |nalu_header_size|, we expect 4 bytes.
127 // Read the length of the next packet of data. Must convert from big endian
128 // to host endian.
henrikg91d6ede2015-09-17 00:24:34 -0700129 RTC_DCHECK_GE(bytes_remaining, (size_t)nalu_header_size);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200130 uint32_t* uint32_data_ptr = reinterpret_cast<uint32_t*>(data_ptr);
Zeke Chin71f6f442015-06-29 14:34:58 -0700131 uint32_t packet_size = CFSwapInt32BigToHost(*uint32_data_ptr);
132 // Update buffer.
133 annexb_buffer->AppendData(kAnnexBHeaderBytes, sizeof(kAnnexBHeaderBytes));
134 annexb_buffer->AppendData(data_ptr + nalu_header_size, packet_size);
135 // Update fragmentation.
136 frag_offsets.push_back(nalu_offset + sizeof(kAnnexBHeaderBytes));
137 frag_lengths.push_back(packet_size);
138 nalu_offset += sizeof(kAnnexBHeaderBytes) + packet_size;
139
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100140 size_t bytes_written = packet_size + sizeof(kAnnexBHeaderBytes);
Zeke Chin71f6f442015-06-29 14:34:58 -0700141 bytes_remaining -= bytes_written;
142 data_ptr += bytes_written;
143 }
henrikg91d6ede2015-09-17 00:24:34 -0700144 RTC_DCHECK_EQ(bytes_remaining, (size_t)0);
Zeke Chin71f6f442015-06-29 14:34:58 -0700145
kthelgasonf8084d42017-08-30 04:47:10 -0700146 std::unique_ptr<RTPFragmentationHeader> header(new RTPFragmentationHeader());
Zeke Chin71f6f442015-06-29 14:34:58 -0700147 header->VerifyAndAllocateFragmentationHeader(frag_offsets.size());
henrikg91d6ede2015-09-17 00:24:34 -0700148 RTC_DCHECK_EQ(frag_lengths.size(), frag_offsets.size());
Zeke Chin71f6f442015-06-29 14:34:58 -0700149 for (size_t i = 0; i < frag_offsets.size(); ++i) {
150 header->fragmentationOffset[i] = frag_offsets[i];
151 header->fragmentationLength[i] = frag_lengths[i];
Zeke Chin71f6f442015-06-29 14:34:58 -0700152 }
kthelgasonf8084d42017-08-30 04:47:10 -0700153 *out_header = std::move(header);
Zeke Chin71f6f442015-06-29 14:34:58 -0700154 CFRelease(contiguous_buffer);
155 return true;
156}
157
philipelcce46fc2015-12-21 03:04:49 -0800158bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer,
159 size_t annexb_buffer_size,
160 CMVideoFormatDescriptionRef video_format,
Kári Tristan Helgason0d247722018-10-26 10:59:28 +0200161 CMSampleBufferRef* out_sample_buffer,
162 CMMemoryPoolRef memory_pool) {
henrikg91d6ede2015-09-17 00:24:34 -0700163 RTC_DCHECK(annexb_buffer);
164 RTC_DCHECK(out_sample_buffer);
tkchin5ed5ed92016-03-08 10:51:54 -0800165 RTC_DCHECK(video_format);
Zeke Chin71f6f442015-06-29 14:34:58 -0700166 *out_sample_buffer = nullptr;
167
Zeke Chin71f6f442015-06-29 14:34:58 -0700168 AnnexBBufferReader reader(annexb_buffer, annexb_buffer_size);
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800169 if (reader.SeekToNextNaluOfType(kSps)) {
170 // Buffer contains an SPS NALU - skip it and the following PPS
171 const uint8_t* data;
172 size_t data_len;
tkchin5ed5ed92016-03-08 10:51:54 -0800173 if (!reader.ReadNalu(&data, &data_len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100174 RTC_LOG(LS_ERROR) << "Failed to read SPS";
Zeke Chin71f6f442015-06-29 14:34:58 -0700175 return false;
176 }
tkchin5ed5ed92016-03-08 10:51:54 -0800177 if (!reader.ReadNalu(&data, &data_len)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100178 RTC_LOG(LS_ERROR) << "Failed to read PPS";
Zeke Chin71f6f442015-06-29 14:34:58 -0700179 return false;
180 }
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800181 } else {
182 // No SPS NALU - start reading from the first NALU in the buffer
183 reader.SeekToStart();
Zeke Chin71f6f442015-06-29 14:34:58 -0700184 }
185
186 // Allocate memory as a block buffer.
Zeke Chin71f6f442015-06-29 14:34:58 -0700187 CMBlockBufferRef block_buffer = nullptr;
Kári Tristan Helgason0d247722018-10-26 10:59:28 +0200188 CFAllocatorRef block_allocator = CMMemoryPoolGetAllocator(memory_pool);
tkchin5ed5ed92016-03-08 10:51:54 -0800189 OSStatus status = CMBlockBufferCreateWithMemoryBlock(
Kári Tristan Helgason0d247722018-10-26 10:59:28 +0200190 kCFAllocatorDefault, nullptr, reader.BytesRemaining(), block_allocator,
191 nullptr, 0, reader.BytesRemaining(), kCMBlockBufferAssureMemoryNowFlag,
Zeke Chin71f6f442015-06-29 14:34:58 -0700192 &block_buffer);
193 if (status != kCMBlockBufferNoErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100194 RTC_LOG(LS_ERROR) << "Failed to create block buffer.";
Zeke Chin71f6f442015-06-29 14:34:58 -0700195 return false;
196 }
197
198 // Make sure block buffer is contiguous.
199 CMBlockBufferRef contiguous_buffer = nullptr;
200 if (!CMBlockBufferIsRangeContiguous(block_buffer, 0, 0)) {
Kári Tristan Helgason0d247722018-10-26 10:59:28 +0200201 status = CMBlockBufferCreateContiguous(kCFAllocatorDefault, block_buffer,
202 block_allocator, nullptr, 0, 0, 0,
203 &contiguous_buffer);
Zeke Chin71f6f442015-06-29 14:34:58 -0700204 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100205 RTC_LOG(LS_ERROR) << "Failed to flatten non-contiguous block buffer: "
206 << status;
Zeke Chin71f6f442015-06-29 14:34:58 -0700207 CFRelease(block_buffer);
208 return false;
209 }
210 } else {
211 contiguous_buffer = block_buffer;
212 block_buffer = nullptr;
213 }
214
215 // Get a raw pointer into allocated memory.
216 size_t block_buffer_size = 0;
217 char* data_ptr = nullptr;
218 status = CMBlockBufferGetDataPointer(contiguous_buffer, 0, nullptr,
219 &block_buffer_size, &data_ptr);
220 if (status != kCMBlockBufferNoErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100221 RTC_LOG(LS_ERROR) << "Failed to get block buffer data pointer.";
Zeke Chin71f6f442015-06-29 14:34:58 -0700222 CFRelease(contiguous_buffer);
223 return false;
224 }
henrikg91d6ede2015-09-17 00:24:34 -0700225 RTC_DCHECK(block_buffer_size == reader.BytesRemaining());
Zeke Chin71f6f442015-06-29 14:34:58 -0700226
227 // Write Avcc NALUs into block buffer memory.
228 AvccBufferWriter writer(reinterpret_cast<uint8_t*>(data_ptr),
229 block_buffer_size);
230 while (reader.BytesRemaining() > 0) {
231 const uint8_t* nalu_data_ptr = nullptr;
232 size_t nalu_data_size = 0;
233 if (reader.ReadNalu(&nalu_data_ptr, &nalu_data_size)) {
234 writer.WriteNalu(nalu_data_ptr, nalu_data_size);
235 }
236 }
237
238 // Create sample buffer.
Kári Tristan Helgason0d247722018-10-26 10:59:28 +0200239 status = CMSampleBufferCreate(kCFAllocatorDefault, contiguous_buffer, true,
240 nullptr, nullptr, video_format, 1, 0, nullptr,
241 0, nullptr, out_sample_buffer);
Zeke Chin71f6f442015-06-29 14:34:58 -0700242 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100243 RTC_LOG(LS_ERROR) << "Failed to create sample buffer.";
Zeke Chin71f6f442015-06-29 14:34:58 -0700244 CFRelease(contiguous_buffer);
245 return false;
246 }
Zeke Chin71f6f442015-06-29 14:34:58 -0700247 CFRelease(contiguous_buffer);
248 return true;
249}
250
tkchin5ed5ed92016-03-08 10:51:54 -0800251CMVideoFormatDescriptionRef CreateVideoFormatDescription(
252 const uint8_t* annexb_buffer,
253 size_t annexb_buffer_size) {
tkchin5ed5ed92016-03-08 10:51:54 -0800254 const uint8_t* param_set_ptrs[2] = {};
255 size_t param_set_sizes[2] = {};
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800256 AnnexBBufferReader reader(annexb_buffer, annexb_buffer_size);
257 // Skip everyting before the SPS, then read the SPS and PPS
258 if (!reader.SeekToNextNaluOfType(kSps)) {
259 return nullptr;
jianjun.zhue1b4d242016-08-15 18:56:18 -0700260 }
tkchin5ed5ed92016-03-08 10:51:54 -0800261 if (!reader.ReadNalu(&param_set_ptrs[0], &param_set_sizes[0])) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100262 RTC_LOG(LS_ERROR) << "Failed to read SPS";
tkchin5ed5ed92016-03-08 10:51:54 -0800263 return nullptr;
264 }
265 if (!reader.ReadNalu(&param_set_ptrs[1], &param_set_sizes[1])) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100266 RTC_LOG(LS_ERROR) << "Failed to read PPS";
tkchin5ed5ed92016-03-08 10:51:54 -0800267 return nullptr;
268 }
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800269
270 // Parse the SPS and PPS into a CMVideoFormatDescription.
271 CMVideoFormatDescriptionRef description = nullptr;
272 OSStatus status = CMVideoFormatDescriptionCreateFromH264ParameterSets(
273 kCFAllocatorDefault, 2, param_set_ptrs, param_set_sizes, 4, &description);
tkchin5ed5ed92016-03-08 10:51:54 -0800274 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100275 RTC_LOG(LS_ERROR) << "Failed to create video format description.";
tkchin5ed5ed92016-03-08 10:51:54 -0800276 return nullptr;
277 }
278 return description;
279}
280
Zeke Chin71f6f442015-06-29 14:34:58 -0700281AnnexBBufferReader::AnnexBBufferReader(const uint8_t* annexb_buffer,
282 size_t length)
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100283 : start_(annexb_buffer), length_(length) {
henrikg91d6ede2015-09-17 00:24:34 -0700284 RTC_DCHECK(annexb_buffer);
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100285 offsets_ = H264::FindNaluIndices(annexb_buffer, length);
286 offset_ = offsets_.begin();
Zeke Chin71f6f442015-06-29 14:34:58 -0700287}
288
Mirko Bonadei17aff352018-07-26 12:20:40 +0200289AnnexBBufferReader::~AnnexBBufferReader() = default;
290
Zeke Chin71f6f442015-06-29 14:34:58 -0700291bool AnnexBBufferReader::ReadNalu(const uint8_t** out_nalu,
292 size_t* out_length) {
henrikg91d6ede2015-09-17 00:24:34 -0700293 RTC_DCHECK(out_nalu);
294 RTC_DCHECK(out_length);
Zeke Chin71f6f442015-06-29 14:34:58 -0700295 *out_nalu = nullptr;
296 *out_length = 0;
297
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100298 if (offset_ == offsets_.end()) {
Zeke Chin71f6f442015-06-29 14:34:58 -0700299 return false;
300 }
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100301 *out_nalu = start_ + offset_->payload_start_offset;
302 *out_length = offset_->payload_size;
303 ++offset_;
Zeke Chin71f6f442015-06-29 14:34:58 -0700304 return true;
305}
306
307size_t AnnexBBufferReader::BytesRemaining() const {
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100308 if (offset_ == offsets_.end()) {
309 return 0;
Zeke Chin71f6f442015-06-29 14:34:58 -0700310 }
Kári Tristan Helgasoncb18ee62016-11-02 15:07:02 +0100311 return length_ - offset_->start_offset;
Zeke Chin71f6f442015-06-29 14:34:58 -0700312}
313
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800314void AnnexBBufferReader::SeekToStart() {
315 offset_ = offsets_.begin();
316}
317
318bool AnnexBBufferReader::SeekToNextNaluOfType(NaluType type) {
319 for (; offset_ != offsets_.end(); ++offset_) {
320 if (offset_->payload_size < 1)
321 continue;
322 if (ParseNaluType(*(start_ + offset_->payload_start_offset)) == type)
323 return true;
324 }
325 return false;
326}
Zeke Chin71f6f442015-06-29 14:34:58 -0700327AvccBufferWriter::AvccBufferWriter(uint8_t* const avcc_buffer, size_t length)
328 : start_(avcc_buffer), offset_(0), length_(length) {
henrikg91d6ede2015-09-17 00:24:34 -0700329 RTC_DCHECK(avcc_buffer);
Zeke Chin71f6f442015-06-29 14:34:58 -0700330}
331
332bool AvccBufferWriter::WriteNalu(const uint8_t* data, size_t data_size) {
333 // Check if we can write this length of data.
334 if (data_size + kAvccHeaderByteSize > BytesRemaining()) {
335 return false;
336 }
337 // Write length header, which needs to be big endian.
338 uint32_t big_endian_length = CFSwapInt32HostToBig(data_size);
339 memcpy(start_ + offset_, &big_endian_length, sizeof(big_endian_length));
340 offset_ += sizeof(big_endian_length);
341 // Write data.
342 memcpy(start_ + offset_, data, data_size);
343 offset_ += data_size;
344 return true;
345}
346
347size_t AvccBufferWriter::BytesRemaining() const {
348 return length_ - offset_;
349}
350
351} // namespace webrtc