| OLD | NEW |
| (Empty) |
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "content/common/gpu/media/vt_video_decode_accelerator_mac.h" | |
| 6 | |
| 7 #include <CoreVideo/CoreVideo.h> | |
| 8 #include <OpenGL/CGLIOSurface.h> | |
| 9 #include <OpenGL/gl.h> | |
| 10 #include <stddef.h> | |
| 11 | |
| 12 #include <algorithm> | |
| 13 #include <memory> | |
| 14 | |
| 15 #include "base/bind.h" | |
| 16 #include "base/logging.h" | |
| 17 #include "base/mac/mac_logging.h" | |
| 18 #include "base/macros.h" | |
| 19 #include "base/memory/ptr_util.h" | |
| 20 #include "base/metrics/histogram_macros.h" | |
| 21 #include "base/sys_byteorder.h" | |
| 22 #include "base/sys_info.h" | |
| 23 #include "base/thread_task_runner_handle.h" | |
| 24 #include "base/version.h" | |
| 25 #include "media/base/limits.h" | |
| 26 #include "ui/gl/gl_context.h" | |
| 27 #include "ui/gl/gl_image_io_surface.h" | |
| 28 #include "ui/gl/gl_implementation.h" | |
| 29 #include "ui/gl/scoped_binders.h" | |
| 30 | |
| 31 using content_common_gpu_media::kModuleVt; | |
| 32 using content_common_gpu_media::InitializeStubs; | |
| 33 using content_common_gpu_media::IsVtInitialized; | |
| 34 using content_common_gpu_media::StubPathMap; | |
| 35 | |
| 36 #define NOTIFY_STATUS(name, status, session_failure) \ | |
| 37 do { \ | |
| 38 OSSTATUS_DLOG(ERROR, status) << name; \ | |
| 39 NotifyError(PLATFORM_FAILURE, session_failure); \ | |
| 40 } while (0) | |
| 41 | |
| 42 namespace content { | |
| 43 | |
| 44 // Only H.264 with 4:2:0 chroma sampling is supported. | |
| 45 static const media::VideoCodecProfile kSupportedProfiles[] = { | |
| 46 media::H264PROFILE_BASELINE, | |
| 47 media::H264PROFILE_MAIN, | |
| 48 media::H264PROFILE_EXTENDED, | |
| 49 media::H264PROFILE_HIGH, | |
| 50 // TODO(hubbe): Try to re-enable this again somehow. Currently it seems | |
| 51 // that some codecs fail to check the profile during initialization and | |
| 52 // then fail on the first frame decode, which currently results in a | |
| 53 // pipeline failure. | |
| 54 // media::H264PROFILE_HIGH10PROFILE, | |
| 55 media::H264PROFILE_SCALABLEBASELINE, | |
| 56 media::H264PROFILE_SCALABLEHIGH, | |
| 57 media::H264PROFILE_STEREOHIGH, | |
| 58 media::H264PROFILE_MULTIVIEWHIGH, | |
| 59 }; | |
| 60 | |
| 61 // Size to use for NALU length headers in AVC format (can be 1, 2, or 4). | |
| 62 static const int kNALUHeaderLength = 4; | |
| 63 | |
| 64 // We request 5 picture buffers from the client, each of which has a texture ID | |
| 65 // that we can bind decoded frames to. We need enough to satisfy preroll, and | |
| 66 // enough to avoid unnecessary stalling, but no more than that. The resource | |
| 67 // requirements are low, as we don't need the textures to be backed by storage. | |
| 68 static const int kNumPictureBuffers = media::limits::kMaxVideoFrames + 1; | |
| 69 | |
| 70 // Maximum number of frames to queue for reordering before we stop asking for | |
| 71 // more. (NotifyEndOfBitstreamBuffer() is called when frames are moved into the | |
| 72 // reorder queue.) | |
| 73 static const int kMaxReorderQueueSize = 16; | |
| 74 | |
| 75 // Build an |image_config| dictionary for VideoToolbox initialization. | |
| 76 static base::ScopedCFTypeRef<CFMutableDictionaryRef> | |
| 77 BuildImageConfig(CMVideoDimensions coded_dimensions) { | |
| 78 base::ScopedCFTypeRef<CFMutableDictionaryRef> image_config; | |
| 79 | |
| 80 // Note that 4:2:0 textures cannot be used directly as RGBA in OpenGL, but are | |
| 81 // lower power than 4:2:2 when composited directly by CoreAnimation. | |
| 82 int32_t pixel_format = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; | |
| 83 #define CFINT(i) CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i) | |
| 84 base::ScopedCFTypeRef<CFNumberRef> cf_pixel_format(CFINT(pixel_format)); | |
| 85 base::ScopedCFTypeRef<CFNumberRef> cf_width(CFINT(coded_dimensions.width)); | |
| 86 base::ScopedCFTypeRef<CFNumberRef> cf_height(CFINT(coded_dimensions.height)); | |
| 87 #undef CFINT | |
| 88 if (!cf_pixel_format.get() || !cf_width.get() || !cf_height.get()) | |
| 89 return image_config; | |
| 90 | |
| 91 image_config.reset( | |
| 92 CFDictionaryCreateMutable( | |
| 93 kCFAllocatorDefault, | |
| 94 3, // capacity | |
| 95 &kCFTypeDictionaryKeyCallBacks, | |
| 96 &kCFTypeDictionaryValueCallBacks)); | |
| 97 if (!image_config.get()) | |
| 98 return image_config; | |
| 99 | |
| 100 CFDictionarySetValue(image_config, kCVPixelBufferPixelFormatTypeKey, | |
| 101 cf_pixel_format); | |
| 102 CFDictionarySetValue(image_config, kCVPixelBufferWidthKey, cf_width); | |
| 103 CFDictionarySetValue(image_config, kCVPixelBufferHeightKey, cf_height); | |
| 104 | |
| 105 return image_config; | |
| 106 } | |
| 107 | |
| 108 // Create a VTDecompressionSession using the provided |pps| and |sps|. If | |
| 109 // |require_hardware| is true, the session must uses real hardware decoding | |
| 110 // (as opposed to software decoding inside of VideoToolbox) to be considered | |
| 111 // successful. | |
| 112 // | |
| 113 // TODO(sandersd): Merge with ConfigureDecoder(), as the code is very similar. | |
| 114 static bool CreateVideoToolboxSession(const uint8_t* sps, size_t sps_size, | |
| 115 const uint8_t* pps, size_t pps_size, | |
| 116 bool require_hardware) { | |
| 117 const uint8_t* data_ptrs[] = {sps, pps}; | |
| 118 const size_t data_sizes[] = {sps_size, pps_size}; | |
| 119 | |
| 120 base::ScopedCFTypeRef<CMFormatDescriptionRef> format; | |
| 121 OSStatus status = CMVideoFormatDescriptionCreateFromH264ParameterSets( | |
| 122 kCFAllocatorDefault, | |
| 123 2, // parameter_set_count | |
| 124 data_ptrs, // ¶meter_set_pointers | |
| 125 data_sizes, // ¶meter_set_sizes | |
| 126 kNALUHeaderLength, // nal_unit_header_length | |
| 127 format.InitializeInto()); | |
| 128 if (status) { | |
| 129 OSSTATUS_DLOG(WARNING, status) | |
| 130 << "Failed to create CMVideoFormatDescription"; | |
| 131 return false; | |
| 132 } | |
| 133 | |
| 134 base::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( | |
| 135 CFDictionaryCreateMutable( | |
| 136 kCFAllocatorDefault, | |
| 137 1, // capacity | |
| 138 &kCFTypeDictionaryKeyCallBacks, | |
| 139 &kCFTypeDictionaryValueCallBacks)); | |
| 140 if (!decoder_config.get()) | |
| 141 return false; | |
| 142 | |
| 143 if (require_hardware) { | |
| 144 CFDictionarySetValue( | |
| 145 decoder_config, | |
| 146 // kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder | |
| 147 CFSTR("RequireHardwareAcceleratedVideoDecoder"), | |
| 148 kCFBooleanTrue); | |
| 149 } | |
| 150 | |
| 151 base::ScopedCFTypeRef<CFMutableDictionaryRef> image_config( | |
| 152 BuildImageConfig(CMVideoFormatDescriptionGetDimensions(format))); | |
| 153 if (!image_config.get()) | |
| 154 return false; | |
| 155 | |
| 156 VTDecompressionOutputCallbackRecord callback = {0}; | |
| 157 | |
| 158 base::ScopedCFTypeRef<VTDecompressionSessionRef> session; | |
| 159 status = VTDecompressionSessionCreate( | |
| 160 kCFAllocatorDefault, | |
| 161 format, // video_format_description | |
| 162 decoder_config, // video_decoder_specification | |
| 163 image_config, // destination_image_buffer_attributes | |
| 164 &callback, // output_callback | |
| 165 session.InitializeInto()); | |
| 166 if (status) { | |
| 167 OSSTATUS_DLOG(WARNING, status) | |
| 168 << "Failed to create VTDecompressionSession"; | |
| 169 return false; | |
| 170 } | |
| 171 | |
| 172 return true; | |
| 173 } | |
| 174 | |
| 175 // The purpose of this function is to preload the generic and hardware-specific | |
| 176 // libraries required by VideoToolbox before the GPU sandbox is enabled. | |
| 177 // VideoToolbox normally loads the hardware-specific libraries lazily, so we | |
| 178 // must actually create a decompression session. If creating a decompression | |
| 179 // session fails, hardware decoding will be disabled (Initialize() will always | |
| 180 // return false). | |
| 181 static bool InitializeVideoToolboxInternal() { | |
| 182 if (!IsVtInitialized()) { | |
| 183 // CoreVideo is also required, but the loader stops after the first path is | |
| 184 // loaded. Instead we rely on the transitive dependency from VideoToolbox to | |
| 185 // CoreVideo. | |
| 186 StubPathMap paths; | |
| 187 paths[kModuleVt].push_back(FILE_PATH_LITERAL( | |
| 188 "/System/Library/Frameworks/VideoToolbox.framework/VideoToolbox")); | |
| 189 if (!InitializeStubs(paths)) { | |
| 190 DLOG(WARNING) << "Failed to initialize VideoToolbox framework"; | |
| 191 return false; | |
| 192 } | |
| 193 } | |
| 194 | |
| 195 // Create a hardware decoding session. | |
| 196 // SPS and PPS data are taken from a 480p sample (buck2.mp4). | |
| 197 const uint8_t sps_normal[] = {0x67, 0x64, 0x00, 0x1e, 0xac, 0xd9, 0x80, 0xd4, | |
| 198 0x3d, 0xa1, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, | |
| 199 0x00, 0x03, 0x00, 0x30, 0x8f, 0x16, 0x2d, 0x9a}; | |
| 200 const uint8_t pps_normal[] = {0x68, 0xe9, 0x7b, 0xcb}; | |
| 201 if (!CreateVideoToolboxSession(sps_normal, arraysize(sps_normal), pps_normal, | |
| 202 arraysize(pps_normal), true)) { | |
| 203 DLOG(WARNING) << "Failed to create hardware VideoToolbox session"; | |
| 204 return false; | |
| 205 } | |
| 206 | |
| 207 // Create a software decoding session. | |
| 208 // SPS and PPS data are taken from a 18p sample (small2.mp4). | |
| 209 const uint8_t sps_small[] = {0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x89, 0x7e, | |
| 210 0x22, 0x10, 0x00, 0x00, 0x3e, 0x90, 0x00, 0x0e, | |
| 211 0xa6, 0x08, 0xf1, 0x22, 0x59, 0xa0}; | |
| 212 const uint8_t pps_small[] = {0x68, 0xe9, 0x79, 0x72, 0xc0}; | |
| 213 if (!CreateVideoToolboxSession(sps_small, arraysize(sps_small), pps_small, | |
| 214 arraysize(pps_small), false)) { | |
| 215 DLOG(WARNING) << "Failed to create software VideoToolbox session"; | |
| 216 return false; | |
| 217 } | |
| 218 | |
| 219 return true; | |
| 220 } | |
| 221 | |
| 222 bool InitializeVideoToolbox() { | |
| 223 // InitializeVideoToolbox() is called only from the GPU process main thread; | |
| 224 // once for sandbox warmup, and then once each time a VTVideoDecodeAccelerator | |
| 225 // is initialized. | |
| 226 static bool attempted = false; | |
| 227 static bool succeeded = false; | |
| 228 | |
| 229 if (!attempted) { | |
| 230 attempted = true; | |
| 231 succeeded = InitializeVideoToolboxInternal(); | |
| 232 } | |
| 233 | |
| 234 return succeeded; | |
| 235 } | |
| 236 | |
| 237 // Route decoded frame callbacks back into the VTVideoDecodeAccelerator. | |
| 238 static void OutputThunk( | |
| 239 void* decompression_output_refcon, | |
| 240 void* source_frame_refcon, | |
| 241 OSStatus status, | |
| 242 VTDecodeInfoFlags info_flags, | |
| 243 CVImageBufferRef image_buffer, | |
| 244 CMTime presentation_time_stamp, | |
| 245 CMTime presentation_duration) { | |
| 246 VTVideoDecodeAccelerator* vda = | |
| 247 reinterpret_cast<VTVideoDecodeAccelerator*>(decompression_output_refcon); | |
| 248 vda->Output(source_frame_refcon, status, image_buffer); | |
| 249 } | |
| 250 | |
| 251 VTVideoDecodeAccelerator::Task::Task(TaskType type) : type(type) { | |
| 252 } | |
| 253 | |
| 254 VTVideoDecodeAccelerator::Task::Task(const Task& other) = default; | |
| 255 | |
| 256 VTVideoDecodeAccelerator::Task::~Task() { | |
| 257 } | |
| 258 | |
| 259 VTVideoDecodeAccelerator::Frame::Frame(int32_t bitstream_id) | |
| 260 : bitstream_id(bitstream_id), | |
| 261 pic_order_cnt(0), | |
| 262 is_idr(false), | |
| 263 reorder_window(0) { | |
| 264 } | |
| 265 | |
| 266 VTVideoDecodeAccelerator::Frame::~Frame() { | |
| 267 } | |
| 268 | |
| 269 VTVideoDecodeAccelerator::PictureInfo::PictureInfo(uint32_t client_texture_id, | |
| 270 uint32_t service_texture_id) | |
| 271 : client_texture_id(client_texture_id), | |
| 272 service_texture_id(service_texture_id) {} | |
| 273 | |
| 274 VTVideoDecodeAccelerator::PictureInfo::~PictureInfo() { | |
| 275 if (gl_image) | |
| 276 gl_image->Destroy(false); | |
| 277 } | |
| 278 | |
| 279 bool VTVideoDecodeAccelerator::FrameOrder::operator()( | |
| 280 const linked_ptr<Frame>& lhs, | |
| 281 const linked_ptr<Frame>& rhs) const { | |
| 282 if (lhs->pic_order_cnt != rhs->pic_order_cnt) | |
| 283 return lhs->pic_order_cnt > rhs->pic_order_cnt; | |
| 284 // If |pic_order_cnt| is the same, fall back on using the bitstream order. | |
| 285 // TODO(sandersd): Assign a sequence number in Decode() and use that instead. | |
| 286 // TODO(sandersd): Using the sequence number, ensure that frames older than | |
| 287 // |kMaxReorderQueueSize| are ordered first, regardless of |pic_order_cnt|. | |
| 288 return lhs->bitstream_id > rhs->bitstream_id; | |
| 289 } | |
| 290 | |
| 291 VTVideoDecodeAccelerator::VTVideoDecodeAccelerator( | |
| 292 const MakeGLContextCurrentCallback& make_context_current_cb, | |
| 293 const BindGLImageCallback& bind_image_cb) | |
| 294 : make_context_current_cb_(make_context_current_cb), | |
| 295 bind_image_cb_(bind_image_cb), | |
| 296 client_(nullptr), | |
| 297 state_(STATE_DECODING), | |
| 298 format_(nullptr), | |
| 299 session_(nullptr), | |
| 300 last_sps_id_(-1), | |
| 301 last_pps_id_(-1), | |
| 302 config_changed_(false), | |
| 303 waiting_for_idr_(true), | |
| 304 missing_idr_logged_(false), | |
| 305 gpu_task_runner_(base::ThreadTaskRunnerHandle::Get()), | |
| 306 decoder_thread_("VTDecoderThread"), | |
| 307 weak_this_factory_(this) { | |
| 308 callback_.decompressionOutputCallback = OutputThunk; | |
| 309 callback_.decompressionOutputRefCon = this; | |
| 310 weak_this_ = weak_this_factory_.GetWeakPtr(); | |
| 311 } | |
| 312 | |
| 313 VTVideoDecodeAccelerator::~VTVideoDecodeAccelerator() { | |
| 314 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 315 } | |
| 316 | |
| 317 bool VTVideoDecodeAccelerator::Initialize(const Config& config, | |
| 318 Client* client) { | |
| 319 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 320 | |
| 321 if (make_context_current_cb_.is_null() || bind_image_cb_.is_null()) { | |
| 322 NOTREACHED() << "GL callbacks are required for this VDA"; | |
| 323 return false; | |
| 324 } | |
| 325 | |
| 326 if (config.is_encrypted) { | |
| 327 NOTREACHED() << "Encrypted streams are not supported for this VDA"; | |
| 328 return false; | |
| 329 } | |
| 330 | |
| 331 if (config.output_mode != Config::OutputMode::ALLOCATE) { | |
| 332 NOTREACHED() << "Only ALLOCATE OutputMode is supported by this VDA"; | |
| 333 return false; | |
| 334 } | |
| 335 | |
| 336 client_ = client; | |
| 337 | |
| 338 if (!InitializeVideoToolbox()) | |
| 339 return false; | |
| 340 | |
| 341 bool profile_supported = false; | |
| 342 for (const auto& supported_profile : kSupportedProfiles) { | |
| 343 if (config.profile == supported_profile) { | |
| 344 profile_supported = true; | |
| 345 break; | |
| 346 } | |
| 347 } | |
| 348 if (!profile_supported) | |
| 349 return false; | |
| 350 | |
| 351 // Spawn a thread to handle parsing and calling VideoToolbox. | |
| 352 if (!decoder_thread_.Start()) | |
| 353 return false; | |
| 354 | |
| 355 // Count the session as successfully initialized. | |
| 356 UMA_HISTOGRAM_ENUMERATION("Media.VTVDA.SessionFailureReason", | |
| 357 SFT_SUCCESSFULLY_INITIALIZED, | |
| 358 SFT_MAX + 1); | |
| 359 return true; | |
| 360 } | |
| 361 | |
| 362 bool VTVideoDecodeAccelerator::FinishDelayedFrames() { | |
| 363 DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); | |
| 364 if (session_) { | |
| 365 OSStatus status = VTDecompressionSessionWaitForAsynchronousFrames(session_); | |
| 366 if (status) { | |
| 367 NOTIFY_STATUS("VTDecompressionSessionWaitForAsynchronousFrames()", | |
| 368 status, SFT_PLATFORM_ERROR); | |
| 369 return false; | |
| 370 } | |
| 371 } | |
| 372 return true; | |
| 373 } | |
| 374 | |
| 375 bool VTVideoDecodeAccelerator::ConfigureDecoder() { | |
| 376 DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); | |
| 377 DCHECK(!last_sps_.empty()); | |
| 378 DCHECK(!last_pps_.empty()); | |
| 379 | |
| 380 // Build the configuration records. | |
| 381 std::vector<const uint8_t*> nalu_data_ptrs; | |
| 382 std::vector<size_t> nalu_data_sizes; | |
| 383 nalu_data_ptrs.reserve(3); | |
| 384 nalu_data_sizes.reserve(3); | |
| 385 nalu_data_ptrs.push_back(&last_sps_.front()); | |
| 386 nalu_data_sizes.push_back(last_sps_.size()); | |
| 387 if (!last_spsext_.empty()) { | |
| 388 nalu_data_ptrs.push_back(&last_spsext_.front()); | |
| 389 nalu_data_sizes.push_back(last_spsext_.size()); | |
| 390 } | |
| 391 nalu_data_ptrs.push_back(&last_pps_.front()); | |
| 392 nalu_data_sizes.push_back(last_pps_.size()); | |
| 393 | |
| 394 // Construct a new format description from the parameter sets. | |
| 395 format_.reset(); | |
| 396 OSStatus status = CMVideoFormatDescriptionCreateFromH264ParameterSets( | |
| 397 kCFAllocatorDefault, | |
| 398 nalu_data_ptrs.size(), // parameter_set_count | |
| 399 &nalu_data_ptrs.front(), // ¶meter_set_pointers | |
| 400 &nalu_data_sizes.front(), // ¶meter_set_sizes | |
| 401 kNALUHeaderLength, // nal_unit_header_length | |
| 402 format_.InitializeInto()); | |
| 403 if (status) { | |
| 404 NOTIFY_STATUS("CMVideoFormatDescriptionCreateFromH264ParameterSets()", | |
| 405 status, SFT_PLATFORM_ERROR); | |
| 406 return false; | |
| 407 } | |
| 408 | |
| 409 // Store the new configuration data. | |
| 410 // TODO(sandersd): Despite the documentation, this seems to return the visible | |
| 411 // size. However, the output always appears to be top-left aligned, so it | |
| 412 // makes no difference. Re-verify this and update the variable name. | |
| 413 CMVideoDimensions coded_dimensions = | |
| 414 CMVideoFormatDescriptionGetDimensions(format_); | |
| 415 coded_size_.SetSize(coded_dimensions.width, coded_dimensions.height); | |
| 416 | |
| 417 // Prepare VideoToolbox configuration dictionaries. | |
| 418 base::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( | |
| 419 CFDictionaryCreateMutable( | |
| 420 kCFAllocatorDefault, | |
| 421 1, // capacity | |
| 422 &kCFTypeDictionaryKeyCallBacks, | |
| 423 &kCFTypeDictionaryValueCallBacks)); | |
| 424 if (!decoder_config.get()) { | |
| 425 DLOG(ERROR) << "Failed to create CFMutableDictionary"; | |
| 426 NotifyError(PLATFORM_FAILURE, SFT_PLATFORM_ERROR); | |
| 427 return false; | |
| 428 } | |
| 429 | |
| 430 CFDictionarySetValue( | |
| 431 decoder_config, | |
| 432 // kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder | |
| 433 CFSTR("EnableHardwareAcceleratedVideoDecoder"), | |
| 434 kCFBooleanTrue); | |
| 435 | |
| 436 base::ScopedCFTypeRef<CFMutableDictionaryRef> image_config( | |
| 437 BuildImageConfig(coded_dimensions)); | |
| 438 if (!image_config.get()) { | |
| 439 DLOG(ERROR) << "Failed to create decoder image configuration"; | |
| 440 NotifyError(PLATFORM_FAILURE, SFT_PLATFORM_ERROR); | |
| 441 return false; | |
| 442 } | |
| 443 | |
| 444 // Ensure that the old decoder emits all frames before the new decoder can | |
| 445 // emit any. | |
| 446 if (!FinishDelayedFrames()) | |
| 447 return false; | |
| 448 | |
| 449 session_.reset(); | |
| 450 status = VTDecompressionSessionCreate( | |
| 451 kCFAllocatorDefault, | |
| 452 format_, // video_format_description | |
| 453 decoder_config, // video_decoder_specification | |
| 454 image_config, // destination_image_buffer_attributes | |
| 455 &callback_, // output_callback | |
| 456 session_.InitializeInto()); | |
| 457 if (status) { | |
| 458 NOTIFY_STATUS("VTDecompressionSessionCreate()", status, | |
| 459 SFT_UNSUPPORTED_STREAM_PARAMETERS); | |
| 460 return false; | |
| 461 } | |
| 462 | |
| 463 // Report whether hardware decode is being used. | |
| 464 bool using_hardware = false; | |
| 465 base::ScopedCFTypeRef<CFBooleanRef> cf_using_hardware; | |
| 466 if (VTSessionCopyProperty( | |
| 467 session_, | |
| 468 // kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder | |
| 469 CFSTR("UsingHardwareAcceleratedVideoDecoder"), | |
| 470 kCFAllocatorDefault, | |
| 471 cf_using_hardware.InitializeInto()) == 0) { | |
| 472 using_hardware = CFBooleanGetValue(cf_using_hardware); | |
| 473 } | |
| 474 UMA_HISTOGRAM_BOOLEAN("Media.VTVDA.HardwareAccelerated", using_hardware); | |
| 475 | |
| 476 return true; | |
| 477 } | |
| 478 | |
| 479 void VTVideoDecodeAccelerator::DecodeTask( | |
| 480 const media::BitstreamBuffer& bitstream, | |
| 481 Frame* frame) { | |
| 482 DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); | |
| 483 | |
| 484 // Map the bitstream buffer. | |
| 485 base::SharedMemory memory(bitstream.handle(), true); | |
| 486 size_t size = bitstream.size(); | |
| 487 if (!memory.Map(size)) { | |
| 488 DLOG(ERROR) << "Failed to map bitstream buffer"; | |
| 489 NotifyError(PLATFORM_FAILURE, SFT_PLATFORM_ERROR); | |
| 490 return; | |
| 491 } | |
| 492 const uint8_t* buf = static_cast<uint8_t*>(memory.memory()); | |
| 493 | |
| 494 // NALUs are stored with Annex B format in the bitstream buffer (start codes), | |
| 495 // but VideoToolbox expects AVC format (length headers), so we must rewrite | |
| 496 // the data. | |
| 497 // | |
| 498 // Locate relevant NALUs and compute the size of the rewritten data. Also | |
| 499 // record any parameter sets for VideoToolbox initialization. | |
| 500 std::vector<uint8_t> sps; | |
| 501 std::vector<uint8_t> spsext; | |
| 502 std::vector<uint8_t> pps; | |
| 503 bool has_slice = false; | |
| 504 size_t data_size = 0; | |
| 505 std::vector<media::H264NALU> nalus; | |
| 506 parser_.SetStream(buf, size); | |
| 507 media::H264NALU nalu; | |
| 508 while (true) { | |
| 509 media::H264Parser::Result result = parser_.AdvanceToNextNALU(&nalu); | |
| 510 if (result == media::H264Parser::kEOStream) | |
| 511 break; | |
| 512 if (result == media::H264Parser::kUnsupportedStream) { | |
| 513 DLOG(ERROR) << "Unsupported H.264 stream"; | |
| 514 NotifyError(PLATFORM_FAILURE, SFT_UNSUPPORTED_STREAM); | |
| 515 return; | |
| 516 } | |
| 517 if (result != media::H264Parser::kOk) { | |
| 518 DLOG(ERROR) << "Failed to parse H.264 stream"; | |
| 519 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 520 return; | |
| 521 } | |
| 522 switch (nalu.nal_unit_type) { | |
| 523 case media::H264NALU::kSPS: | |
| 524 result = parser_.ParseSPS(&last_sps_id_); | |
| 525 if (result == media::H264Parser::kUnsupportedStream) { | |
| 526 DLOG(ERROR) << "Unsupported SPS"; | |
| 527 NotifyError(PLATFORM_FAILURE, SFT_UNSUPPORTED_STREAM); | |
| 528 return; | |
| 529 } | |
| 530 if (result != media::H264Parser::kOk) { | |
| 531 DLOG(ERROR) << "Could not parse SPS"; | |
| 532 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 533 return; | |
| 534 } | |
| 535 sps.assign(nalu.data, nalu.data + nalu.size); | |
| 536 spsext.clear(); | |
| 537 break; | |
| 538 | |
| 539 case media::H264NALU::kSPSExt: | |
| 540 // TODO(sandersd): Check that the previous NALU was an SPS. | |
| 541 spsext.assign(nalu.data, nalu.data + nalu.size); | |
| 542 break; | |
| 543 | |
| 544 case media::H264NALU::kPPS: | |
| 545 result = parser_.ParsePPS(&last_pps_id_); | |
| 546 if (result == media::H264Parser::kUnsupportedStream) { | |
| 547 DLOG(ERROR) << "Unsupported PPS"; | |
| 548 NotifyError(PLATFORM_FAILURE, SFT_UNSUPPORTED_STREAM); | |
| 549 return; | |
| 550 } | |
| 551 if (result != media::H264Parser::kOk) { | |
| 552 DLOG(ERROR) << "Could not parse PPS"; | |
| 553 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 554 return; | |
| 555 } | |
| 556 pps.assign(nalu.data, nalu.data + nalu.size); | |
| 557 break; | |
| 558 | |
| 559 case media::H264NALU::kSliceDataA: | |
| 560 case media::H264NALU::kSliceDataB: | |
| 561 case media::H264NALU::kSliceDataC: | |
| 562 case media::H264NALU::kNonIDRSlice: | |
| 563 case media::H264NALU::kIDRSlice: | |
| 564 // Compute the |pic_order_cnt| for the picture from the first slice. | |
| 565 if (!has_slice) { | |
| 566 // Verify that we are not trying to decode a slice without an IDR. | |
| 567 if (waiting_for_idr_) { | |
| 568 if (nalu.nal_unit_type == media::H264NALU::kIDRSlice) { | |
| 569 waiting_for_idr_ = false; | |
| 570 } else { | |
| 571 // We can't compute anything yet, bail on this frame. | |
| 572 has_slice = true; | |
| 573 break; | |
| 574 } | |
| 575 } | |
| 576 | |
| 577 media::H264SliceHeader slice_hdr; | |
| 578 result = parser_.ParseSliceHeader(nalu, &slice_hdr); | |
| 579 if (result == media::H264Parser::kUnsupportedStream) { | |
| 580 DLOG(ERROR) << "Unsupported slice header"; | |
| 581 NotifyError(PLATFORM_FAILURE, SFT_UNSUPPORTED_STREAM); | |
| 582 return; | |
| 583 } | |
| 584 if (result != media::H264Parser::kOk) { | |
| 585 DLOG(ERROR) << "Could not parse slice header"; | |
| 586 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 587 return; | |
| 588 } | |
| 589 | |
| 590 // TODO(sandersd): Maintain a cache of configurations and reconfigure | |
| 591 // when a slice references a new config. | |
| 592 DCHECK_EQ(slice_hdr.pic_parameter_set_id, last_pps_id_); | |
| 593 const media::H264PPS* pps = | |
| 594 parser_.GetPPS(slice_hdr.pic_parameter_set_id); | |
| 595 if (!pps) { | |
| 596 DLOG(ERROR) << "Mising PPS referenced by slice"; | |
| 597 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 598 return; | |
| 599 } | |
| 600 | |
| 601 DCHECK_EQ(pps->seq_parameter_set_id, last_sps_id_); | |
| 602 const media::H264SPS* sps = parser_.GetSPS(pps->seq_parameter_set_id); | |
| 603 if (!sps) { | |
| 604 DLOG(ERROR) << "Mising SPS referenced by PPS"; | |
| 605 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 606 return; | |
| 607 } | |
| 608 | |
| 609 if (!poc_.ComputePicOrderCnt(sps, slice_hdr, &frame->pic_order_cnt)) { | |
| 610 DLOG(ERROR) << "Unable to compute POC"; | |
| 611 NotifyError(UNREADABLE_INPUT, SFT_INVALID_STREAM); | |
| 612 return; | |
| 613 } | |
| 614 | |
| 615 if (nalu.nal_unit_type == media::H264NALU::kIDRSlice) | |
| 616 frame->is_idr = true; | |
| 617 | |
| 618 if (sps->vui_parameters_present_flag && | |
| 619 sps->bitstream_restriction_flag) { | |
| 620 frame->reorder_window = std::min(sps->max_num_reorder_frames, | |
| 621 kMaxReorderQueueSize - 1); | |
| 622 } | |
| 623 } | |
| 624 has_slice = true; | |
| 625 default: | |
| 626 nalus.push_back(nalu); | |
| 627 data_size += kNALUHeaderLength + nalu.size; | |
| 628 break; | |
| 629 } | |
| 630 } | |
| 631 | |
| 632 // Initialize VideoToolbox. | |
| 633 if (!sps.empty() && sps != last_sps_) { | |
| 634 last_sps_.swap(sps); | |
| 635 last_spsext_.swap(spsext); | |
| 636 config_changed_ = true; | |
| 637 } | |
| 638 if (!pps.empty() && pps != last_pps_) { | |
| 639 last_pps_.swap(pps); | |
| 640 config_changed_ = true; | |
| 641 } | |
| 642 if (config_changed_) { | |
| 643 // Only reconfigure at IDRs to avoid corruption. | |
| 644 if (frame->is_idr) { | |
| 645 config_changed_ = false; | |
| 646 | |
| 647 if (last_sps_.empty()) { | |
| 648 DLOG(ERROR) << "Invalid configuration; no SPS"; | |
| 649 NotifyError(INVALID_ARGUMENT, SFT_INVALID_STREAM); | |
| 650 return; | |
| 651 } | |
| 652 if (last_pps_.empty()) { | |
| 653 DLOG(ERROR) << "Invalid configuration; no PPS"; | |
| 654 NotifyError(INVALID_ARGUMENT, SFT_INVALID_STREAM); | |
| 655 return; | |
| 656 } | |
| 657 | |
| 658 // ConfigureDecoder() calls NotifyError() on failure. | |
| 659 if (!ConfigureDecoder()) | |
| 660 return; | |
| 661 } | |
| 662 } | |
| 663 | |
| 664 // If no IDR has been seen yet, skip decoding. | |
| 665 if (has_slice && (!session_ || waiting_for_idr_) && config_changed_) { | |
| 666 if (!missing_idr_logged_) { | |
| 667 LOG(ERROR) << "Illegal attempt to decode without IDR. " | |
| 668 << "Discarding decode requests until next IDR."; | |
| 669 missing_idr_logged_ = true; | |
| 670 } | |
| 671 has_slice = false; | |
| 672 } | |
| 673 | |
| 674 // If there is nothing to decode, drop the bitstream buffer by returning an | |
| 675 // empty frame. | |
| 676 if (!has_slice) { | |
| 677 // Keep everything in order by flushing first. | |
| 678 if (!FinishDelayedFrames()) | |
| 679 return; | |
| 680 gpu_task_runner_->PostTask(FROM_HERE, base::Bind( | |
| 681 &VTVideoDecodeAccelerator::DecodeDone, weak_this_, frame)); | |
| 682 return; | |
| 683 } | |
| 684 | |
| 685 // If the session is not configured by this point, fail. | |
| 686 if (!session_) { | |
| 687 DLOG(ERROR) << "Cannot decode without configuration"; | |
| 688 NotifyError(INVALID_ARGUMENT, SFT_INVALID_STREAM); | |
| 689 return; | |
| 690 } | |
| 691 | |
| 692 // Update the frame metadata with configuration data. | |
| 693 frame->coded_size = coded_size_; | |
| 694 | |
| 695 // Create a memory-backed CMBlockBuffer for the translated data. | |
| 696 // TODO(sandersd): Pool of memory blocks. | |
| 697 base::ScopedCFTypeRef<CMBlockBufferRef> data; | |
| 698 OSStatus status = CMBlockBufferCreateWithMemoryBlock( | |
| 699 kCFAllocatorDefault, | |
| 700 nullptr, // &memory_block | |
| 701 data_size, // block_length | |
| 702 kCFAllocatorDefault, // block_allocator | |
| 703 nullptr, // &custom_block_source | |
| 704 0, // offset_to_data | |
| 705 data_size, // data_length | |
| 706 0, // flags | |
| 707 data.InitializeInto()); | |
| 708 if (status) { | |
| 709 NOTIFY_STATUS("CMBlockBufferCreateWithMemoryBlock()", status, | |
| 710 SFT_PLATFORM_ERROR); | |
| 711 return; | |
| 712 } | |
| 713 | |
| 714 // Make sure that the memory is actually allocated. | |
| 715 // CMBlockBufferReplaceDataBytes() is documented to do this, but prints a | |
| 716 // message each time starting in Mac OS X 10.10. | |
| 717 status = CMBlockBufferAssureBlockMemory(data); | |
| 718 if (status) { | |
| 719 NOTIFY_STATUS("CMBlockBufferAssureBlockMemory()", status, | |
| 720 SFT_PLATFORM_ERROR); | |
| 721 return; | |
| 722 } | |
| 723 | |
| 724 // Copy NALU data into the CMBlockBuffer, inserting length headers. | |
| 725 size_t offset = 0; | |
| 726 for (size_t i = 0; i < nalus.size(); i++) { | |
| 727 media::H264NALU& nalu = nalus[i]; | |
| 728 uint32_t header = base::HostToNet32(static_cast<uint32_t>(nalu.size)); | |
| 729 status = CMBlockBufferReplaceDataBytes( | |
| 730 &header, data, offset, kNALUHeaderLength); | |
| 731 if (status) { | |
| 732 NOTIFY_STATUS("CMBlockBufferReplaceDataBytes()", status, | |
| 733 SFT_PLATFORM_ERROR); | |
| 734 return; | |
| 735 } | |
| 736 offset += kNALUHeaderLength; | |
| 737 status = CMBlockBufferReplaceDataBytes(nalu.data, data, offset, nalu.size); | |
| 738 if (status) { | |
| 739 NOTIFY_STATUS("CMBlockBufferReplaceDataBytes()", status, | |
| 740 SFT_PLATFORM_ERROR); | |
| 741 return; | |
| 742 } | |
| 743 offset += nalu.size; | |
| 744 } | |
| 745 | |
| 746 // Package the data in a CMSampleBuffer. | |
| 747 base::ScopedCFTypeRef<CMSampleBufferRef> sample; | |
| 748 status = CMSampleBufferCreate( | |
| 749 kCFAllocatorDefault, | |
| 750 data, // data_buffer | |
| 751 true, // data_ready | |
| 752 nullptr, // make_data_ready_callback | |
| 753 nullptr, // make_data_ready_refcon | |
| 754 format_, // format_description | |
| 755 1, // num_samples | |
| 756 0, // num_sample_timing_entries | |
| 757 nullptr, // &sample_timing_array | |
| 758 1, // num_sample_size_entries | |
| 759 &data_size, // &sample_size_array | |
| 760 sample.InitializeInto()); | |
| 761 if (status) { | |
| 762 NOTIFY_STATUS("CMSampleBufferCreate()", status, SFT_PLATFORM_ERROR); | |
| 763 return; | |
| 764 } | |
| 765 | |
| 766 // Send the frame for decoding. | |
| 767 // Asynchronous Decompression allows for parallel submission of frames | |
| 768 // (without it, DecodeFrame() does not return until the frame has been | |
| 769 // decoded). We don't enable Temporal Processing so that frames are always | |
| 770 // returned in decode order; this makes it easier to avoid deadlock. | |
| 771 VTDecodeFrameFlags decode_flags = | |
| 772 kVTDecodeFrame_EnableAsynchronousDecompression; | |
| 773 status = VTDecompressionSessionDecodeFrame( | |
| 774 session_, | |
| 775 sample, // sample_buffer | |
| 776 decode_flags, // decode_flags | |
| 777 reinterpret_cast<void*>(frame), // source_frame_refcon | |
| 778 nullptr); // &info_flags_out | |
| 779 if (status) { | |
| 780 NOTIFY_STATUS("VTDecompressionSessionDecodeFrame()", status, | |
| 781 SFT_DECODE_ERROR); | |
| 782 return; | |
| 783 } | |
| 784 } | |
| 785 | |
| 786 // This method may be called on any VideoToolbox thread. | |
| 787 void VTVideoDecodeAccelerator::Output( | |
| 788 void* source_frame_refcon, | |
| 789 OSStatus status, | |
| 790 CVImageBufferRef image_buffer) { | |
| 791 if (status) { | |
| 792 NOTIFY_STATUS("Decoding", status, SFT_DECODE_ERROR); | |
| 793 return; | |
| 794 } | |
| 795 | |
| 796 // The type of |image_buffer| is CVImageBuffer, but we only handle | |
| 797 // CVPixelBuffers. This should be guaranteed as we set | |
| 798 // kCVPixelBufferOpenGLCompatibilityKey in |image_config|. | |
| 799 // | |
| 800 // Sometimes, for unknown reasons (http://crbug.com/453050), |image_buffer| is | |
| 801 // NULL, which causes CFGetTypeID() to crash. While the rest of the code would | |
| 802 // smoothly handle NULL as a dropped frame, we choose to fail permanantly here | |
| 803 // until the issue is better understood. | |
| 804 if (!image_buffer || CFGetTypeID(image_buffer) != CVPixelBufferGetTypeID()) { | |
| 805 DLOG(ERROR) << "Decoded frame is not a CVPixelBuffer"; | |
| 806 NotifyError(PLATFORM_FAILURE, SFT_DECODE_ERROR); | |
| 807 return; | |
| 808 } | |
| 809 | |
| 810 Frame* frame = reinterpret_cast<Frame*>(source_frame_refcon); | |
| 811 frame->image.reset(image_buffer, base::scoped_policy::RETAIN); | |
| 812 gpu_task_runner_->PostTask(FROM_HERE, base::Bind( | |
| 813 &VTVideoDecodeAccelerator::DecodeDone, weak_this_, frame)); | |
| 814 } | |
| 815 | |
| 816 void VTVideoDecodeAccelerator::DecodeDone(Frame* frame) { | |
| 817 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 818 DCHECK_EQ(1u, pending_frames_.count(frame->bitstream_id)); | |
| 819 Task task(TASK_FRAME); | |
| 820 task.frame = pending_frames_[frame->bitstream_id]; | |
| 821 pending_frames_.erase(frame->bitstream_id); | |
| 822 task_queue_.push(task); | |
| 823 ProcessWorkQueues(); | |
| 824 } | |
| 825 | |
| 826 void VTVideoDecodeAccelerator::FlushTask(TaskType type) { | |
| 827 DCHECK(decoder_thread_.task_runner()->BelongsToCurrentThread()); | |
| 828 FinishDelayedFrames(); | |
| 829 | |
| 830 // Always queue a task, even if FinishDelayedFrames() fails, so that | |
| 831 // destruction always completes. | |
| 832 gpu_task_runner_->PostTask(FROM_HERE, base::Bind( | |
| 833 &VTVideoDecodeAccelerator::FlushDone, weak_this_, type)); | |
| 834 } | |
| 835 | |
| 836 void VTVideoDecodeAccelerator::FlushDone(TaskType type) { | |
| 837 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 838 task_queue_.push(Task(type)); | |
| 839 ProcessWorkQueues(); | |
| 840 } | |
| 841 | |
| 842 void VTVideoDecodeAccelerator::Decode(const media::BitstreamBuffer& bitstream) { | |
| 843 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 844 if (bitstream.id() < 0) { | |
| 845 DLOG(ERROR) << "Invalid bitstream, id: " << bitstream.id(); | |
| 846 if (base::SharedMemory::IsHandleValid(bitstream.handle())) | |
| 847 base::SharedMemory::CloseHandle(bitstream.handle()); | |
| 848 NotifyError(INVALID_ARGUMENT, SFT_INVALID_STREAM); | |
| 849 return; | |
| 850 } | |
| 851 DCHECK_EQ(0u, assigned_bitstream_ids_.count(bitstream.id())); | |
| 852 assigned_bitstream_ids_.insert(bitstream.id()); | |
| 853 Frame* frame = new Frame(bitstream.id()); | |
| 854 pending_frames_[frame->bitstream_id] = make_linked_ptr(frame); | |
| 855 decoder_thread_.task_runner()->PostTask( | |
| 856 FROM_HERE, base::Bind(&VTVideoDecodeAccelerator::DecodeTask, | |
| 857 base::Unretained(this), bitstream, frame)); | |
| 858 } | |
| 859 | |
| 860 void VTVideoDecodeAccelerator::AssignPictureBuffers( | |
| 861 const std::vector<media::PictureBuffer>& pictures) { | |
| 862 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 863 | |
| 864 for (const media::PictureBuffer& picture : pictures) { | |
| 865 DCHECK(!picture_info_map_.count(picture.id())); | |
| 866 assigned_picture_ids_.insert(picture.id()); | |
| 867 available_picture_ids_.push_back(picture.id()); | |
| 868 DCHECK_LE(1u, picture.internal_texture_ids().size()); | |
| 869 DCHECK_LE(1u, picture.texture_ids().size()); | |
| 870 picture_info_map_.insert(std::make_pair( | |
| 871 picture.id(), | |
| 872 base::WrapUnique(new PictureInfo(picture.internal_texture_ids()[0], | |
| 873 picture.texture_ids()[0])))); | |
| 874 } | |
| 875 | |
| 876 // Pictures are not marked as uncleared until after this method returns, and | |
| 877 // they will be broken if they are used before that happens. So, schedule | |
| 878 // future work after that happens. | |
| 879 gpu_task_runner_->PostTask(FROM_HERE, base::Bind( | |
| 880 &VTVideoDecodeAccelerator::ProcessWorkQueues, weak_this_)); | |
| 881 } | |
| 882 | |
| 883 void VTVideoDecodeAccelerator::ReusePictureBuffer(int32_t picture_id) { | |
| 884 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 885 DCHECK(picture_info_map_.count(picture_id)); | |
| 886 PictureInfo* picture_info = picture_info_map_.find(picture_id)->second.get(); | |
| 887 picture_info->cv_image.reset(); | |
| 888 picture_info->gl_image->Destroy(false); | |
| 889 picture_info->gl_image = nullptr; | |
| 890 | |
| 891 if (assigned_picture_ids_.count(picture_id) != 0) { | |
| 892 available_picture_ids_.push_back(picture_id); | |
| 893 ProcessWorkQueues(); | |
| 894 } else { | |
| 895 client_->DismissPictureBuffer(picture_id); | |
| 896 } | |
| 897 } | |
| 898 | |
| 899 void VTVideoDecodeAccelerator::ProcessWorkQueues() { | |
| 900 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 901 switch (state_) { | |
| 902 case STATE_DECODING: | |
| 903 // TODO(sandersd): Batch where possible. | |
| 904 while (state_ == STATE_DECODING) { | |
| 905 if (!ProcessReorderQueue() && !ProcessTaskQueue()) | |
| 906 break; | |
| 907 } | |
| 908 return; | |
| 909 | |
| 910 case STATE_ERROR: | |
| 911 // Do nothing until Destroy() is called. | |
| 912 return; | |
| 913 | |
| 914 case STATE_DESTROYING: | |
| 915 // Drop tasks until we are ready to destruct. | |
| 916 while (!task_queue_.empty()) { | |
| 917 if (task_queue_.front().type == TASK_DESTROY) { | |
| 918 delete this; | |
| 919 return; | |
| 920 } | |
| 921 task_queue_.pop(); | |
| 922 } | |
| 923 return; | |
| 924 } | |
| 925 } | |
| 926 | |
| 927 bool VTVideoDecodeAccelerator::ProcessTaskQueue() { | |
| 928 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 929 DCHECK_EQ(state_, STATE_DECODING); | |
| 930 | |
| 931 if (task_queue_.empty()) | |
| 932 return false; | |
| 933 | |
| 934 const Task& task = task_queue_.front(); | |
| 935 switch (task.type) { | |
| 936 case TASK_FRAME: | |
| 937 if (reorder_queue_.size() < kMaxReorderQueueSize && | |
| 938 (!task.frame->is_idr || reorder_queue_.empty())) { | |
| 939 assigned_bitstream_ids_.erase(task.frame->bitstream_id); | |
| 940 client_->NotifyEndOfBitstreamBuffer(task.frame->bitstream_id); | |
| 941 reorder_queue_.push(task.frame); | |
| 942 task_queue_.pop(); | |
| 943 return true; | |
| 944 } | |
| 945 return false; | |
| 946 | |
| 947 case TASK_FLUSH: | |
| 948 DCHECK_EQ(task.type, pending_flush_tasks_.front()); | |
| 949 if (reorder_queue_.size() == 0) { | |
| 950 pending_flush_tasks_.pop(); | |
| 951 client_->NotifyFlushDone(); | |
| 952 task_queue_.pop(); | |
| 953 return true; | |
| 954 } | |
| 955 return false; | |
| 956 | |
| 957 case TASK_RESET: | |
| 958 DCHECK_EQ(task.type, pending_flush_tasks_.front()); | |
| 959 if (reorder_queue_.size() == 0) { | |
| 960 waiting_for_idr_ = true; | |
| 961 pending_flush_tasks_.pop(); | |
| 962 client_->NotifyResetDone(); | |
| 963 task_queue_.pop(); | |
| 964 return true; | |
| 965 } | |
| 966 return false; | |
| 967 | |
| 968 case TASK_DESTROY: | |
| 969 NOTREACHED() << "Can't destroy while in STATE_DECODING"; | |
| 970 NotifyError(ILLEGAL_STATE, SFT_PLATFORM_ERROR); | |
| 971 return false; | |
| 972 } | |
| 973 } | |
| 974 | |
| 975 bool VTVideoDecodeAccelerator::ProcessReorderQueue() { | |
| 976 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 977 DCHECK_EQ(state_, STATE_DECODING); | |
| 978 | |
| 979 if (reorder_queue_.empty()) | |
| 980 return false; | |
| 981 | |
| 982 // If the next task is a flush (because there is a pending flush or becuase | |
| 983 // the next frame is an IDR), then we don't need a full reorder buffer to send | |
| 984 // the next frame. | |
| 985 bool flushing = !task_queue_.empty() && | |
| 986 (task_queue_.front().type != TASK_FRAME || | |
| 987 task_queue_.front().frame->is_idr); | |
| 988 | |
| 989 size_t reorder_window = std::max(0, reorder_queue_.top()->reorder_window); | |
| 990 if (flushing || reorder_queue_.size() > reorder_window) { | |
| 991 if (ProcessFrame(*reorder_queue_.top())) { | |
| 992 reorder_queue_.pop(); | |
| 993 return true; | |
| 994 } | |
| 995 } | |
| 996 | |
| 997 return false; | |
| 998 } | |
| 999 | |
| 1000 bool VTVideoDecodeAccelerator::ProcessFrame(const Frame& frame) { | |
| 1001 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1002 DCHECK_EQ(state_, STATE_DECODING); | |
| 1003 | |
| 1004 // If the next pending flush is for a reset, then the frame will be dropped. | |
| 1005 bool resetting = !pending_flush_tasks_.empty() && | |
| 1006 pending_flush_tasks_.front() == TASK_RESET; | |
| 1007 | |
| 1008 if (!resetting && frame.image.get()) { | |
| 1009 // If the |coded_size| has changed, request new picture buffers and then | |
| 1010 // wait for them. | |
| 1011 // TODO(sandersd): If GpuVideoDecoder didn't specifically check the size of | |
| 1012 // textures, this would be unnecessary, as the size is actually a property | |
| 1013 // of the texture binding, not the texture. We rebind every frame, so the | |
| 1014 // size passed to ProvidePictureBuffers() is meaningless. | |
| 1015 if (picture_size_ != frame.coded_size) { | |
| 1016 // Dismiss current pictures. | |
| 1017 for (int32_t picture_id : assigned_picture_ids_) | |
| 1018 client_->DismissPictureBuffer(picture_id); | |
| 1019 assigned_picture_ids_.clear(); | |
| 1020 available_picture_ids_.clear(); | |
| 1021 | |
| 1022 // Request new pictures. | |
| 1023 picture_size_ = frame.coded_size; | |
| 1024 client_->ProvidePictureBuffers(kNumPictureBuffers, 1, coded_size_, | |
| 1025 GL_TEXTURE_RECTANGLE_ARB); | |
| 1026 return false; | |
| 1027 } | |
| 1028 if (!SendFrame(frame)) | |
| 1029 return false; | |
| 1030 } | |
| 1031 | |
| 1032 return true; | |
| 1033 } | |
| 1034 | |
| 1035 bool VTVideoDecodeAccelerator::SendFrame(const Frame& frame) { | |
| 1036 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1037 DCHECK_EQ(state_, STATE_DECODING); | |
| 1038 | |
| 1039 if (available_picture_ids_.empty()) | |
| 1040 return false; | |
| 1041 | |
| 1042 int32_t picture_id = available_picture_ids_.back(); | |
| 1043 DCHECK(picture_info_map_.count(picture_id)); | |
| 1044 PictureInfo* picture_info = picture_info_map_.find(picture_id)->second.get(); | |
| 1045 DCHECK(!picture_info->cv_image); | |
| 1046 DCHECK(!picture_info->gl_image); | |
| 1047 | |
| 1048 if (!make_context_current_cb_.Run()) { | |
| 1049 DLOG(ERROR) << "Failed to make GL context current"; | |
| 1050 NotifyError(PLATFORM_FAILURE, SFT_PLATFORM_ERROR); | |
| 1051 return false; | |
| 1052 } | |
| 1053 | |
| 1054 scoped_refptr<gl::GLImageIOSurface> gl_image( | |
| 1055 new gl::GLImageIOSurface(frame.coded_size, GL_BGRA_EXT)); | |
| 1056 if (!gl_image->InitializeWithCVPixelBuffer( | |
| 1057 frame.image.get(), gfx::GenericSharedMemoryId(), | |
| 1058 gfx::BufferFormat::YUV_420_BIPLANAR)) { | |
| 1059 NOTIFY_STATUS("Failed to initialize GLImageIOSurface", PLATFORM_FAILURE, | |
| 1060 SFT_PLATFORM_ERROR); | |
| 1061 } | |
| 1062 | |
| 1063 if (!bind_image_cb_.Run(picture_info->client_texture_id, | |
| 1064 GL_TEXTURE_RECTANGLE_ARB, gl_image, false)) { | |
| 1065 DLOG(ERROR) << "Failed to bind image"; | |
| 1066 NotifyError(PLATFORM_FAILURE, SFT_PLATFORM_ERROR); | |
| 1067 return false; | |
| 1068 } | |
| 1069 | |
| 1070 // Assign the new image(s) to the the picture info. | |
| 1071 picture_info->gl_image = gl_image; | |
| 1072 picture_info->cv_image = frame.image; | |
| 1073 available_picture_ids_.pop_back(); | |
| 1074 | |
| 1075 // TODO(sandersd): Currently, the size got from | |
| 1076 // CMVideoFormatDescriptionGetDimensions is visible size. We pass it to | |
| 1077 // GpuVideoDecoder so that GpuVideoDecoder can use correct visible size in | |
| 1078 // resolution changed. We should find the correct API to get the real | |
| 1079 // coded size and fix it. | |
| 1080 client_->PictureReady(media::Picture(picture_id, frame.bitstream_id, | |
| 1081 gfx::Rect(frame.coded_size), | |
| 1082 true)); | |
| 1083 return true; | |
| 1084 } | |
| 1085 | |
| 1086 void VTVideoDecodeAccelerator::NotifyError( | |
| 1087 Error vda_error_type, | |
| 1088 VTVDASessionFailureType session_failure_type) { | |
| 1089 DCHECK_LT(session_failure_type, SFT_MAX + 1); | |
| 1090 if (!gpu_thread_checker_.CalledOnValidThread()) { | |
| 1091 gpu_task_runner_->PostTask(FROM_HERE, base::Bind( | |
| 1092 &VTVideoDecodeAccelerator::NotifyError, weak_this_, vda_error_type, | |
| 1093 session_failure_type)); | |
| 1094 } else if (state_ == STATE_DECODING) { | |
| 1095 state_ = STATE_ERROR; | |
| 1096 UMA_HISTOGRAM_ENUMERATION("Media.VTVDA.SessionFailureReason", | |
| 1097 session_failure_type, | |
| 1098 SFT_MAX + 1); | |
| 1099 client_->NotifyError(vda_error_type); | |
| 1100 } | |
| 1101 } | |
| 1102 | |
| 1103 void VTVideoDecodeAccelerator::QueueFlush(TaskType type) { | |
| 1104 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1105 pending_flush_tasks_.push(type); | |
| 1106 decoder_thread_.task_runner()->PostTask( | |
| 1107 FROM_HERE, base::Bind(&VTVideoDecodeAccelerator::FlushTask, | |
| 1108 base::Unretained(this), type)); | |
| 1109 | |
| 1110 // If this is a new flush request, see if we can make progress. | |
| 1111 if (pending_flush_tasks_.size() == 1) | |
| 1112 ProcessWorkQueues(); | |
| 1113 } | |
| 1114 | |
| 1115 void VTVideoDecodeAccelerator::Flush() { | |
| 1116 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1117 QueueFlush(TASK_FLUSH); | |
| 1118 } | |
| 1119 | |
| 1120 void VTVideoDecodeAccelerator::Reset() { | |
| 1121 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1122 QueueFlush(TASK_RESET); | |
| 1123 } | |
| 1124 | |
| 1125 void VTVideoDecodeAccelerator::Destroy() { | |
| 1126 DCHECK(gpu_thread_checker_.CalledOnValidThread()); | |
| 1127 | |
| 1128 // In a forceful shutdown, the decoder thread may be dead already. | |
| 1129 if (!decoder_thread_.IsRunning()) { | |
| 1130 delete this; | |
| 1131 return; | |
| 1132 } | |
| 1133 | |
| 1134 // For a graceful shutdown, return assigned buffers and flush before | |
| 1135 // destructing |this|. | |
| 1136 // TODO(sandersd): Prevent the decoder from reading buffers before discarding | |
| 1137 // them. | |
| 1138 for (int32_t bitstream_id : assigned_bitstream_ids_) | |
| 1139 client_->NotifyEndOfBitstreamBuffer(bitstream_id); | |
| 1140 assigned_bitstream_ids_.clear(); | |
| 1141 state_ = STATE_DESTROYING; | |
| 1142 QueueFlush(TASK_DESTROY); | |
| 1143 } | |
| 1144 | |
| 1145 bool VTVideoDecodeAccelerator::TryToSetupDecodeOnSeparateThread( | |
| 1146 const base::WeakPtr<Client>& decode_client, | |
| 1147 const scoped_refptr<base::SingleThreadTaskRunner>& decode_task_runner) { | |
| 1148 return false; | |
| 1149 } | |
| 1150 | |
| 1151 // static | |
| 1152 media::VideoDecodeAccelerator::SupportedProfiles | |
| 1153 VTVideoDecodeAccelerator::GetSupportedProfiles() { | |
| 1154 SupportedProfiles profiles; | |
| 1155 for (const auto& supported_profile : kSupportedProfiles) { | |
| 1156 SupportedProfile profile; | |
| 1157 profile.profile = supported_profile; | |
| 1158 profile.min_resolution.SetSize(16, 16); | |
| 1159 profile.max_resolution.SetSize(4096, 2160); | |
| 1160 profiles.push_back(profile); | |
| 1161 } | |
| 1162 return profiles; | |
| 1163 } | |
| 1164 | |
| 1165 } // namespace content | |
| OLD | NEW |