glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 1 | /* |
| 2 | * libjingle |
| 3 | * Copyright 2015 Google Inc. |
| 4 | * |
| 5 | * Redistribution and use in source and binary forms, with or without |
| 6 | * modification, are permitted provided that the following conditions are met: |
| 7 | * |
| 8 | * 1. Redistributions of source code must retain the above copyright notice, |
| 9 | * this list of conditions and the following disclaimer. |
| 10 | * 2. Redistributions in binary form must reproduce the above copyright notice, |
| 11 | * this list of conditions and the following disclaimer in the documentation |
| 12 | * and/or other materials provided with the distribution. |
| 13 | * 3. The name of the author may not be used to endorse or promote products |
| 14 | * derived from this software without specific prior written permission. |
| 15 | * |
| 16 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED |
| 17 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 18 | * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO |
| 19 | * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 20 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; |
| 22 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, |
| 23 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR |
| 24 | * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF |
| 25 | * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 26 | * |
| 27 | */ |
| 28 | |
| 29 | #include "talk/app/webrtc/java/jni/androidmediaencoder_jni.h" |
| 30 | #include "talk/app/webrtc/java/jni/classreferenceholder.h" |
| 31 | #include "talk/app/webrtc/java/jni/androidmediacodeccommon.h" |
| 32 | #include "webrtc/base/bind.h" |
| 33 | #include "webrtc/base/checks.h" |
| 34 | #include "webrtc/base/logging.h" |
| 35 | #include "webrtc/base/thread.h" |
| 36 | #include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h" |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 37 | #include "webrtc/modules/video_coding/utility/include/quality_scaler.h" |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 38 | #include "webrtc/modules/video_coding/utility/include/vp8_header_parser.h" |
asapersson | ef5d5e4 | 2015-09-22 01:40:42 -0700 | [diff] [blame] | 39 | #include "webrtc/system_wrappers/interface/field_trial.h" |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 40 | #include "webrtc/system_wrappers/interface/logcat_trace_context.h" |
| 41 | #include "third_party/libyuv/include/libyuv/convert.h" |
| 42 | #include "third_party/libyuv/include/libyuv/convert_from.h" |
| 43 | #include "third_party/libyuv/include/libyuv/video_common.h" |
| 44 | |
| 45 | using rtc::Bind; |
| 46 | using rtc::Thread; |
| 47 | using rtc::ThreadManager; |
| 48 | using rtc::scoped_ptr; |
| 49 | |
| 50 | using webrtc::CodecSpecificInfo; |
| 51 | using webrtc::EncodedImage; |
Miguel Casas-Sanchez | 4765070 | 2015-05-29 17:21:40 -0700 | [diff] [blame] | 52 | using webrtc::VideoFrame; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 53 | using webrtc::RTPFragmentationHeader; |
| 54 | using webrtc::VideoCodec; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 55 | using webrtc::VideoCodecType; |
| 56 | using webrtc::kVideoCodecH264; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 57 | using webrtc::kVideoCodecVP8; |
| 58 | |
| 59 | namespace webrtc_jni { |
| 60 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 61 | // H.264 start code length. |
| 62 | #define H264_SC_LENGTH 4 |
| 63 | // Maximum allowed NALUs in one output frame. |
| 64 | #define MAX_NALUS_PERFRAME 32 |
| 65 | // Maximum supported HW video encoder resolution. |
| 66 | #define MAX_VIDEO_WIDTH 1280 |
| 67 | #define MAX_VIDEO_HEIGHT 1280 |
| 68 | // Maximum supported HW video encoder fps. |
| 69 | #define MAX_VIDEO_FPS 30 |
| 70 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 71 | // MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses |
| 72 | // Android's MediaCodec SDK API behind the scenes to implement (hopefully) |
| 73 | // HW-backed video encode. This C++ class is implemented as a very thin shim, |
| 74 | // delegating all of the interesting work to org.webrtc.MediaCodecVideoEncoder. |
| 75 | // MediaCodecVideoEncoder is created, operated, and destroyed on a single |
| 76 | // thread, currently the libjingle Worker thread. |
| 77 | class MediaCodecVideoEncoder : public webrtc::VideoEncoder, |
| 78 | public rtc::MessageHandler { |
| 79 | public: |
| 80 | virtual ~MediaCodecVideoEncoder(); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 81 | explicit MediaCodecVideoEncoder(JNIEnv* jni, VideoCodecType codecType); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 82 | |
| 83 | // webrtc::VideoEncoder implementation. Everything trampolines to |
| 84 | // |codec_thread_| for execution. |
| 85 | int32_t InitEncode(const webrtc::VideoCodec* codec_settings, |
| 86 | int32_t /* number_of_cores */, |
| 87 | size_t /* max_payload_size */) override; |
| 88 | int32_t Encode( |
Miguel Casas-Sanchez | 4765070 | 2015-05-29 17:21:40 -0700 | [diff] [blame] | 89 | const webrtc::VideoFrame& input_image, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 90 | const webrtc::CodecSpecificInfo* /* codec_specific_info */, |
| 91 | const std::vector<webrtc::VideoFrameType>* frame_types) override; |
| 92 | int32_t RegisterEncodeCompleteCallback( |
| 93 | webrtc::EncodedImageCallback* callback) override; |
| 94 | int32_t Release() override; |
| 95 | int32_t SetChannelParameters(uint32_t /* packet_loss */, |
| 96 | int64_t /* rtt */) override; |
| 97 | int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override; |
| 98 | |
| 99 | // rtc::MessageHandler implementation. |
| 100 | void OnMessage(rtc::Message* msg) override; |
| 101 | |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 102 | void OnDroppedFrame() override; |
| 103 | |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 104 | int GetTargetFramerate() override; |
| 105 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 106 | private: |
| 107 | // CHECK-fail if not running on |codec_thread_|. |
| 108 | void CheckOnCodecThread(); |
| 109 | |
| 110 | // Release() and InitEncode() in an attempt to restore the codec to an |
| 111 | // operable state. Necessary after all manner of OMX-layer errors. |
| 112 | void ResetCodec(); |
| 113 | |
| 114 | // Implementation of webrtc::VideoEncoder methods above, all running on the |
| 115 | // codec thread exclusively. |
| 116 | // |
| 117 | // If width==0 then this is assumed to be a re-initialization and the |
| 118 | // previously-current values are reused instead of the passed parameters |
| 119 | // (makes it easier to reason about thread-safety). |
| 120 | int32_t InitEncodeOnCodecThread(int width, int height, int kbps, int fps); |
| 121 | int32_t EncodeOnCodecThread( |
Miguel Casas-Sanchez | 4765070 | 2015-05-29 17:21:40 -0700 | [diff] [blame] | 122 | const webrtc::VideoFrame& input_image, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 123 | const std::vector<webrtc::VideoFrameType>* frame_types); |
| 124 | int32_t RegisterEncodeCompleteCallbackOnCodecThread( |
| 125 | webrtc::EncodedImageCallback* callback); |
| 126 | int32_t ReleaseOnCodecThread(); |
| 127 | int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate); |
| 128 | |
| 129 | // Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members. |
| 130 | int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info); |
| 131 | jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info); |
| 132 | bool GetOutputBufferInfoIsKeyFrame(JNIEnv* jni, jobject j_output_buffer_info); |
| 133 | jlong GetOutputBufferInfoPresentationTimestampUs( |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 134 | JNIEnv* jni, jobject j_output_buffer_info); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 135 | |
| 136 | // Deliver any outputs pending in the MediaCodec to our |callback_| and return |
| 137 | // true on success. |
| 138 | bool DeliverPendingOutputs(JNIEnv* jni); |
| 139 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 140 | // Search for H.264 start codes. |
| 141 | int32_t NextNaluPosition(uint8_t *buffer, size_t buffer_size); |
| 142 | |
| 143 | // Type of video codec. |
| 144 | VideoCodecType codecType_; |
| 145 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 146 | // Valid all the time since RegisterEncodeCompleteCallback() Invoke()s to |
| 147 | // |codec_thread_| synchronously. |
| 148 | webrtc::EncodedImageCallback* callback_; |
| 149 | |
| 150 | // State that is constant for the lifetime of this object once the ctor |
| 151 | // returns. |
| 152 | scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec. |
| 153 | ScopedGlobalRef<jclass> j_media_codec_video_encoder_class_; |
| 154 | ScopedGlobalRef<jobject> j_media_codec_video_encoder_; |
| 155 | jmethodID j_init_encode_method_; |
| 156 | jmethodID j_dequeue_input_buffer_method_; |
| 157 | jmethodID j_encode_method_; |
| 158 | jmethodID j_release_method_; |
| 159 | jmethodID j_set_rates_method_; |
| 160 | jmethodID j_dequeue_output_buffer_method_; |
| 161 | jmethodID j_release_output_buffer_method_; |
| 162 | jfieldID j_color_format_field_; |
| 163 | jfieldID j_info_index_field_; |
| 164 | jfieldID j_info_buffer_field_; |
| 165 | jfieldID j_info_is_key_frame_field_; |
| 166 | jfieldID j_info_presentation_timestamp_us_field_; |
| 167 | |
| 168 | // State that is valid only between InitEncode() and the next Release(). |
| 169 | // Touched only on codec_thread_ so no explicit synchronization necessary. |
| 170 | int width_; // Frame width in pixels. |
| 171 | int height_; // Frame height in pixels. |
| 172 | bool inited_; |
| 173 | uint16_t picture_id_; |
| 174 | enum libyuv::FourCC encoder_fourcc_; // Encoder color space format. |
| 175 | int last_set_bitrate_kbps_; // Last-requested bitrate in kbps. |
| 176 | int last_set_fps_; // Last-requested frame rate. |
| 177 | int64_t current_timestamp_us_; // Current frame timestamps in us. |
| 178 | int frames_received_; // Number of frames received by encoder. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 179 | int frames_encoded_; // Number of frames encoded by encoder. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 180 | int frames_dropped_; // Number of frames dropped by encoder. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 181 | int frames_in_queue_; // Number of frames in encoder queue. |
| 182 | int64_t start_time_ms_; // Start time for statistics. |
| 183 | int current_frames_; // Number of frames in the current statistics interval. |
| 184 | int current_bytes_; // Encoded bytes in the current statistics interval. |
| 185 | int current_encoding_time_ms_; // Overall encoding time in the current second |
| 186 | int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame. |
| 187 | int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame. |
| 188 | std::vector<int32_t> timestamps_; // Video frames timestamp queue. |
| 189 | std::vector<int64_t> render_times_ms_; // Video frames render time queue. |
| 190 | std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to |
| 191 | // encoder input. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 192 | int32_t output_timestamp_; // Last output frame timestamp from timestamps_ Q. |
| 193 | int64_t output_render_time_ms_; // Last output frame render time from |
| 194 | // render_times_ms_ queue. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 195 | // Frame size in bytes fed to MediaCodec. |
| 196 | int yuv_size_; |
| 197 | // True only when between a callback_->Encoded() call return a positive value |
| 198 | // and the next Encode() call being ignored. |
| 199 | bool drop_next_input_frame_; |
| 200 | // Global references; must be deleted in Release(). |
| 201 | std::vector<jobject> input_buffers_; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 202 | scoped_ptr<webrtc::QualityScaler> quality_scaler_; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 203 | // Dynamic resolution change, off by default. |
| 204 | bool scale_; |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 205 | int updated_framerate_; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 206 | }; |
| 207 | |
| 208 | MediaCodecVideoEncoder::~MediaCodecVideoEncoder() { |
| 209 | // Call Release() to ensure no more callbacks to us after we are deleted. |
| 210 | Release(); |
| 211 | } |
| 212 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 213 | MediaCodecVideoEncoder::MediaCodecVideoEncoder( |
| 214 | JNIEnv* jni, VideoCodecType codecType) : |
| 215 | codecType_(codecType), |
| 216 | callback_(NULL), |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 217 | inited_(false), |
| 218 | picture_id_(0), |
| 219 | codec_thread_(new Thread()), |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 220 | quality_scaler_(new webrtc::QualityScaler()), |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 221 | j_media_codec_video_encoder_class_( |
| 222 | jni, |
| 223 | FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")), |
| 224 | j_media_codec_video_encoder_( |
| 225 | jni, |
| 226 | jni->NewObject(*j_media_codec_video_encoder_class_, |
| 227 | GetMethodID(jni, |
| 228 | *j_media_codec_video_encoder_class_, |
| 229 | "<init>", |
| 230 | "()V"))) { |
| 231 | ScopedLocalRefFrame local_ref_frame(jni); |
| 232 | // It would be nice to avoid spinning up a new thread per MediaCodec, and |
| 233 | // instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug |
| 234 | // 2732 means that deadlocks abound. This class synchronously trampolines |
| 235 | // to |codec_thread_|, so if anything else can be coming to _us_ from |
| 236 | // |codec_thread_|, or from any thread holding the |_sendCritSect| described |
| 237 | // in the bug, we have a problem. For now work around that with a dedicated |
| 238 | // thread. |
| 239 | codec_thread_->SetName("MediaCodecVideoEncoder", NULL); |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 240 | RTC_CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder"; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 241 | |
| 242 | jclass j_output_buffer_info_class = |
| 243 | FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo"); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 244 | j_init_encode_method_ = GetMethodID( |
| 245 | jni, |
| 246 | *j_media_codec_video_encoder_class_, |
| 247 | "initEncode", |
| 248 | "(Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;IIII)" |
| 249 | "[Ljava/nio/ByteBuffer;"); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 250 | j_dequeue_input_buffer_method_ = GetMethodID( |
| 251 | jni, *j_media_codec_video_encoder_class_, "dequeueInputBuffer", "()I"); |
| 252 | j_encode_method_ = GetMethodID( |
| 253 | jni, *j_media_codec_video_encoder_class_, "encode", "(ZIIJ)Z"); |
| 254 | j_release_method_ = |
| 255 | GetMethodID(jni, *j_media_codec_video_encoder_class_, "release", "()V"); |
| 256 | j_set_rates_method_ = GetMethodID( |
| 257 | jni, *j_media_codec_video_encoder_class_, "setRates", "(II)Z"); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 258 | j_dequeue_output_buffer_method_ = GetMethodID( |
| 259 | jni, |
| 260 | *j_media_codec_video_encoder_class_, |
| 261 | "dequeueOutputBuffer", |
| 262 | "()Lorg/webrtc/MediaCodecVideoEncoder$OutputBufferInfo;"); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 263 | j_release_output_buffer_method_ = GetMethodID( |
| 264 | jni, *j_media_codec_video_encoder_class_, "releaseOutputBuffer", "(I)Z"); |
| 265 | |
| 266 | j_color_format_field_ = |
| 267 | GetFieldID(jni, *j_media_codec_video_encoder_class_, "colorFormat", "I"); |
| 268 | j_info_index_field_ = |
| 269 | GetFieldID(jni, j_output_buffer_info_class, "index", "I"); |
| 270 | j_info_buffer_field_ = GetFieldID( |
| 271 | jni, j_output_buffer_info_class, "buffer", "Ljava/nio/ByteBuffer;"); |
| 272 | j_info_is_key_frame_field_ = |
| 273 | GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z"); |
| 274 | j_info_presentation_timestamp_us_field_ = GetFieldID( |
| 275 | jni, j_output_buffer_info_class, "presentationTimestampUs", "J"); |
| 276 | CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed"; |
| 277 | AllowBlockingCalls(); |
| 278 | } |
| 279 | |
| 280 | int32_t MediaCodecVideoEncoder::InitEncode( |
| 281 | const webrtc::VideoCodec* codec_settings, |
| 282 | int32_t /* number_of_cores */, |
| 283 | size_t /* max_payload_size */) { |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 284 | const int kMinWidth = 320; |
| 285 | const int kMinHeight = 180; |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 286 | // QP is obtained from VP8-bitstream for HW, so the QP corresponds to the |
| 287 | // (internal) range: [0, 127]. And we cannot change QP_max in HW, so it is |
| 288 | // always = 127. Note that in SW, QP is that of the user-level range [0, 63]. |
| 289 | const int kMaxQP = 127; |
| 290 | const int kLowQpThresholdDenominator = 3; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 291 | if (codec_settings == NULL) { |
| 292 | ALOGE("NULL VideoCodec instance"); |
| 293 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 294 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 295 | // Factory should guard against other codecs being used with us. |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 296 | RTC_CHECK(codec_settings->codecType == codecType_) |
| 297 | << "Unsupported codec " << codec_settings->codecType << " for " |
| 298 | << codecType_; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 299 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 300 | ALOGD("InitEncode request"); |
asapersson | ef5d5e4 | 2015-09-22 01:40:42 -0700 | [diff] [blame] | 301 | |
| 302 | scale_ = webrtc::field_trial::FindFullName( |
| 303 | "WebRTC-MediaCodecVideoEncoder-AutomaticResize") == "Enabled"; |
| 304 | ALOGD("Automatic resize: %s", scale_ ? "enabled" : "disabled"); |
| 305 | |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 306 | if (scale_ && codecType_ == kVideoCodecVP8) { |
| 307 | quality_scaler_->Init(kMaxQP / kLowQpThresholdDenominator, true); |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 308 | quality_scaler_->SetMinResolution(kMinWidth, kMinHeight); |
| 309 | quality_scaler_->ReportFramerate(codec_settings->maxFramerate); |
jackychen | e2b34b7 | 2015-07-24 14:12:24 -0700 | [diff] [blame] | 310 | updated_framerate_ = codec_settings->maxFramerate; |
| 311 | } else { |
| 312 | updated_framerate_ = -1; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 313 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 314 | return codec_thread_->Invoke<int32_t>( |
| 315 | Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread, |
| 316 | this, |
| 317 | codec_settings->width, |
| 318 | codec_settings->height, |
| 319 | codec_settings->startBitrate, |
| 320 | codec_settings->maxFramerate)); |
| 321 | } |
| 322 | |
| 323 | int32_t MediaCodecVideoEncoder::Encode( |
Miguel Casas-Sanchez | 4765070 | 2015-05-29 17:21:40 -0700 | [diff] [blame] | 324 | const webrtc::VideoFrame& frame, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 325 | const webrtc::CodecSpecificInfo* /* codec_specific_info */, |
| 326 | const std::vector<webrtc::VideoFrameType>* frame_types) { |
| 327 | return codec_thread_->Invoke<int32_t>(Bind( |
| 328 | &MediaCodecVideoEncoder::EncodeOnCodecThread, this, frame, frame_types)); |
| 329 | } |
| 330 | |
| 331 | int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallback( |
| 332 | webrtc::EncodedImageCallback* callback) { |
| 333 | return codec_thread_->Invoke<int32_t>( |
| 334 | Bind(&MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread, |
| 335 | this, |
| 336 | callback)); |
| 337 | } |
| 338 | |
| 339 | int32_t MediaCodecVideoEncoder::Release() { |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 340 | ALOGD("EncoderRelease request"); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 341 | return codec_thread_->Invoke<int32_t>( |
| 342 | Bind(&MediaCodecVideoEncoder::ReleaseOnCodecThread, this)); |
| 343 | } |
| 344 | |
| 345 | int32_t MediaCodecVideoEncoder::SetChannelParameters(uint32_t /* packet_loss */, |
| 346 | int64_t /* rtt */) { |
| 347 | return WEBRTC_VIDEO_CODEC_OK; |
| 348 | } |
| 349 | |
| 350 | int32_t MediaCodecVideoEncoder::SetRates(uint32_t new_bit_rate, |
| 351 | uint32_t frame_rate) { |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 352 | if (scale_ && codecType_ == kVideoCodecVP8) { |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 353 | quality_scaler_->ReportFramerate(frame_rate); |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 354 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 355 | return codec_thread_->Invoke<int32_t>( |
| 356 | Bind(&MediaCodecVideoEncoder::SetRatesOnCodecThread, |
| 357 | this, |
| 358 | new_bit_rate, |
| 359 | frame_rate)); |
| 360 | } |
| 361 | |
| 362 | void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) { |
| 363 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 364 | ScopedLocalRefFrame local_ref_frame(jni); |
| 365 | |
| 366 | // We only ever send one message to |this| directly (not through a Bind()'d |
| 367 | // functor), so expect no ID/data. |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 368 | RTC_CHECK(!msg->message_id) << "Unexpected message!"; |
| 369 | RTC_CHECK(!msg->pdata) << "Unexpected message!"; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 370 | CheckOnCodecThread(); |
| 371 | if (!inited_) { |
| 372 | return; |
| 373 | } |
| 374 | |
| 375 | // It would be nice to recover from a failure here if one happened, but it's |
| 376 | // unclear how to signal such a failure to the app, so instead we stay silent |
| 377 | // about it and let the next app-called API method reveal the borkedness. |
| 378 | DeliverPendingOutputs(jni); |
| 379 | codec_thread_->PostDelayed(kMediaCodecPollMs, this); |
| 380 | } |
| 381 | |
| 382 | void MediaCodecVideoEncoder::CheckOnCodecThread() { |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 383 | RTC_CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread()) |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 384 | << "Running on wrong thread!"; |
| 385 | } |
| 386 | |
| 387 | void MediaCodecVideoEncoder::ResetCodec() { |
| 388 | ALOGE("ResetCodec"); |
| 389 | if (Release() != WEBRTC_VIDEO_CODEC_OK || |
| 390 | codec_thread_->Invoke<int32_t>(Bind( |
| 391 | &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this, |
| 392 | width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) { |
| 393 | // TODO(fischman): wouldn't it be nice if there was a way to gracefully |
| 394 | // degrade to a SW encoder at this point? There isn't one AFAICT :( |
| 395 | // https://code.google.com/p/webrtc/issues/detail?id=2920 |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | int32_t MediaCodecVideoEncoder::InitEncodeOnCodecThread( |
| 400 | int width, int height, int kbps, int fps) { |
| 401 | CheckOnCodecThread(); |
| 402 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 403 | ScopedLocalRefFrame local_ref_frame(jni); |
| 404 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 405 | ALOGD("InitEncodeOnCodecThread Type: %d. %d x %d. Bitrate: %d kbps. Fps: %d", |
| 406 | (int)codecType_, width, height, kbps, fps); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 407 | if (kbps == 0) { |
| 408 | kbps = last_set_bitrate_kbps_; |
| 409 | } |
| 410 | if (fps == 0) { |
| 411 | fps = last_set_fps_; |
| 412 | } |
| 413 | |
| 414 | width_ = width; |
| 415 | height_ = height; |
| 416 | last_set_bitrate_kbps_ = kbps; |
| 417 | last_set_fps_ = fps; |
| 418 | yuv_size_ = width_ * height_ * 3 / 2; |
| 419 | frames_received_ = 0; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 420 | frames_encoded_ = 0; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 421 | frames_dropped_ = 0; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 422 | frames_in_queue_ = 0; |
| 423 | current_timestamp_us_ = 0; |
| 424 | start_time_ms_ = GetCurrentTimeMs(); |
| 425 | current_frames_ = 0; |
| 426 | current_bytes_ = 0; |
| 427 | current_encoding_time_ms_ = 0; |
| 428 | last_input_timestamp_ms_ = -1; |
| 429 | last_output_timestamp_ms_ = -1; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 430 | output_timestamp_ = 0; |
| 431 | output_render_time_ms_ = 0; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 432 | timestamps_.clear(); |
| 433 | render_times_ms_.clear(); |
| 434 | frame_rtc_times_ms_.clear(); |
| 435 | drop_next_input_frame_ = false; |
| 436 | picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF; |
| 437 | // We enforce no extra stride/padding in the format creation step. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 438 | jobject j_video_codec_enum = JavaEnumFromIndex( |
| 439 | jni, "MediaCodecVideoEncoder$VideoCodecType", codecType_); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 440 | jobjectArray input_buffers = reinterpret_cast<jobjectArray>( |
| 441 | jni->CallObjectMethod(*j_media_codec_video_encoder_, |
| 442 | j_init_encode_method_, |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 443 | j_video_codec_enum, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 444 | width_, |
| 445 | height_, |
| 446 | kbps, |
| 447 | fps)); |
| 448 | CHECK_EXCEPTION(jni); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 449 | if (IsNull(jni, input_buffers)) { |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 450 | return WEBRTC_VIDEO_CODEC_ERROR; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 451 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 452 | |
| 453 | inited_ = true; |
| 454 | switch (GetIntField(jni, *j_media_codec_video_encoder_, |
| 455 | j_color_format_field_)) { |
| 456 | case COLOR_FormatYUV420Planar: |
| 457 | encoder_fourcc_ = libyuv::FOURCC_YU12; |
| 458 | break; |
| 459 | case COLOR_FormatYUV420SemiPlanar: |
| 460 | case COLOR_QCOM_FormatYUV420SemiPlanar: |
| 461 | case COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m: |
| 462 | encoder_fourcc_ = libyuv::FOURCC_NV12; |
| 463 | break; |
| 464 | default: |
| 465 | LOG(LS_ERROR) << "Wrong color format."; |
| 466 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 467 | } |
| 468 | size_t num_input_buffers = jni->GetArrayLength(input_buffers); |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 469 | RTC_CHECK(input_buffers_.empty()) |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 470 | << "Unexpected double InitEncode without Release"; |
| 471 | input_buffers_.resize(num_input_buffers); |
| 472 | for (size_t i = 0; i < num_input_buffers; ++i) { |
| 473 | input_buffers_[i] = |
| 474 | jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i)); |
| 475 | int64 yuv_buffer_capacity = |
| 476 | jni->GetDirectBufferCapacity(input_buffers_[i]); |
| 477 | CHECK_EXCEPTION(jni); |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 478 | RTC_CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity"; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 479 | } |
| 480 | CHECK_EXCEPTION(jni); |
| 481 | |
| 482 | codec_thread_->PostDelayed(kMediaCodecPollMs, this); |
| 483 | return WEBRTC_VIDEO_CODEC_OK; |
| 484 | } |
| 485 | |
| 486 | int32_t MediaCodecVideoEncoder::EncodeOnCodecThread( |
Miguel Casas-Sanchez | 4765070 | 2015-05-29 17:21:40 -0700 | [diff] [blame] | 487 | const webrtc::VideoFrame& frame, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 488 | const std::vector<webrtc::VideoFrameType>* frame_types) { |
| 489 | CheckOnCodecThread(); |
| 490 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 491 | ScopedLocalRefFrame local_ref_frame(jni); |
| 492 | |
| 493 | if (!inited_) { |
| 494 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 495 | } |
| 496 | frames_received_++; |
| 497 | if (!DeliverPendingOutputs(jni)) { |
| 498 | ResetCodec(); |
| 499 | // Continue as if everything's fine. |
| 500 | } |
| 501 | |
| 502 | if (drop_next_input_frame_) { |
| 503 | ALOGV("Encoder drop frame - failed callback."); |
| 504 | drop_next_input_frame_ = false; |
| 505 | return WEBRTC_VIDEO_CODEC_OK; |
| 506 | } |
| 507 | |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 508 | RTC_CHECK(frame_types->size() == 1) << "Unexpected stream count"; |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 509 | // Check framerate before spatial resolution change. |
| 510 | if (scale_ && codecType_ == kVideoCodecVP8) { |
| 511 | quality_scaler_->OnEncodeFrame(frame); |
| 512 | updated_framerate_ = quality_scaler_->GetTargetFramerate(); |
| 513 | } |
| 514 | const VideoFrame& input_frame = (scale_ && codecType_ == kVideoCodecVP8) ? |
| 515 | quality_scaler_->GetScaledFrame(frame) : frame; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 516 | |
| 517 | if (input_frame.width() != width_ || input_frame.height() != height_) { |
| 518 | ALOGD("Frame resolution change from %d x %d to %d x %d", |
| 519 | width_, height_, input_frame.width(), input_frame.height()); |
| 520 | width_ = input_frame.width(); |
| 521 | height_ = input_frame.height(); |
| 522 | ResetCodec(); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 523 | return WEBRTC_VIDEO_CODEC_OK; |
| 524 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 525 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 526 | // Check if we accumulated too many frames in encoder input buffers |
| 527 | // or the encoder latency exceeds 70 ms and drop frame if so. |
| 528 | if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) { |
| 529 | int encoder_latency_ms = last_input_timestamp_ms_ - |
| 530 | last_output_timestamp_ms_; |
| 531 | if (frames_in_queue_ > 2 || encoder_latency_ms > 70) { |
| 532 | ALOGD("Drop frame - encoder is behind by %d ms. Q size: %d", |
| 533 | encoder_latency_ms, frames_in_queue_); |
| 534 | frames_dropped_++; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 535 | // Report dropped frame to quality_scaler_. |
| 536 | OnDroppedFrame(); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 537 | return WEBRTC_VIDEO_CODEC_OK; |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_, |
| 542 | j_dequeue_input_buffer_method_); |
| 543 | CHECK_EXCEPTION(jni); |
| 544 | if (j_input_buffer_index == -1) { |
| 545 | // Video codec falls behind - no input buffer available. |
| 546 | ALOGV("Encoder drop frame - no input buffers available"); |
| 547 | frames_dropped_++; |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 548 | // Report dropped frame to quality_scaler_. |
| 549 | OnDroppedFrame(); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 550 | return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887. |
| 551 | } |
| 552 | if (j_input_buffer_index == -2) { |
| 553 | ResetCodec(); |
| 554 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 555 | } |
| 556 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 557 | ALOGV("Encoder frame in # %d. TS: %lld. Q: %d", |
| 558 | frames_received_ - 1, current_timestamp_us_ / 1000, frames_in_queue_); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 559 | |
| 560 | jobject j_input_buffer = input_buffers_[j_input_buffer_index]; |
| 561 | uint8* yuv_buffer = |
| 562 | reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer)); |
| 563 | CHECK_EXCEPTION(jni); |
henrikg | 91d6ede | 2015-09-17 00:24:34 -0700 | [diff] [blame] | 564 | RTC_CHECK(yuv_buffer) << "Indirect buffer??"; |
| 565 | RTC_CHECK(!libyuv::ConvertFromI420( |
| 566 | input_frame.buffer(webrtc::kYPlane), input_frame.stride(webrtc::kYPlane), |
| 567 | input_frame.buffer(webrtc::kUPlane), input_frame.stride(webrtc::kUPlane), |
| 568 | input_frame.buffer(webrtc::kVPlane), input_frame.stride(webrtc::kVPlane), |
| 569 | yuv_buffer, width_, width_, height_, encoder_fourcc_)) |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 570 | << "ConvertFromI420 failed"; |
| 571 | last_input_timestamp_ms_ = current_timestamp_us_ / 1000; |
| 572 | frames_in_queue_++; |
| 573 | |
| 574 | // Save input image timestamps for later output |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 575 | timestamps_.push_back(input_frame.timestamp()); |
| 576 | render_times_ms_.push_back(input_frame.render_time_ms()); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 577 | frame_rtc_times_ms_.push_back(GetCurrentTimeMs()); |
| 578 | |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 579 | bool key_frame = frame_types->front() != webrtc::kDeltaFrame; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 580 | bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_, |
| 581 | j_encode_method_, |
| 582 | key_frame, |
| 583 | j_input_buffer_index, |
| 584 | yuv_size_, |
| 585 | current_timestamp_us_); |
| 586 | CHECK_EXCEPTION(jni); |
| 587 | current_timestamp_us_ += 1000000 / last_set_fps_; |
| 588 | |
| 589 | if (!encode_status || !DeliverPendingOutputs(jni)) { |
| 590 | ResetCodec(); |
| 591 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 592 | } |
| 593 | |
| 594 | return WEBRTC_VIDEO_CODEC_OK; |
| 595 | } |
| 596 | |
| 597 | int32_t MediaCodecVideoEncoder::RegisterEncodeCompleteCallbackOnCodecThread( |
| 598 | webrtc::EncodedImageCallback* callback) { |
| 599 | CheckOnCodecThread(); |
| 600 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 601 | ScopedLocalRefFrame local_ref_frame(jni); |
| 602 | callback_ = callback; |
| 603 | return WEBRTC_VIDEO_CODEC_OK; |
| 604 | } |
| 605 | |
| 606 | int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() { |
| 607 | if (!inited_) { |
| 608 | return WEBRTC_VIDEO_CODEC_OK; |
| 609 | } |
| 610 | CheckOnCodecThread(); |
| 611 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 612 | ALOGD("EncoderReleaseOnCodecThread: Frames received: %d. Encoded: %d. " |
| 613 | "Dropped: %d.", frames_received_, frames_encoded_, frames_dropped_); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 614 | ScopedLocalRefFrame local_ref_frame(jni); |
| 615 | for (size_t i = 0; i < input_buffers_.size(); ++i) |
| 616 | jni->DeleteGlobalRef(input_buffers_[i]); |
| 617 | input_buffers_.clear(); |
| 618 | jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_); |
| 619 | CHECK_EXCEPTION(jni); |
| 620 | rtc::MessageQueueManager::Clear(this); |
| 621 | inited_ = false; |
| 622 | return WEBRTC_VIDEO_CODEC_OK; |
| 623 | } |
| 624 | |
| 625 | int32_t MediaCodecVideoEncoder::SetRatesOnCodecThread(uint32_t new_bit_rate, |
| 626 | uint32_t frame_rate) { |
| 627 | CheckOnCodecThread(); |
| 628 | if (last_set_bitrate_kbps_ == new_bit_rate && |
| 629 | last_set_fps_ == frame_rate) { |
| 630 | return WEBRTC_VIDEO_CODEC_OK; |
| 631 | } |
| 632 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 633 | ScopedLocalRefFrame local_ref_frame(jni); |
| 634 | if (new_bit_rate > 0) { |
| 635 | last_set_bitrate_kbps_ = new_bit_rate; |
| 636 | } |
| 637 | if (frame_rate > 0) { |
| 638 | last_set_fps_ = frame_rate; |
| 639 | } |
| 640 | bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_, |
| 641 | j_set_rates_method_, |
| 642 | last_set_bitrate_kbps_, |
| 643 | last_set_fps_); |
| 644 | CHECK_EXCEPTION(jni); |
| 645 | if (!ret) { |
| 646 | ResetCodec(); |
| 647 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 648 | } |
| 649 | return WEBRTC_VIDEO_CODEC_OK; |
| 650 | } |
| 651 | |
| 652 | int MediaCodecVideoEncoder::GetOutputBufferInfoIndex( |
| 653 | JNIEnv* jni, |
| 654 | jobject j_output_buffer_info) { |
| 655 | return GetIntField(jni, j_output_buffer_info, j_info_index_field_); |
| 656 | } |
| 657 | |
| 658 | jobject MediaCodecVideoEncoder::GetOutputBufferInfoBuffer( |
| 659 | JNIEnv* jni, |
| 660 | jobject j_output_buffer_info) { |
| 661 | return GetObjectField(jni, j_output_buffer_info, j_info_buffer_field_); |
| 662 | } |
| 663 | |
| 664 | bool MediaCodecVideoEncoder::GetOutputBufferInfoIsKeyFrame( |
| 665 | JNIEnv* jni, |
| 666 | jobject j_output_buffer_info) { |
| 667 | return GetBooleanField(jni, j_output_buffer_info, j_info_is_key_frame_field_); |
| 668 | } |
| 669 | |
| 670 | jlong MediaCodecVideoEncoder::GetOutputBufferInfoPresentationTimestampUs( |
| 671 | JNIEnv* jni, |
| 672 | jobject j_output_buffer_info) { |
| 673 | return GetLongField( |
| 674 | jni, j_output_buffer_info, j_info_presentation_timestamp_us_field_); |
| 675 | } |
| 676 | |
| 677 | bool MediaCodecVideoEncoder::DeliverPendingOutputs(JNIEnv* jni) { |
| 678 | while (true) { |
| 679 | jobject j_output_buffer_info = jni->CallObjectMethod( |
| 680 | *j_media_codec_video_encoder_, j_dequeue_output_buffer_method_); |
| 681 | CHECK_EXCEPTION(jni); |
| 682 | if (IsNull(jni, j_output_buffer_info)) { |
| 683 | break; |
| 684 | } |
| 685 | |
| 686 | int output_buffer_index = |
| 687 | GetOutputBufferInfoIndex(jni, j_output_buffer_info); |
| 688 | if (output_buffer_index == -1) { |
| 689 | ResetCodec(); |
| 690 | return false; |
| 691 | } |
| 692 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 693 | // Get key and config frame flags. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 694 | jobject j_output_buffer = |
| 695 | GetOutputBufferInfoBuffer(jni, j_output_buffer_info); |
| 696 | bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 697 | |
| 698 | // Get frame timestamps from a queue - for non config frames only. |
| 699 | int64_t frame_encoding_time_ms = 0; |
| 700 | last_output_timestamp_ms_ = |
| 701 | GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) / |
| 702 | 1000; |
| 703 | if (frames_in_queue_ > 0) { |
| 704 | output_timestamp_ = timestamps_.front(); |
| 705 | timestamps_.erase(timestamps_.begin()); |
| 706 | output_render_time_ms_ = render_times_ms_.front(); |
| 707 | render_times_ms_.erase(render_times_ms_.begin()); |
| 708 | frame_encoding_time_ms = GetCurrentTimeMs() - frame_rtc_times_ms_.front(); |
| 709 | frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin()); |
| 710 | frames_in_queue_--; |
| 711 | } |
| 712 | |
| 713 | // Extract payload. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 714 | size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer); |
| 715 | uint8* payload = reinterpret_cast<uint8_t*>( |
| 716 | jni->GetDirectBufferAddress(j_output_buffer)); |
| 717 | CHECK_EXCEPTION(jni); |
| 718 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 719 | ALOGV("Encoder frame out # %d. Key: %d. Size: %d. TS: %lld." |
| 720 | " Latency: %lld. EncTime: %lld", |
| 721 | frames_encoded_, key_frame, payload_size, |
| 722 | last_output_timestamp_ms_, |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 723 | last_input_timestamp_ms_ - last_output_timestamp_ms_, |
| 724 | frame_encoding_time_ms); |
| 725 | |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 726 | if (payload_size && scale_ && codecType_ == kVideoCodecVP8) |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 727 | quality_scaler_->ReportQP(webrtc::vp8::GetQP(payload)); |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 728 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 729 | // Calculate and print encoding statistics - every 3 seconds. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 730 | frames_encoded_++; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 731 | current_frames_++; |
| 732 | current_bytes_ += payload_size; |
| 733 | current_encoding_time_ms_ += frame_encoding_time_ms; |
| 734 | int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_; |
| 735 | if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs && |
| 736 | current_frames_ > 0) { |
| 737 | ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d," |
| 738 | " encTime: %d for last %d ms", |
| 739 | current_bytes_ * 8 / statistic_time_ms, |
| 740 | last_set_bitrate_kbps_, |
| 741 | (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms, |
| 742 | current_encoding_time_ms_ / current_frames_, statistic_time_ms); |
| 743 | start_time_ms_ = GetCurrentTimeMs(); |
| 744 | current_frames_ = 0; |
| 745 | current_bytes_ = 0; |
| 746 | current_encoding_time_ms_ = 0; |
| 747 | } |
| 748 | |
| 749 | // Callback - return encoded frame. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 750 | int32_t callback_status = 0; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 751 | if (callback_) { |
| 752 | scoped_ptr<webrtc::EncodedImage> image( |
| 753 | new webrtc::EncodedImage(payload, payload_size, payload_size)); |
| 754 | image->_encodedWidth = width_; |
| 755 | image->_encodedHeight = height_; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 756 | image->_timeStamp = output_timestamp_; |
| 757 | image->capture_time_ms_ = output_render_time_ms_; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 758 | image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame); |
| 759 | image->_completeFrame = true; |
| 760 | |
| 761 | webrtc::CodecSpecificInfo info; |
| 762 | memset(&info, 0, sizeof(info)); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 763 | info.codecType = codecType_; |
| 764 | if (codecType_ == kVideoCodecVP8) { |
| 765 | info.codecSpecific.VP8.pictureId = picture_id_; |
| 766 | info.codecSpecific.VP8.nonReference = false; |
| 767 | info.codecSpecific.VP8.simulcastIdx = 0; |
| 768 | info.codecSpecific.VP8.temporalIdx = webrtc::kNoTemporalIdx; |
| 769 | info.codecSpecific.VP8.layerSync = false; |
| 770 | info.codecSpecific.VP8.tl0PicIdx = webrtc::kNoTl0PicIdx; |
| 771 | info.codecSpecific.VP8.keyIdx = webrtc::kNoKeyIdx; |
| 772 | picture_id_ = (picture_id_ + 1) & 0x7FFF; |
| 773 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 774 | |
| 775 | // Generate a header describing a single fragment. |
| 776 | webrtc::RTPFragmentationHeader header; |
| 777 | memset(&header, 0, sizeof(header)); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 778 | if (codecType_ == kVideoCodecVP8) { |
| 779 | header.VerifyAndAllocateFragmentationHeader(1); |
| 780 | header.fragmentationOffset[0] = 0; |
| 781 | header.fragmentationLength[0] = image->_length; |
| 782 | header.fragmentationPlType[0] = 0; |
| 783 | header.fragmentationTimeDiff[0] = 0; |
| 784 | } else if (codecType_ == kVideoCodecH264) { |
| 785 | // For H.264 search for start codes. |
| 786 | int32_t scPositions[MAX_NALUS_PERFRAME + 1] = {}; |
| 787 | int32_t scPositionsLength = 0; |
| 788 | int32_t scPosition = 0; |
| 789 | while (scPositionsLength < MAX_NALUS_PERFRAME) { |
| 790 | int32_t naluPosition = NextNaluPosition( |
| 791 | payload + scPosition, payload_size - scPosition); |
| 792 | if (naluPosition < 0) { |
| 793 | break; |
| 794 | } |
| 795 | scPosition += naluPosition; |
| 796 | scPositions[scPositionsLength++] = scPosition; |
| 797 | scPosition += H264_SC_LENGTH; |
| 798 | } |
| 799 | if (scPositionsLength == 0) { |
| 800 | ALOGE("Start code is not found!"); |
| 801 | ALOGE("Data 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x", |
| 802 | image->_buffer[0], image->_buffer[1], image->_buffer[2], |
| 803 | image->_buffer[3], image->_buffer[4], image->_buffer[5]); |
| 804 | ResetCodec(); |
| 805 | return false; |
| 806 | } |
| 807 | scPositions[scPositionsLength] = payload_size; |
| 808 | header.VerifyAndAllocateFragmentationHeader(scPositionsLength); |
| 809 | for (size_t i = 0; i < scPositionsLength; i++) { |
| 810 | header.fragmentationOffset[i] = scPositions[i] + H264_SC_LENGTH; |
| 811 | header.fragmentationLength[i] = |
| 812 | scPositions[i + 1] - header.fragmentationOffset[i]; |
| 813 | header.fragmentationPlType[i] = 0; |
| 814 | header.fragmentationTimeDiff[i] = 0; |
| 815 | } |
| 816 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 817 | |
| 818 | callback_status = callback_->Encoded(*image, &info, &header); |
| 819 | } |
| 820 | |
| 821 | // Return output buffer back to the encoder. |
| 822 | bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_, |
| 823 | j_release_output_buffer_method_, |
| 824 | output_buffer_index); |
| 825 | CHECK_EXCEPTION(jni); |
| 826 | if (!success) { |
| 827 | ResetCodec(); |
| 828 | return false; |
| 829 | } |
| 830 | |
| 831 | if (callback_status > 0) { |
| 832 | drop_next_input_frame_ = true; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 833 | // Theoretically could handle callback_status<0 here, but unclear what |
| 834 | // that would mean for us. |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 835 | } |
| 836 | } |
| 837 | |
| 838 | return true; |
| 839 | } |
| 840 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 841 | int32_t MediaCodecVideoEncoder::NextNaluPosition( |
| 842 | uint8_t *buffer, size_t buffer_size) { |
| 843 | if (buffer_size < H264_SC_LENGTH) { |
| 844 | return -1; |
| 845 | } |
| 846 | uint8_t *head = buffer; |
| 847 | // Set end buffer pointer to 4 bytes before actual buffer end so we can |
| 848 | // access head[1], head[2] and head[3] in a loop without buffer overrun. |
| 849 | uint8_t *end = buffer + buffer_size - H264_SC_LENGTH; |
| 850 | |
| 851 | while (head < end) { |
| 852 | if (head[0]) { |
| 853 | head++; |
| 854 | continue; |
| 855 | } |
| 856 | if (head[1]) { // got 00xx |
| 857 | head += 2; |
| 858 | continue; |
| 859 | } |
| 860 | if (head[2]) { // got 0000xx |
| 861 | head += 3; |
| 862 | continue; |
| 863 | } |
| 864 | if (head[3] != 0x01) { // got 000000xx |
glaznev@webrtc.org | dc08a23 | 2015-03-06 23:32:20 +0000 | [diff] [blame] | 865 | head++; // xx != 1, continue searching. |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 866 | continue; |
| 867 | } |
| 868 | return (int32_t)(head - buffer); |
| 869 | } |
| 870 | return -1; |
| 871 | } |
| 872 | |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 873 | void MediaCodecVideoEncoder::OnDroppedFrame() { |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 874 | if (scale_ && codecType_ == kVideoCodecVP8) |
jackychen | 98d8cf5 | 2015-05-21 11:12:02 -0700 | [diff] [blame] | 875 | quality_scaler_->ReportDroppedFrame(); |
jackychen | 61b4d51 | 2015-04-21 15:30:11 -0700 | [diff] [blame] | 876 | } |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 877 | |
jackychen | 6e2ce6e | 2015-07-13 16:26:33 -0700 | [diff] [blame] | 878 | int MediaCodecVideoEncoder::GetTargetFramerate() { |
| 879 | return updated_framerate_; |
| 880 | } |
| 881 | |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 882 | MediaCodecVideoEncoderFactory::MediaCodecVideoEncoderFactory() { |
| 883 | JNIEnv* jni = AttachCurrentThreadIfNeeded(); |
| 884 | ScopedLocalRefFrame local_ref_frame(jni); |
| 885 | jclass j_encoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoEncoder"); |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 886 | supported_codecs_.clear(); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 887 | |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 888 | bool is_vp8_hw_supported = jni->CallStaticBooleanMethod( |
| 889 | j_encoder_class, |
| 890 | GetStaticMethodID(jni, j_encoder_class, "isVp8HwSupported", "()Z")); |
| 891 | CHECK_EXCEPTION(jni); |
| 892 | if (is_vp8_hw_supported) { |
| 893 | ALOGD("VP8 HW Encoder supported."); |
| 894 | supported_codecs_.push_back(VideoCodec(kVideoCodecVP8, "VP8", |
| 895 | MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS)); |
| 896 | } |
| 897 | |
| 898 | bool is_h264_hw_supported = jni->CallStaticBooleanMethod( |
| 899 | j_encoder_class, |
| 900 | GetStaticMethodID(jni, j_encoder_class, "isH264HwSupported", "()Z")); |
| 901 | CHECK_EXCEPTION(jni); |
| 902 | if (is_h264_hw_supported) { |
| 903 | ALOGD("H.264 HW Encoder supported."); |
| 904 | supported_codecs_.push_back(VideoCodec(kVideoCodecH264, "H264", |
| 905 | MAX_VIDEO_WIDTH, MAX_VIDEO_HEIGHT, MAX_VIDEO_FPS)); |
| 906 | } |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 907 | } |
| 908 | |
| 909 | MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {} |
| 910 | |
| 911 | webrtc::VideoEncoder* MediaCodecVideoEncoderFactory::CreateVideoEncoder( |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 912 | VideoCodecType type) { |
| 913 | if (supported_codecs_.empty()) { |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 914 | return NULL; |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 915 | } |
| 916 | for (std::vector<VideoCodec>::const_iterator it = supported_codecs_.begin(); |
| 917 | it != supported_codecs_.end(); ++it) { |
| 918 | if (it->type == type) { |
| 919 | ALOGD("Create HW video encoder for type %d (%s).", |
| 920 | (int)type, it->name.c_str()); |
| 921 | return new MediaCodecVideoEncoder(AttachCurrentThreadIfNeeded(), type); |
| 922 | } |
| 923 | } |
| 924 | return NULL; |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 925 | } |
| 926 | |
| 927 | const std::vector<MediaCodecVideoEncoderFactory::VideoCodec>& |
| 928 | MediaCodecVideoEncoderFactory::codecs() const { |
| 929 | return supported_codecs_; |
| 930 | } |
| 931 | |
| 932 | void MediaCodecVideoEncoderFactory::DestroyVideoEncoder( |
| 933 | webrtc::VideoEncoder* encoder) { |
glaznev@webrtc.org | b28474c | 2015-02-23 17:44:27 +0000 | [diff] [blame] | 934 | ALOGD("Destroy video encoder."); |
glaznev@webrtc.org | 18c9247 | 2015-02-18 18:42:55 +0000 | [diff] [blame] | 935 | delete encoder; |
| 936 | } |
| 937 | |
| 938 | } // namespace webrtc_jni |
| 939 | |