• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
12 // Everything declared/defined in this header is only required when WebRTC is
13 // build with H264 support, please do not move anything out of the
14 // #ifdef unless needed and tested.
15 #ifdef WEBRTC_USE_H264
16 
17 #include "modules/video_coding/codecs/h264/h264_encoder_impl.h"
18 
19 #include <limits>
20 #include <string>
21 
22 #include "absl/strings/match.h"
23 #include "common_video/libyuv/include/webrtc_libyuv.h"
24 #include "modules/video_coding/utility/simulcast_rate_allocator.h"
25 #include "modules/video_coding/utility/simulcast_utility.h"
26 #include "rtc_base/checks.h"
27 #include "rtc_base/logging.h"
28 #include "rtc_base/time_utils.h"
29 #include "system_wrappers/include/metrics.h"
30 #include "third_party/libyuv/include/libyuv/convert.h"
31 #include "third_party/libyuv/include/libyuv/scale.h"
32 #include "third_party/openh264/src/codec/api/svc/codec_api.h"
33 #include "third_party/openh264/src/codec/api/svc/codec_app_def.h"
34 #include "third_party/openh264/src/codec/api/svc/codec_def.h"
35 #include "third_party/openh264/src/codec/api/svc/codec_ver.h"
36 
37 namespace webrtc {
38 
39 namespace {
40 
41 const bool kOpenH264EncoderDetailedLogging = false;
42 
43 // QP scaling thresholds.
44 static const int kLowH264QpThreshold = 24;
45 static const int kHighH264QpThreshold = 37;
46 
47 // Used by histograms. Values of entries should not be changed.
48 enum H264EncoderImplEvent {
49   kH264EncoderEventInit = 0,
50   kH264EncoderEventError = 1,
51   kH264EncoderEventMax = 16,
52 };
53 
NumberOfThreads(int width,int height,int number_of_cores)54 int NumberOfThreads(int width, int height, int number_of_cores) {
55   // TODO(hbos): In Chromium, multiple threads do not work with sandbox on Mac,
56   // see crbug.com/583348. Until further investigated, only use one thread.
57   //  if (width * height >= 1920 * 1080 && number_of_cores > 8) {
58   //    return 8;  // 8 threads for 1080p on high perf machines.
59   //  } else if (width * height > 1280 * 960 && number_of_cores >= 6) {
60   //    return 3;  // 3 threads for 1080p.
61   //  } else if (width * height > 640 * 480 && number_of_cores >= 3) {
62   //    return 2;  // 2 threads for qHD/HD.
63   //  } else {
64   //    return 1;  // 1 thread for VGA or less.
65   //  }
66   // TODO(sprang): Also check sSliceArgument.uiSliceNum om GetEncoderPrams(),
67   //               before enabling multithreading here.
68   return 1;
69 }
70 
ConvertToVideoFrameType(EVideoFrameType type)71 VideoFrameType ConvertToVideoFrameType(EVideoFrameType type) {
72   switch (type) {
73     case videoFrameTypeIDR:
74       return VideoFrameType::kVideoFrameKey;
75     case videoFrameTypeSkip:
76     case videoFrameTypeI:
77     case videoFrameTypeP:
78     case videoFrameTypeIPMixed:
79       return VideoFrameType::kVideoFrameDelta;
80     case videoFrameTypeInvalid:
81       break;
82   }
83   RTC_NOTREACHED() << "Unexpected/invalid frame type: " << type;
84   return VideoFrameType::kEmptyFrame;
85 }
86 
87 }  // namespace
88 
89 // Helper method used by H264EncoderImpl::Encode.
90 // Copies the encoded bytes from |info| to |encoded_image| and updates the
91 // fragmentation information of |frag_header|. The |encoded_image->_buffer| may
92 // be deleted and reallocated if a bigger buffer is required.
93 //
94 // After OpenH264 encoding, the encoded bytes are stored in |info| spread out
95 // over a number of layers and "NAL units". Each NAL unit is a fragment starting
96 // with the four-byte start code {0,0,0,1}. All of this data (including the
97 // start codes) is copied to the |encoded_image->_buffer| and the |frag_header|
98 // is updated to point to each fragment, with offsets and lengths set as to
99 // exclude the start codes.
RtpFragmentize(EncodedImage * encoded_image,SFrameBSInfo * info,RTPFragmentationHeader * frag_header)100 static void RtpFragmentize(EncodedImage* encoded_image,
101                            SFrameBSInfo* info,
102                            RTPFragmentationHeader* frag_header) {
103   // Calculate minimum buffer size required to hold encoded data.
104   size_t required_capacity = 0;
105   size_t fragments_count = 0;
106   for (int layer = 0; layer < info->iLayerNum; ++layer) {
107     const SLayerBSInfo& layerInfo = info->sLayerInfo[layer];
108     for (int nal = 0; nal < layerInfo.iNalCount; ++nal, ++fragments_count) {
109       RTC_CHECK_GE(layerInfo.pNalLengthInByte[nal], 0);
110       // Ensure |required_capacity| will not overflow.
111       RTC_CHECK_LE(layerInfo.pNalLengthInByte[nal],
112                    std::numeric_limits<size_t>::max() - required_capacity);
113       required_capacity += layerInfo.pNalLengthInByte[nal];
114     }
115   }
116   // TODO(nisse): Use a cache or buffer pool to avoid allocation?
117   encoded_image->SetEncodedData(EncodedImageBuffer::Create(required_capacity));
118 
119   // Iterate layers and NAL units, note each NAL unit as a fragment and copy
120   // the data to |encoded_image->_buffer|.
121   const uint8_t start_code[4] = {0, 0, 0, 1};
122   frag_header->VerifyAndAllocateFragmentationHeader(fragments_count);
123   size_t frag = 0;
124   encoded_image->set_size(0);
125   for (int layer = 0; layer < info->iLayerNum; ++layer) {
126     const SLayerBSInfo& layerInfo = info->sLayerInfo[layer];
127     // Iterate NAL units making up this layer, noting fragments.
128     size_t layer_len = 0;
129     for (int nal = 0; nal < layerInfo.iNalCount; ++nal, ++frag) {
130       // Because the sum of all layer lengths, |required_capacity|, fits in a
131       // |size_t|, we know that any indices in-between will not overflow.
132       RTC_DCHECK_GE(layerInfo.pNalLengthInByte[nal], 4);
133       RTC_DCHECK_EQ(layerInfo.pBsBuf[layer_len + 0], start_code[0]);
134       RTC_DCHECK_EQ(layerInfo.pBsBuf[layer_len + 1], start_code[1]);
135       RTC_DCHECK_EQ(layerInfo.pBsBuf[layer_len + 2], start_code[2]);
136       RTC_DCHECK_EQ(layerInfo.pBsBuf[layer_len + 3], start_code[3]);
137       frag_header->fragmentationOffset[frag] =
138           encoded_image->size() + layer_len + sizeof(start_code);
139       frag_header->fragmentationLength[frag] =
140           layerInfo.pNalLengthInByte[nal] - sizeof(start_code);
141       layer_len += layerInfo.pNalLengthInByte[nal];
142     }
143     // Copy the entire layer's data (including start codes).
144     memcpy(encoded_image->data() + encoded_image->size(), layerInfo.pBsBuf,
145            layer_len);
146     encoded_image->set_size(encoded_image->size() + layer_len);
147   }
148 }
149 
H264EncoderImpl(const cricket::VideoCodec & codec)150 H264EncoderImpl::H264EncoderImpl(const cricket::VideoCodec& codec)
151     : packetization_mode_(H264PacketizationMode::SingleNalUnit),
152       max_payload_size_(0),
153       number_of_cores_(0),
154       encoded_image_callback_(nullptr),
155       has_reported_init_(false),
156       has_reported_error_(false) {
157   RTC_CHECK(absl::EqualsIgnoreCase(codec.name, cricket::kH264CodecName));
158   std::string packetization_mode_string;
159   if (codec.GetParam(cricket::kH264FmtpPacketizationMode,
160                      &packetization_mode_string) &&
161       packetization_mode_string == "1") {
162     packetization_mode_ = H264PacketizationMode::NonInterleaved;
163   }
164   downscaled_buffers_.reserve(kMaxSimulcastStreams - 1);
165   encoded_images_.reserve(kMaxSimulcastStreams);
166   encoders_.reserve(kMaxSimulcastStreams);
167   configurations_.reserve(kMaxSimulcastStreams);
168   tl0sync_limit_.reserve(kMaxSimulcastStreams);
169 }
170 
~H264EncoderImpl()171 H264EncoderImpl::~H264EncoderImpl() {
172   Release();
173 }
174 
InitEncode(const VideoCodec * inst,const VideoEncoder::Settings & settings)175 int32_t H264EncoderImpl::InitEncode(const VideoCodec* inst,
176                                     const VideoEncoder::Settings& settings) {
177   ReportInit();
178   if (!inst || inst->codecType != kVideoCodecH264) {
179     ReportError();
180     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
181   }
182   if (inst->maxFramerate == 0) {
183     ReportError();
184     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
185   }
186   if (inst->width < 1 || inst->height < 1) {
187     ReportError();
188     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
189   }
190 
191   int32_t release_ret = Release();
192   if (release_ret != WEBRTC_VIDEO_CODEC_OK) {
193     ReportError();
194     return release_ret;
195   }
196 
197   int number_of_streams = SimulcastUtility::NumberOfSimulcastStreams(*inst);
198   bool doing_simulcast = (number_of_streams > 1);
199 
200   if (doing_simulcast &&
201       !SimulcastUtility::ValidSimulcastParameters(*inst, number_of_streams)) {
202     return WEBRTC_VIDEO_CODEC_ERR_SIMULCAST_PARAMETERS_NOT_SUPPORTED;
203   }
204   downscaled_buffers_.resize(number_of_streams - 1);
205   encoded_images_.resize(number_of_streams);
206   encoders_.resize(number_of_streams);
207   pictures_.resize(number_of_streams);
208   configurations_.resize(number_of_streams);
209   tl0sync_limit_.resize(number_of_streams);
210 
211   number_of_cores_ = settings.number_of_cores;
212   max_payload_size_ = settings.max_payload_size;
213   codec_ = *inst;
214 
215   // Code expects simulcastStream resolutions to be correct, make sure they are
216   // filled even when there are no simulcast layers.
217   if (codec_.numberOfSimulcastStreams == 0) {
218     codec_.simulcastStream[0].width = codec_.width;
219     codec_.simulcastStream[0].height = codec_.height;
220   }
221 
222   for (int i = 0, idx = number_of_streams - 1; i < number_of_streams;
223        ++i, --idx) {
224     ISVCEncoder* openh264_encoder;
225     // Create encoder.
226     if (WelsCreateSVCEncoder(&openh264_encoder) != 0) {
227       // Failed to create encoder.
228       RTC_LOG(LS_ERROR) << "Failed to create OpenH264 encoder";
229       RTC_DCHECK(!openh264_encoder);
230       Release();
231       ReportError();
232       return WEBRTC_VIDEO_CODEC_ERROR;
233     }
234     RTC_DCHECK(openh264_encoder);
235     if (kOpenH264EncoderDetailedLogging) {
236       int trace_level = WELS_LOG_DETAIL;
237       openh264_encoder->SetOption(ENCODER_OPTION_TRACE_LEVEL, &trace_level);
238     }
239     // else WELS_LOG_DEFAULT is used by default.
240 
241     // Store h264 encoder.
242     encoders_[i] = openh264_encoder;
243 
244     // Set internal settings from codec_settings
245     configurations_[i].simulcast_idx = idx;
246     configurations_[i].sending = false;
247     configurations_[i].width = codec_.simulcastStream[idx].width;
248     configurations_[i].height = codec_.simulcastStream[idx].height;
249     configurations_[i].max_frame_rate = static_cast<float>(codec_.maxFramerate);
250     configurations_[i].frame_dropping_on = codec_.H264()->frameDroppingOn;
251     configurations_[i].key_frame_interval = codec_.H264()->keyFrameInterval;
252     configurations_[i].num_temporal_layers =
253         codec_.simulcastStream[idx].numberOfTemporalLayers;
254 
255     // Create downscaled image buffers.
256     if (i > 0) {
257       downscaled_buffers_[i - 1] = I420Buffer::Create(
258           configurations_[i].width, configurations_[i].height,
259           configurations_[i].width, configurations_[i].width / 2,
260           configurations_[i].width / 2);
261     }
262 
263     // Codec_settings uses kbits/second; encoder uses bits/second.
264     configurations_[i].max_bps = codec_.maxBitrate * 1000;
265     configurations_[i].target_bps = codec_.startBitrate * 1000;
266 
267     // Create encoder parameters based on the layer configuration.
268     SEncParamExt encoder_params = CreateEncoderParams(i);
269 
270     // Initialize.
271     if (openh264_encoder->InitializeExt(&encoder_params) != 0) {
272       RTC_LOG(LS_ERROR) << "Failed to initialize OpenH264 encoder";
273       Release();
274       ReportError();
275       return WEBRTC_VIDEO_CODEC_ERROR;
276     }
277     // TODO(pbos): Base init params on these values before submitting.
278     int video_format = EVideoFormatType::videoFormatI420;
279     openh264_encoder->SetOption(ENCODER_OPTION_DATAFORMAT, &video_format);
280 
281     // Initialize encoded image. Default buffer size: size of unencoded data.
282 
283     const size_t new_capacity =
284         CalcBufferSize(VideoType::kI420, codec_.simulcastStream[idx].width,
285                        codec_.simulcastStream[idx].height);
286     encoded_images_[i].SetEncodedData(EncodedImageBuffer::Create(new_capacity));
287     encoded_images_[i]._completeFrame = true;
288     encoded_images_[i]._encodedWidth = codec_.simulcastStream[idx].width;
289     encoded_images_[i]._encodedHeight = codec_.simulcastStream[idx].height;
290     encoded_images_[i].set_size(0);
291 
292     tl0sync_limit_[i] = configurations_[i].num_temporal_layers;
293   }
294 
295   SimulcastRateAllocator init_allocator(codec_);
296   VideoBitrateAllocation allocation =
297       init_allocator.Allocate(VideoBitrateAllocationParameters(
298           DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate));
299   SetRates(RateControlParameters(allocation, codec_.maxFramerate));
300   return WEBRTC_VIDEO_CODEC_OK;
301 }
302 
Release()303 int32_t H264EncoderImpl::Release() {
304   while (!encoders_.empty()) {
305     ISVCEncoder* openh264_encoder = encoders_.back();
306     if (openh264_encoder) {
307       RTC_CHECK_EQ(0, openh264_encoder->Uninitialize());
308       WelsDestroySVCEncoder(openh264_encoder);
309     }
310     encoders_.pop_back();
311   }
312   downscaled_buffers_.clear();
313   configurations_.clear();
314   encoded_images_.clear();
315   pictures_.clear();
316   tl0sync_limit_.clear();
317   return WEBRTC_VIDEO_CODEC_OK;
318 }
319 
RegisterEncodeCompleteCallback(EncodedImageCallback * callback)320 int32_t H264EncoderImpl::RegisterEncodeCompleteCallback(
321     EncodedImageCallback* callback) {
322   encoded_image_callback_ = callback;
323   return WEBRTC_VIDEO_CODEC_OK;
324 }
325 
SetRates(const RateControlParameters & parameters)326 void H264EncoderImpl::SetRates(const RateControlParameters& parameters) {
327   if (encoders_.empty()) {
328     RTC_LOG(LS_WARNING) << "SetRates() while uninitialized.";
329     return;
330   }
331 
332   if (parameters.framerate_fps < 1.0) {
333     RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps;
334     return;
335   }
336 
337   if (parameters.bitrate.get_sum_bps() == 0) {
338     // Encoder paused, turn off all encoding.
339     for (size_t i = 0; i < configurations_.size(); ++i) {
340       configurations_[i].SetStreamState(false);
341     }
342     return;
343   }
344 
345   codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps);
346 
347   size_t stream_idx = encoders_.size() - 1;
348   for (size_t i = 0; i < encoders_.size(); ++i, --stream_idx) {
349     // Update layer config.
350     configurations_[i].target_bps =
351         parameters.bitrate.GetSpatialLayerSum(stream_idx);
352     configurations_[i].max_frame_rate = parameters.framerate_fps;
353 
354     if (configurations_[i].target_bps) {
355       configurations_[i].SetStreamState(true);
356 
357       // Update h264 encoder.
358       SBitrateInfo target_bitrate;
359       memset(&target_bitrate, 0, sizeof(SBitrateInfo));
360       target_bitrate.iLayer = SPATIAL_LAYER_ALL,
361       target_bitrate.iBitrate = configurations_[i].target_bps;
362       encoders_[i]->SetOption(ENCODER_OPTION_BITRATE, &target_bitrate);
363       encoders_[i]->SetOption(ENCODER_OPTION_FRAME_RATE,
364                               &configurations_[i].max_frame_rate);
365     } else {
366       configurations_[i].SetStreamState(false);
367     }
368   }
369 }
370 
Encode(const VideoFrame & input_frame,const std::vector<VideoFrameType> * frame_types)371 int32_t H264EncoderImpl::Encode(
372     const VideoFrame& input_frame,
373     const std::vector<VideoFrameType>* frame_types) {
374   if (encoders_.empty()) {
375     ReportError();
376     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
377   }
378   if (!encoded_image_callback_) {
379     RTC_LOG(LS_WARNING)
380         << "InitEncode() has been called, but a callback function "
381            "has not been set with RegisterEncodeCompleteCallback()";
382     ReportError();
383     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
384   }
385 
386   rtc::scoped_refptr<const I420BufferInterface> frame_buffer =
387       input_frame.video_frame_buffer()->ToI420();
388 
389   bool send_key_frame = false;
390   for (size_t i = 0; i < configurations_.size(); ++i) {
391     if (configurations_[i].key_frame_request && configurations_[i].sending) {
392       send_key_frame = true;
393       break;
394     }
395   }
396 
397   if (!send_key_frame && frame_types) {
398     for (size_t i = 0; i < configurations_.size(); ++i) {
399       const size_t simulcast_idx =
400           static_cast<size_t>(configurations_[i].simulcast_idx);
401       if (configurations_[i].sending && simulcast_idx < frame_types->size() &&
402           (*frame_types)[simulcast_idx] == VideoFrameType::kVideoFrameKey) {
403         send_key_frame = true;
404         break;
405       }
406     }
407   }
408 
409   RTC_DCHECK_EQ(configurations_[0].width, frame_buffer->width());
410   RTC_DCHECK_EQ(configurations_[0].height, frame_buffer->height());
411 
412   // Encode image for each layer.
413   for (size_t i = 0; i < encoders_.size(); ++i) {
414     // EncodeFrame input.
415     pictures_[i] = {0};
416     pictures_[i].iPicWidth = configurations_[i].width;
417     pictures_[i].iPicHeight = configurations_[i].height;
418     pictures_[i].iColorFormat = EVideoFormatType::videoFormatI420;
419     pictures_[i].uiTimeStamp = input_frame.ntp_time_ms();
420     // Downscale images on second and ongoing layers.
421     if (i == 0) {
422       pictures_[i].iStride[0] = frame_buffer->StrideY();
423       pictures_[i].iStride[1] = frame_buffer->StrideU();
424       pictures_[i].iStride[2] = frame_buffer->StrideV();
425       pictures_[i].pData[0] = const_cast<uint8_t*>(frame_buffer->DataY());
426       pictures_[i].pData[1] = const_cast<uint8_t*>(frame_buffer->DataU());
427       pictures_[i].pData[2] = const_cast<uint8_t*>(frame_buffer->DataV());
428     } else {
429       pictures_[i].iStride[0] = downscaled_buffers_[i - 1]->StrideY();
430       pictures_[i].iStride[1] = downscaled_buffers_[i - 1]->StrideU();
431       pictures_[i].iStride[2] = downscaled_buffers_[i - 1]->StrideV();
432       pictures_[i].pData[0] =
433           const_cast<uint8_t*>(downscaled_buffers_[i - 1]->DataY());
434       pictures_[i].pData[1] =
435           const_cast<uint8_t*>(downscaled_buffers_[i - 1]->DataU());
436       pictures_[i].pData[2] =
437           const_cast<uint8_t*>(downscaled_buffers_[i - 1]->DataV());
438       // Scale the image down a number of times by downsampling factor.
439       libyuv::I420Scale(pictures_[i - 1].pData[0], pictures_[i - 1].iStride[0],
440                         pictures_[i - 1].pData[1], pictures_[i - 1].iStride[1],
441                         pictures_[i - 1].pData[2], pictures_[i - 1].iStride[2],
442                         configurations_[i - 1].width,
443                         configurations_[i - 1].height, pictures_[i].pData[0],
444                         pictures_[i].iStride[0], pictures_[i].pData[1],
445                         pictures_[i].iStride[1], pictures_[i].pData[2],
446                         pictures_[i].iStride[2], configurations_[i].width,
447                         configurations_[i].height, libyuv::kFilterBilinear);
448     }
449 
450     if (!configurations_[i].sending) {
451       continue;
452     }
453     if (frame_types != nullptr) {
454       // Skip frame?
455       if ((*frame_types)[i] == VideoFrameType::kEmptyFrame) {
456         continue;
457       }
458     }
459     if (send_key_frame) {
460       // API doc says ForceIntraFrame(false) does nothing, but calling this
461       // function forces a key frame regardless of the |bIDR| argument's value.
462       // (If every frame is a key frame we get lag/delays.)
463       encoders_[i]->ForceIntraFrame(true);
464       configurations_[i].key_frame_request = false;
465     }
466     // EncodeFrame output.
467     SFrameBSInfo info;
468     memset(&info, 0, sizeof(SFrameBSInfo));
469 
470     // Encode!
471     int enc_ret = encoders_[i]->EncodeFrame(&pictures_[i], &info);
472     if (enc_ret != 0) {
473       RTC_LOG(LS_ERROR)
474           << "OpenH264 frame encoding failed, EncodeFrame returned " << enc_ret
475           << ".";
476       ReportError();
477       return WEBRTC_VIDEO_CODEC_ERROR;
478     }
479 
480     encoded_images_[i]._encodedWidth = configurations_[i].width;
481     encoded_images_[i]._encodedHeight = configurations_[i].height;
482     encoded_images_[i].SetTimestamp(input_frame.timestamp());
483     encoded_images_[i]._frameType = ConvertToVideoFrameType(info.eFrameType);
484     encoded_images_[i].SetSpatialIndex(configurations_[i].simulcast_idx);
485 
486     // Split encoded image up into fragments. This also updates
487     // |encoded_image_|.
488     RTPFragmentationHeader frag_header;
489     RtpFragmentize(&encoded_images_[i], &info, &frag_header);
490 
491     // Encoder can skip frames to save bandwidth in which case
492     // |encoded_images_[i]._length| == 0.
493     if (encoded_images_[i].size() > 0) {
494       // Parse QP.
495       h264_bitstream_parser_.ParseBitstream(encoded_images_[i].data(),
496                                             encoded_images_[i].size());
497       h264_bitstream_parser_.GetLastSliceQp(&encoded_images_[i].qp_);
498 
499       // Deliver encoded image.
500       CodecSpecificInfo codec_specific;
501       codec_specific.codecType = kVideoCodecH264;
502       codec_specific.codecSpecific.H264.packetization_mode =
503           packetization_mode_;
504       codec_specific.codecSpecific.H264.temporal_idx = kNoTemporalIdx;
505       codec_specific.codecSpecific.H264.idr_frame =
506           info.eFrameType == videoFrameTypeIDR;
507       codec_specific.codecSpecific.H264.base_layer_sync = false;
508       if (configurations_[i].num_temporal_layers > 1) {
509         const uint8_t tid = info.sLayerInfo[0].uiTemporalId;
510         codec_specific.codecSpecific.H264.temporal_idx = tid;
511         codec_specific.codecSpecific.H264.base_layer_sync =
512             tid > 0 && tid < tl0sync_limit_[i];
513         if (codec_specific.codecSpecific.H264.base_layer_sync) {
514           tl0sync_limit_[i] = tid;
515         }
516         if (tid == 0) {
517           tl0sync_limit_[i] = configurations_[i].num_temporal_layers;
518         }
519       }
520       encoded_image_callback_->OnEncodedImage(encoded_images_[i],
521                                               &codec_specific, &frag_header);
522     }
523   }
524   return WEBRTC_VIDEO_CODEC_OK;
525 }
526 
527 // Initialization parameters.
528 // There are two ways to initialize. There is SEncParamBase (cleared with
529 // memset(&p, 0, sizeof(SEncParamBase)) used in Initialize, and SEncParamExt
530 // which is a superset of SEncParamBase (cleared with GetDefaultParams) used
531 // in InitializeExt.
CreateEncoderParams(size_t i) const532 SEncParamExt H264EncoderImpl::CreateEncoderParams(size_t i) const {
533   SEncParamExt encoder_params;
534   encoders_[i]->GetDefaultParams(&encoder_params);
535   if (codec_.mode == VideoCodecMode::kRealtimeVideo) {
536     encoder_params.iUsageType = CAMERA_VIDEO_REAL_TIME;
537   } else if (codec_.mode == VideoCodecMode::kScreensharing) {
538     encoder_params.iUsageType = SCREEN_CONTENT_REAL_TIME;
539   } else {
540     RTC_NOTREACHED();
541   }
542   encoder_params.iPicWidth = configurations_[i].width;
543   encoder_params.iPicHeight = configurations_[i].height;
544   encoder_params.iTargetBitrate = configurations_[i].target_bps;
545   // Keep unspecified. WebRTC's max codec bitrate is not the same setting
546   // as OpenH264's iMaxBitrate. More details in https://crbug.com/webrtc/11543
547   encoder_params.iMaxBitrate = UNSPECIFIED_BIT_RATE;
548   // Rate Control mode
549   encoder_params.iRCMode = RC_BITRATE_MODE;
550   encoder_params.fMaxFrameRate = configurations_[i].max_frame_rate;
551 
552   // The following parameters are extension parameters (they're in SEncParamExt,
553   // not in SEncParamBase).
554   encoder_params.bEnableFrameSkip = configurations_[i].frame_dropping_on;
555   // |uiIntraPeriod|    - multiple of GOP size
556   // |keyFrameInterval| - number of frames
557   encoder_params.uiIntraPeriod = configurations_[i].key_frame_interval;
558   encoder_params.uiMaxNalSize = 0;
559   // Threading model: use auto.
560   //  0: auto (dynamic imp. internal encoder)
561   //  1: single thread (default value)
562   // >1: number of threads
563   encoder_params.iMultipleThreadIdc = NumberOfThreads(
564       encoder_params.iPicWidth, encoder_params.iPicHeight, number_of_cores_);
565   // The base spatial layer 0 is the only one we use.
566   encoder_params.sSpatialLayers[0].iVideoWidth = encoder_params.iPicWidth;
567   encoder_params.sSpatialLayers[0].iVideoHeight = encoder_params.iPicHeight;
568   encoder_params.sSpatialLayers[0].fFrameRate = encoder_params.fMaxFrameRate;
569   encoder_params.sSpatialLayers[0].iSpatialBitrate =
570       encoder_params.iTargetBitrate;
571   encoder_params.sSpatialLayers[0].iMaxSpatialBitrate =
572       encoder_params.iMaxBitrate;
573   encoder_params.iTemporalLayerNum = configurations_[i].num_temporal_layers;
574   if (encoder_params.iTemporalLayerNum > 1) {
575     encoder_params.iNumRefFrame = 1;
576   }
577   RTC_LOG(INFO) << "OpenH264 version is " << OPENH264_MAJOR << "."
578                 << OPENH264_MINOR;
579   switch (packetization_mode_) {
580     case H264PacketizationMode::SingleNalUnit:
581       // Limit the size of the packets produced.
582       encoder_params.sSpatialLayers[0].sSliceArgument.uiSliceNum = 1;
583       encoder_params.sSpatialLayers[0].sSliceArgument.uiSliceMode =
584           SM_SIZELIMITED_SLICE;
585       encoder_params.sSpatialLayers[0].sSliceArgument.uiSliceSizeConstraint =
586           static_cast<unsigned int>(max_payload_size_);
587       RTC_LOG(INFO) << "Encoder is configured with NALU constraint: "
588                     << max_payload_size_ << " bytes";
589       break;
590     case H264PacketizationMode::NonInterleaved:
591       // When uiSliceMode = SM_FIXEDSLCNUM_SLICE, uiSliceNum = 0 means auto
592       // design it with cpu core number.
593       // TODO(sprang): Set to 0 when we understand why the rate controller borks
594       //               when uiSliceNum > 1.
595       encoder_params.sSpatialLayers[0].sSliceArgument.uiSliceNum = 1;
596       encoder_params.sSpatialLayers[0].sSliceArgument.uiSliceMode =
597           SM_FIXEDSLCNUM_SLICE;
598       break;
599   }
600   return encoder_params;
601 }
602 
ReportInit()603 void H264EncoderImpl::ReportInit() {
604   if (has_reported_init_)
605     return;
606   RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
607                             kH264EncoderEventInit, kH264EncoderEventMax);
608   has_reported_init_ = true;
609 }
610 
ReportError()611 void H264EncoderImpl::ReportError() {
612   if (has_reported_error_)
613     return;
614   RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
615                             kH264EncoderEventError, kH264EncoderEventMax);
616   has_reported_error_ = true;
617 }
618 
GetEncoderInfo() const619 VideoEncoder::EncoderInfo H264EncoderImpl::GetEncoderInfo() const {
620   EncoderInfo info;
621   info.supports_native_handle = false;
622   info.implementation_name = "OpenH264";
623   info.scaling_settings =
624       VideoEncoder::ScalingSettings(kLowH264QpThreshold, kHighH264QpThreshold);
625   info.is_hardware_accelerated = false;
626   info.has_internal_source = false;
627   info.supports_simulcast = true;
628   return info;
629 }
630 
SetStreamState(bool send_stream)631 void H264EncoderImpl::LayerConfig::SetStreamState(bool send_stream) {
632   if (send_stream && !sending) {
633     // Need a key frame if we have not sent this stream before.
634     key_frame_request = true;
635   }
636   sending = send_stream;
637 }
638 
639 }  // namespace webrtc
640 
641 #endif  // WEBRTC_USE_H264
642