From 1244b8848837d6f07097ae7f41345324809e5a19 Mon Sep 17 00:00:00 2001 From: Packit Date: Sep 15 2020 12:39:59 +0000 Subject: libyami-1.3.1 base --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..921eaf4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +Makefile +Makefile.in +config.h +config.h.in +stamp-h1 +libtool +aclocal.m4 +configure +config.log +config.status +*~ +*.la +*.lo +.libs/ +.deps/ +autom4te.cache/ +m4/ +pkgconfig/ +aux/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..fd7cf4f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,80 @@ +dist: xenial +sudo: required + +language: c++ +compiler: g++ +os: linux + +before_install: + - test "${TRAVIS_BRANCH}" != 'coverity_scan' -o "${TRAVIS_JOB_NUMBER##*.}" = '1' || exit 0 + - echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca- + - pip install --user cpp-coveralls + - sudo apt-get -qq update + - sudo apt-get install -y build-essential + - sudo apt-get install -y autoconf + - sudo apt-get install -y automake + - sudo apt-get install -y libtool + - sudo apt-get install -y m4 + - sudo apt-get install -y lcov + - sudo apt-get install -y perl + - sudo apt-get install -y pkg-config + - sudo apt-get install -y libdrm-dev + - sudo apt-get install -y autoconf + - sudo apt-get install -y libegl1-mesa-dev + - sudo apt-get install -y libgl1-mesa-dev + - sudo apt-get install -y libwayland-dev + - sudo apt-get install -y libx11-dev + - sudo apt-get install -y libxext-dev + - sudo apt-get install -y libxfixes-dev + - sudo apt-get install -y intel-gpu-tools + - sudo apt-get install -y libv4l-0 + - sudo apt-get install -y libv4l-dev + - sudo apt-get install -y libcogl-gles2-dev + - git clone https://github.com/intel/libva.git + - (cd libva && ./autogen.sh && ./configure --prefix=/usr && sudo make install) + + +addons: + coverity_scan: + project: + name: "intel/libyami" + description: "Build submitted via Travis CI" + notification_email: + build_command_prepend: "./autogen.sh; ./configure --prefix=/opt/yami --enable-h264enc --enable-jpegenc --enable-vp8enc --enable-vp9enc --enable-h265enc --enable-mpeg2dec --enable-vp8dec --enable-vp9dec --enable-jpegdec --enable-h264dec --enable-h265dec --enable-vc1dec --enable-v4l2" + build_command: "make -j8" + branch_pattern: coverity_scan + +script: + - if [[ "${COVERITY_SCAN_BRANCH}" == 1 ]]; + then + echo "Don't build on coverty_scan branch."; + exit 0; + fi + - ./autogen.sh --prefix=/opt/yami --enable-h264enc --enable-jpegenc --enable-vp8enc --enable-vp9enc --enable-h265enc --enable-mpeg2dec --enable-vp8dec --enable-vp9dec --enable-jpegdec --enable-h264dec --enable-h265dec --enable-vc1dec --enable-v4l2 + - make -j8 ; sudo make install + - make check + +after_success: + - coveralls --exclude lib --exclude tests --gcov-options '\-lp' + +notifications: +# Emails are sent to the committer's git-configured email address by default, +# but only if they have access to the repository. To enable Travis on your +# public project, just go to travis-ci.org and flip the switch on for +# your project. To configure your git email address, use: +# git config --global user.email me@example.com + email: + on_success: always + on_failure: always + +# Slack notifications +# + + +# IRC notifications disabled by default. +# Uncomment next 5 lines to send notifications to chat.freenode.net#caffe +# irc: +# channels: +# - "chat.freenode.net#intel-media" +# template: +# - "%{repository}/%{branch} (%{commit} - %{author}): %{message}" diff --git a/Android.mk b/Android.mk new file mode 100644 index 0000000..a5f1aeb --- /dev/null +++ b/Android.mk @@ -0,0 +1,38 @@ +LOCAL_PATH := $(call my-dir) +LIBYAMICODEC_PATH := $(LOCAL_PATH) +include $(CLEAR_VARS) +include $(LIBYAMICODEC_PATH)/common.mk + +include $(LIBYAMICODEC_PATH)/common/Android.mk +include $(LIBYAMICODEC_PATH)/codecparsers/Android.mk +include $(LIBYAMICODEC_PATH)/vaapi/Android.mk +include $(LIBYAMICODEC_PATH)/decoder/Android.mk +include $(LIBYAMICODEC_PATH)/encoder/Android.mk +include $(LIBYAMICODEC_PATH)/vpp/Android.mk +include $(LIBYAMICODEC_PATH)/capi/Android.mk + +include $(CLEAR_VARS) +include $(LIBYAMICODEC_PATH)/common.mk + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libva \ + libva-android \ + libc++ \ + +LOCAL_WHOLE_STATIC_LIBRARIES := \ + libyami_common \ + libcodecparser \ + libyami_vaapi \ + libyami_vpp \ + libyami_decoder \ + libyami_encoder \ + libyami_capi \ + +LOCAL_EXPORT_C_INCLUDE_DIRS := \ + $(LIBYAMICODEC_PATH)/interface + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami + +include $(BUILD_SHARED_LIBRARY) diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..a0e6adb --- /dev/null +++ b/Makefile.am @@ -0,0 +1,81 @@ +ACLOCAL_AMFLAGS = -I m4 + +# Extra clean files so that maintainer-clean removes *everything* +DISTCLEANFILES = \ + aclocal.m4 autom4te.cache compile config.guess config.sub \ + configure config.h.in config.h.in~ depcomp install-sh ltmain.sh \ + Makefile.in missing + +if ENABLE_TESTS +SUBDIRS = gtestsrc common codecparsers vaapi decoder encoder vpp pkgconfig +else +SUBDIRS = common codecparsers vaapi decoder encoder vpp pkgconfig +endif + +if ENABLE_DOCS +SUBDIRS += doc +endif + +SUBDIRS += capi + +if ENABLE_V4L2 +SUBDIRS += v4l2 +endif + +libyami_source_h = \ + interface/Yami.h \ + interface/YamiC.h \ + $(NULL) + +lib_LTLIBRARIES = libyami.la +libyami_la_SOURCES = +libyami_includedir = $(includedir)/libyami +libyami_include_HEADERS = $(libyami_source_h) +# Dummy C++ source to cause C++ linking +nodist_EXTRA_libyami_la_SOURCES = dummy.cxx +libyami_la_LDFLAGS = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + $(NULL) + +libyami_la_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(LIBVA_DRM_CFLAGS) \ + $(NULL) + +libyami_la_LIBADD = common/libyami_common.la \ + codecparsers/libyami_codecparser.la \ + vaapi/libyami_vaapi.la \ + decoder/libyami_decoder.la \ + encoder/libyami_encoder.la \ + vpp/libyami_vpp.la \ + $(NULL) + +libyami_la_LIBADD += capi/libyami_capi.la + +if ENABLE_X11 +libyami_la_LDFLAGS += $(LIBVA_X11_LIBS) $(X11_LIBS) +libyami_la_CPPFLAGS += $(LIBVA_X11_CFLAGS) +endif + +libyami_la_LDFLAGS += $(AM_LDFLAGS) +libyami_la_CPPFLAGS += $(AM_CPPFLAGS) + +if ENABLE_V4L2 +lib_LTLIBRARIES += libyami_v4l2.la +libyami_v4l2_la_SOURCES = +# Dummy C++ source to cause C++ linking +nodist_EXTRA_libyami_v4l2_la_SOURCES = dummy.cxx +# for library version +libyami_v4l2_la_LDFLAGS = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(AM_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + $(NULL) + +libyami_v4l2_la_LIBADD = libyami.la \ + v4l2/libyamiv4l2.la \ + $(NULL) +endif diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..622b0f2 --- /dev/null +++ b/NEWS @@ -0,0 +1,317 @@ +libyami NEWS -- summary of changes. 2018-09-19 +Copyright (c) 2010, The WebM Project authors. +Copyright (C) 2011-2018 Intel Corporation +Copyright (C) 2015-2016 Alibaba + +libyami 1.3.1(API:0.6.0) release, work with libva 2.2.1.pre1 release +===================== +Major improvements: ++af43e95 h264dec: fix low lantecy mode ++160286a Add flags for SDL signoff called SDL325 - Compile With Defenses Enabled ++727db97 common: add RGB 10 bits support ++46c15b1 common: add RGB565 support ++946b7ac common: add XRGB, ARGB, XBGR, ABGR support ++9e1fc1d android: re-enable android build ++3745982 yamivpp: add rotation function for vpp + +libyami 1.2.0(API:0.5.0) release, work with libva 1.8.1 release +===================== +Major improvements: ++180c3d5 improve vp9 10 bit decoder conformance ++8d29d2d improve h265 8/10 bit decoder conformance ++5b09484 add decoder/display zero-copy API. ++e46f03b use decoder/display zero copy API in v4l2 decoder ++441ee54 expose vp9 qp setting to the user. + +We change API to from 0.4.0 to 0.5.0 for following interface changes. ++1fe162e get/set surface in SurfaceAllocParams ++7560ce7 add VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF + +libyami 1.1.0(API:0.4.0) release, work with libva 1.7.3 release +===================== +We add following major features: ++c8299ca add h265 10 bits decoder ++ea3bc34 add vp9 10 bits decoder ++c7364f0 add h265 10 bits encoder ++3daae20 add Hue, Saturation, Brightness and Contrast to vpp ++0c8299c fix memory leak issue in v4l2 ++71ec018 fix h264 baseline encoder fail issue ++d39104d fix h264/h265 encoder generate invalid frame for long GOP +-h265,vp9 10 bits conformance pass rate is not high. + + +We change API from 0.3.2 to 0.4.0 since following interface change ++7c6050b add enablePrefixNalUnit to h264 encoder ++3daae20 add Hue, Saturation, Brightness and Contrast to vpp ++c7364f0 add h265 10 bits encoder + +libyami 1.0.1(API:0.3.2) release, work with libva 1.7.3 release +===================== +This release mainly for SVC-T CBR support.We add following features: ++0a241d2 add h264 SVC-T CBR support. This need libva 1.7.3. ++77ba612 fix h264/h265 nalread issue in 32 bits arch ++2c1fcf3 h264parser: change luma_weight_lx from int8_t to int16_t to avoid overflow ++e2a9e07 vp8parser: fix one decoder conformance issue. ++fb83012 make yocto buildable ++518088e add wireframe function to ocl filters ++other small issues. + +We change API from 0.3.0 to 0.3.2 since following interface change ++518088e add wireframe function to ocl filters ++0a241d2 add h264 SVC-T CBR support. + + +libyami 1.0.0(API:0.3.0) release, work with libva 2016Q3 release +===================== +We add following major features: ++ 7423a97 add vp9 encoder ++ f6f1483 add sharpening, denoise, deinterlace for vpp ++ 366d909 add support for 422H, 422V and 444P ++ 2d4a536 add wayland support to v4l2decoder ++ 784ea0f improve h264 encoder speed for memory limited system ++ e57989f improve mpeg2 pass rate from 70% to 100% ++ 112b921 improve vc1 pass rate from 70% to 92% ++ 7f2e032 add profile setting for h264encoder ++ some more encoder setting for h264 and h265 ++ more bugs fix and features please refer to git log +- convert odd resolution from NV12 to I420 will make output yuv twisted +- some unittest will failed. + +We change API from 0.2.0 to 0.3.0 since following interface change +9f45ee7 add vp9 encoder +765cb6d add single header Yami.h/YamiC.h for user to include +99b85bc map tr1 name space to std name space +ea0b5fd add SVC-T support for h264 CQP mode +366d909 add support for jpeg 422H, 422V and 444P +2d4a536 add wayland support to v4l2decoder +1b53e29 deleted some unused encoder API +3147d36 enc264: implement I/P/B QP setting on CQP mode +f6f1483 vpp: add denoise,sharpening and deinterlace + + + +libyami 0.4.0 release, work with libva 2016Q2 release +===================== +We relicensed entire project from LGPL to Apache V2 ++add mpeg2 decoder ++add vc1 decoder ++merge all so to single libyami.so +-mpeg2/vc1 pass conformance rate is 70% + fix patch should ready in near future. + + + +libyami 0.3.1 release, work with libva 2015Q4 release +===================== ++b frame for h264 encoder ++CBR for h265 encoder ++yamitransocde application, it will do zero copy transcode, much faster than yamiencode ++fix static library link issue ++fix various issue in vaapidisplay, vp8dec, h264enc, h265enc, factory +-transocde application will use default configuration, it did not use user set one. +-if you use latest ffmpeg, vp9 decoder will failed for some clips.mentioned in #347. + it's not core library's issue. It's a yamidecode's issue. + You can use ffmpeg 2.6 as workaround. + + +libyami 0.3.0 release, work with libva 2015Q3 release +===================== ++h265 decoder ++h265 encoder ++new mode -2 for yamidecode, it will output per frame md5 for decoded yuv ++some bug fix for vp8,vp9,h264 conformance. ++simplify configure.ac + +libyami 0.2.5 release, work with libva 2015Q2 release +===================== ++update codec parser to latest version ++fix all compile warnings. ++add CBR for h264 and vp8 encoder. ++add "SharedPtr getOutput()" to decoder ++fix one loop filter issue in vp8dec ++1 bug in NativeDisplayDrm ++handle annexb format codec data in h264 decoder ++one “deref NULL” bug in v4l2 encoder. ++self-register enc/dec/vpp with their factories. ++add a simple player to demo decoder api usage(200 lines) ++add grid application to demo MxN ways decode + dipslay ++select driver name base on decoder profile + + +libyami 0.2.4 release +===================== ++add vpp interface for c++ ++fix momory leak, uinitilized variable and invalid read reported by valgrind ++3 bug fix for vp8 encoder. ++.gitignore file ++ update correct profile name for vp9 since libva updated. ++fix "resolution changed in v4l2 egl mode makes yami crash" issue +-decode output dump can't gusss output fourcc from file extension + + + +libyami 0.2.3 release +===================== ++add VIDIOC_G_CROP to io ctrl ++fix one ImagePtr leak issue, since ImagePtr hold DisplayPtr, it also leak VaapiDisplay + +libyami 0.2.2 release +===================== + +features update +--------------- ++fix one include issue in capi header ++3 fixes for vp9 decoder and parser ++use cabac as default entropy mode for h264 encoder ++fix servral issues when we use v4l2 decoder in gles mode + +libyami 0.2.1 release +===================== +the main target of this release is bug fix, especially the busy waiting issue. + +features update +--------------- ++fix one busy waiting bug in v4l2decoder. + -It will drain out cpu resource even we pause the video. ++4 patches apply to fix vp9 conformance test. ++add fakedec, it's good start for performance measure. ++fix random crash bug when we use "yamidecoder -m -1" + +libyami 0.2.0 release +===================== + +features update +--------------- ++ add VP9 decoder ++ add VP8 encoder ++ add JPEG encoder ++ add Demux support leverage libavformat,: --enable-avformat + - yamidecode runs ok when there is no xwindow rendering (-m -1/0) + - v4l2decode is ok when there is with or w/o rendering + - support libvaformat from the version installed in Ubuntu13.10 + - known issue: when there is video rendering, yamidecode blocks at + XGetWindowAttributes() after libva dlopen(i965_drv). + Add XInitThreads() make things worse. It is strange. ++ Fps update for "-m -1", we get stable performance data now ++ V4l2 fixes: seek, unconditionally stop ++ enable FFmpeg to use libyami for h264 decoding, create example player to + demonstrate it, especially on rendering video as texture through dma_buf + https://github.com/01org/player-ffmpeg-yami + +known issues +--------------- +- for avformat support in yamidecode, when there is video rendering, + yamidecode blocks at XGetWindowAttributes() after libva dlopen(i965_drv). + Add XInitThreads() make things worse. It is strange. + v4l2decode doesn't have such issue. (yamidecode is one thread application) + +thoughts on libyami (media framework and window system support) +-------------------------------------------------- +these points are not our priority yet. + ++ Wayland support + We did a lot to support Wayland before: + - add Wayland platform support in libva and driver, does hack to + copy wayland-drm protocol from mesa/egl + - add Wayland platform in middleware, gstreamer-vaapi for example + + the detects are: + - so far, only plain rendering is supported: wl_surface_attach/wl_surface_damage; + texture video rendering is still a gap + - the shared wl_display/wl_window/wl_event_queue are complex and problematic + + it should be much easier with dma_buf. + We neend't do anything special for native window system in either vaapi driver or + codec library. with dma_buf handle exported, application can draw the video + frame (dma_buf) by EGL/GLES, EGL handle native window system automatically(including + wrap it into a wl_buffer internally). + ++ GStreamer support + We usually do a lot on hw video buffer sharing in GStreamer, hw video buffer are + platform dependent, but the framework requires to wrap them in a generic way. we do + a lot in decoder to wrap a platform dependent handle into a subclass of base + video buffer, then unwrap it in video sink. and tries best to hide hw detail when + a sw component request to access the frame data. + + it becomes simple when hw codec support dma_buf, since dma_buf is Linux generic. + it is possible that hw video become not the 2nd class citizen any more. we don't + need additional wrapper in decoder side, and we don't need a special video sink + for each hw video type. + ++ dma_buf rendering for legacy support + in the above ideas, we usually consider EGL/GLES rendering context, how about + legacy usage? it is simple as well. + + DRI3 protocol support dma_buf, it means a dma_buf handle can be sent to server + for window update. Keith said mesa is using it, and on server side glamor handle + the dma_buf. the remaining gap is that YUV buffer hasn't been supported yet, but + not hard to add it. + +libyami 0.1.4 release +===================== + +features update +--------------- + - Additional fixes(most are thread race condition) for v4l2 wrapper (egl/gles) + - Add glx support in v4l2 wrapper + - Basic transcoding support: encoder test accepts input data from decoder output + - Testscript is added, it supports one-run-for-all: with a folder including h264/vp8/jpeg/raw-ref, + we can test them in one run. It serves as BAT (basic acceptance test) for pull request merge. + - Report fps in decode test, support decoding only test (skip rendering) + - Vp8/jpeg are supported in v4l2 decoder as well + - Decode test can be built/run without X11 + - Code refinement for decoder test output and encoder classes + - dma_buf fixes, when video frame is exported as dma_buf, it renders well as texture + - with additional patch for chrome: + V4L2VDA/V4L2VEA pass chrome video unit test + video playback in browser draft ok + - for v4l2 wrapper, see: https://github.com/halleyzhao/yami-share/blob/master/Yami_V4L2_wrapper_for_Chrome.pdf + +known issues +--------------- + - this release is fully tested by validation team + - some jpeg file similarity <0.99 (~0.98) after decoding + https://github.com/01org/libyami/issues/108 + +future release plan: +==================== + Dec: v0.2 + jpeg encoder + vp9 decoder + vp8 encoder (depends on driver availability) + initial ffmpeg support + + Feb'15: v0.3 + unified input/output buffer of yami + transcoding support with unified input/output buffer + camera dma_buf support, camera with jpeg input + use yami in ffmpeg for hw codec + + Future: + h265 decoder + + +Libyami 0.1 release note +=========================== + +Libyami is core video library to accelerate decoding/encoding based on libva. +Libyami can be treated as development kit for VAAPI. It is developed by C++ language, with simple/efficient APIs, without external dependencies. +libyami targets two type of usage: + - Hardware accelerated codec is the major gap (there is existing media framework ), for example: Chromeos/Android, maybe ffmpeg. + - Usage is simple enough that codec is the major interest, for example: remote desktop client/server, video surveillance. +So far H.264 decode/encode, VP8 and JPEG decode are supported. VP8/JPEG encode support is under development. + +There are rich tests/examples in yami for a try. The tests can run without Window system (X11/Wayland etc), +some modes of video output are supported: including raw data dump and some modes of texture (TFP, drm flink name, dma_buf). + +More details see: https://github.com/01org/libyami/wiki + +Known issues: + some jpeg file similarity <0.99 (~0.98) after decoding + https://github.com/01org/libyami/issues/108 + playback performance through gst-omx is not good: + https://github.com/01org/libyami/issues/34 + Encodeing quality through gst-omx is not good: + https://github.com/01org/libyami/issues/36 + + legacy codec: mpeg2 decoder/encoder, vc1 decoder, mpeg4/h263 decoder/encoder diff --git a/README.md b/README.md new file mode 100644 index 0000000..b17572c --- /dev/null +++ b/README.md @@ -0,0 +1,150 @@ +[![Build Status](https://travis-ci.org/intel/libyami.svg?branch=apache)](https://travis-ci.org/intel/libyami) +[![Coverity Scan Build Status](https://scan.coverity.com/projects/11605/badge.svg)](https://scan.coverity.com/projects/01org-libyami) + +libyami +------- +Yet Another Media Infrastructure. + +It is YUMMY to your video experience on Linux like platform. + + +Yami is core building block for media solution. it parses video stream + +and decodes them leverage hardware acceleration. + + + * Copyright (c) 2010, The WebM Project authors. + + * Copyright (C) 2011-2018 Intel Corporation + + * Copyright (C) 2015-2016 Alibaba + + +License +------- +libyami libraries are available under the terms of the + +Apache License 2.0 + + +Overview +-------- +libyami consists of several libraries: + + * `codecparsers`: it is bit stream parser, + * `common`: common objects/operation to work with vaapi (hw acceleration interface) + * `decoder`: video decoder implementation + * `encoder`: video encoder implementation + * `vpp`: video post process implementation + + +Features +-------- + * MPEG-2, VC-1, WMV 9 (WMV3), H.264, HEVC (H.265), VP8, VP9, and JPEG ad-hoc decoders + * H.264, HEVC (H.265), VP8, VP9, and JPEG ad-hoc encoders + * Sharpening, Denoise, Deinterlace, Hue, Saturation, Brightness, Contrast, CSC and scaling + + +Requirements +------------ +Hardware requirements + + * Intel Sandybridge, Ivybridge, Haswell, Broadwell, Skylake, Kaby Lake (HD Graphics) + * Intel Bay Trail, Braswell, Apollo Lake, Gemini Lake + + +Sources +------- +Git repository for work-in-progress changes is available at: + + + + +Demos, Examples and Test Applications +--------------------------------------------------- +The libyami-utils project provides various example, test and demo +applications that use libyami. For more details, please refer to + + https://github.com/01org/libyami-utils + + +Simple api demo application +--------------------------- +https://github.com/01org/libyami-utils/blob/master/examples/simpleplayer.cpp + + +FFmpeg integration +-------------------------- +You can refer to https://github.com/01org/ffmpeg_libyami for FFmpeg integration. + +You can report FFmpeg related issue to https://github.com/01org/ffmpeg_libyami/issues + + +Build instructions +------------------ +https://github.com/01org/libyami/wiki/Build + + +Docs +---- +http://01org.github.io/libyami_doxygen/index.html + + +Testing +------- + +Unit Tests + + The gtest framework library is required + in order to write and compile unit tests in libyami. To make it convenient to + use, we add gtest source to subdirectory `gtestsrc`. The gtest documentation + can be found in their source tree under `docs` (online or in the subdirectory + `gtestsrc`). + + To build gtest and enable the unit tests, when configuring libyami you need to + specify: + + --enable-tests + +Contributing +------------ +Create pull request at https://github.com/01org/libyami/compare + + +Code style +---------- +https://github.com/01org/libyami/wiki/Coding-Style + + +Review process +-------------- + Create pull requests at + + We highly recommend that unit tests accompany your contributed patches. See + "Testing" section above. However, we do understand that not everything can + be tested by a unit test. So use your best judgement to determine if a unit + test is appropriate for your contribution. The maintainer(s) reserve the + right to refuse submission's without unit tests, when reasonable, or if a + submission causes existing unit tests to regress. + + +Mail list +--------- +libyami@lists.01.org + + +Reporting Bugs +-------------- +Bugs can be reported in the github system at: + + + + +## Reporting a security issue + +Please mail to secure-opensource@intel.com directly for security issue + + +FAQ +--- +https://github.com/01org/libyami/wiki/FAQ diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..9beb325 --- /dev/null +++ b/autogen.sh @@ -0,0 +1,29 @@ + +PROJECT="libyami" + +test -n "$srcdir" || srcdir="`dirname \"$0\"`" +test -n "$srcdir" || srcdir=. + +if ! test -f "$srcdir/configure.ac"; then + echo "Failed to find the top-level $PROJECT directory" + exit 1 +fi + +olddir="`pwd`" +cd "$srcdir" + +mkdir -p m4 + +AUTORECONF=`which autoreconf` +if test -z $AUTORECONF; then + echo "*** No autoreconf found ***" + exit 1 +else + autoreconf -v --install || exit $? +fi + +cd "$olddir" + +if test -z "$NOCONFIGURE"; then + $srcdir/configure "$@" && echo "Now type 'make' to compile $PROJECT." +fi diff --git a/build/GenVer.py b/build/GenVer.py new file mode 100644 index 0000000..dd0d7f9 --- /dev/null +++ b/build/GenVer.py @@ -0,0 +1,40 @@ +#! /usr/bin/env python3 +""" + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import re +import os.path as path + +def query(config, name): + m = re.search('m4_define\\(\\[' + name + '\\], *([0-9]*)\\)', config) + return m.group(1) + +def replace(tpl, config, dest, src): + v = query(config, src) + return tpl.replace(dest, v) + +cur = path.dirname(__file__) +root = path.abspath(path.join(cur, "..")) +with open(path.join(root, "interface/YamiVersion.h.in")) as f: + tpl = f.read() +with open(path.join(root, "configure.ac")) as f: + config = f.read() +tpl = replace(tpl, config, '@YAMI_API_MAJOR_VERSION@', 'yami_api_major_version') +tpl = replace(tpl, config, '@YAMI_API_MINOR_VERSION@', 'yami_api_minor_version') +tpl = replace(tpl, config, '@YAMI_API_MICRO_VERSION@', 'yami_api_micro_version') + +with open(path.join(root, "interface/YamiVersion.h"), "w") as f: + f.write(tpl) diff --git a/capi/Android.mk b/capi/Android.mk new file mode 100644 index 0000000..bd601a3 --- /dev/null +++ b/capi/Android.mk @@ -0,0 +1,24 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + VideoDecoderCapi.cpp \ + VideoEncoderCapi.cpp \ + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../common \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva \ + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libc++ + +LOCAL_ALLOW_UNDEFINED_SYMBOLS := true + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_capi +include $(BUILD_STATIC_LIBRARY) diff --git a/capi/Makefile.am b/capi/Makefile.am new file mode 100644 index 0000000..d5cbc91 --- /dev/null +++ b/capi/Makefile.am @@ -0,0 +1,44 @@ +libyami_capi_source_c = \ + VideoDecoderCapi.cpp \ + VideoEncoderCapi.cpp \ + $(NULL) + +libyami_capi_source_h = \ + ../interface/VideoDecoderCapi.h \ + ../interface/VideoEncoderCapi.h \ + $(NULL) + +libyami_capi_source_h_priv = \ + $(NULL) + +libyami_capi_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(NULL) + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_capi_cppflags = \ + $(LIBVA_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +noinst_LTLIBRARIES = libyami_capi.la +libyami_capiincludedir = $(includedir)/libyami +libyami_capiinclude_HEADERS = $(libyami_capi_source_h) +noinst_HEADERS = $(libyami_capi_source_h_priv) +libyami_capi_la_SOURCES = $(libyami_capi_source_c) +libyami_capi_la_LDFLAGS = $(libyami_capi_ldflags) $(AM_LDFLAGS) +libyami_capi_la_CPPFLAGS = $(libyami_capi_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in + + diff --git a/capi/Makefile.unittest b/capi/Makefile.unittest new file mode 100644 index 0000000..d4e2d6e --- /dev/null +++ b/capi/Makefile.unittest @@ -0,0 +1,29 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + $(NULL) + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_capi.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest + $(builddir)/unittest + diff --git a/capi/VideoDecoderCapi.cpp b/capi/VideoDecoderCapi.cpp new file mode 100644 index 0000000..ae7fdd3 --- /dev/null +++ b/capi/VideoDecoderCapi.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "VideoDecoderCapi.h" +#include "VideoDecoderInterface.h" +#include "VideoDecoderHost.h" + +#include + +using namespace YamiMediaCodec; + +class SharedPtrHold { +public: + SharedPtrHold(SharedPtr frame) + : frame(frame) + { + } + +private: + SharedPtr frame; +}; + +static void freeHold(VideoFrame* frame) +{ + delete (SharedPtrHold*)frame->user_data; +} + +DecodeHandler createDecoder(const char *mimeType) +{ + return createVideoDecoder(mimeType); +} + +void decodeSetNativeDisplay(DecodeHandler p, NativeDisplay* display) +{ + if (p) + ((IVideoDecoder*)p)->setNativeDisplay(display); +} + +YamiStatus decodeStart(DecodeHandler p, VideoConfigBuffer* buffer) +{ + if(p) + return ((IVideoDecoder*)p)->start(buffer); + else + return YAMI_FAIL; +} + +YamiStatus decodeReset(DecodeHandler p, VideoConfigBuffer* buffer) +{ + if(p) + return ((IVideoDecoder*)p)->reset(buffer); + else + return YAMI_FAIL; +} + +void decodeStop(DecodeHandler p) +{ + if(p) + ((IVideoDecoder*)p)->stop(); +} + +void decodeFlush(DecodeHandler p) +{ + if(p) + ((IVideoDecoder*)p)->flush(); +} + +YamiStatus decodeDecode(DecodeHandler p, VideoDecodeBuffer* buffer) +{ + if(p) + return ((IVideoDecoder*)p)->decode(buffer); + else + return YAMI_FAIL; +} + +VideoFrame* decodeGetOutput(DecodeHandler p) +{ + if (p) { + SharedPtr frame = ((IVideoDecoder*)p)->getOutput(); + if (frame) { + SharedPtrHold* hold = new SharedPtrHold(frame); + frame->user_data = (intptr_t)hold; + frame->free = freeHold; + return frame.get(); + } + } + return NULL; +} + +const VideoFormatInfo* decodeGetFormatInfo(DecodeHandler p) +{ + return (p ? ((IVideoDecoder*)p)->getFormatInfo() : NULL); +} + +void releaseDecoder(DecodeHandler p) +{ + if (p) + releaseVideoDecoder((IVideoDecoder*)p); +} + +void releaseLock(DecodeHandler p) +{ + if(p) + ((IVideoDecoder*)p)->releaseLock(); +} + diff --git a/capi/VideoEncoderCapi.cpp b/capi/VideoEncoderCapi.cpp new file mode 100644 index 0000000..c2f646f --- /dev/null +++ b/capi/VideoEncoderCapi.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "VideoEncoderCapi.h" +#include "VideoEncoderInterface.h" +#include "VideoEncoderHost.h" + +using namespace YamiMediaCodec; + +EncodeHandler createEncoder(const char *mimeType) +{ + return createVideoEncoder(mimeType); +} + +void encodeSetNativeDisplay(EncodeHandler p, NativeDisplay * display) +{ + if(p) + ((IVideoEncoder*)p)->setNativeDisplay(display); +} + +YamiStatus encodeStart(EncodeHandler p) +{ + if(p) + return ((IVideoEncoder*)p)->start(); + else + return YAMI_FAIL; +} + +void encodeStop(EncodeHandler p) +{ + if(p) + ((IVideoEncoder*)p)->stop(); +} + +static void freeFrame(VideoFrame* frame) +{ + if (frame && frame->free) { + frame->free(frame); + } +} + +YamiStatus encodeEncode(EncodeHandler p, VideoFrame* frame) +{ + if (!p) + return YAMI_INVALID_PARAM; + SharedPtr f(frame, freeFrame); + return ((IVideoEncoder*)p)->encode(f); +} + +YamiStatus encodeEncodeRawData(EncodeHandler p, VideoFrameRawData* inBuffer) +{ + if(p) + return ((IVideoEncoder*)p)->encode(inBuffer); + else + return YAMI_FAIL; +} + +YamiStatus encodeGetOutput(EncodeHandler p, VideoEncOutputBuffer* outBuffer, bool withWait) +{ + if(p) + return ((IVideoEncoder*)p)->getOutput(outBuffer, withWait); + else + return YAMI_FAIL; +} + +YamiStatus encodeGetParameters(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncParams) +{ + if(p) + return ((IVideoEncoder*)p)->getParameters(type, videoEncParams); + else + return YAMI_FAIL; +} + +YamiStatus encodeSetParameters(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncParams) +{ + if(p) + return ((IVideoEncoder*)p)->setParameters(type, videoEncParams); + else + return YAMI_FAIL; +} + +YamiStatus encodeGetMaxOutSize(EncodeHandler p, uint32_t* maxSize) +{ + if(p) + return ((IVideoEncoder*)p)->getMaxOutSize(maxSize); + else + return YAMI_FAIL; +} + +void releaseEncoder(EncodeHandler p) +{ + if (p) + releaseVideoEncoder((IVideoEncoder*)p); +} + +YamiStatus getStatistics(EncodeHandler p, VideoStatistics* videoStat) +{ + if(p) + return ((IVideoEncoder*)p)->getStatistics(videoStat); + else + return YAMI_FAIL; +} + +YamiStatus getConfig(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncConfig) +{ + if(p) + return ((IVideoEncoder*)p)->getConfig(type, videoEncConfig); + else + return YAMI_FAIL; +} + +YamiStatus setConfig(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncConfig) +{ + if(p) + return ((IVideoEncoder*)p)->setConfig(type, videoEncConfig); + else + return YAMI_FAIL; +} diff --git a/capi/unittest_main.cpp b/capi/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/capi/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/codecparsers/Android.mk b/codecparsers/Android.mk new file mode 100644 index 0000000..7a4945f --- /dev/null +++ b/codecparsers/Android.mk @@ -0,0 +1,30 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + bitReader.cpp \ + bitWriter.cpp \ + h264Parser.cpp \ + h265Parser.cpp \ + jpegParser.cpp \ + mpeg2_parser.cpp \ + nalReader.cpp \ + vc1Parser.cpp \ + vp8_bool_decoder.cpp \ + vp8_parser.cpp \ + vp9parser.cpp \ + vp9quant.c \ + dboolhuff.c \ + +LOCAL_C_INCLUDES := \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../interface + +LOCAL_SHARED_LIBRARIES := \ + libcutils \ + liblog + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libcodecparser +include $(BUILD_STATIC_LIBRARY) diff --git a/codecparsers/Makefile.am b/codecparsers/Makefile.am new file mode 100644 index 0000000..5690b50 --- /dev/null +++ b/codecparsers/Makefile.am @@ -0,0 +1,139 @@ +libyami_codecparser_source_c = \ + bitReader.cpp \ + bitWriter.cpp \ + nalReader.cpp \ + dboolhuff.c \ + $(NULL) + +if BUILD_JPEG_PARSER +libyami_codecparser_source_c += \ + jpegParser.cpp \ + $(NULL) +endif + +if BUILD_H264_DECODER +libyami_codecparser_source_c += \ + h264Parser.cpp \ + $(NULL) +endif + +if BUILD_MPEG2_DECODER +libyami_codecparser_source_c += \ + mpeg2_parser.cpp \ + $(NULL) +endif + +if BUILD_VP8_DECODER +libyami_codecparser_source_c += \ + vp8_bool_decoder.cpp \ + vp8_parser.cpp \ + $(NULL) +endif + +if BUILD_H265_DECODER +libyami_codecparser_source_c += \ + h265Parser.cpp \ + $(NULL) +endif + +if BUILD_VC1_DECODER +libyami_codecparser_source_c += \ + vc1Parser.cpp \ + $(NULL) +endif + +if BUILD_VP9_DECODER +libyami_codecparser_source_c += \ + vp9quant.c \ + vp9parser.cpp \ + $(NULL) +endif + +libyami_codecparser_source_h_priv = \ + bitReader.h \ + bitWriter.h \ + nalReader.h \ + $(NULL) + +if BUILD_JPEG_PARSER +libyami_codecparser_source_h_priv += \ + jpegParser.h \ + $(NULL) +endif + +if BUILD_H264_DECODER +libyami_codecparser_source_h_priv += \ + h264Parser.h \ + $(NULL) +endif + +if BUILD_MPEG2_DECODER +libyami_codecparser_source_h_priv += \ + mpeg2_parser.h \ + $(NULL) +endif + +if BUILD_VP8_DECODER +libyami_codecparser_source_h_priv += \ + vp8_bool_decoder.h \ + vp8_parser.h \ + $(NULL) +endif + +libyami_codecparser_source_h_priv += \ + dboolhuff.h \ + $(NULL) +EXTRA_DIST = dboolhuff.LICENSE dboolhuff.PATENTS dboolhuff.AUTHORS + +if BUILD_H265_DECODER +libyami_codecparser_source_h_priv += \ + h265Parser.h \ + $(NULL) +endif + +if BUILD_VC1_DECODER +libyami_codecparser_source_h_priv += \ + vc1Parser.h \ + $(NULL) +endif + +if BUILD_VP9_DECODER +libyami_codecparser_source_h_priv += \ + vp9quant.h \ + vp9parser.h \ + $(NULL) +endif + +libyami_codecparser_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(NULL) + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_codecparser_cppflags = \ + -Dvp8_norm=libyami_vp8_norm \ + -Dvp8dx_start_decode=libyami_vp8dx_start_decode \ + -Dvp8dx_bool_decoder_fill=libyami_vp8dx_bool_decoder_fill \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +noinst_LTLIBRARIES = libyami_codecparser.la +libyami_codecparserincludedir = ${includedir}/libyami +libyami_codecparserinclude_HEADERS = $(libyami_codecparser_source_h) +noinst_HEADERS = $(libyami_codecparser_source_h_priv) +libyami_codecparser_la_SOURCES = $(libyami_codecparser_source_c) +libyami_codecparser_la_LDFLAGS = $(libyami_codecparser_ldflags) $(AM_LDFLAGS) +libyami_codecparser_la_CPPFLAGS = $(libyami_codecparser_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in + + diff --git a/codecparsers/Makefile.unittest b/codecparsers/Makefile.unittest new file mode 100644 index 0000000..19a98a2 --- /dev/null +++ b/codecparsers/Makefile.unittest @@ -0,0 +1,69 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + bitReader_unittest.cpp \ + nalReader_unittest.cpp \ + bitWriter_unittest.cpp \ + $(NULL) + +if BUILD_VP8_DECODER +unittest_SOURCES += \ + vp8_bool_decoder_unittest.cpp \ + $(NULL) +endif + +if BUILD_JPEG_PARSER +unittest_SOURCES += \ + jpegParser_unittest.cpp \ + $(NULL) +endif + +if BUILD_H264_DECODER +unittest_SOURCES += \ + h264Parser_unittest.cpp \ + $(NULL) +endif + +if BUILD_H265_DECODER +unittest_SOURCES += \ + h265Parser_unittest.cpp \ + $(NULL) +endif + +if BUILD_MPEG2_DECODER +unittest_SOURCES += \ + mpeg2_parser_unittest.cpp \ + $(NULL) +endif + +if BUILD_VC1_DECODER +unittest_SOURCES += \ + vc1Parser_unittest.cpp \ + $(NULL) +endif + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_codecparser.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest + $(builddir)/unittest + diff --git a/codecparsers/README.ijg b/codecparsers/README.ijg new file mode 100644 index 0000000..a28ead3 --- /dev/null +++ b/codecparsers/README.ijg @@ -0,0 +1,381 @@ +The Independent JPEG Group's JPEG software +========================================== + +README for release 9a of 19-Jan-2014 +==================================== + +This distribution contains the ninth public release of the Independent JPEG +Group's free JPEG software. You are welcome to redistribute this software and +to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. + +This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone, +Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson, +Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers, +and other members of the Independent JPEG Group. + +IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee +(previously known as JPEG, together with ITU-T SG16). + + +DOCUMENTATION ROADMAP +===================== + +This file contains the following sections: + +OVERVIEW General description of JPEG and the IJG software. +LEGAL ISSUES Copyright, lack of warranty, terms of distribution. +REFERENCES Where to learn more about JPEG. +ARCHIVE LOCATIONS Where to find newer versions of this software. +ACKNOWLEDGMENTS Special thanks. +FILE FORMAT WARS Software *not* to get. +TO DO Plans for future IJG releases. + +Other documentation files in the distribution are: + +User documentation: + install.txt How to configure and install the IJG software. + usage.txt Usage instructions for cjpeg, djpeg, jpegtran, + rdjpgcom, and wrjpgcom. + *.1 Unix-style man pages for programs (same info as usage.txt). + wizard.txt Advanced usage instructions for JPEG wizards only. + change.log Version-to-version change highlights. +Programmer and internal documentation: + libjpeg.txt How to use the JPEG library in your own programs. + example.c Sample code for calling the JPEG library. + structure.txt Overview of the JPEG library's internal structure. + filelist.txt Road map of IJG files. + coderules.txt Coding style rules --- please read if you contribute code. + +Please read at least the files install.txt and usage.txt. Some information +can also be found in the JPEG FAQ (Frequently Asked Questions) article. See +ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. + +If you want to understand how the JPEG code works, we suggest reading one or +more of the REFERENCES, then looking at the documentation files (in roughly +the order listed) before diving into the code. + + +OVERVIEW +======== + +This package contains C software to implement JPEG image encoding, decoding, +and transcoding. JPEG (pronounced "jay-peg") is a standardized compression +method for full-color and gray-scale images. + +This software implements JPEG baseline, extended-sequential, and progressive +compression processes. Provision is made for supporting all variants of these +processes, although some uncommon parameter settings aren't implemented yet. +We have made no provision for supporting the hierarchical or lossless +processes defined in the standard. + +We provide a set of library routines for reading and writing JPEG image files, +plus two sample applications "cjpeg" and "djpeg", which use the library to +perform conversion between JPEG and some other popular image file formats. +The library is intended to be reused in other applications. + +In order to support file conversion and viewing software, we have included +considerable functionality beyond the bare JPEG coding/decoding capability; +for example, the color quantization modules are not strictly part of JPEG +decoding, but they are essential for output to colormapped file formats or +colormapped displays. These extra functions can be compiled out of the +library if not required for a particular application. + +We have also included "jpegtran", a utility for lossless transcoding between +different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple +applications for inserting and extracting textual comments in JFIF files. + +The emphasis in designing this software has been on achieving portability and +flexibility, while also making it fast enough to be useful. In particular, +the software is not intended to be read as a tutorial on JPEG. (See the +REFERENCES section for introductory material.) Rather, it is intended to +be reliable, portable, industrial-strength code. We do not claim to have +achieved that goal in every aspect of the software, but we strive for it. + +We welcome the use of this software as a component of commercial products. +No royalty is required, but we do ask for an acknowledgement in product +documentation, as described under LEGAL ISSUES. + + +LEGAL ISSUES +============ + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2014, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltmain.sh). Another support script, install-sh, is copyright by X Consortium +but is also freely distributable. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent (now expired), GIF reading +support has been removed altogether, and the GIF writer has been simplified +to produce "uncompressed GIFs". This technique does not use the LZW +algorithm; the resulting GIF files are larger than usual, but are readable +by all standard GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + + +REFERENCES +========== + +We recommend reading one or more of these references before trying to +understand the innards of the JPEG software. + +The best short technical introduction to the JPEG compression algorithm is + Wallace, Gregory K. "The JPEG Still Picture Compression Standard", + Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. +(Adjacent articles in that issue discuss MPEG motion picture compression, +applications of JPEG, and related topics.) If you don't have the CACM issue +handy, a PostScript file containing a revised version of Wallace's article is +available at http://www.ijg.org/files/wallace.ps.gz. The file (actually +a preprint for an article that appeared in IEEE Trans. Consumer Electronics) +omits the sample images that appeared in CACM, but it includes corrections +and some added material. Note: the Wallace article is copyright ACM and IEEE, +and it may not be used for commercial purposes. + +A somewhat less technical, more leisurely introduction to JPEG can be found in +"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by +M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides +good explanations and example C code for a multitude of compression methods +including JPEG. It is an excellent source if you are comfortable reading C +code but don't know much about data compression in general. The book's JPEG +sample code is far from industrial-strength, but when you are ready to look +at a full implementation, you've got one here... + +The best currently available description of JPEG is the textbook "JPEG Still +Image Data Compression Standard" by William B. Pennebaker and Joan L. +Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. +Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG +standards (DIS 10918-1 and draft DIS 10918-2). +Although this is by far the most detailed and comprehensive exposition of +JPEG publicly available, we point out that it is still missing an explanation +of the most essential properties and algorithms of the underlying DCT +technology. +If you think that you know about DCT-based JPEG after reading this book, +then you are in delusion. The real fundamentals and corresponding potential +of DCT-based JPEG are not publicly known so far, and that is the reason for +all the mistaken developments taking place in the image coding domain. + +The original JPEG standard is divided into two parts, Part 1 being the actual +specification, while Part 2 covers compliance testing methods. Part 1 is +titled "Digital Compression and Coding of Continuous-tone Still Images, +Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS +10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of +Continuous-tone Still Images, Part 2: Compliance testing" and has document +numbers ISO/IEC IS 10918-2, ITU-T T.83. +IJG JPEG 8 introduced an implementation of the JPEG SmartScale extension +which is specified in two documents: A contributed document at ITU and ISO +with title "ITU-T JPEG-Plus Proposal for Extending ITU-T T.81 for Advanced +Image Coding", April 2006, Geneva, Switzerland. The latest version of this +document is Revision 3. And a contributed document ISO/IEC JTC1/SC29/WG1 N +5799 with title "Evolution of JPEG", June/July 2011, Berlin, Germany. +IJG JPEG 9 introduces a reversible color transform for improved lossless +compression which is described in a contributed document ISO/IEC JTC1/SC29/ +WG1 N 6080 with title "JPEG 9 Lossless Coding", June/July 2012, Paris, +France. + +The JPEG standard does not specify all details of an interchangeable file +format. For the omitted details we follow the "JFIF" conventions, revision +1.02. JFIF 1.02 has been adopted as an Ecma International Technical Report +and thus received a formal publication status. It is available as a free +download in PDF format from +http://www.ecma-international.org/publications/techreports/E-TR-098.htm. +A PostScript version of the JFIF document is available at +http://www.ijg.org/files/jfif.ps.gz. There is also a plain text version at +http://www.ijg.org/files/jfif.txt.gz, but it is missing the figures. + +The TIFF 6.0 file format specification can be obtained by FTP from +ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme +found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. +IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). +Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 +(Compression tag 7). Copies of this Note can be obtained from +http://www.ijg.org/files/. It is expected that the next revision +of the TIFF spec will replace the 6.0 JPEG design with the Note's design. +Although IJG's own code does not support TIFF/JPEG, the free libtiff library +uses our library to implement TIFF/JPEG per the Note. + + +ARCHIVE LOCATIONS +================= + +The "official" archive site for this software is www.ijg.org. +The most recent released version can always be found there in +directory "files". This particular version will be archived as +http://www.ijg.org/files/jpegsrc.v9a.tar.gz, and in Windows-compatible +"zip" archive format as http://www.ijg.org/files/jpegsr9a.zip. + +The JPEG FAQ (Frequently Asked Questions) article is a source of some +general information about JPEG. +It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/ +and other news.answers archive sites, including the official news.answers +archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/. +If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu +with body + send usenet/news.answers/jpeg-faq/part1 + send usenet/news.answers/jpeg-faq/part2 + + +ACKNOWLEDGMENTS +=============== + +Thank to Juergen Bruder for providing me with a copy of the common DCT +algorithm article, only to find out that I had come to the same result +in a more direct and comprehensible way with a more generative approach. + +Thank to Istvan Sebestyen and Joan L. Mitchell for inviting me to the +ITU JPEG (Study Group 16) meeting in Geneva, Switzerland. + +Thank to Thomas Wiegand and Gary Sullivan for inviting me to the +Joint Video Team (MPEG & ITU) meeting in Geneva, Switzerland. + +Thank to Thomas Richter and Daniel Lee for inviting me to the +ISO/IEC JTC1/SC29/WG1 (previously known as JPEG, together with ITU-T SG16) +meeting in Berlin, Germany. + +Thank to John Korejwa and Massimo Ballerini for inviting me to +fruitful consultations in Boston, MA and Milan, Italy. + +Thank to Hendrik Elstner, Roland Fassauer, Simone Zuck, Guenther +Maier-Gerber, Walter Stoeber, Fred Schmitz, and Norbert Braunagel +for corresponding business development. + +Thank to Nico Zschach and Dirk Stelling of the technical support team +at the Digital Images company in Halle for providing me with extra +equipment for configuration tests. + +Thank to Richard F. Lyon (then of Foveon Inc.) for fruitful +communication about JPEG configuration in Sigma Photo Pro software. + +Thank to Andrew Finkenstadt for hosting the ijg.org site. + +Last but not least special thank to Thomas G. Lane for the original +design and development of this singular software package. + + +FILE FORMAT WARS +================ + +The ISO/IEC JTC1/SC29/WG1 standards committee (previously known as JPEG, +together with ITU-T SG16) currently promotes different formats containing +the name "JPEG" which is misleading because these formats are incompatible +with original DCT-based JPEG and are based on faulty technologies. +IJG therefore does not and will not support such momentary mistakes +(see REFERENCES). +There exist also distributions under the name "OpenJPEG" promoting such +kind of formats which is misleading because they don't support original +JPEG images. +We have no sympathy for the promotion of inferior formats. Indeed, one of +the original reasons for developing this free software was to help force +convergence on common, interoperable format standards for JPEG files. +Don't use an incompatible file format! +(In any case, our decoder will remain capable of reading existing JPEG +image files indefinitely.) + +The ISO committee pretends to be "responsible for the popular JPEG" in their +public reports which is not true because they don't respond to actual +requirements for the maintenance of the original JPEG specification. +Furthermore, the ISO committee pretends to "ensure interoperability" with +their standards which is not true because their "standards" support only +application-specific and proprietary use cases and contain mathematically +incorrect code. + +There are currently different distributions in circulation containing the +name "libjpeg" which is misleading because they don't have the features and +are incompatible with formats supported by actual IJG libjpeg distributions. +One of those fakes is released by members of the ISO committee and just uses +the name of libjpeg for misdirection of people, similar to the abuse of the +name JPEG as described above, while having nothing in common with actual IJG +libjpeg distributions and containing mathematically incorrect code. +The other one claims to be a "derivative" or "fork" of the original libjpeg, +but violates the license conditions as described under LEGAL ISSUES above +and violates basic C programming properties. +We have no sympathy for the release of misleading, incorrect and illegal +distributions derived from obsolete code bases. +Don't use an obsolete code base! + +According to the UCC (Uniform Commercial Code) law, IJG has the lawful and +legal right to foreclose on certain standardization bodies and other +institutions or corporations that knowingly perform substantial and +systematic deceptive acts and practices, fraud, theft, and damaging of the +value of the people of this planet without their knowing, willing and +intentional consent. +The titles, ownership, and rights of these institutions and all their assets +are now duly secured and held in trust for the free people of this planet. +People of the planet, on every country, may have a financial interest in +the assets of these former principals, agents, and beneficiaries of the +foreclosed institutions and corporations. +IJG asserts what is: that each man, woman, and child has unalienable value +and rights granted and deposited in them by the Creator and not any one of +the people is subordinate to any artificial principality, corporate fiction +or the special interest of another without their appropriate knowing, +willing and intentional consent made by contract or accommodation agreement. +IJG expresses that which already was. +The people have already determined and demanded that public administration +entities, national governments, and their supporting judicial systems must +be fully transparent, accountable, and liable. +IJG has secured the value for all concerned free people of the planet. + +A partial list of foreclosed institutions and corporations ("Hall of Shame") +is currently prepared and will be published later. + + +TO DO +===== + +Version 9 is the second release of a new generation JPEG standard +to overcome the limitations of the original JPEG specification, +and is the first true source reference JPEG codec. +More features are being prepared for coming releases... + +Please send bug reports, offers of help, etc. to jpeg-info@jpegclub.org. diff --git a/codecparsers/bitReader.cpp b/codecparsers/bitReader.cpp new file mode 100644 index 0000000..5169dc4 --- /dev/null +++ b/codecparsers/bitReader.cpp @@ -0,0 +1,134 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "bitReader.h" + +#define LOAD8BYTESDATA_BE(x) \ + (((uint64_t)((const uint8_t*)(x))[0] << 56) | \ + ((uint64_t)((const uint8_t*)(x))[1] << 48) | \ + ((uint64_t)((const uint8_t*)(x))[2] << 40) | \ + ((uint64_t)((const uint8_t*)(x))[3] << 32) | \ + ((uint64_t)((const uint8_t*)(x))[4] << 24) | \ + ((uint64_t)((const uint8_t*)(x))[5] << 16) | \ + ((uint64_t)((const uint8_t*)(x))[6] << 8) | \ + ((uint64_t)((const uint8_t*)(x))[7])) + +namespace YamiParser { + +const uint32_t BitReader::CACHEBYTES = sizeof(unsigned long int); + +BitReader::BitReader(const uint8_t* pdata, uint32_t size) + : m_stream(pdata) + , m_size(size) + , m_cache(0) + , m_loadBytes(0) + , m_bitsInCache(0) +{ + if (size) + assert(pdata); +} + +void BitReader::loadDataToCache(uint32_t nbytes) +{ + unsigned long int tmp = 0; + const uint8_t* pStart = m_stream + m_loadBytes; + + if (nbytes == 8) + tmp = LOAD8BYTESDATA_BE(pStart); + else { + for (uint32_t i = 0; i < nbytes; i++) { + tmp <<= 8; + tmp |= pStart[i]; + } + } + + m_cache = tmp; + m_loadBytes += nbytes; + m_bitsInCache = nbytes << 3; +} + +inline void BitReader::reload() +{ + assert(m_size >= m_loadBytes); + uint32_t remainingBytes = m_size - m_loadBytes; + if (remainingBytes > 0) + loadDataToCache(std::min(remainingBytes, CACHEBYTES)); +} + +inline uint32_t BitReader::extractBitsFromCache(uint32_t nbits) +{ + if (!nbits) + return 0; + uint32_t tmp = 0; + tmp = m_cache << ((CACHEBYTES << 3) - m_bitsInCache) >> ((CACHEBYTES << 3) - nbits); + m_bitsInCache -= nbits; + return tmp; +} + +bool BitReader::read(uint32_t& v, uint32_t nbits) +{ + assert(nbits <= (CACHEBYTES << 3)); + + if (nbits <= m_bitsInCache) { + v = extractBitsFromCache(nbits); + return true; + } + /*not enough bits, need to save remaining bits + in current cache and then reload more bits*/ + uint32_t toBeReadBits = nbits - m_bitsInCache; + uint32_t tmp = extractBitsFromCache(m_bitsInCache); + reload(); + if (toBeReadBits > m_bitsInCache) + return false; + v = tmp << toBeReadBits | extractBitsFromCache(toBeReadBits); + return true; +} + +uint32_t BitReader::read(uint32_t nbits) +{ + uint32_t res; + if (read(res, nbits)) + return res; + return 0; +} + +bool BitReader::skip(uint32_t nbits) +{ + uint32_t tmp; + uint32_t size = sizeof(tmp) << 3; + while (nbits > size) { + if (!readT(tmp)) + return false; + nbits -= size; + } + if (!read(tmp, nbits)) + return false; + return true; +} + +uint32_t BitReader::peek(uint32_t nbits) const +{ + BitReader tmp(*this); + + return tmp.read(nbits); +} + +} /*namespace YamiParser*/ diff --git a/codecparsers/bitReader.h b/codecparsers/bitReader.h new file mode 100644 index 0000000..0cfc20e --- /dev/null +++ b/codecparsers/bitReader.h @@ -0,0 +1,116 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef bitReader_h +#define bitReader_h + +#include +#include /*std::min*/ + +namespace YamiParser { + +class BitReader { +public: + static const uint32_t CACHEBYTES; + BitReader(const uint8_t* data, uint32_t size); + virtual ~BitReader() {} + + /* Read specified bits(<= 8*sizeof(uint32_t)) as a uint32_t to v */ + /* if not enough data, it will return false, eat all data and keep v untouched */ + bool read(uint32_t& v, uint32_t nbits); + /* Read specified bits(<= 8*sizeof(uint32_t)) as a uint32_t return value */ + /* will return 0 if not enough data*/ + uint32_t read(uint32_t nbits); + + /*TODO: change to this to read, and change read to readBits */ + template + inline bool readT(T& v, uint32_t nbits); + + template + inline bool readT(T& v); + + inline bool readT(bool& v); + + /*read the next nbits bits from the bitstream but not advance the bitstream pointer*/ + uint32_t peek(uint32_t nbits) const; + + /* this version will check read beyond boundary */ + template + bool peek(T& v, uint32_t nbits) const; + + bool skip(uint32_t nbits); + + /* Get the total bits that had been read from bitstream, and the return + * value also is the position of the next bit to be read. */ + uint64_t getPos() const + { + return (static_cast(m_loadBytes) << 3) - m_bitsInCache; + } + + uint64_t getRemainingBitsCount() const + { + return m_bitsInCache + (static_cast(m_size - m_loadBytes) << 3); + } + + bool end() const + { + return (getPos() >= (static_cast(m_size) << 3)); + } + +protected: + virtual void loadDataToCache(uint32_t nbytes); + + const uint8_t* m_stream; /*a pointer to source data*/ + uint32_t m_size; /*the size of source data in bytes*/ + unsigned long int m_cache; /*the buffer which load less than or equal to 8 bytes*/ + uint32_t m_loadBytes; /*the total bytes of data read from source data*/ + uint32_t m_bitsInCache; /*the remaining bits in cache*/ +private: + inline uint32_t extractBitsFromCache(uint32_t nbits); + inline void reload(); +}; + +template +bool BitReader::readT(T& v, uint32_t nbits) +{ + uint32_t tmp; + if (!read(tmp, nbits)) + return false; + v = tmp; + return true; +} + +template +bool BitReader::readT(T& v) +{ + return readT(v, sizeof(v) << 3); +} + +bool BitReader::readT(bool& v) +{ + return readT(v, 1); +} + +template +bool BitReader::peek(T& v, uint32_t nbits) const +{ + BitReader tmp(*this); + return tmp.readT(v, nbits); +} + +} /*namespace YamiParser*/ + +#endif diff --git a/codecparsers/bitReader_unittest.cpp b/codecparsers/bitReader_unittest.cpp new file mode 100644 index 0000000..743629c --- /dev/null +++ b/codecparsers/bitReader_unittest.cpp @@ -0,0 +1,99 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "bitReader.h" + +// library headers +#include "common/unittest.h" + +// system libraries +#include +#include + +namespace YamiParser { + +class BitReaderTest + : public ::testing::Test +{ +protected: + std::vector& largeData() const + { + static const uint32_t nBytes = + (std::numeric_limits::max() >> 3) + 1; + static std::vector data(nBytes); + + return data; + } +}; + +#define BITREADER_TEST(name) \ + TEST_F(BitReaderTest, name) + +BITREADER_TEST(NoOverflow) +{ + std::vector& data = largeData(); + const uint32_t nBytes = data.size(); + + ASSERT_EQ(0u, nBytes % (1024 * 1024 * 512)); + + BitReader reader(&data[0], nBytes); + + EXPECT_FALSE(reader.end()); + EXPECT_EQ(0u, reader.getPos()); + EXPECT_EQ(static_cast(nBytes) << 3, + reader.getRemainingBitsCount()); + + const uint32_t nReads = nBytes / BitReader::CACHEBYTES; + const uint32_t rem = nBytes % BitReader::CACHEBYTES; + const uint32_t bitsPerRead = BitReader::CACHEBYTES << 3; + for (uint32_t i(0); i < nReads; ++i) + reader.read(bitsPerRead); + reader.read(rem << 3); + + EXPECT_EQ(static_cast(nBytes) << 3, reader.getPos()); + EXPECT_TRUE(reader.end()); + EXPECT_EQ(0u, reader.getRemainingBitsCount()); +} + +void checkBitreadEmpty(BitReader& reader) +{ + EXPECT_TRUE(reader.end()); + EXPECT_EQ(0u, reader.getPos()); + EXPECT_EQ(0u, + reader.getRemainingBitsCount()); + bool b; + EXPECT_FALSE(reader.readT(b)); + EXPECT_TRUE(reader.end()); +} + +BITREADER_TEST(NullInit) +{ + uint8_t data = 0; + BitReader r1(&data, 0); + checkBitreadEmpty(r1); + + BitReader r2(NULL, 0); + checkBitreadEmpty(r2); + + EXPECT_DEATH(BitReader r3(NULL, 1), ""); +} + +} // namespace YamiParser diff --git a/codecparsers/bitWriter.cpp b/codecparsers/bitWriter.cpp new file mode 100644 index 0000000..9bcb14d --- /dev/null +++ b/codecparsers/bitWriter.cpp @@ -0,0 +1,124 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "bitWriter.h" +#include "common/log.h" +#include + +namespace YamiParser { + +const uint32_t CACHEBYTES = sizeof(unsigned long int); +const uint32_t CACHEBITS = sizeof(unsigned long int) * 8; + +// clip to keep lowest n bits +#define CLIPBITS(value, n) ((value) & ((1 << (n)) - 1)); + +BitWriter::BitWriter(uint32_t size) + : m_cache(0) + , m_bitsInCache(0) +{ + m_bs.reserve(size); +} + +uint8_t* BitWriter::getBitWriterData() +{ + uint8_t* buf; + flushCache(); + + buf = m_bs.size() ? static_cast(&m_bs[0]) : NULL; + return buf; +} + +void BitWriter::flushCache() +{ + uint8_t tmp, i, bytesInCache; + + // make sure m_bitsInCache is byte aligned, else trailing bits should be + // padded + if (m_bitsInCache % 8) + writeToBytesAligned(); + + assert(!(m_bitsInCache % 8)); + + bytesInCache = m_bitsInCache / 8; + + for (i = 0; i < bytesInCache; i++) { + tmp = static_cast(m_cache >> (m_bitsInCache - (i + 1) * 8)); + m_bs.push_back(tmp); + } + + m_cache = 0; + m_bitsInCache = 0; +} + +bool BitWriter::writeBits(uint32_t value, uint32_t numBits) +{ + if (value >= (uint64_t)1 << numBits) { + WARNING("Write Bits: value overflow"); + } + + ASSERT((m_bitsInCache <= CACHEBITS) && (numBits <= CACHEBITS)); + + uint32_t bitLeft = CACHEBITS - m_bitsInCache; + + if (bitLeft > numBits) { + m_cache = (m_cache << numBits | value); + m_bitsInCache += numBits; + } else { + m_cache = ((m_cache << bitLeft) | (value >> (numBits - bitLeft))); + m_bitsInCache = CACHEBITS; + flushCache(); + m_cache = value; + m_bitsInCache = numBits - bitLeft; + } + + return true; +} + +bool BitWriter::writeBytes(uint8_t* data, uint32_t numBytes) +{ + if (!data || !numBytes) + return false; + + if ((m_bitsInCache % 8) == 0) { + flushCache(); + m_bs.insert(m_bs.end(), data, data + numBytes); + } else { + for (uint32_t i = 0; i < numBytes; i++) + writeBits(data[i], 8); + } + + return true; +} + +void BitWriter::writeToBytesAligned(bool bit) +{ + uint8_t padBits = m_bitsInCache & 0x7; + uint32_t value; + if (padBits) { + if (bit) + value = (1 << (8 - padBits)) - 1; + else + value = 0; + writeBits(value, 8 - padBits); + } +} + +} /*namespace YamiParser*/ diff --git a/codecparsers/bitWriter.h b/codecparsers/bitWriter.h new file mode 100644 index 0000000..36d7ffd --- /dev/null +++ b/codecparsers/bitWriter.h @@ -0,0 +1,67 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef bitWriter_h +#define bitWriter_h + +#include +#include + +namespace YamiParser { + +#define BIT_WRITER_DEFAULT_BUFFER_SIZE 0x1000 + +class BitWriter { +public: + /* size is used to set bit stream buffer capacity, + a default buffer size may be set to avoid memory reallocated frequently + */ + BitWriter(uint32_t size = BIT_WRITER_DEFAULT_BUFFER_SIZE); + + /* Write a value with numBits into bitstream */ + bool writeBits(uint32_t value, uint32_t numBits); + + /* Write an array with numBytes into bitstream */ + bool writeBytes(uint8_t* data, uint32_t numBytes); + + /* Pad some zeros to make sure bitsteam byte aligned */ + void writeToBytesAligned(bool bit = false); + + /* get encoded bitstream buffer */ + uint8_t* getBitWriterData(); + + /* get encoded bits count + * it is recommended to call getCodedBitsCount prior to getBitWriterData, + * because getBitWriterData may pad some bits to make sure byte aligned, + * then the padded bits will be caculated as coded bits. + * */ + uint64_t getCodedBitsCount() const + { + return static_cast(m_bs.size() * 8) + m_bitsInCache; + } + +protected: + void flushCache(); + + std::vector m_bs; /* encoded bitstream buffer */ + + long int m_cache; /* a 32 or 64 bits cache buffer */ + uint32_t m_bitsInCache; /* used bits in cache*/ +}; + +} /*namespace YamiParser*/ + +#endif diff --git a/codecparsers/bitWriter_unittest.cpp b/codecparsers/bitWriter_unittest.cpp new file mode 100644 index 0000000..af8ec35 --- /dev/null +++ b/codecparsers/bitWriter_unittest.cpp @@ -0,0 +1,60 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "bitWriter.h" + +// library headers +#include "common/unittest.h" + +namespace YamiParser { + +static const uint16_t writeArrary[16][2] = { + { 1, 1 }, { 2, 2 }, { 3, 2 }, { 4, 3 }, + { 5, 3 }, { 6, 3 }, { 7, 3 }, { 8, 4 }, + { 9, 4 }, { 10, 4 }, { 11, 4 }, { 12, 4 }, + { 13, 4 }, { 14, 4 }, { 15, 4 }, { 16, 5 } +}; + +class BitWriterTest + : public ::testing::Test { +}; + +#define BITWriter_TEST(name) \ + TEST_F(BitWriterTest, name) + +BITWriter_TEST(Writer_Simple) +{ + BitWriter Writer; + + EXPECT_EQ(0u, Writer.getCodedBitsCount()); + EXPECT_EQ(NULL, Writer.getBitWriterData()); + + uint32_t i, bitsSum; + + for (i = 0, bitsSum = 0; i < 16; i++) { + EXPECT_TRUE(Writer.writeBits(writeArrary[i][0], writeArrary[i][1])); + bitsSum += writeArrary[i][1]; + } + + EXPECT_EQ(bitsSum, Writer.getCodedBitsCount()); +} + +} // namespace YamiParser diff --git a/codecparsers/dboolhuff.AUTHORS b/codecparsers/dboolhuff.AUTHORS new file mode 100644 index 0000000..a9aa481 --- /dev/null +++ b/codecparsers/dboolhuff.AUTHORS @@ -0,0 +1,100 @@ +# This file is automatically generated from the git commit history +# by tools/gen_authors.sh. + +Aaron Watry +Abo Talib Mahfoodh +Adrian Grange +Ahmad Sharif +Alexander Voronov +Alex Converse +Alexis Ballier +Alok Ahuja +Alpha Lam +A.Mahfoodh +Ami Fischman +Andoni Morales Alastruey +Andres Mejia +Aron Rosenberg +Attila Nagy +changjun.yang +chm +Christian Duvivier +Daniel Kang +Deb Mukherjee +Dmitry Kovalev +Dragan Mrdjan +Erik Niemeyer +Fabio Pedretti +Frank Galligan +Fredrik Söderquist +Fritz Koenig +Gaute Strokkenes +Giuseppe Scrivano +Guillaume Martres +Guillermo Ballester Valor +Hangyu Kuang +Henrik Lundin +Hui Su +Ivan Maltz +James Berry +James Zern +Jan Kratochvil +Janne Salonen +Jeff Faust +Jeff Muizelaar +Jeff Petkau +Jim Bankoski +Jingning Han +Johann Koenig +John Koleszar +Joshua Bleecher Snyder +Joshua Litt +Justin Clift +Justin Lebar +KO Myung-Hun +Lou Quillio +Luca Barbato +Makoto Kato +Mans Rullgard +Marco Paniconi +Mark Mentovai +Martin Ettl +Martin Storsjo +Matthew Heaney +Michael Kohler +Mike Frysinger +Mike Hommey +Mikhal Shemer +Morton Jonuschat +Parag Salasakar +Pascal Massimino +Patrik Westin +Paul Wilkins +Pavol Rusnak +Paweł Hajdan +Philip Jägenstedt +Priit Laes +Rafael Ávila de Espíndola +Rafaël Carré +Ralph Giles +Rob Bradford +Ronald S. Bultje +Sami Pietilä +Scott Graham +Scott LaVarnway +Shimon Doodkin +Stefan Holmer +Suman Sunkara +Taekhyun Kim +Takanori MATSUURA +Tamar Levy +Tero Rintaluoma +Thijs Vermeir +Timothy B. Terriberry +Tom Finegan +Vignesh Venkatasubramanian +Yaowu Xu +Yunqing Wang +Google Inc. +The Mozilla Foundation +The Xiph.Org Foundation diff --git a/codecparsers/dboolhuff.LICENSE b/codecparsers/dboolhuff.LICENSE new file mode 100644 index 0000000..1ce4434 --- /dev/null +++ b/codecparsers/dboolhuff.LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2010, The WebM Project authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google, nor the WebM Project, nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/codecparsers/dboolhuff.PATENTS b/codecparsers/dboolhuff.PATENTS new file mode 100644 index 0000000..4414d83 --- /dev/null +++ b/codecparsers/dboolhuff.PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer, and otherwise run, modify and propagate the contents of this +implementation of VP8, where such license applies only to those patent +claims, both currently owned by Google and acquired in the future, +licensable by Google that are necessarily infringed by this +implementation of VP8. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of VP8 or any code incorporated within this +implementation of VP8 constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of VP8 +shall terminate as of the date such litigation is filed. diff --git a/codecparsers/dboolhuff.c b/codecparsers/dboolhuff.c new file mode 100644 index 0000000..692d78b --- /dev/null +++ b/codecparsers/dboolhuff.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2010 The WebM project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + + +#include "dboolhuff.h" + +int +vp8dx_start_decode (BOOL_DECODER * br, + const unsigned char *source, + unsigned int source_sz, vp8_decrypt_cb * decrypt_cb, void *decrypt_state) +{ + br->user_buffer_end = source + source_sz; + br->user_buffer = source; + br->value = 0; + br->count = -8; + br->range = 255; + br->decrypt_cb = decrypt_cb; + br->decrypt_state = decrypt_state; + + if (source_sz && !source) + return 1; + + /* Populate the buffer */ + vp8dx_bool_decoder_fill (br); + + return 0; +} + +void +vp8dx_bool_decoder_fill (BOOL_DECODER * br) +{ + const unsigned char *bufptr = br->user_buffer; + VP8_BD_VALUE value = br->value; + int count = br->count; + int shift = VP8_BD_VALUE_SIZE - 8 - (count + 8); + size_t bytes_left = br->user_buffer_end - bufptr; + size_t bits_left = bytes_left * CHAR_BIT; + int x = (int) (shift + CHAR_BIT - bits_left); + int loop_end = 0; + unsigned char decrypted[sizeof (VP8_BD_VALUE) + 1]; + + if (br->decrypt_cb) { + size_t n = + bytes_left > sizeof (decrypted) ? sizeof (decrypted) : bytes_left; + br->decrypt_cb (br->decrypt_state, bufptr, decrypted, (int) n); + bufptr = decrypted; + } + + if (x >= 0) { + count += VP8_LOTS_OF_BITS; + loop_end = x; + } + + if (x < 0 || bits_left) { + while (shift >= loop_end) { + count += CHAR_BIT; + value |= (VP8_BD_VALUE) * bufptr << shift; + ++bufptr; + ++br->user_buffer; + shift -= CHAR_BIT; + } + } + + br->value = value; + br->count = count; +} diff --git a/codecparsers/dboolhuff.h b/codecparsers/dboolhuff.h new file mode 100644 index 0000000..a54253e --- /dev/null +++ b/codecparsers/dboolhuff.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2010 The WebM project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + + +#ifndef DBOOLHUFF_H_ +#define DBOOLHUFF_H_ + +#include +#include +#include + +typedef size_t VP8_BD_VALUE; + +#define VP8_BD_VALUE_SIZE ((int)sizeof(VP8_BD_VALUE)*CHAR_BIT) + +/*This is meant to be a large, positive constant that can still be efficiently + loaded as an immediate (on platforms like ARM, for example). + Even relatively modest values like 100 would work fine.*/ +#define VP8_LOTS_OF_BITS (0x40000000) + +/*Decrypt n bytes of data from input -> output, using the decrypt_state + passed in VP8D_SET_DECRYPTOR. +*/ +typedef void (vp8_decrypt_cb)(void *decrypt_state, const unsigned char *input, + unsigned char *output, int count); + +typedef struct +{ + const unsigned char *user_buffer_end; + const unsigned char *user_buffer; + VP8_BD_VALUE value; + int count; + unsigned int range; + vp8_decrypt_cb *decrypt_cb; + void *decrypt_state; +} BOOL_DECODER; + +extern const unsigned char vp8_norm[256]; + +int vp8dx_start_decode(BOOL_DECODER *br, + const unsigned char *source, + unsigned int source_sz, + vp8_decrypt_cb *decrypt_cb, + void *decrypt_state); + +void vp8dx_bool_decoder_fill(BOOL_DECODER *br); + + +static inline int vp8dx_decode_bool(BOOL_DECODER *br, int probability) { + unsigned int bit = 0; + VP8_BD_VALUE value; + unsigned int split; + VP8_BD_VALUE bigsplit; + int count; + unsigned int range; + + split = 1 + (((br->range - 1) * probability) >> 8); + + if(br->count < 0) + vp8dx_bool_decoder_fill(br); + + value = br->value; + count = br->count; + + bigsplit = (VP8_BD_VALUE)split << (VP8_BD_VALUE_SIZE - 8); + + range = split; + + if (value >= bigsplit) + { + range = br->range - split; + value = value - bigsplit; + bit = 1; + } + + { + register unsigned int shift = vp8_norm[range]; + range <<= shift; + value <<= shift; + count -= shift; + } + br->value = value; + br->count = count; + br->range = range; + + return bit; +} + +static inline int vp8_decode_value(BOOL_DECODER *br, int bits) +{ + int z = 0; + int bit; + + for (bit = bits - 1; bit >= 0; bit--) + { + z |= (vp8dx_decode_bool(br, 0x80) << bit); + } + + return z; +} + +static inline int vp8dx_bool_error(BOOL_DECODER *br) +{ + /* Check if we have reached the end of the buffer. + * + * Variable 'count' stores the number of bits in the 'value' buffer, minus + * 8. The top byte is part of the algorithm, and the remainder is buffered + * to be shifted into it. So if count == 8, the top 16 bits of 'value' are + * occupied, 8 for the algorithm and 8 in the buffer. + * + * When reading a byte from the user's buffer, count is filled with 8 and + * one byte is filled into the value buffer. When we reach the end of the + * data, count is additionally filled with VP8_LOTS_OF_BITS. So when + * count == VP8_LOTS_OF_BITS - 1, the user's data has been exhausted. + */ + if ((br->count > VP8_BD_VALUE_SIZE) && (br->count < VP8_LOTS_OF_BITS)) + { + /* We have tried to decode bits after the end of + * stream was encountered. + */ + return 1; + } + + /* No error. */ + return 0; +} + +#endif /* DBOOLHUFF_H_*/ diff --git a/codecparsers/h264Parser.cpp b/codecparsers/h264Parser.cpp new file mode 100644 index 0000000..22117a1 --- /dev/null +++ b/codecparsers/h264Parser.cpp @@ -0,0 +1,984 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "h264Parser.h" + +#include +#include + +#define READ(f) \ + do { \ + if (!br.readT(f)) { \ + ERROR("failed to read %s", #f); \ + return false; \ + } \ + } while (0) + +#define READ_BITS(f, bits) \ + do { \ + if (!br.readT(f, bits)) { \ + ERROR("failed to read %d to %s", bits, #f); \ + return false; \ + } \ + } while (0) + +#define READ_UE(f) \ + do { \ + if (!br.readUe(f)) { \ + ERROR("failed to readUe %s", #f); \ + return false; \ + } \ + } while (0) + +#define READ_SE(f) \ + do { \ + if (!br.readSe(f)) { \ + ERROR("failed to readSe %s", #f); \ + return false; \ + } \ + } while (0) + +namespace YamiParser { +namespace H264 { + +//according to Table 7-3 +static const uint8_t Default_4x4_Intra[16] = { + 6, 13, 13, 20, + 20, 20, 28, 28, + 28, 28, 32, 32, + 32, 37, 37, 42 +}; +static const uint8_t Default_4x4_Inter[16] = { + 10, 14, 14, 20, + 20, 20, 24, 24, + 24, 24, 27, 27, + 27, 30, 30, 34 +}; + +//according to Table 7-4 +static const uint8_t Default_8x8_Intra[64] = { + 6, 10, 10, 13, 11, 13, 16, 16, + 16, 16, 18, 18, 18, 18, 18, 23, + 23, 23, 23, 23, 23, 25, 25, 25, + 25, 25, 25, 25, 27, 27, 27, 27, + 27, 27, 27, 27, 29, 29, 29, 29, + 29, 29, 29, 31, 31, 31, 31, 31, + 31, 33, 33, 33, 33, 33, 36, 36, + 36, 36, 38, 38, 38, 40, 40, 42 +}; +static const uint8_t Default_8x8_Inter[64] = { + 9, 13, 13, 15, 13, 15, 17, 17, + 17, 17, 19, 19, 19, 19, 19, 21, + 21, 21, 21, 21, 21, 22, 22, 22, + 22, 22, 22, 22, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, + 25, 25, 25, 27, 27, 27, 27, 27, + 27, 28, 28, 28, 28, 28, 30, 30, + 30, 30, 32, 32, 32, 33, 33, 35 +}; + +//definded according to Table 7-2 +const uint8_t* Default_Scaling_List[12] = { + Default_4x4_Intra, Default_4x4_Intra, Default_4x4_Intra, + Default_4x4_Inter, Default_4x4_Inter, Default_4x4_Inter, + Default_8x8_Intra, Default_8x8_Inter, Default_8x8_Intra, + Default_8x8_Inter, Default_8x8_Intra, Default_8x8_Inter +}; + +//Find the first occurrence of the subsequence position in the string src. +//@src, the pointer to source data. +//@size, the lenght of source data in bytes. +static int32_t searchStartPos(const uint8_t* src, uint32_t size) +{ + //Loop size -2 times at most because the subsequence contains 3 characters. + for (uint32_t i = 0; i < size - 2; i++) + if ((src[i] == 0x00) && (src[i + 1] == 0x00) && (src[i + 2] == 0x01)) + return i; + return -1; +} + +//7.3.2.1.1.1 Scaling list syntax +static bool scalingList(NalReader& br, uint8_t* sl, uint32_t size, uint32_t index) +{ + uint8_t lastScale = 8; + uint8_t nextScale = 8; + int32_t delta_scale; + for (uint32_t j = 0; j < size; j++) { + if (nextScale) { + READ_SE(delta_scale); + nextScale = (lastScale + delta_scale + 256) % 256; + } + if (!j && !nextScale) { + memcpy(sl, Default_Scaling_List[index], size); + break; + } + sl[j] = (!nextScale) ? lastScale : nextScale; + lastScale = sl[j]; + } + return true; +} + +PPS::PPS() +{ + memset(this, 0, offsetof(PPS, m_sps)); +} + +PPS::~PPS() +{ + free(slice_group_id); +} + +//according to G.7.3.1.1 +bool NalUnit::parseSvcExtension(BitReader& br) +{ + READ(m_svc.idr_flag); + READ_BITS(m_svc.priority_id, 6); + READ(m_svc.no_inter_layer_pred_flag); + READ_BITS(m_svc.dependency_id, 3); + READ_BITS(m_svc.quality_id, 4); + READ_BITS(m_svc.temporal_id, 3); + READ(m_svc.use_ref_base_pic_flag); + READ(m_svc.discardable_flag); + READ(m_svc.output_flag); + READ_BITS(m_svc.reserved_three_2bits, 2); + return true; +} + +//according to H.7.3.1.1 +bool NalUnit::parseMvcExtension(BitReader& br) +{ + READ(m_mvc.non_idr_flag); + READ_BITS(m_mvc.priority_id, 6); + READ_BITS(m_mvc.view_id, 10); + READ_BITS(m_mvc.temporal_id, 3); + READ(m_mvc.anchor_pic_flag); + READ(m_mvc.inter_view_flag); + return true; +} + +bool NalUnit::parseNalUnit(const uint8_t* src, size_t size) +{ + if (!src || !size) + return false; + + m_data = src; + m_size = size; + BitReader br(m_data, m_size); + + br.skip(1); // forbidden_zero_bit + READ_BITS(nal_ref_idc, 2); + READ_BITS(nal_unit_type, 5); + //7-1 + m_idrPicFlag = (nal_unit_type == 5 ? 1 : 0); + m_nalUnitHeaderBytes = 1; + + bool svc_extension_flag; + if (nal_unit_type == NAL_PREFIX_UNIT + || nal_unit_type == NAL_SLICE_EXT + || nal_unit_type == NAL_SLICE_EXT_DEPV) { + READ(svc_extension_flag); + if (svc_extension_flag) { + if (!parseSvcExtension(br)) + return false; + //G.7.4.1.1 + m_idrPicFlag = m_svc.idr_flag; + } else { + if (!parseMvcExtension(br)) + return false; + //H.7.4.1.1 + m_idrPicFlag = !m_mvc.non_idr_flag; + } + m_nalUnitHeaderBytes += 3; + } + + return true; +} + +const uint8_t Parser::EXTENDED_SAR = 255; + +bool Parser::hrdParameters(HRDParameters* hrd, NalReader& br) +{ + READ_UE(hrd->cpb_cnt_minus1); + if (hrd->cpb_cnt_minus1 > MAX_CPB_CNT_MINUS1) + return false; + READ_BITS(hrd->bit_rate_scale, 4); + READ_BITS(hrd->cpb_size_scale, 4); + + for (uint32_t SchedSelIdx = 0; SchedSelIdx <= hrd->cpb_cnt_minus1; SchedSelIdx++) { + READ_UE(hrd->bit_rate_value_minus1[SchedSelIdx]); + READ_UE(hrd->cpb_size_value_minus1[SchedSelIdx]); + READ(hrd->cbr_flag[SchedSelIdx]); + } + + READ_BITS(hrd->initial_cpb_removal_delay_length_minus1, 5); + READ_BITS(hrd->cpb_removal_delay_length_minus1, 5); + READ_BITS(hrd->dpb_output_delay_length_minus1, 5); + READ_BITS(hrd->time_offset_length, 5); + + return true; +} + +bool Parser::vuiParameters(SharedPtr& sps, NalReader& br) +{ + VUIParameters* vui = &sps->m_vui; + READ(vui->aspect_ratio_info_present_flag); + if (vui->aspect_ratio_info_present_flag) { + READ(vui->aspect_ratio_idc); + if (vui->aspect_ratio_idc == EXTENDED_SAR) { + READ(vui->sar_width); + READ(vui->sar_height); + } + } + + READ(vui->overscan_info_present_flag); + if (vui->overscan_info_present_flag) + READ(vui->overscan_appropriate_flag); + + READ(vui->video_signal_type_present_flag); + if (vui->video_signal_type_present_flag) { + READ_BITS(vui->video_format, 3); + READ(vui->video_full_range_flag); + READ(vui->colour_description_present_flag); + if (vui->colour_description_present_flag) { + READ(vui->colour_primaries); + READ(vui->transfer_characteristics); + READ(vui->matrix_coefficients); + } + } + + READ(vui->chroma_loc_info_present_flag); + if (vui->chroma_loc_info_present_flag) { + READ_UE(vui->chroma_sample_loc_type_top_field); + //chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field + //specify the location of chroma samples, and it shall be in the range of 0 to 5 + if (vui->chroma_sample_loc_type_top_field > 5) + return false; + READ_UE(vui->chroma_sample_loc_type_bottom_field); + if (vui->chroma_sample_loc_type_bottom_field > 5) + return false; + } + + READ(vui->timing_info_present_flag); + if (vui->timing_info_present_flag) { + READ(vui->num_units_in_tick); + READ(vui->time_scale); + READ(vui->fixed_frame_rate_flag); + } + + READ(vui->nal_hrd_parameters_present_flag); + if (vui->nal_hrd_parameters_present_flag) { + if (!hrdParameters(&vui->nal_hrd_parameters, br)) + return false; + } + + READ(vui->vcl_hrd_parameters_present_flag); + if (vui->vcl_hrd_parameters_present_flag) { + if (!hrdParameters(&vui->vcl_hrd_parameters, br)) + return false; + } + + if (vui->nal_hrd_parameters_present_flag || vui->vcl_hrd_parameters_present_flag) + READ(vui->low_delay_hrd_flag); + + READ(vui->pic_struct_present_flag); + READ(vui->bitstream_restriction_flag); + if (vui->bitstream_restriction_flag) { + READ(vui->motion_vectors_over_pic_boundaries_flag); + READ_UE(vui->max_bytes_per_pic_denom); + READ_UE(vui->max_bits_per_mb_denom); + //max_bits_per_mb_denom in the range of 0 to 16 + if (vui->max_bits_per_mb_denom > 16) + return false; + //both log2_max_mv_length_horizontal and log2_max_mv_length_vertical + //shall be in the range of 0 to 16 + READ_UE(vui->log2_max_mv_length_horizontal); + READ_UE(vui->log2_max_mv_length_vertical); + if (vui->log2_max_mv_length_horizontal > 16 + || vui->log2_max_mv_length_vertical > 16) + return false; + READ_UE(vui->max_num_reorder_frames); + READ_UE(vui->max_dec_frame_buffering); + } + + return true; +} + +bool Parser::parseSps(SharedPtr& sps, const NalUnit* nalu) +{ + NalReader br(nalu->m_data + nalu->m_nalUnitHeaderBytes, + nalu->m_size - nalu->m_nalUnitHeaderBytes); + + READ(sps->profile_idc); + READ(sps->constraint_set0_flag); + READ(sps->constraint_set1_flag); + READ(sps->constraint_set2_flag); + READ(sps->constraint_set3_flag); + READ(sps->constraint_set4_flag); + READ(sps->constraint_set5_flag); + br.skip(2); //reserved_zero_2bits + READ(sps->level_idc); + READ_UE(sps->sps_id); + if (sps->sps_id > MAX_SPS_ID) + return false; + + //when chroma_format_idc is not present, + //it shall be inferred to be equal to 1 (4:2:0 chroma format) + sps->chroma_format_idc = 1; + sps->bit_depth_luma_minus8 = 0; + sps->bit_depth_chroma_minus8 = 0; + + //when seq_scaling_matrix_present_flag is not present, + //it shall be inferred to be euqal to 0, and the elements of + //scaling lists specified by Flat_4x4_16 and Flat_8x8_16 which + //include the default values euqal to 16 + memset(sps->scaling_lists_4x4, SCALING_LIST_DEFAULT_VALUE, + sizeof(sps->scaling_lists_4x4)); + memset(sps->scaling_lists_8x8, SCALING_LIST_DEFAULT_VALUE, + sizeof(sps->scaling_lists_8x8)); + + if (sps->profile_idc == PROFILE_HIGH + || sps->profile_idc == PROFILE_HIGH_10 + || sps->profile_idc == PROFILE_HIGH_422 + || sps->profile_idc == PROFILE_HIGH_444 + || sps->profile_idc == PROFILE_CAVLC_444_INTRA + || sps->profile_idc == PROFILE_SCALABLE_BASELINE + || sps->profile_idc == PROFILE_SCALABLE_HIGH + || sps->profile_idc == PROFILE_MULTIVIEW_HIGH + || sps->profile_idc == PROFILE_STEREO_HIGH + || sps->profile_idc == PROFILE_MULTIVIEW_DEPTH_HIGH) { + READ_UE(sps->chroma_format_idc); + if (sps->chroma_format_idc > MAX_CHROMA_FORMAT_IDC) + return false; + if (sps->chroma_format_idc == MAX_CHROMA_FORMAT_IDC) + READ(sps->separate_colour_plane_flag); + + //both bit_depth_luma_minus8 and bit_depth_chroma_minus8 shall be + //in the range of 0 to 6. When they are not present, its shall be inferred + //to be equal to 0, at the begining of this function + READ_UE(sps->bit_depth_luma_minus8); + READ_UE(sps->bit_depth_chroma_minus8); + if (sps->bit_depth_luma_minus8 > 6 + || sps->bit_depth_chroma_minus8 > 6) + return false; + READ(sps->qpprime_y_zero_transform_bypass_flag); + + READ(sps->seq_scaling_matrix_present_flag); + + //according to Table 7-2, Scaling list fall-back rule set A + const uint8_t* const Fall_Back_Scaling_List[12] = { + Default_4x4_Intra, sps->scaling_lists_4x4[0], sps->scaling_lists_4x4[1], + Default_4x4_Inter, sps->scaling_lists_4x4[3], sps->scaling_lists_4x4[4], + Default_8x8_Intra, Default_8x8_Inter, sps->scaling_lists_8x8[0], + sps->scaling_lists_8x8[1], sps->scaling_lists_8x8[2], sps->scaling_lists_8x8[3] + }; + + if (sps->seq_scaling_matrix_present_flag) { + uint32_t loop = (sps->chroma_format_idc != 3) ? 8 : 12; + for (uint32_t i = 0; i < loop; i++) { + READ(sps->seq_scaling_list_present_flag[i]); + if (sps->seq_scaling_list_present_flag[i]) { + if (i < 6) { + if (!scalingList(br, sps->scaling_lists_4x4[i], 16, i)) + return false; + } + else { + if (!scalingList(br, sps->scaling_lists_8x8[i - 6], 64, i)) + return false; + } + } else { + if(i < 6) + memcpy(sps->scaling_lists_4x4[i], Fall_Back_Scaling_List[i], 16); + else + memcpy(sps->scaling_lists_8x8[i - 6], Fall_Back_Scaling_List[i], 64); + } + } + } + } + + //log2_max_frame_num_minus4 specifies the value of the variable MaxFrameNum that + //is used in frame_num related, and shall be in the range of 0 to 12 + READ_UE(sps->log2_max_frame_num_minus4); + if (sps->log2_max_frame_num_minus4 > 12) + return false; + sps->m_maxFrameNum = 1 << (sps->log2_max_frame_num_minus4 + 4); + READ_UE(sps->pic_order_cnt_type); + if (sps->pic_order_cnt_type > 2) + return false; + if (!sps->pic_order_cnt_type) { + //log2_max_pic_order_cnt_lsb_minus4 specifies the value of the variable + //MaxPicOrderCntLsb that is used in the decoing process for picture order + //count, and shall be in the range of 0 to 12 + READ_UE(sps->log2_max_pic_order_cnt_lsb_minus4); + if (sps->log2_max_pic_order_cnt_lsb_minus4 > 12) + return false; + } else if (sps->pic_order_cnt_type == 1) { + READ(sps->delta_pic_order_always_zero_flag); + READ_SE(sps->offset_for_non_ref_pic); + READ_SE(sps->offset_for_top_to_bottom_field); + READ_UE(sps->num_ref_frames_in_pic_order_cnt_cycle); + if (sps->num_ref_frames_in_pic_order_cnt_cycle > 255) + return false; + for (uint32_t i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++) + READ_SE(sps->offset_for_ref_frame[i]); + } + + READ_UE(sps->num_ref_frames); + READ(sps->gaps_in_frame_num_value_allowed_flag); + READ_UE(sps->pic_width_in_mbs_minus1); + READ_UE(sps->pic_height_in_map_units_minus1); + READ(sps->frame_mbs_only_flag); + + if (!sps->frame_mbs_only_flag) + READ(sps->mb_adaptive_frame_field_flag); + + READ(sps->direct_8x8_inference_flag); + READ(sps->frame_cropping_flag); + if (sps->frame_cropping_flag) { + READ_UE(sps->frame_crop_left_offset); + READ_UE(sps->frame_crop_right_offset); + READ_UE(sps->frame_crop_top_offset); + READ_UE(sps->frame_crop_bottom_offset); + } + + READ(sps->vui_parameters_present_flag); + if (sps->vui_parameters_present_flag) { + if (!vuiParameters(sps, br)) + return false; + } + + //according to 7.4.2.1.1 + if (sps->separate_colour_plane_flag) + sps->m_chromaArrayType = 0; + else + sps->m_chromaArrayType = sps->chroma_format_idc; + + //Calculate width and height + uint32_t width, height; + uint32_t picHeightInMapUnits; + uint32_t picWidthInMbs, frameHeightInMbs; + picWidthInMbs = sps->pic_width_in_mbs_minus1 + 1; //7-12 + width = picWidthInMbs << 4; + //7-15 + picHeightInMapUnits = sps->pic_height_in_map_units_minus1 + 1; + //7-17 + frameHeightInMbs = (2 - sps->frame_mbs_only_flag) * picHeightInMapUnits; + height = frameHeightInMbs << 4; + + sps->m_width = width; + sps->m_height = height; + + if (sps->frame_cropping_flag) { + //according Table 6-1, used to calc sps->width + //when frame_cropping_flag is equal to 1 + uint32_t subWidthC[] = { 1, 2, 2, 1, 1 }; + uint32_t subHeightC[] = { 1, 2, 1, 1, 1 }; + uint32_t cropUnitX, cropUnitY; + if (!sps->m_chromaArrayType) { + cropUnitX = 1; + cropUnitY = 2 - sps->frame_mbs_only_flag; + } else { + cropUnitX = subWidthC[sps->chroma_format_idc]; + cropUnitY = subHeightC[sps->chroma_format_idc] * (2 - sps->frame_mbs_only_flag); + } + + width -= cropUnitX * (sps->frame_crop_left_offset + sps->frame_crop_right_offset); + height -= cropUnitY * (sps->frame_crop_top_offset + sps->frame_crop_bottom_offset); + + sps->m_cropRectWidth = width; + sps->m_cropRectHeight = height; + sps->m_cropX = cropUnitX * sps->frame_crop_left_offset; + sps->m_cropY = cropUnitY * sps->frame_crop_top_offset; + } + + m_spsMap[sps->sps_id] = sps; + + return true; +} + +bool Parser::parsePps(SharedPtr& pps, const NalUnit* nalu) +{ + SharedPtr sps; + bool pic_scaling_matrix_present_flag; + int32_t qp_bd_offset; + + NalReader br(nalu->m_data + nalu->m_nalUnitHeaderBytes, + nalu->m_size - nalu->m_nalUnitHeaderBytes); + + READ_UE(pps->pps_id); + READ_UE(pps->sps_id); + if (pps->pps_id > MAX_PPS_ID || pps->sps_id > MAX_SPS_ID) + return false; + + sps = searchSps(pps->sps_id); + if (!sps) + return false; + + pps->m_sps = sps; + qp_bd_offset = 6 * (sps->bit_depth_luma_minus8 + sps->separate_colour_plane_flag); + + //the default value of pic_scaling_matrix_present_flag is zero, + //when pic_scaling_matrix_present_flag is equal to 0, pps scaling + //lists shall be inferred to be equal to those specified by the sps + memcpy(&pps->scaling_lists_4x4, &sps->scaling_lists_4x4, + sizeof(sps->scaling_lists_4x4)); + memcpy(&pps->scaling_lists_8x8, &sps->scaling_lists_8x8, + sizeof(sps->scaling_lists_8x8)); + + READ(pps->entropy_coding_mode_flag); + READ(pps->pic_order_present_flag); + READ_UE(pps->num_slice_groups_minus1); + //num_slice_groups_minus1 in the range of 0 to 7, according to A.2.1 + if (pps->num_slice_groups_minus1 > 7) + return false; + if (pps->num_slice_groups_minus1 > 0) { + READ_UE(pps->slice_group_map_type); + if (pps->slice_group_map_type > SLICE_GROUP_ASSIGNMENT) + return false; + if (!pps->slice_group_map_type) { + for (uint32_t iGroup = 0; iGroup <= pps->num_slice_groups_minus1; iGroup++) + READ_UE(pps->run_length_minus1[iGroup]); + } else if (pps->slice_group_map_type == SLIEC_GROUP_FOREGROUND_LEFTOVER) { + for (uint32_t iGroup = 0; iGroup < pps->num_slice_groups_minus1; iGroup++) { + READ_UE(pps->top_left[iGroup]); + READ_UE(pps->bottom_right[iGroup]); + } + } else if (pps->slice_group_map_type == SLICE_GROUP_CHANGING3 + || pps->slice_group_map_type == SLICE_GROUP_CHANGING4 + || pps->slice_group_map_type == SLICE_GROUP_CHANGING5) { + READ(pps->slice_group_change_direction_flag); + READ_UE(pps->slice_group_change_rate_minus1); + } else if (pps->slice_group_map_type == SLICE_GROUP_ASSIGNMENT) { + READ_UE(pps->pic_size_in_map_units_minus1); + int32_t bits = ceil(log2(pps->num_slice_groups_minus1 + 1)); + pps->slice_group_id = + (uint8_t*)malloc(sizeof(uint8_t)*(pps->pic_size_in_map_units_minus1 + 1)); + if (!pps->slice_group_id) + return false; + for (uint32_t i = 0; i <= pps->pic_size_in_map_units_minus1; i++) + READ_BITS(pps->slice_group_id[i], bits); + } + } + + READ_UE(pps->num_ref_idx_l0_active_minus1); + READ_UE(pps->num_ref_idx_l1_active_minus1); + if (pps->num_ref_idx_l0_active_minus1 > 31 + || pps->num_ref_idx_l1_active_minus1 > 31) + goto error; + READ(pps->weighted_pred_flag); + READ_BITS(pps->weighted_bipred_idc, 2); + READ_SE(pps->pic_init_qp_minus26); + if (pps->pic_init_qp_minus26 < -(26 + qp_bd_offset) + || pps->pic_init_qp_minus26 > 25) + goto error; + READ_SE(pps->pic_init_qs_minus26); + if (pps->pic_init_qs_minus26 < -26 + || pps->pic_init_qs_minus26 > 25) + goto error; + READ_SE(pps->chroma_qp_index_offset); + if (pps->chroma_qp_index_offset < -12 + || pps->chroma_qp_index_offset > 12) + goto error; + pps->second_chroma_qp_index_offset = pps->chroma_qp_index_offset; + READ(pps->deblocking_filter_control_present_flag); + READ(pps->constrained_intra_pred_flag); + READ(pps->redundant_pic_cnt_present_flag); + + if (br.moreRbspData()) { + READ(pps->transform_8x8_mode_flag); + READ(pic_scaling_matrix_present_flag); + + //according to Table 7-2, Scaling list fall-back rule set A + const uint8_t* const Fall_Back_A_Scaling_List[12] = { + Default_4x4_Intra, pps->scaling_lists_4x4[0], pps->scaling_lists_4x4[1], + Default_4x4_Inter, pps->scaling_lists_4x4[3], pps->scaling_lists_4x4[4], + Default_8x8_Intra, Default_8x8_Inter, pps->scaling_lists_8x8[0], + pps->scaling_lists_8x8[1], pps->scaling_lists_8x8[2], pps->scaling_lists_8x8[3] + }; + //according to Table 7-2, Scaling list fall-back rule set B + const uint8_t* const Fall_Back_B_Scaling_List[12] = { + sps->scaling_lists_4x4[0], pps->scaling_lists_4x4[0], pps->scaling_lists_4x4[1], + sps->scaling_lists_4x4[3], pps->scaling_lists_4x4[3], pps->scaling_lists_4x4[4], + sps->scaling_lists_8x8[0], sps->scaling_lists_8x8[1], pps->scaling_lists_8x8[0], + pps->scaling_lists_8x8[1], pps->scaling_lists_8x8[2], pps->scaling_lists_8x8[3] + }; + if (pic_scaling_matrix_present_flag) { + uint32_t loop = 6 + + ((sps->chroma_format_idc != 3) ? 2 : 6) * pps->transform_8x8_mode_flag; + for (uint32_t i = 0; i < loop; i++) { + READ(pps->pic_scaling_list_present_flag[i]); + if (pps->pic_scaling_list_present_flag[i]) { + if (i < 6) { + if (!scalingList(br, pps->scaling_lists_4x4[i], 16, i)) + return false; + } + else { + if (!scalingList(br, pps->scaling_lists_8x8[i - 6], 64, i)) + return false; + } + } else if (!sps->seq_scaling_matrix_present_flag) { + //fall-back rule set A be used + if (i < 6) + memcpy(pps->scaling_lists_4x4[i], Fall_Back_A_Scaling_List[i], 16); + else + memcpy(pps->scaling_lists_8x8[i - 6], Fall_Back_A_Scaling_List[i], 64); + } else { + //fall-back rule set B be used + if (i < 6) + memcpy(pps->scaling_lists_4x4[i], Fall_Back_B_Scaling_List[i], 16); + else + memcpy(pps->scaling_lists_8x8[i - 6], Fall_Back_B_Scaling_List[i], 64); + } + } + } + READ_SE(pps->second_chroma_qp_index_offset); + if (pps->second_chroma_qp_index_offset < -12 + || pps->second_chroma_qp_index_offset > 12) + goto error; + } + + m_ppsMap[pps->pps_id] = pps; + + return true; +error: + free(pps->slice_group_id); + return false; +} + +inline SharedPtr +Parser::searchPps(uint8_t id) const +{ + SharedPtr res; + PpsMap::const_iterator it = m_ppsMap.find(id); + if (it != m_ppsMap.end()) + res = it->second; + return res; +} + +inline SharedPtr +Parser::searchSps(uint8_t id) const +{ + SharedPtr res; + SpsMap::const_iterator it = m_spsMap.find(id); + if (it != m_spsMap.end()) + res = it->second; + return res; +} + +SliceHeader::SliceHeader() +{ + memset(this, 0, offsetof(SliceHeader, m_pps)); +} + +bool SliceHeader::refPicListModification(NalReader& br, RefPicListModification* pm0, + RefPicListModification* pm1, bool is_mvc) +{ + uint32_t i = 0; + if (!IS_I_SLICE(slice_type) && !IS_SI_SLICE(slice_type)) { + READ(ref_pic_list_modification_flag_l0); + if (ref_pic_list_modification_flag_l0) { + do { + READ_UE(pm0[i].modification_of_pic_nums_idc); + if (pm0[i].modification_of_pic_nums_idc == 0 + || pm0[i].modification_of_pic_nums_idc == 1) { + READ_UE(pm0[i].abs_diff_pic_num_minus1); + if (pm0[i].abs_diff_pic_num_minus1 > m_maxPicNum - 1) + return false; + } else if (pm0[i].modification_of_pic_nums_idc == 2) { + READ_UE(pm0[i].long_term_pic_num); + } else if (is_mvc && (pm0[i].modification_of_pic_nums_idc == 4 + || pm0[i].modification_of_pic_nums_idc == 5)) { + READ_UE(pm0[i].abs_diff_view_idx_minus1); + } + } while (pm0[i++].modification_of_pic_nums_idc != 3); + n_ref_pic_list_modification_l0 = i; + } + } + + if (IS_B_SLICE(slice_type)) { + i = 0; + READ(ref_pic_list_modification_flag_l1); + if (ref_pic_list_modification_flag_l1) { + do { + READ_UE(pm1[i].modification_of_pic_nums_idc); + if (pm1[i].modification_of_pic_nums_idc == 0 + || pm1[i].modification_of_pic_nums_idc == 1) { + READ_UE(pm1[i].abs_diff_pic_num_minus1); + if (pm1[i].abs_diff_pic_num_minus1 > m_maxPicNum - 1) + return false; + } else if (pm1[i].modification_of_pic_nums_idc == 2) { + READ_UE(pm1[i].long_term_pic_num); + } else if (is_mvc && (pm1[i].modification_of_pic_nums_idc == 4 + || pm1[i].modification_of_pic_nums_idc == 5)) { + READ_UE(pm1[i].abs_diff_view_idx_minus1); + } + } while (pm1[i++].modification_of_pic_nums_idc != 3); + } + n_ref_pic_list_modification_l1 = i; + } + + return true; +} + +bool SliceHeader::decRefPicMarking(NalUnit* nalu, NalReader& br) +{ + if (nalu->m_idrPicFlag) { + READ(dec_ref_pic_marking.no_output_of_prior_pics_flag); + READ(dec_ref_pic_marking.long_term_reference_flag); + } else { + READ(dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag); + if (dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag) { + uint32_t i = 0; + RefPicMarking* const subpm = dec_ref_pic_marking.ref_pic_marking; + do { + READ_UE(subpm[i].memory_management_control_operation); + if (subpm[i].memory_management_control_operation == 1 + || subpm[i].memory_management_control_operation == 3) + READ_UE(subpm[i].difference_of_pic_nums_minus1); + if (subpm[i].memory_management_control_operation == 2) + READ_UE(subpm[i].long_term_pic_num); + if (subpm[i].memory_management_control_operation == 3 + || subpm[i].memory_management_control_operation == 6) + READ_UE(subpm[i].long_term_frame_idx); + if (subpm[i].memory_management_control_operation == 4) + READ_UE(subpm[i].max_long_term_frame_idx_plus1); + } while (subpm[i++].memory_management_control_operation != 0); + dec_ref_pic_marking.n_ref_pic_marking = --i; + } + } + return true; +} + +bool SliceHeader::predWeightTable(NalReader& br, uint8_t chromaArrayType) +{ + PredWeightTable& preTab = pred_weight_table; + READ_UE(preTab.luma_log2_weight_denom); + if (preTab.luma_log2_weight_denom > 7) + return false; + if (chromaArrayType) + READ_UE(preTab.chroma_log2_weight_denom); + for (uint32_t i = 0; i <= num_ref_idx_l0_active_minus1; i++) { + READ(preTab.luma_weight_l0_flag); + if (preTab.luma_weight_l0_flag) { + //7.4.3.2 + READ_SE(preTab.luma_weight_l0[i]); + READ_SE(preTab.luma_offset_l0[i]); + if (preTab.luma_weight_l0[i] < -128 + || preTab.luma_weight_l0[i] > 127 + || preTab.luma_offset_l0[i] < -128 + || preTab.luma_offset_l0[i] > 127) + return false; + } else { + preTab.luma_weight_l0[i] = 1 << preTab.luma_log2_weight_denom; + } + if (chromaArrayType) { + READ(preTab.chroma_weight_l0_flag); + for (uint32_t j = 0; j < 2; j++) { + if (preTab.chroma_weight_l0_flag) { + READ_SE(preTab.chroma_weight_l0[i][j]); + READ_SE(preTab.chroma_offset_l0[i][j]); + } else { + preTab.chroma_weight_l0[i][j] = 1 << preTab.chroma_log2_weight_denom; + } + } + } + } + if (IS_B_SLICE(slice_type)) + for (uint32_t i = 0; i <= num_ref_idx_l1_active_minus1; i++) { + READ(preTab.luma_weight_l1_flag); + if (preTab.luma_weight_l1_flag) { + READ_SE(preTab.luma_weight_l1[i]); + READ_SE(preTab.luma_offset_l1[i]); + } else { + preTab.luma_weight_l1[i] = 1 << preTab.luma_log2_weight_denom; + } + if (chromaArrayType) { + READ(preTab.chroma_weight_l1_flag); + for (uint32_t j = 0; j < 2; j++) { + if (preTab.chroma_weight_l1_flag) { + READ_SE(preTab.chroma_weight_l1[i][j]); + READ_SE(preTab.chroma_offset_l1[i][j]); + } else { + preTab.chroma_weight_l1[i][j] = 1 << preTab.chroma_log2_weight_denom; + } + } + } + } + return true; +} + +bool SliceHeader::parseHeader(Parser* nalparser, NalUnit* nalu) +{ + uint32_t pps_id; + SharedPtr sps; + + if (!nalu->m_size) + return false; + + NalReader br(nalu->m_data + nalu->m_nalUnitHeaderBytes, + nalu->m_size - nalu->m_nalUnitHeaderBytes); + + READ_UE(first_mb_in_slice); + READ_UE(slice_type); + READ_UE(pps_id); + if (pps_id > MAX_PPS_ID) + return false; + + m_pps = nalparser->searchPps(pps_id); + if (!m_pps) + return false; + + sps = m_pps->m_sps; + + //set default values for fields that might not be present in the bitstream + //and have valid defaults + num_ref_idx_l0_active_minus1 = m_pps->num_ref_idx_l0_active_minus1; + num_ref_idx_l1_active_minus1 = m_pps->num_ref_idx_l1_active_minus1; + + if (sps->separate_colour_plane_flag == 1) + READ_BITS(colour_plane_id, 2); + + READ_BITS(frame_num, sps->log2_max_frame_num_minus4 + 4); + + if (!sps->frame_mbs_only_flag) { + READ(field_pic_flag); + if (field_pic_flag) + READ(bottom_field_flag); + } + + //calculate MaxPicNum + if (field_pic_flag) + m_maxPicNum = 2 * sps->m_maxFrameNum; + else + m_maxPicNum = sps->m_maxFrameNum; + + if (nalu->m_idrPicFlag) { + READ_UE(idr_pic_id); + if (idr_pic_id > MAX_IDR_PIC_ID) + return false; + } + + if (!sps->pic_order_cnt_type) { + READ_BITS(pic_order_cnt_lsb, sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + if (m_pps->pic_order_present_flag && !field_pic_flag) + READ_SE(delta_pic_order_cnt_bottom); + } + + if (sps->pic_order_cnt_type == 1 && !sps->delta_pic_order_always_zero_flag) { + READ_SE(delta_pic_order_cnt[0]); + if (m_pps->pic_order_present_flag && !field_pic_flag) + READ_SE(delta_pic_order_cnt[1]); + } + + if (m_pps->redundant_pic_cnt_present_flag) { + READ_UE(redundant_pic_cnt); + if (redundant_pic_cnt > 127) + return false; + } + + if (IS_B_SLICE(slice_type)) + READ(direct_spatial_mv_pred_flag); + + if (IS_P_SLICE(slice_type) || IS_SP_SLICE(slice_type) || IS_B_SLICE(slice_type)) { + READ(num_ref_idx_active_override_flag); + if (num_ref_idx_active_override_flag) { + READ_UE(num_ref_idx_l0_active_minus1); + if (num_ref_idx_l0_active_minus1 > 31) + return false; + if (IS_B_SLICE(slice_type)) { + READ_UE(num_ref_idx_l1_active_minus1); + if (num_ref_idx_l1_active_minus1 > 31) + return false; + } + } + } + + if (nalu->nal_unit_type == NAL_SLICE_EXT + || nalu->nal_unit_type == NAL_SLICE_EXT_DEPV) + refPicListModification(br, ref_pic_list_modification_l0, + ref_pic_list_modification_l1, true); + else + refPicListModification(br, ref_pic_list_modification_l0, + ref_pic_list_modification_l1, false); + + if ((m_pps->weighted_pred_flag && (IS_P_SLICE(slice_type) || IS_SP_SLICE(slice_type))) + || (m_pps->weighted_bipred_idc == 1 && IS_B_SLICE(slice_type))) { + if (!predWeightTable(br, sps->m_chromaArrayType)) + return false; + } + + if (nalu->nal_ref_idc) { + if (!decRefPicMarking(nalu, br)) + return false; + } + + if (m_pps->entropy_coding_mode_flag + && !IS_I_SLICE(slice_type) && !IS_SI_SLICE(slice_type)) { + READ_UE(cabac_init_idc); + if (cabac_init_idc > 2) + return false; + } + + READ_SE(slice_qp_delta); + //according to 7-29, the value of slice_qp_delta shall be limited + //so that sliceQPY is in the range of -QpBdOffsetY to +51. + //sliceQPY = 26 + pic_init_qp_minus26 + slice_qp_delta + //QpBdOffsetY = 6 * bit_depth_luma_minus8. + int32_t QpBdOffsetY = -6 * sps->bit_depth_luma_minus8; + int32_t sliceQPY = 26 + m_pps->pic_init_qp_minus26 + slice_qp_delta; + if (sliceQPY < QpBdOffsetY || sliceQPY > 51) + return false; + + if (IS_SP_SLICE(slice_type) || IS_SI_SLICE(slice_type)) { + if (IS_SP_SLICE(slice_type)) + READ(sp_for_switch_flag); + READ_SE(slice_qs_delta); + } + + if (m_pps->deblocking_filter_control_present_flag) { + READ_UE(disable_deblocking_filter_idc); + if (disable_deblocking_filter_idc > 2) + return false; + if (disable_deblocking_filter_idc != 1) { + READ_SE(slice_alpha_c0_offset_div2); + READ_SE(slice_beta_offset_div2); + } + } + + // The value of slice_group_map_type in the range [0, 6], when it is equal to + //3, 4 and 5 specify changing slice groups + if (m_pps->num_slice_groups_minus1 > 0 + && m_pps->slice_group_map_type >= 3 + && m_pps->slice_group_map_type <= 5) { + uint32_t picWidthInMbs = sps->pic_width_in_mbs_minus1 + 1; + uint32_t picHeightInMapUnits = sps->pic_height_in_map_units_minus1 + 1; + uint32_t picSizeInMapUnits = picWidthInMbs * picHeightInMapUnits; + uint32_t sliceGroupChangeRate = m_pps->slice_group_change_rate_minus1 + 1; + const uint32_t n = ceil(log2(picSizeInMapUnits / sliceGroupChangeRate + 1)); + READ_BITS(slice_group_change_cycle, n); + } + + m_headerSize = br.getPos(); + m_emulationPreventionBytes = br.getEpbCnt(); + + return true; +} + +} +} diff --git a/codecparsers/h264Parser.h b/codecparsers/h264Parser.h new file mode 100644 index 0000000..399aab7 --- /dev/null +++ b/codecparsers/h264Parser.h @@ -0,0 +1,456 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * NOTES: + * All the following structs and classes definded base on the spec of H264, + * you can see H.264 specification at http://www.itu.int/rec/T-REC-H.264. + * And in this header file, there are two categories of code-styles for variables. + * Some of them looks like "NalUnit::nal_ref_idc" which separated by underline, + * that is to say, these variables defined in H264 spec and assigned by reading bits + * from video bits stream directly, on my purpose, it is helpful for you to find where + * they are in spec quickly. Some of variables defined use CamelCase because these + * variables assigned by other variables. + */ + +#ifndef h264parser_h +#define h264parser_h + +#include "nalReader.h" +#include "VideoCommonDefs.h" + +#include +#include + +namespace YamiParser { +namespace H264 { + +#define MAX_SPS_ID 31 +#define MAX_PPS_ID 255 +#define MAX_IDR_PIC_ID 65535 + +//get the coding type of the slice according to Table 7-6 +#define IS_P_SLICE(slice_type) ((slice_type) % 5 == 0) +#define IS_B_SLICE(slice_type) ((slice_type) % 5 == 1) +#define IS_I_SLICE(slice_type) ((slice_type) % 5 == 2) +#define IS_SP_SLICE(slice_type) ((slice_type) % 5 == 3) +#define IS_SI_SLICE(slice_type) ((slice_type) % 5 == 4) + +enum SliceGroupMapType { + SLICE_GROUP_INTERLEAVED, + SLICE_GROUP_DISPERSED_MAPPING, + SLIEC_GROUP_FOREGROUND_LEFTOVER, + //3, 4, 5 specify changing slice groups. when num_slice_groups_numus + //is not equal to 1, slice_group_map_type shall not be equal to 3, 4, or 5 + SLICE_GROUP_CHANGING3, + SLICE_GROUP_CHANGING4, + SLICE_GROUP_CHANGING5, + SLICE_GROUP_ASSIGNMENT +}; + +enum Profile { + PROFILE_CAVLC_444_INTRA = 44, //A.2.11 + PROFILE_BASELINE = 66, //A.2.1 + PROFILE_MAIN = 77, //A.2.2 + PROFILE_SCALABLE_BASELINE = 83, //G.10.1.1 + PROFILE_SCALABLE_HIGH = 86, //G.10.1.2 + PROFILE_EXTENDED = 88, //A.2.3 + PROFILE_HIGH = 100, //A.2.4 + PROFILE_HIGH_10 = 110, //A.2.5 + PROFILE_MULTIVIEW_HIGH = 118, //H.10.1.1 + PROFILE_HIGH_422 = 122, //A.2.6 + PROFILE_STEREO_HIGH = 128, //H.10.1.2 + PROFILE_MULTIVIEW_DEPTH_HIGH = 138, //I.10.1.1 + PROFILE_HIGH_444 = 244, //A.2.7 +}; + +//according 8.5.6 +static const uint8_t zigzag_scans_4x4[16] = { + 0, 1, 4, 8, + 5, 2, 3, 6, + 9, 12, 13, 10, + 7, 11, 14, 15 +}; + +static const uint8_t zigzag_scans_8x8[64] = { + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63 +}; + +#define transform_coefficients_for_frame_macroblocks(dest, src, len, mode) \ + { \ + if ((dest) != (src)) { \ + for (uint32_t l = 0; l < (len); l++) \ + (dest)[zigzag_scans_##mode[l]] = (src)[l]; \ + } \ + } + +//according to Table 7-1 +enum NalUnitType { + NAL_UNSPECIFIED, //unspecified + NAL_SLICE_NONIDR, //coded slice of a non-IDR picture + NAL_SLICE_DPA, //coded slice data partiiton A + NAL_SLICE_DPB, //coded slice data partition B + NAL_SLICE_DPC, //coded slice data partition C + NAL_SLICE_IDR, //coded slice of an IDR picture + NAL_SEI, //supplemental enhancement information (SEI) + NAL_SPS, //sequence parameter set + NAL_PPS, //picture parameter set + NAL_AU_DELIMITER, //access unit delimiter + NAL_SEQ_END, //end of sequence + NAL_STREAM_END, //end of stream + NAL_FILLER_DATA, //filler data + NAL_SPS_EXT, //sequence parameter set extension + NAL_PREFIX_UNIT, //prefix NAL unit + NAL_SUBSET_SPS, //subset sequence parameter set + //16 -18 reserved + NAL_SLICE_AUX = 19, //coded slice of an auxiliary coded picture without partitioning + NAL_SLICE_EXT, //coded slice extension + NAL_SLICE_EXT_DEPV //coded slice extension for depth view components + //22 & 23 reserved, 24 - 31 unspecified +}; + +struct NaluHeadMvcExt { + bool non_idr_flag; + uint8_t priority_id; + uint16_t view_id; + uint8_t temporal_id; + bool anchor_pic_flag; + bool inter_view_flag; +}; + +struct NaluHeadSvcExt { + bool idr_flag; + uint8_t priority_id; + bool no_inter_layer_pred_flag; + uint8_t dependency_id; + uint8_t quality_id; + uint8_t temporal_id; + bool use_ref_base_pic_flag; + bool discardable_flag; + bool output_flag; + uint8_t reserved_three_2bits; +}; + +class Parser; + +class NalUnit { +public: + //the min size of a valid nal unit + enum { + NAL_UNIT_SEQUENCE_SIZE = 4 + }; + + /* nal should be a complete nal unit buffer without start code or length bytes */ + bool parseNalUnit(const uint8_t* nal, size_t size); + +public: + const uint8_t* m_data; + uint32_t m_size; + + uint16_t nal_ref_idc; + uint16_t nal_unit_type; + + //calc value, used by other syntax structs + bool m_idrPicFlag; + uint8_t m_nalUnitHeaderBytes; + + NaluHeadMvcExt m_mvc; + NaluHeadSvcExt m_svc; + +private: + bool parseSvcExtension(BitReader& br); + bool parseMvcExtension(BitReader& br); +}; + +struct HRDParameters { + uint8_t cpb_cnt_minus1; + uint8_t bit_rate_scale; + uint8_t cpb_size_scale; + uint32_t bit_rate_value_minus1[32]; + uint32_t cpb_size_value_minus1[32]; + bool cbr_flag[32]; + uint8_t initial_cpb_removal_delay_length_minus1; + uint8_t cpb_removal_delay_length_minus1; + uint8_t dpb_output_delay_length_minus1; + uint8_t time_offset_length; +}; + +struct VUIParameters { + bool aspect_ratio_info_present_flag; + uint8_t aspect_ratio_idc; + uint16_t sar_width; + uint16_t sar_height; + bool overscan_info_present_flag; + bool overscan_appropriate_flag; + bool video_signal_type_present_flag; + uint8_t video_format; + bool video_full_range_flag; + bool colour_description_present_flag; + uint8_t colour_primaries; + uint8_t transfer_characteristics; + uint8_t matrix_coefficients; + bool chroma_loc_info_present_flag; + uint8_t chroma_sample_loc_type_top_field; + uint8_t chroma_sample_loc_type_bottom_field; + bool timing_info_present_flag; + uint32_t num_units_in_tick; + uint32_t time_scale; + bool fixed_frame_rate_flag; + bool nal_hrd_parameters_present_flag; + HRDParameters nal_hrd_parameters; + bool vcl_hrd_parameters_present_flag; + HRDParameters vcl_hrd_parameters; + bool low_delay_hrd_flag; + bool pic_struct_present_flag; + bool bitstream_restriction_flag; + bool motion_vectors_over_pic_boundaries_flag; + uint32_t max_bytes_per_pic_denom; + uint32_t max_bits_per_mb_denom; + uint32_t log2_max_mv_length_horizontal; + uint32_t log2_max_mv_length_vertical; + uint32_t max_num_reorder_frames; + uint32_t max_dec_frame_buffering; +}; + +struct SPS { + uint8_t profile_idc; + bool constraint_set0_flag; + bool constraint_set1_flag; + bool constraint_set2_flag; + bool constraint_set3_flag; + bool constraint_set4_flag; + bool constraint_set5_flag; + uint8_t level_idc; + uint32_t sps_id; //seq_parameter_set_id + uint8_t chroma_format_idc; + bool separate_colour_plane_flag; + uint8_t bit_depth_luma_minus8; + uint8_t bit_depth_chroma_minus8; + bool qpprime_y_zero_transform_bypass_flag; + bool seq_scaling_matrix_present_flag; + bool seq_scaling_list_present_flag[12]; + uint8_t scaling_lists_4x4[6][16]; + uint8_t scaling_lists_8x8[6][64]; + uint8_t log2_max_frame_num_minus4; + uint8_t pic_order_cnt_type; + uint8_t log2_max_pic_order_cnt_lsb_minus4; + bool delta_pic_order_always_zero_flag; + int32_t offset_for_non_ref_pic; + int32_t offset_for_top_to_bottom_field; + uint8_t num_ref_frames_in_pic_order_cnt_cycle; + int32_t offset_for_ref_frame[255]; + uint32_t num_ref_frames; + bool gaps_in_frame_num_value_allowed_flag; + uint32_t pic_width_in_mbs_minus1; + uint32_t pic_height_in_map_units_minus1; + bool frame_mbs_only_flag; + bool mb_adaptive_frame_field_flag; + bool direct_8x8_inference_flag; + bool frame_cropping_flag; + uint32_t frame_crop_left_offset; + uint32_t frame_crop_right_offset; + uint32_t frame_crop_top_offset; + uint32_t frame_crop_bottom_offset; + bool vui_parameters_present_flag; + VUIParameters m_vui; + + //Because these variables calced from other variables instead of + //reading from bits stream, so using different style and spec do like this + //used to calc slice`s maxPicNum + uint32_t m_maxFrameNum; + + uint8_t m_chromaArrayType; + + int32_t m_width; + int32_t m_height; + int32_t m_cropX; + int32_t m_cropY; + int32_t m_cropRectWidth; + int32_t m_cropRectHeight; +}; + +struct PPS { + PPS(); + ~PPS(); + + uint32_t pps_id; + uint32_t sps_id; + + + bool entropy_coding_mode_flag; + bool pic_order_present_flag; + uint32_t num_slice_groups_minus1; + uint8_t slice_group_map_type; + uint32_t run_length_minus1[8]; + uint32_t top_left[8]; + uint32_t bottom_right[8]; + bool slice_group_change_direction_flag; + uint32_t slice_group_change_rate_minus1; + uint32_t pic_size_in_map_units_minus1; + uint8_t* slice_group_id; + uint8_t num_ref_idx_l0_active_minus1; + uint8_t num_ref_idx_l1_active_minus1; + bool weighted_pred_flag; + uint8_t weighted_bipred_idc; + int8_t pic_init_qp_minus26; + int8_t pic_init_qs_minus26; + int8_t chroma_qp_index_offset; + bool deblocking_filter_control_present_flag; + bool constrained_intra_pred_flag; + bool redundant_pic_cnt_present_flag; + bool transform_8x8_mode_flag; + bool pic_scaling_list_present_flag[12]; + uint8_t scaling_lists_4x4[6][16]; + uint8_t scaling_lists_8x8[6][64]; + int8_t second_chroma_qp_index_offset; + SharedPtr m_sps; + //Because these variables is non pod type, it can not use memset and use offsetof to weed out it +}; + +struct RefPicListModification { + uint8_t modification_of_pic_nums_idc; + uint32_t abs_diff_pic_num_minus1; + uint32_t long_term_pic_num; + uint32_t abs_diff_view_idx_minus1; +}; + +struct PredWeightTable { + uint8_t luma_log2_weight_denom; + uint8_t chroma_log2_weight_denom; + bool luma_weight_l0_flag; + //32 is the max of num_ref_idx_l0_active_minus1 + int16_t luma_weight_l0[32]; + int8_t luma_offset_l0[32]; + bool chroma_weight_l0_flag; + int16_t chroma_weight_l0[32][2]; + int8_t chroma_offset_l0[32][2]; + bool luma_weight_l1_flag; + int16_t luma_weight_l1[32]; + int8_t luma_offset_l1[32]; + bool chroma_weight_l1_flag; + int16_t chroma_weight_l1[32][2]; + int8_t chroma_offset_l1[32][2]; +}; + +struct RefPicMarking { + uint8_t memory_management_control_operation; + uint32_t difference_of_pic_nums_minus1; + uint32_t long_term_pic_num; + uint32_t long_term_frame_idx; + uint32_t max_long_term_frame_idx_plus1; +}; + +struct DecRefPicMarking { + bool no_output_of_prior_pics_flag; + bool long_term_reference_flag; + bool adaptive_ref_pic_marking_mode_flag; + RefPicMarking ref_pic_marking[10]; + uint8_t n_ref_pic_marking; +}; + +class SliceHeader { +public: + SliceHeader(); + bool parseHeader(Parser* nalparser, NalUnit* nalu); + +private: + bool refPicListModification(NalReader& nr, + RefPicListModification* pm0, RefPicListModification* pm1, bool is_mvc); + bool predWeightTable(NalReader& nr, uint8_t chroma_array_type); + bool decRefPicMarking(NalUnit* nalu, NalReader& nr); + +public: + uint32_t first_mb_in_slice; + uint32_t slice_type; + uint8_t colour_plane_id; + uint16_t frame_num; + bool field_pic_flag; + bool bottom_field_flag; + uint32_t idr_pic_id; + uint16_t pic_order_cnt_lsb; + int32_t delta_pic_order_cnt_bottom; + int32_t delta_pic_order_cnt[2]; + uint8_t redundant_pic_cnt; + bool direct_spatial_mv_pred_flag; + bool num_ref_idx_active_override_flag; + uint8_t num_ref_idx_l0_active_minus1; + uint8_t num_ref_idx_l1_active_minus1; + bool ref_pic_list_modification_flag_l0; + uint8_t n_ref_pic_list_modification_l0; + RefPicListModification ref_pic_list_modification_l0[32]; + bool ref_pic_list_modification_flag_l1; + uint8_t n_ref_pic_list_modification_l1; + RefPicListModification ref_pic_list_modification_l1[32]; + PredWeightTable pred_weight_table; + DecRefPicMarking dec_ref_pic_marking; + uint8_t cabac_init_idc; + int8_t slice_qp_delta; + bool sp_for_switch_flag; + int8_t slice_qs_delta; + uint8_t disable_deblocking_filter_idc; + int8_t slice_alpha_c0_offset_div2; + int8_t slice_beta_offset_div2; + uint16_t slice_group_change_cycle; + + //the allowned max value of abs_diff_pic_num_minus1 + uint32_t m_maxPicNum; + + //the size of the slice header in bits + uint32_t m_headerSize; + + //the number of emulation prevention bytes + uint32_t m_emulationPreventionBytes; + SharedPtr m_pps; + //Because these variables is non pod type, it can not use memset and use offsetof to weed out it +}; + +class Parser { +public: + enum { + MAX_CPB_CNT_MINUS1 = 31, + MAX_CHROMA_FORMAT_IDC = 3, + SCALING_LIST_DEFAULT_VALUE = 16 + }; + + typedef std::map > SpsMap; + typedef std::map > PpsMap; + + bool parseSps(SharedPtr& sps, const NalUnit* nalu); + bool parsePps(SharedPtr& pps, const NalUnit* nalu); + + inline SharedPtr searchPps(uint8_t id) const; + inline SharedPtr searchSps(uint8_t id) const; + +private: + bool hrdParameters(HRDParameters* hrd, NalReader& nr); + bool vuiParameters(SharedPtr& sps, NalReader& nr); + + static const uint8_t EXTENDED_SAR; + SpsMap m_spsMap; + PpsMap m_ppsMap; +}; + +} +} + +#endif diff --git a/codecparsers/h264Parser_unittest.cpp b/codecparsers/h264Parser_unittest.cpp new file mode 100644 index 0000000..a4118c0 --- /dev/null +++ b/codecparsers/h264Parser_unittest.cpp @@ -0,0 +1,213 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "h264Parser.h" + +// library headers +#include "common/Array.h" +#include "common/unittest.h" +#include "common/nalreader.h" + +namespace YamiParser { +namespace H264 { + + using YamiMediaCodec::NalReader; + + const static std::array g_SimpleH264 = { + 0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, 0x28, 0xab, 0x40, 0xb0, 0x4a, + 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x79, 0x08, + 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x03, 0x9c, 0x30, 0x00, 0x00, 0x00, + 0x01, 0x65, 0xb8, 0x20, 0x19, 0x09, 0xf4, 0xa0, 0x97, 0x12, 0x5b, 0xaa, + 0x1d, 0x1d, 0x71, 0x2f, 0x30, 0xfe, 0xa0, 0x80, 0x7d, 0x32, 0xf6, 0xae, + 0x7f, 0x6d, 0xd2, 0x1c, 0x59, 0xfe, 0xc7, 0x15, 0x7c, 0x08, 0xa4, 0xa2, + 0x80, 0xed, 0x28, 0xfc, 0xcf, 0x73, 0x1c, 0x36, 0x1f, 0x33, 0x7e, 0x3a, + 0xd2, 0xcf, 0x46, 0xa8, 0x29, 0x79, 0x10, 0x7e, 0x14, 0x49, 0x63, 0xc5, + 0x93, 0x30, 0x16, 0x4b, 0x55, 0xef, 0x8f, 0x2b, 0x77, 0xb6, 0x62, 0x20, + 0x54, 0x1c, 0x49, 0x22, 0xda, 0xe8, 0xfd, 0x9c, 0xad, 0x5b, 0x3b, 0xaa, + 0x1f, 0x2f, 0xff, 0x30, 0xe0, 0x76, 0x49, 0xa7, 0x3f, 0x45, 0xd8, 0x9d, + 0x43, 0x41, 0xda, 0xd8, 0x8b, 0x7a, 0xa4, 0x77, 0x74, 0x83, 0xe5, 0x51, + 0x2c, 0x2e, 0x60, 0xfa, 0xcc, 0x35, 0x8f, 0x65, 0x7b, 0xa0, 0xd8, 0xfc, + 0xcd, 0x11, 0xa8, 0x6e, 0xae, 0xc8, 0x89, 0xe3, 0xdc, 0x2f, 0xa3, 0x4d, + 0x0d, 0x7a, 0xdd, 0xdd, 0x02, 0x59, 0xc4, 0xc3, 0xde, 0xda, 0x74, 0x2a, + 0xea, 0xbc, 0x85, 0x40, 0x97, 0x9f, 0x2f, 0x4d, 0x12, 0x74, 0x5d, 0x0f, + 0x29, 0xed, 0x23, 0xf6, 0x65, 0x3e, 0xd6, 0x35, 0x40, 0xea, 0xce, 0x2a, + 0xf6, 0x74, 0xbb, 0x88, 0x13, 0xb7, 0xa7, 0x04, 0xdd, 0x0f, 0x47, 0x52, + 0xbd, 0xef, 0xe0, 0xd2, 0x26, 0x8c, 0x56, 0xf3, 0x3f, 0xe7, 0x53, 0xba, + 0x4e, 0xc0, 0x62, 0xec, 0xbc, 0x56, 0x1c, 0x1c, 0xce, 0xf1, 0x01, 0x62, + 0x53, 0xdd, 0x1f, 0x55, 0x18, 0x32, 0xfb, 0x22, 0x40, 0xc9, 0xdf, 0x1e, + 0x77, 0x82, 0x80, 0x62, 0xec, 0x08, 0xc8, 0xc6, 0x64, 0x85, 0xb1, 0x38, + 0x48, 0x59, 0x76, 0xc3, 0x1e, 0x6a, 0x19, 0x11, 0xfd, 0x83, 0x4e, 0x0b, + 0xd1, 0xb0, 0x17, 0x2d, 0xde, 0x76, 0x9c, 0x90, 0x59, 0xa3, 0xe4, 0xe8, + 0x30, 0x88, 0x5c, 0x8c, 0x85, 0x47, 0xfe, 0x07, 0x88, 0x68, 0x1b, 0xbd, + 0x8a, 0x99, 0xc1, 0x5f, 0x6b, 0x0c, 0xfd, 0xbd, 0x33, 0x1a, 0x3f, 0xc1, + 0x7b, 0x97, 0xbb, 0x8a, 0xf2, 0x49, 0xda, 0x3e, 0xb8, 0x5e, 0xae, 0xbc, + 0xe2, 0x64, 0xc5, 0xfa, 0xa2, 0xeb, 0xc9, 0xcb, 0x7f, 0xf6, 0x78, 0xa3, + 0xa0, 0x8f, 0xae, 0xb0, 0x63, 0x09, 0x1b, 0x25, 0x49, 0x13, 0xdf, 0x65, + 0x4e, 0x73, 0xfc, 0xf0, 0xed, 0xd0, 0x42, 0x84, 0xc7, 0x78, 0xc0, 0xe7, + 0xe5, 0x15, 0x97, 0xc3, 0x13, 0xe9, 0x6f, 0xd2, 0xe3, 0x46, 0xa3, 0x84, + 0x9a, 0x51, 0xe5, 0x27, 0x5e, 0x00, 0x37, 0x5e, 0x8e, 0x1b, 0xd0, 0xdf, + 0xe0, 0xa2, 0x90, 0x1b, 0x96, 0x74, 0xca, 0xae, 0x7e, 0x61, 0x79, 0xe7, + 0x9f, 0x7a, 0x5a, 0x52, 0xe9, 0x60, 0x24, 0x07, 0x56, 0x07, 0x06, 0xb7, + 0xaa, 0x55, 0x48, 0xf3, 0x5b, 0x3c, 0x18, 0xce, 0x78, 0xf4, 0x36, 0x69, + 0xf3, 0xb0, 0x89, 0x6e, 0x96, 0x42, 0x47, 0x12, 0xef, 0x30, 0x1e, 0xff, + 0xb8, 0xfc, 0x94, 0x02, 0x8d, 0xa6, 0x5d, 0x01, 0xc4, 0xa0, 0xbe, 0xe7, + 0x6d, 0x21, 0xc5, 0xe1, 0x4d, 0xf7, 0x8b, 0x23, 0xd5, 0xac, 0x1a, 0xe4, + 0xba, 0xb1, 0x1e, 0x0c, 0x60, 0xe0, 0xcd, 0x60, 0xe1, 0x13, 0xa7, 0x35, + 0x12, 0x50, 0x40, 0x33, 0x81, 0x80, 0x05, 0x6e, 0xc4, 0xc6, 0xd6, 0xb5, + 0x38, 0xa2, 0x96, 0xee, 0x94, 0x37, 0xcf, 0x70, 0xdb, 0xec, 0x27, 0x6e, + 0x8e, 0x9b, 0xaa, 0x38, 0x85, 0x15, 0x09, 0x10, 0x01, 0xba, 0x7e, 0x18, + 0xb8, 0x05, 0xba, 0x4b, 0x76, 0x7e, 0x78, 0x8f, 0xaa, 0xaa, 0xaf, 0x5f, + 0xad, 0x42, 0x62, 0x76, 0x1f, 0x0f, 0xfe, 0x8d, 0x74, 0x24, 0xc8, 0x48, + 0x55, 0x54, 0xcf, 0x5b, 0x97, 0xf7, 0x10, 0x6f, 0x9a, 0xe2, 0xb4, 0xfa, + 0x53, 0x2d, 0x37, 0x2b, 0xd0, 0x50, 0x5a, 0x29, 0x99, 0xd6, 0x37, 0xdb, + 0xa7, 0x45, 0x33, 0x42, 0x34, 0x91, 0xad, 0xa2, 0x87, 0xf8, 0xa3, 0x6a, + 0xb2, 0x52, 0xe4, 0x37, 0x37, 0x92, 0x8b, 0xd2, 0xad, 0x91, 0xa5, 0xbd, + 0xcb, 0x0e, 0x32, 0x3b, 0xf9, 0x47, 0x2f, 0xd8, 0xc0, 0x50, 0x7e, 0x24, + 0xb7, 0xe6, 0x0b, 0xc2, 0x55, 0xb7, 0x11, 0x11, 0x04, 0x6a, 0x39, 0x54, + 0x66, 0xb1, 0x97, 0x94, 0x40, 0x98, 0xac, 0xf1, 0x07, 0x90, 0x74, 0xf7, + 0xab, 0x58, 0x05, 0x3d, 0x1a, 0xa5, 0x50, 0x48, 0x3f, 0x6f, 0xb1, 0x87, + 0x78, 0xf9, 0x7e, 0xbc, 0x0e, 0xdf, 0x05, 0x70, 0xa1, 0xd1, 0x55, 0xe9, + 0x76, 0x2f, 0xd5, 0x58, 0x31, 0x5d, 0x57, 0x17, 0x5e, 0xf0, 0xaa, 0xa7, + 0x3a, 0xe1, 0x72, 0xaf, 0x6f, 0x9c, 0x8f, 0xff, 0x34, 0x24, 0x2e, 0xed, + 0x46, 0x6e, 0xad, 0xd0, 0xfb, 0xcf, 0x28, 0xdd, 0xc9, 0x2e, 0x53, 0x3e, + 0xa5, 0xc0, 0xda, 0xcb, 0x32, 0x95, 0x13, 0xd6, 0x89, 0x6d, 0x3f, 0xa6, + 0x81, 0xc7, 0xa5, 0x47, 0x43, 0x7f, 0xe5, 0xd4, 0x82, 0xfa, 0x0d, 0xd1, + 0x93, 0x27, 0x06, 0xb5, 0x55, 0x37, 0x60, 0x20, 0xe1, 0x12, 0xf5, 0xf1, + 0xa6, 0x5e, 0x51, 0x79, 0x5e, 0x3d, 0xee, 0xab, 0xf1, 0xf7, 0x7d, 0x72, + 0x95, 0x59, 0xbb, 0x29, 0xba, 0x24, 0x85, 0xa9, 0xba, 0x52, 0x59, 0x64, + 0xee, 0x90, 0x19, 0x7c, 0x91, 0x4e, 0x1a, 0x4f, 0xd4, 0xed, 0x54, 0x01, + 0x86, 0x33, 0x78, 0xfe, 0x71, 0xdb, 0xd6, 0x36, 0x3b, 0xba, 0x5e, 0xd4, + 0x2c, 0x28, 0xa4, 0x97, 0x19, 0xb8, 0xf5, 0x6b, 0x30, 0x60, 0x4a, 0xf8, + 0xb7, 0x6d, 0x54, 0x2a, 0x52, 0x36, 0xae, 0xb1, 0x65, 0x26, 0xe6, 0xf5, + 0x2b, 0x12, 0x1c, 0x3b, 0x80, 0x0a, 0x4e, 0xf4, 0x9c, 0xd4, 0x28, 0x32, + 0x8e, 0x7c, 0x3f, 0x4d, 0xee, 0x54, 0xd8, 0x5e, 0xe9, 0x2d, 0xf3, 0x1d, + 0x20, 0xb3, 0x7b, 0x31, 0xcf, 0x4b, 0x76, 0x81, 0x39, 0xe8, 0xb2, 0x94, + 0x07, 0x3c, 0x7f, 0x38, 0xfa, 0x13, 0x25, 0x9f, 0xe7, 0x8d, 0xfb, 0xea, + 0x76, 0xe4, 0x2c, 0x14, 0x9e, 0x37, 0x32, 0x54, 0x62, 0xd2, 0x1e, 0xca, + 0x4d, 0xb7, 0x7c, 0x92, 0x52, 0x04, 0x67, 0xfa, 0x87, 0x86, 0x3f, 0xf2, + 0xdf, 0xaf, 0xac, 0x86, 0x10, 0x20, 0x68, 0x8f, 0xbe, 0xc4, 0x01, 0x6d, + 0x22, 0xe5, 0x0d, 0x37, 0x19, 0xb2, 0x83, 0x08, 0x75, 0xc3, 0x5a, 0xc1, + 0xc4, 0x9c, 0x44, 0xba, 0x18, 0x0f, 0x76, 0xdc, 0xc9, 0x3c, 0xd6, 0x59, + 0x67, 0x5d, 0xa0, 0x3b, 0x0b, 0x7d, 0xb0, 0x18, 0xff, 0xf6, 0x84, 0x43, + 0x81, 0xee, 0x5f, 0x4d, 0x58, 0x22, 0x29, 0x00, 0x78, 0x53, 0xb4, 0x61, + 0x0a, 0x38, 0x8d, 0x1a, 0xf5, 0xa1, 0x1b, 0x6c, 0x65, 0x75, 0x2a, 0xa2, + 0xe6, 0x30, 0xc3, 0x8d, 0x00, 0xd4, 0xe5, 0x7c, 0x14, 0x5c, 0x94, 0xb2, + 0xe8, 0x90, 0x4e, 0x38, 0xf1, 0x5a, 0x80, 0x5e, 0xa7, 0xae, 0xce, 0x3a, + 0x8c, 0x14, 0x44, 0x4b, 0x8e, 0x00, 0x8a, 0x37, 0x1d, 0x55, 0xe3, 0xa1, + 0x8f, 0x38, 0x33, 0x96, 0xcd, 0xf5, 0x9a, 0x00, 0x0a, 0xe5, 0x3d, 0xa0, + 0x59, 0x56, 0xfe, 0xf4, 0x74, 0x85, 0x58, 0x76, 0x38, 0x7c, 0xaf, 0x93, + 0x97, 0x4a, 0x41, 0x15, 0x7e, 0xfe, 0x8a, 0x5e, 0x34, 0x95, 0x06, 0xd6, + 0x64, 0xa0 + }; + + class H264ParserTest : public ::testing::Test { + + protected: + void checkH264Sps(Parser& parser, const NalUnit* nalu) + { + SharedPtr sps(new SPS()); + memset(sps.get(), 0, sizeof(SPS)); + + ASSERT_EQ(NAL_SPS, nalu->nal_unit_type); + ASSERT_TRUE(parser.parseSps(sps, nalu)); + EXPECT_EQ(77, sps->profile_idc); + EXPECT_EQ(40, sps->level_idc); + EXPECT_EQ(0u, sps->sps_id); + EXPECT_EQ(0, sps->pic_order_cnt_type); + EXPECT_FALSE(sps->gaps_in_frame_num_value_allowed_flag); + + EXPECT_EQ(21u, sps->pic_width_in_mbs_minus1); + EXPECT_EQ(17u, sps->pic_height_in_map_units_minus1); + EXPECT_TRUE(sps->frame_mbs_only_flag); + EXPECT_FALSE(sps->frame_cropping_flag); + EXPECT_TRUE(sps->vui_parameters_present_flag); + EXPECT_TRUE(sps->m_vui.timing_info_present_flag); + EXPECT_FALSE(sps->m_vui.vcl_hrd_parameters_present_flag); + EXPECT_FALSE(sps->m_vui.bitstream_restriction_flag); + } + + void checkH264Pps(Parser& parser, const NalUnit* nalu) + { + SharedPtr pps(new PPS()); + + ASSERT_EQ(NAL_PPS, nalu->nal_unit_type); + ASSERT_TRUE(parser.parsePps(pps, nalu)); + EXPECT_EQ(0u, pps->pps_id); + EXPECT_EQ(0u, pps->sps_id); + + EXPECT_TRUE(pps->entropy_coding_mode_flag); + EXPECT_EQ(0u, pps->num_slice_groups_minus1); + EXPECT_FALSE(pps->num_ref_idx_l0_active_minus1); + EXPECT_FALSE(pps->num_ref_idx_l1_active_minus1); + EXPECT_FALSE(pps->weighted_pred_flag); + EXPECT_FALSE(pps->weighted_bipred_idc); + EXPECT_EQ(14, pps->pic_init_qp_minus26); + EXPECT_EQ(0, pps->pic_init_qs_minus26); + EXPECT_EQ(0, pps->chroma_qp_index_offset); + EXPECT_TRUE(pps->deblocking_filter_control_present_flag); + EXPECT_FALSE(pps->constrained_intra_pred_flag); + EXPECT_FALSE(pps->redundant_pic_cnt_present_flag); + EXPECT_FALSE(pps->transform_8x8_mode_flag); + EXPECT_FALSE(pps->second_chroma_qp_index_offset); + } + + void checkH264SliceHeader(Parser& parser, NalUnit* nalu) + { + SharedPtr slice(new SliceHeader); + + ASSERT_EQ(NAL_SLICE_IDR, nalu->nal_unit_type); + ASSERT_TRUE(slice->parseHeader(&parser, nalu)); + EXPECT_EQ(0u, slice->first_mb_in_slice); + EXPECT_EQ(2u, slice->slice_type); + EXPECT_EQ(0, slice->frame_num); + EXPECT_EQ(0, slice->slice_qp_delta); + EXPECT_EQ(2, slice->slice_alpha_c0_offset_div2); + EXPECT_EQ(2, slice->slice_beta_offset_div2); + } + }; + +#define H264_PARSER_TEST(name) TEST_F(H264ParserTest, name) + + H264_PARSER_TEST(Parse_Simple) + { + const uint8_t* nal; + int32_t size; + NalUnit nalu; + NalReader nr(&g_SimpleH264[0], g_SimpleH264.size()); + Parser parser; + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNalUnit(nal, size)); + checkH264Sps(parser, &nalu); + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNalUnit(nal, size)); + checkH264Pps(parser, &nalu); + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNalUnit(nal, size)); + checkH264SliceHeader(parser, &nalu); + + ASSERT_FALSE(HasFailure()); + } + +} // namespace H264 +} // namespace YamiParser diff --git a/codecparsers/h265Parser.cpp b/codecparsers/h265Parser.cpp new file mode 100644 index 0000000..0dea3a6 --- /dev/null +++ b/codecparsers/h265Parser.cpp @@ -0,0 +1,1546 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "h265Parser.h" + +#include +#include +#include //offsetof + +#define POWER32SUB2 0xFFFFFFFE +#define POWER15 (1 << 15) + +#define CHECK_RANGE_INT32(var, min, max) \ + { \ + if ((var) < (min) || (var) > (max)) { \ + ERROR("%s(%d) should be in the range[%d, %d]", #var, var, min, max); \ + return false; \ + } \ + } + +#define CHECK_RANGE_UINT32(var, min, max) \ + { \ + if ((var) < (min) || (var) > (max)) { \ + ERROR("%s(%u) should be in the range[%u, %u]", #var, var, min, max); \ + return false; \ + } \ + } + +#define READ(f) \ + do { \ + if (!br.readT(f)) { \ + ERROR("failed to read %s", #f); \ + return false; \ + } \ + } while (0) + +#define READ_BITS(f, bits) \ + do { \ + if (!br.readT(f, bits)) { \ + ERROR("failed to read %d to %s", bits, #f); \ + return false; \ + } \ + } while (0) + +#define CHECK_READ_BITS(f, bits, min, max) \ + do { \ + READ_BITS(f, bits); \ + CHECK_RANGE_UINT32(f, min, max); \ + } while (0) + +#define READ_UE(f) \ + do { \ + if (!br.readUe(f)) { \ + ERROR("failed to readUe %s", #f); \ + return false; \ + } \ + } while (0) + +#define CHECK_READ_UE(f, min, max) \ + do { \ + READ_UE(f); \ + CHECK_RANGE_UINT32(f, min, max); \ + } while (0) + +#define READ_SE(f) \ + do { \ + if (!br.readSe(f)) { \ + ERROR("failed to readSe %s", #f); \ + return false; \ + } \ + } while (0) + +#define CHECK_READ_SE(f, min, max) \ + do { \ + READ_SE(f); \ + CHECK_RANGE_INT32(f, min, max); \ + } while (0) + +#define SKIP(bits) \ + do { \ + if (!br.skip(bits)) { \ + ERROR("failed to skip"); \ + return false; \ + } \ + } while (0) + +namespace YamiParser { +namespace H265 { + +#define SET_DEF_FOR_ORDERING_INFO(var) \ + if (!var->var##_sub_layer_ordering_info_present_flag && \ + var->var##_max_sub_layers_minus1) { \ + for (uint32_t i = 0; i <= var->var##_max_sub_layers_minus1 - 1U; i++) { \ + var->var##_max_dec_pic_buffering_minus1[i] = \ + var->var##_max_dec_pic_buffering_minus1[var->var##_max_sub_layers_minus1]; \ + var->var##_max_num_reorder_pics[i] = \ + var->var##_max_num_reorder_pics[var->var##_max_sub_layers_minus1]; \ + var->var##_max_latency_increase_plus1[i] = \ + var->var##_max_latency_increase_plus1[var->var##_max_sub_layers_minus1]; \ + } \ + } + +#define PARSE_SUB_LAYER_ORDERING_INFO(var, br) \ + { \ + uint32_t start = var->var##_sub_layer_ordering_info_present_flag ? 0 : var->var##_max_sub_layers_minus1; \ + for (uint32_t i = start; i <= var->var##_max_sub_layers_minus1; i++) { \ + CHECK_READ_UE(var->var##_max_dec_pic_buffering_minus1[i], 0, MAXDPBSIZE - 1); \ + \ + CHECK_READ_UE(var->var##_max_num_reorder_pics[i], 0, var->var##_max_dec_pic_buffering_minus1[i]); \ + \ + CHECK_READ_UE(var->var##_max_latency_increase_plus1[i], 0, POWER32SUB2); \ + } \ + } + +// Table 7-5 +static const uint8_t DefaultScalingList0[16] = { + 16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16, + 16, 16, 16, 16 +}; + +// Table 7-6 +static const uint8_t DefaultScalingList1[64] = { + 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 17, 16, 17, 16, 17, 18, + 17, 18, 18, 17, 18, 21, 19, 20, + 21, 20, 19, 21, 24, 22, 22, 24, + 24, 22, 22, 24, 25, 25, 27, 30, + 27, 25, 25, 29, 31, 35, 35, 31, + 29, 36, 41, 44, 41, 36, 47, 54, + 54, 47, 65, 70, 65, 88, 88, 115 +}; + +static const uint8_t DefaultScalingList2[64] = { + 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 17, 17, 17, 17, 17, 18, + 18, 18, 18, 18, 18, 20, 20, 20, + 20, 20, 20, 20, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, + 25, 25, 25, 28, 28, 28, 28, 28, + 28, 33, 33, 33, 33, 33, 41, 41, + 41, 41, 54, 54, 54, 71, 71, 91 +}; + +VPS::VPS() +{ + memset(this, 0, offsetof(VPS, hrd_layer_set_idx)); +} + +VPS::~VPS() +{ +} + +SPS::SPS() +{ + memset(this, 0, offsetof(SPS, vps)); +} + +PPS::PPS() +{ + memset(this, 0, offsetof(PPS, sps)); +} + +SliceHeader::SliceHeader() +{ + memset(this, 0, offsetof(SliceHeader, pps)); +} + +SliceHeader::~SliceHeader() +{ +} + +uint32_t SliceHeader::getSliceDataByteOffset() const +{ + return NalUnit::NALU_HEAD_SIZE + (headerSize + 7) / 8 - emulationPreventionBytes; +} + +bool SliceHeader::isBSlice() const +{ + return slice_type == 0; +} + +bool SliceHeader::isPSlice() const +{ + return slice_type == 1; +} + +bool SliceHeader::isISlice() const +{ + return slice_type == 2; +} + +// Find the first occurrence of the subsequence position in the string src. +// @src, the pointer to source data. +// @size, the lenght of source data in bytes. +static const uint8_t* searchStartPos(const uint8_t* src, uint32_t size) +{ + const uint8_t seq[] = {0x00, 0x00, 0x01}; + const uint8_t* start = NULL; + start = std::search(src, src + size, seq, seq + 3); + if (start == src + size) + start = NULL; + return start; +} + +// 7.3.1 NAL unit syntax +bool NalUnit::parseNaluHeader(const uint8_t* data, size_t size) +{ + if (!data || !size) { + ERROR("data is NULL, or size is 0"); + return false; + } + + m_data = data; + m_size = size; + if (m_size < NALU_HEAD_SIZE) { + ERROR("m_size(%d) < NALU_HEAD_SIZE(%d)", m_size, NALU_HEAD_SIZE); + return false; + } + + BitReader br(m_data, m_size); + + // forbidden_zero_bit + SKIP(1); + + READ_BITS(nal_unit_type, 6); + READ_BITS(nuh_layer_id, 6); + READ_BITS(nuh_temporal_id_plus1, 3); + + return true; +} + +uint8_t Parser::EXTENDED_SAR = 255; + +SharedPtr Parser::getVps(uint8_t id) const +{ + SharedPtr res; + VpsMap::const_iterator it = m_vps.find(id); + if (it != m_vps.end()) + res = it->second; + else + WARNING("can't get the VPS by ID(%d)", id); + return res; +} + +SharedPtr Parser::getSps(uint8_t id) const +{ + SharedPtr res; + SpsMap::const_iterator it = m_sps.find(id); + if (it != m_sps.end()) + res = it->second; + else + WARNING("can't get the SPS by ID(%d)", id); + return res; +} + +SharedPtr Parser::getPps(uint8_t id) const +{ + SharedPtr res; + PpsMap::const_iterator it = m_pps.find(id); + if (it != m_pps.end()) + res = it->second; + else + WARNING("can't get the PPS by ID(%d)", id); + return res; +} + +// 7.3.3 Profile, tier and level syntax +bool Parser::profileTierLevel(ProfileTierLevel* ptl, NalReader& br, + uint8_t maxNumSubLayersMinus1) +{ + READ_BITS(ptl->general_profile_space, 2); + READ(ptl->general_tier_flag); + READ_BITS(ptl->general_profile_idc, 5); + for (uint32_t j = 0; j < 32; j++) + READ(ptl->general_profile_compatibility_flag[j]); + READ(ptl->general_progressive_source_flag); + READ(ptl->general_interlaced_source_flag); + READ(ptl->general_non_packed_constraint_flag); + READ(ptl->general_frame_only_constraint_flag); + if (ptl->general_profile_idc == 4 + || ptl->general_profile_compatibility_flag[4] + || ptl->general_profile_idc == 5 + || ptl->general_profile_compatibility_flag[5] + || ptl->general_profile_idc == 6 + || ptl->general_profile_compatibility_flag[6] + || ptl->general_profile_idc == 7 + || ptl->general_profile_compatibility_flag[7]) { + //The number of bits in this syntax structure is not affected by this condition + READ(ptl->general_max_12bit_constraint_flag); + READ(ptl->general_max_10bit_constraint_flag); + READ(ptl->general_max_8bit_constraint_flag); + READ(ptl->general_max_422chroma_constraint_flag); + READ(ptl->general_max_420chroma_constraint_flag); + READ(ptl->general_max_monochrome_constraint_flag); + READ(ptl->general_intra_constraint_flag); + READ(ptl->general_one_picture_only_constraint_flag); + READ(ptl->general_lower_bit_rate_constraint_flag); + // general_reserved_zero_34bits + SKIP(34); + } else { + //general_reserved_zero_43bits + SKIP(43); + } + if ((ptl->general_profile_idc >= 1 && ptl->general_profile_idc <= 5) + || ptl->general_profile_compatibility_flag[1] + || ptl->general_profile_compatibility_flag[2] + || ptl->general_profile_compatibility_flag[3] + || ptl->general_profile_compatibility_flag[4] + || ptl->general_profile_compatibility_flag[5]) + //The number of bits in this syntax structure is not affected by this condition + READ(ptl->general_inbld_flag); + else + SKIP(1); // general_reserved_zero_bit + READ(ptl->general_level_idc); + for (uint32_t i = 0; i < maxNumSubLayersMinus1; i++) { + READ(ptl->sub_layer_profile_present_flag[i]); + READ(ptl->sub_layer_level_present_flag[i]); + } + if (maxNumSubLayersMinus1 > 0) { + for (uint32_t i = maxNumSubLayersMinus1; i < 8; i++) + SKIP(2); // reserved_zero_2bits + } + for (uint32_t i = 0; i < maxNumSubLayersMinus1; i++) { + if (ptl->sub_layer_profile_present_flag[i]) { + READ_BITS(ptl->sub_layer_profile_space[i], 2); + READ(ptl->sub_layer_tier_flag[i]); + READ_BITS(ptl->sub_layer_profile_idc[i], 5); + for (uint32_t j = 0; j < 32; j++) + READ(ptl->sub_layer_profile_compatibility_flag[i][j]); + READ(ptl->sub_layer_progressive_source_flag[i]); + READ(ptl->sub_layer_interlaced_source_flag[i]); + READ(ptl->sub_layer_non_packed_constraint_flag[i]); + READ(ptl->sub_layer_frame_only_constraint_flag[i]); + if (ptl->sub_layer_profile_idc[i] == 4 + || ptl->sub_layer_profile_compatibility_flag[i][4] + || ptl->sub_layer_profile_idc[i] == 5 + || ptl->sub_layer_profile_compatibility_flag[i][5] + || ptl->sub_layer_profile_idc[i] == 6 + || ptl->sub_layer_profile_compatibility_flag[i][6] + || ptl->sub_layer_profile_idc[i] == 7 + || ptl->sub_layer_profile_compatibility_flag[i][7]) { + //The number of bits in this syntax structure is not affected by this condition + READ(ptl->sub_layer_max_12bit_constraint_flag[i]); + READ(ptl->sub_layer_max_10bit_constraint_flag[i]); + READ(ptl->sub_layer_max_8bit_constraint_flag[i]); + READ(ptl->sub_layer_max_422chroma_constraint_flag[i]); + READ(ptl->sub_layer_max_420chroma_constraint_flag[i]); + READ(ptl->sub_layer_max_monochrome_constraint_flag[i]); + READ(ptl->sub_layer_intra_constraint_flag[i]); + READ(ptl->sub_layer_one_picture_only_constraint_flag[i]); + READ(ptl->sub_layer_lower_bit_rate_constraint_flag[i]); + // sub_layer_reserved_zero_34bits + SKIP(34); + } else { + //sub_layer_reserved_zero_43bits + SKIP(43); + } + if ((ptl->sub_layer_profile_idc[i] >= 1 && ptl->sub_layer_profile_idc[i] <= 5) + || ptl->sub_layer_profile_compatibility_flag[1] + || ptl->sub_layer_profile_compatibility_flag[2] + || ptl->sub_layer_profile_compatibility_flag[3] + || ptl->sub_layer_profile_compatibility_flag[4] + || ptl->sub_layer_profile_compatibility_flag[5]) + //The number of bits in this syntax structure is not affected by this condition + READ(ptl->sub_layer_inbld_flag[i]); + else + SKIP(1); // sub_layer_reserved_zero_bit[i] + } + if (ptl->sub_layer_level_present_flag[i]) + READ(ptl->sub_layer_level_idc[i]); + } + + return true; +} + +// E.2.3 Sub-layer HRD parameters syntax +bool Parser::subLayerHrdParameters(SubLayerHRDParameters* subParams, + NalReader& br, uint32_t cpbCnt, + uint8_t subPicParamsPresentFlag) +{ + for (uint32_t i = 0; i <= cpbCnt; i++) { + if (i == 0) { + CHECK_READ_UE(subParams->bit_rate_value_minus1[i], 0, POWER32SUB2); + CHECK_READ_UE(subParams->cpb_size_value_minus1[i], 0, POWER32SUB2); + } + else { + CHECK_READ_UE(subParams->bit_rate_value_minus1[i], subParams->bit_rate_value_minus1[i - 1], POWER32SUB2); + CHECK_READ_UE(subParams->cpb_size_value_minus1[i], 0, subParams->cpb_size_value_minus1[i - 1] + 1); + } + if (subPicParamsPresentFlag) { + if (i == 0) { + CHECK_READ_UE(subParams->cpb_size_du_value_minus1[i], 0, POWER32SUB2); + CHECK_READ_UE(subParams->bit_rate_du_value_minus1[i], 0, POWER32SUB2); + } + else { + CHECK_READ_UE(subParams->cpb_size_du_value_minus1[i], 0, subParams->cpb_size_du_value_minus1[i - 1] + 1); + CHECK_READ_UE(subParams->bit_rate_du_value_minus1[i], subParams->bit_rate_du_value_minus1[i - 1], POWER32SUB2); + } + } + READ(subParams->cbr_flag[i]); + } + return true; +} + +// E.2.2 HRD parameters syntax +bool Parser::hrdParameters(HRDParameters* params, NalReader& br, + uint8_t commonInfPresentFlag, + uint8_t maxNumSubLayersMinus1) +{ + // set default values, when these syntax elements are not present, they are + // inferred to be euqal to 23. + params->initial_cpb_removal_delay_length_minus1 = 23; + params->au_cpb_removal_delay_length_minus1 = 23; + params->dpb_output_delay_length_minus1 = 23; + + if (commonInfPresentFlag) { + READ(params->nal_hrd_parameters_present_flag); + READ(params->vcl_hrd_parameters_present_flag); + if (params->nal_hrd_parameters_present_flag + || params->vcl_hrd_parameters_present_flag) { + READ(params->sub_pic_hrd_params_present_flag); + if (params->sub_pic_hrd_params_present_flag) { + READ(params->tick_divisor_minus2); + READ_BITS(params->du_cpb_removal_delay_increment_length_minus1, 5); + READ(params->sub_pic_cpb_params_in_pic_timing_sei_flag); + READ_BITS(params->dpb_output_delay_du_length_minus1, 5); + } + READ_BITS(params->bit_rate_scale, 4); + READ_BITS(params->cpb_size_scale, 4); + if (params->sub_pic_hrd_params_present_flag) + READ_BITS(params->cpb_size_du_scale, 4); + READ_BITS(params->initial_cpb_removal_delay_length_minus1, 5); + READ_BITS(params->au_cpb_removal_delay_length_minus1, 5); + READ_BITS(params->dpb_output_delay_length_minus1, 5); + } + } + for (uint32_t i = 0; i <= maxNumSubLayersMinus1; i++) { + READ(params->fixed_pic_rate_general_flag[i]); + + if (!params->fixed_pic_rate_general_flag[i]) + READ(params->fixed_pic_rate_within_cvs_flag[i]); + else + params->fixed_pic_rate_within_cvs_flag[i] = 1; + + if (params->fixed_pic_rate_within_cvs_flag[i]) + CHECK_READ_UE(params->elemental_duration_in_tc_minus1[i], 0, 2047); + else + READ(params->low_delay_hrd_flag[i]); + + if (!params->low_delay_hrd_flag[i]) + CHECK_READ_UE(params->cpb_cnt_minus1[i], 0, 31); + + if (params->nal_hrd_parameters_present_flag) { + if (!subLayerHrdParameters(¶ms->sublayer_hrd_params[i], br, + params->cpb_cnt_minus1[i], + params->sub_pic_hrd_params_present_flag)) + return false; + } + + if (params->vcl_hrd_parameters_present_flag) { + if (!subLayerHrdParameters(¶ms->sublayer_hrd_params[i], br, + params->cpb_cnt_minus1[i], + params->sub_pic_hrd_params_present_flag)) + return false; + } + } + + return true; +} + +// E.2 VUI parameters syntax +bool Parser::vuiParameters(SPS* sps, NalReader& br) +{ + if (!sps) { + ERROR("SPS is NULL"); + return false; + } + + VuiParameters* vui = &sps->vui_params; + + // set default values + vui->video_format = 5; // MAC + // the chromaticity is unspecified or is determined by the application + vui->colour_primaries = 2; + // the transfer characteristics are unspecified or are determined by the + // application + vui->transfer_characteristics = 2; + vui->matrix_coeffs = 2; + vui->motion_vectors_over_pic_boundaries_flag = 1; + vui->max_bytes_per_pic_denom = 2; + vui->max_bits_per_min_cu_denom = 1; + vui->log2_max_mv_length_horizontal = 15; + vui->log2_max_mv_length_vertical = 15; + if (sps->profile_tier_level.general_progressive_source_flag && sps->profile_tier_level.general_interlaced_source_flag) + vui->frame_field_info_present_flag = 1; + + READ(vui->aspect_ratio_info_present_flag); + if (vui->aspect_ratio_info_present_flag) { + READ(vui->aspect_ratio_idc); + if (vui->aspect_ratio_idc == EXTENDED_SAR) { + READ(vui->sar_width); + READ(vui->sar_height); + } + } + READ(vui->overscan_info_present_flag); + if (vui->overscan_info_present_flag) + READ(vui->overscan_appropriate_flag); + READ(vui->video_signal_type_present_flag); + if (vui->video_signal_type_present_flag) { + READ_BITS(vui->video_format, 3); + READ(vui->video_full_range_flag); + READ(vui->colour_description_present_flag); + if (vui->colour_description_present_flag) { + READ(vui->colour_primaries); + READ(vui->transfer_characteristics); + READ(vui->matrix_coeffs); + } + } + READ(vui->chroma_loc_info_present_flag); + if (vui->chroma_loc_info_present_flag) { + CHECK_READ_UE(vui->chroma_sample_loc_type_top_field, 0, 5); + CHECK_READ_UE(vui->chroma_sample_loc_type_bottom_field, 0, 5); + } + READ(vui->neutral_chroma_indication_flag); + READ(vui->field_seq_flag); + READ(vui->frame_field_info_present_flag); + READ(vui->default_display_window_flag); + if (vui->default_display_window_flag) { + READ_UE(vui->def_disp_win_left_offset); + READ_UE(vui->def_disp_win_right_offset); + READ_UE(vui->def_disp_win_top_offset); + READ_UE(vui->def_disp_win_bottom_offset); + } + READ(vui->vui_timing_info_present_flag); + if (vui->vui_timing_info_present_flag) { + READ(vui->vui_num_units_in_tick); + READ(vui->vui_time_scale); + READ(vui->vui_poc_proportional_to_timing_flag); + if (vui->vui_poc_proportional_to_timing_flag) + CHECK_READ_UE(vui->vui_num_ticks_poc_diff_one_minus1, 0, POWER32SUB2); + + READ(vui->vui_hrd_parameters_present_flag); + if (vui->vui_hrd_parameters_present_flag) + if (!hrdParameters(&vui->hrd_params, br, 1, + sps->sps_max_sub_layers_minus1)) + return false; + } + READ(vui->bitstream_restriction_flag); + if (vui->bitstream_restriction_flag) { + READ(vui->tiles_fixed_structure_flag); + READ(vui->motion_vectors_over_pic_boundaries_flag); + READ(vui->restricted_ref_pic_lists_flag); + CHECK_READ_UE(vui->min_spatial_segmentation_idc, 0, 4095); + CHECK_READ_UE(vui->max_bytes_per_pic_denom, 0, 16); + CHECK_READ_UE(vui->max_bits_per_min_cu_denom, 0, 16); + CHECK_READ_UE(vui->log2_max_mv_length_horizontal, 0, 16); + CHECK_READ_UE(vui->log2_max_mv_length_vertical, 0, 15); + } + else { + vui->motion_vectors_over_pic_boundaries_flag = 1; + vui->log2_max_mv_length_horizontal = 15; + vui->log2_max_mv_length_vertical = 15; + } + + return true; +} + +bool Parser::useDefaultScalingLists(uint8_t* dstList, uint8_t* dstDcList, + uint8_t sizeId, uint8_t matrixId) +{ + // Table 7-3-Specification of siezId + switch (sizeId) { + case 0: // 4x4 + memcpy(dstList, DefaultScalingList0, 16); + break; + case 1: // 8x8 + case 2: // 16x16 + if (matrixId <= 2) + memcpy(dstList, DefaultScalingList1, 64); + else + memcpy(dstList, DefaultScalingList2, 64); + break; + case 3: // 32x32 + if (!matrixId) + memcpy(dstList, DefaultScalingList1, 64); + else + memcpy(dstList, DefaultScalingList2, 64); + break; + default: + ERROR("Can't get the scaling list by sizeId(%d)", sizeId); + return false; + } + + if (sizeId > 1) + dstDcList[matrixId] = 16; + + return true; +} + +// 7.3.4 Scaling list data syntax +bool Parser::scalingListData(ScalingList* dest_scaling_list, NalReader& br) +{ + uint8_t* dstDcList = NULL; + uint8_t* dstList = NULL; + uint8_t* refList = NULL; + + size_t size = 64; + uint8_t refMatrixId = 0; + bool scaling_list_pred_mode_flag = false; + uint8_t scaling_list_pred_matrix_id_delta = 0; + uint8_t nextCoef; + uint8_t coefNum; + int16_t scaling_list_delta_coef; + + for (uint32_t sizeId = 0; sizeId < 4; sizeId++) { + for (uint32_t matrixId = 0; matrixId < 6; + matrixId += (sizeId == 3) ? 3 : 1) { + size = 64; + // Table 7-3 + switch (sizeId) { + case 0: // 4x4 + dstList = dest_scaling_list->scalingList4x4[matrixId]; + size = 16; + break; + case 1: // 8x8 + dstList = dest_scaling_list->scalingList8x8[matrixId]; + break; + case 2: // 16x16 + dstList = dest_scaling_list->scalingList16x16[matrixId]; + dstDcList = dest_scaling_list->scalingListDC16x16; + break; + case 3: // 32x32 + dstList = dest_scaling_list->scalingList32x32[matrixId]; + dstDcList = dest_scaling_list->scalingListDC32x32; + } + + READ_BITS(scaling_list_pred_mode_flag, 1); + if (!scaling_list_pred_mode_flag) { + if (sizeId < 3) { + CHECK_READ_UE(scaling_list_pred_matrix_id_delta, 0, matrixId); + } + else if (3 == sizeId) { + // as spec "7.4.5 Scaling list data semantics", + // matrixId should be equal to 3 when scaling_list_pred_matrix_id_delta + // is greater than 0. + CHECK_READ_UE(scaling_list_pred_matrix_id_delta, 0, matrixId / 3); + } + else { + ERROR("sizeId(%u) should be in the range of[0, 3].", sizeId); + return false; + } + if (!scaling_list_pred_matrix_id_delta) { + if (!useDefaultScalingLists(dstList, dstDcList, sizeId, matrixId)) + return false; + } else { + //7-40 + refMatrixId = matrixId - scaling_list_pred_matrix_id_delta * (sizeId == 3 ? 3 : 1); + // get referrence list + switch (sizeId) { + case 0: // 4x4 + refList = dest_scaling_list->scalingList4x4[refMatrixId]; + break; + case 1: // 8x8 + refList = dest_scaling_list->scalingList8x8[refMatrixId]; + break; + case 2: // 16x16 + refList = dest_scaling_list->scalingList16x16[refMatrixId]; + break; + case 3: // 32x32 + refList = dest_scaling_list->scalingList32x32[refMatrixId]; + } + + for (uint32_t i = 0; i < size; i++) + dstList[i] = refList[i]; + + if (sizeId > 1) + dstDcList[matrixId] = dstDcList[refMatrixId]; + } + } else { + nextCoef = 8; + coefNum = std::min(64, (1 << (4 + (sizeId << 1)))); + + if (sizeId > 1) { + int32_t scaling_list_dc_coef_minus8; + CHECK_READ_SE(scaling_list_dc_coef_minus8, -7, 247); + dstDcList[matrixId] = scaling_list_dc_coef_minus8 + 8; + nextCoef = dstDcList[matrixId]; + } + + for (uint32_t i = 0; i < coefNum; i++) { + CHECK_READ_SE(scaling_list_delta_coef, -128, 127); + nextCoef = (nextCoef + scaling_list_delta_coef + 256) % 256; + dstList[i] = nextCoef; + } + } + } + } + + return true; +} + +// 7.3.7 Short-term reference picture set syntax +bool Parser::stRefPicSet(ShortTermRefPicSet* stRef, NalReader& br, + uint8_t stRpsIdx, SPS* sps) +{ + int32_t i, j; + uint8_t refRpsIdx = 0; + int32_t deltaRps = 0; + int32_t dPoc; + ShortTermRefPicSet* refPic; + + // When use_delta_flag[ j ] is not present, its value is inferred to be equal + // to 1. + for (j = 0; j < 16; j++) + stRef->use_delta_flag[j] = 1; + + if (stRpsIdx != 0) + READ(stRef->inter_ref_pic_set_prediction_flag); + if (stRef->inter_ref_pic_set_prediction_flag) { + if (stRpsIdx == sps->num_short_term_ref_pic_sets) + CHECK_READ_UE(stRef->delta_idx_minus1, 0, stRpsIdx); + // 7-57 + refRpsIdx = stRpsIdx - (stRef->delta_idx_minus1 + 1); + READ(stRef->delta_rps_sign); + CHECK_READ_UE(stRef->abs_delta_rps_minus1, 0, POWER15 - 1); + // 7-58 + deltaRps = (1 - 2 * stRef->delta_rps_sign) * (stRef->abs_delta_rps_minus1 + 1); + + refPic = &sps->short_term_ref_pic_set[refRpsIdx]; + for (j = 0; j <= refPic->NumDeltaPocs; j++) { + READ(stRef->used_by_curr_pic_flag[j]); + if (!stRef->used_by_curr_pic_flag[j]) + READ(stRef->use_delta_flag[j]); + } + + // 7-59 + i = 0; + for (j = refPic->NumPositivePics - 1; j >= 0; j--) { + dPoc = refPic->DeltaPocS1[j] + deltaRps; + if (dPoc < 0 && stRef->use_delta_flag[refPic->NumNegativePics + j]) { + stRef->DeltaPocS0[i] = dPoc; + stRef->UsedByCurrPicS0[i++] = stRef->used_by_curr_pic_flag[refPic->NumNegativePics + j]; + } + } + if (deltaRps < 0 && stRef->use_delta_flag[refPic->NumDeltaPocs]) { + stRef->DeltaPocS0[i] = deltaRps; + stRef->UsedByCurrPicS0[i++] = stRef->used_by_curr_pic_flag[refPic->NumDeltaPocs]; + } + for (j = 0; j < refPic->NumNegativePics; j++) { + dPoc = refPic->DeltaPocS0[j] + deltaRps; + if (dPoc < 0 && stRef->use_delta_flag[j]) { + stRef->DeltaPocS0[i] = dPoc; + stRef->UsedByCurrPicS0[i++] = stRef->used_by_curr_pic_flag[j]; + } + } + stRef->NumNegativePics = i; + + // 7-60 + i = 0; + for (j = refPic->NumNegativePics - 1; j >= 0; j--) { + dPoc = refPic->DeltaPocS0[j] + deltaRps; + if (dPoc > 0 && stRef->use_delta_flag[j]) { + stRef->DeltaPocS1[i] = dPoc; + stRef->UsedByCurrPicS1[i++] = stRef->used_by_curr_pic_flag[j]; + } + } + if (deltaRps > 0 && stRef->use_delta_flag[refPic->NumDeltaPocs]) { + stRef->DeltaPocS1[i] = deltaRps; + stRef->UsedByCurrPicS1[i++] = stRef->used_by_curr_pic_flag[refPic->NumDeltaPocs]; + } + for (j = 0; j < refPic->NumPositivePics; j++) { + dPoc = refPic->DeltaPocS1[j] + deltaRps; + if (dPoc > 0 && stRef->use_delta_flag[refPic->NumNegativePics + j]) { + stRef->DeltaPocS1[i] = dPoc; + stRef->UsedByCurrPicS1[i++] = stRef->used_by_curr_pic_flag[refPic->NumNegativePics + j]; + } + } + stRef->NumPositivePics = i; + } + else { + uint8_t maxDecPicBufferingMinus1 = sps->sps_max_dec_pic_buffering_minus1[sps->sps_max_sub_layers_minus1]; + + CHECK_READ_UE(stRef->num_negative_pics, 0, maxDecPicBufferingMinus1); + + CHECK_READ_UE(stRef->num_positive_pics, 0, maxDecPicBufferingMinus1 - stRef->num_negative_pics); + + // 7-61 & 7-62 + stRef->NumNegativePics = stRef->num_negative_pics; + stRef->NumPositivePics = stRef->num_positive_pics; + + for (i = 0; i < stRef->num_negative_pics; i++) { + //delta_poc_s0_minus1 is equal to -3 in some clips. + READ_UE(stRef->delta_poc_s0_minus1[i]); + if (i == 0) // 7-65 + stRef->DeltaPocS0[i] = -(stRef->delta_poc_s0_minus1[i] + 1); + else // 7-67 + stRef->DeltaPocS0[i] = stRef->DeltaPocS0[i - 1] - (stRef->delta_poc_s0_minus1[i] + 1); + + READ(stRef->used_by_curr_pic_s0_flag[i]); + // 7-63 + stRef->UsedByCurrPicS0[i] = stRef->used_by_curr_pic_s0_flag[i]; + } + for (i = 0; i < stRef->num_positive_pics; i++) { + READ_UE(stRef->delta_poc_s1_minus1[i]); + if (i == 0) + stRef->DeltaPocS1[i] = stRef->delta_poc_s1_minus1[i] + 1; + else + stRef->DeltaPocS1[i] = stRef->DeltaPocS1[i - 1] + (stRef->delta_poc_s1_minus1[i] + 1); + + READ(stRef->used_by_curr_pic_s1_flag[i]); + // 7-64 + stRef->UsedByCurrPicS1[i] = stRef->used_by_curr_pic_s1_flag[i]; + } + } + + stRef->NumDeltaPocs = stRef->NumPositivePics + stRef->NumNegativePics; + + return true; +} + +// 7.3.6.2 Reference picture list modification syntax +bool Parser::refPicListsModification(SliceHeader* slice, NalReader& br, + int32_t numPicTotalCurr) +{ + uint32_t nbits = ceil(log2(numPicTotalCurr)); + RefPicListModification* rplm = &slice->ref_pic_list_modification; + memset(rplm, 0, sizeof(RefPicListModification)); + READ(rplm->ref_pic_list_modification_flag_l0); + if (rplm->ref_pic_list_modification_flag_l0) { + for (uint32_t i = 0; i <= slice->num_ref_idx_l0_active_minus1; i++) { + READ_BITS(rplm->list_entry_l0[i], nbits); + } + } + if (slice->isBSlice()) { + READ(rplm->ref_pic_list_modification_flag_l1); + if (rplm->ref_pic_list_modification_flag_l1) + for (uint32_t i = 0; i <= slice->num_ref_idx_l1_active_minus1; i++) { + READ_BITS(rplm->list_entry_l1[i], nbits); + } + } + + return true; +} + +//merge parse l0 and l1 for function predWeightTable +#define SUB_PRED_WEIGHT_TABLE(slice, pwt, br, sps, mode) \ + { \ + uint32_t i, j; \ + for (i = 0; i <= slice->num_ref_idx_##mode##_active_minus1; i++) \ + READ_BITS(pwt->luma_weight_##mode##_flag[i], 1); \ + if (sps->chroma_format_idc) { \ + for (i = 0; i <= slice->num_ref_idx_##mode##_active_minus1; i++) \ + READ_BITS(pwt->chroma_weight_##mode##_flag[i], 1); \ + } \ + for (i = 0; i <= slice->num_ref_idx_##mode##_active_minus1; i++) { \ + if (pwt->luma_weight_##mode##_flag[i]) { \ + READ_SE(pwt->delta_luma_weight_##mode[i]); \ + CHECK_RANGE_INT32(pwt->delta_luma_weight_##mode[i], -128, 127); \ + READ_SE(pwt->luma_offset_##mode[i]); \ + } \ + if (pwt->chroma_weight_##mode##_flag[i]) { \ + for (j = 0; j < 2; j++) { \ + READ_SE(pwt->delta_chroma_weight_##mode[i][j]); \ + CHECK_RANGE_INT32(pwt->delta_chroma_weight_##mode[i][j], -128, 127); \ + READ_SE(pwt->delta_chroma_offset_##mode[i][j]); \ + } \ + } \ + } \ + } + +// 7.3.6.3 Weighted prediction parameters syntax +bool Parser::predWeightTable(SliceHeader* slice, NalReader& br) +{ + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); + PredWeightTable* const pwt = &slice->pred_weight_table; + + // shall be in the range of 0 to 7, inclusive. + CHECK_READ_UE(pwt->luma_log2_weight_denom, 0, 7); + + if (sps->chroma_format_idc) + READ_SE(pwt->delta_chroma_log2_weight_denom); + + SUB_PRED_WEIGHT_TABLE(slice, pwt, br, sps, l0); + + if (slice->isBSlice()) + SUB_PRED_WEIGHT_TABLE(slice, pwt, br, sps, l1); + + return true; +} + +// 7.3.2.1 Video parameter set RBSP syntax +bool Parser::parseVps(const NalUnit* nalu) +{ + SharedPtr vps(new VPS()); + + NalReader br(nalu->m_data + NalUnit::NALU_HEAD_SIZE, + nalu->m_size - NalUnit::NALU_HEAD_SIZE); + + READ_BITS(vps->vps_id, 4); + READ(vps->vps_base_layer_internal_flag); + READ(vps->vps_base_layer_available_flag); + READ_BITS(vps->vps_max_layers_minus1, 6); + CHECK_READ_BITS(vps->vps_max_sub_layers_minus1, 3, 0, MAXSUBLAYERS - 1); + READ(vps->vps_temporal_id_nesting_flag); + SKIP(16); // vps_reserved_0xffff_16bits + if (!profileTierLevel(&vps->profile_tier_level, br, + vps->vps_max_sub_layers_minus1)) + return false; + READ(vps->vps_sub_layer_ordering_info_present_flag); + + //parse + PARSE_SUB_LAYER_ORDERING_INFO(vps, br); + + // set default values + // 1) When vps_max_dec_pic_buffering_minus1[ i ] is not present for i in the + // range of 0 to vps_max_sub_layers_minus1 -1, inclusive, due to + // vps_sub_layer_ordering_info_present_flag being equal to 0, it is + // inferred + // to be equal to vps_max_dec_pic_buffering_minus1[ + // vps_max_sub_layers_minus1 ]. + // 2) When vps_base_layer_internal_flag is equal to 0, + // vps_max_dec_pic_buffering_minus1[ i ] + // shall be equal to 0 and decoders shall ignore the value of + // vps_max_dec_pic_buffering_minus1[ i ]. + SET_DEF_FOR_ORDERING_INFO(vps); + + READ_BITS(vps->vps_max_layer_id, 6); + // shall be in the range of 0 to 1023, inclusive. + CHECK_READ_UE(vps->vps_num_layer_sets_minus1, 0, 1023); + + for (uint32_t i = 1; i <= vps->vps_num_layer_sets_minus1; i++) { + for (uint32_t j = 0; j <= vps->vps_max_layer_id; j++) + SKIP(1); // layer_id_included_flag + } + READ(vps->vps_timing_info_present_flag); + if (vps->vps_timing_info_present_flag) { + READ(vps->vps_num_units_in_tick); + READ(vps->vps_time_scale); + READ(vps->vps_poc_proportional_to_timing_flag); + if (vps->vps_poc_proportional_to_timing_flag) + CHECK_READ_UE(vps->vps_num_ticks_poc_diff_one_minus1, 0, POWER32SUB2); + + // vps_num_hrd_parameters shall be in the range of [0, + // vps_num_layer_sets_minus1 + 1], + // and vps_num_layer_sets_minus shall be in the range [0, 1023] + CHECK_READ_UE(vps->vps_num_hrd_parameters, 0, vps->vps_num_layer_sets_minus1 + 1); + vps->hrd_layer_set_idx.reserve(vps->vps_num_hrd_parameters); + vps->cprms_present_flag.resize(vps->vps_num_hrd_parameters, 0); + uint32_t idxMin = vps->vps_base_layer_internal_flag ? 0 : 1; + for (uint32_t i = 0; i < vps->vps_num_hrd_parameters; i++) { + uint32_t hrd_layer_set_idx; + CHECK_READ_UE(hrd_layer_set_idx, idxMin, vps->vps_num_layer_sets_minus1); + vps->hrd_layer_set_idx.push_back(hrd_layer_set_idx); + if (i > 0) + READ_BITS(vps->cprms_present_flag[i], 1); + hrdParameters(&vps->hrd_parameters, br, vps->cprms_present_flag[i], + vps->vps_max_sub_layers_minus1); + } + } + + READ(vps->vps_extension_flag); + if (vps->vps_extension_flag) { + while (br.moreRbspData()) + SKIP(1); // vps_extension_data_flag + } + br.rbspTrailingBits(); + m_vps[vps->vps_id] = vps; + + return true; +} + +// 7.3.2.2 Sequence parameter set RBSP syntax +bool Parser::parseSps(const NalUnit* nalu) +{ + SharedPtr sps(new SPS()); + SharedPtr vps; + // Table 6-1 + uint8_t subWidthC[5] = { 1, 2, 2, 1, 1 }; + uint8_t subHeightC[5] = { 1, 2, 1, 1, 1 }; + + NalReader br(nalu->m_data + NalUnit::NALU_HEAD_SIZE, + nalu->m_size - NalUnit::NALU_HEAD_SIZE); + + READ_BITS(sps->vps_id, 4); + vps = getVps(sps->vps_id); + if (!vps) + return false; + sps->vps = vps; + + CHECK_READ_BITS(sps->sps_max_sub_layers_minus1, 3, 0, MAXSUBLAYERS - 1); + + READ(sps->sps_temporal_id_nesting_flag); + + if (!profileTierLevel(&sps->profile_tier_level, br, + sps->sps_max_sub_layers_minus1)) + return false; + + CHECK_READ_UE(sps->sps_id, 0, MAXSPSCOUNT); + + // shall be in the range of 0 to 3, inclusive. + CHECK_READ_UE(sps->chroma_format_idc, 0, 3); + if (sps->chroma_format_idc == 3) + READ(sps->separate_colour_plane_flag); + + // used for parsing slice + if (sps->separate_colour_plane_flag) + sps->chroma_array_type = 0; + else + sps->chroma_array_type = sps->chroma_format_idc; + + READ_UE(sps->pic_width_in_luma_samples); + READ_UE(sps->pic_height_in_luma_samples); + READ(sps->conformance_window_flag); + if (sps->conformance_window_flag) { + READ_UE(sps->conf_win_left_offset); + READ_UE(sps->conf_win_right_offset); + READ_UE(sps->conf_win_top_offset); + READ_UE(sps->conf_win_bottom_offset); + } + sps->width = sps->pic_width_in_luma_samples; + sps->height = sps->pic_height_in_luma_samples; + if (sps->conformance_window_flag) { + //D-28 + sps->croppedWidth = sps->pic_width_in_luma_samples - + subWidthC[sps->chroma_format_idc] * + (sps->conf_win_left_offset + sps->conf_win_right_offset); + //D-29 + sps->croppedHeight = sps->pic_height_in_luma_samples - + subHeightC[sps->chroma_format_idc] * + (sps->conf_win_top_offset + sps->conf_win_bottom_offset); + + sps->croppedLeft = subWidthC[sps->chroma_format_idc] * sps->conf_win_left_offset; + sps->croppedTop = subHeightC[sps->chroma_format_idc] * sps->conf_win_top_offset; + } + + CHECK_READ_UE(sps->bit_depth_luma_minus8, 0, 8); + CHECK_READ_UE(sps->bit_depth_chroma_minus8, 0, 8); + + CHECK_READ_UE(sps->log2_max_pic_order_cnt_lsb_minus4, 0, 12); + + READ(sps->sps_sub_layer_ordering_info_present_flag); + + //parse + PARSE_SUB_LAYER_ORDERING_INFO(sps, br); + + // set default values + // When sps_max_dec_pic_buffering_minus1[ i ] is not present for i + // in the range of0 to sps_max_sub_layers_minus1 - 1, inclusive, + // due to sps_sub_layer_ordering_info_present_flag being equal to 0, + // it is inferred to be equal to sps_max_dec_pic_buffering_minus1[ + // sps_max_sub_layers_minus1 ]. + // And also apply for sps_max_num_reorder_pics[i] and + // sps_max_latency_increase_plus1[i]. + SET_DEF_FOR_ORDERING_INFO(sps); + + READ_UE(sps->log2_min_luma_coding_block_size_minus3); + READ_UE(sps->log2_diff_max_min_luma_coding_block_size); + READ_UE(sps->log2_min_transform_block_size_minus2); + READ_UE(sps->log2_diff_max_min_transform_block_size); + READ_UE(sps->max_transform_hierarchy_depth_inter); + READ_UE(sps->max_transform_hierarchy_depth_intra); + READ_BITS(sps->scaling_list_enabled_flag, 1); + if (sps->scaling_list_enabled_flag) { + READ(sps->sps_scaling_list_data_present_flag); + if (sps->sps_scaling_list_data_present_flag) { + if (!scalingListData(&sps->scaling_list, br)) + return false; + } + } + READ(sps->amp_enabled_flag); + READ(sps->sample_adaptive_offset_enabled_flag); + READ(sps->pcm_enabled_flag); + if (sps->pcm_enabled_flag) { + READ_BITS(sps->pcm_sample_bit_depth_luma_minus1, 4); + READ_BITS(sps->pcm_sample_bit_depth_chroma_minus1, 4); + READ_UE(sps->log2_min_pcm_luma_coding_block_size_minus3); + READ_UE(sps->log2_diff_max_min_pcm_luma_coding_block_size); + READ(sps->pcm_loop_filter_disabled_flag); + } + CHECK_READ_UE(sps->num_short_term_ref_pic_sets, 0, MAXSHORTTERMRPSCOUNT); + + for (uint32_t i = 0; i < sps->num_short_term_ref_pic_sets; i++) { + if (!stRefPicSet(&sps->short_term_ref_pic_set[i], br, i, sps.get())) + return false; + } + + READ(sps->long_term_ref_pics_present_flag); + if (sps->long_term_ref_pics_present_flag) { + CHECK_READ_UE(sps->num_long_term_ref_pics_sps, 0, 32); + uint32_t nbits = sps->log2_max_pic_order_cnt_lsb_minus4 + 4; + for (uint32_t i = 0; i < sps->num_long_term_ref_pics_sps; i++) { + READ_BITS(sps->lt_ref_pic_poc_lsb_sps[i], nbits); + READ(sps->used_by_curr_pic_lt_sps_flag[i]); + } + } + + READ(sps->temporal_mvp_enabled_flag); + READ(sps->strong_intra_smoothing_enabled_flag); + READ(sps->vui_parameters_present_flag); + if (sps->vui_parameters_present_flag) { + if (!vuiParameters(sps.get(), br)) + return false; + } + + READ(sps->sps_extension_present_flag); + + // remaining some extension elements, it is not necessary for me, so ignore. + // maybe add in the future. + + m_sps[sps->sps_id] = sps; + + return true; +} + +// 7.3.2.3 Picture parameter set RBSP syntax +bool Parser::parsePps(const NalUnit* nalu) +{ + SharedPtr pps(new PPS()); + SharedPtr sps; + + uint32_t minCbLog2SizeY; + uint32_t ctbLog2SizeY; + uint32_t ctbSizeY; + + NalReader br(nalu->m_data + NalUnit::NALU_HEAD_SIZE, + nalu->m_size - NalUnit::NALU_HEAD_SIZE); + + // set default values + pps->uniform_spacing_flag = 1; + pps->loop_filter_across_tiles_enabled_flag = 1; + + CHECK_READ_UE(pps->pps_id, 0, MAXPPSCOUNT); + CHECK_READ_UE(pps->sps_id, 0, MAXSPSCOUNT); + + sps = getSps(pps->sps_id); + if (!sps) + return false; + pps->sps = sps; + + // 7-10 + minCbLog2SizeY = sps->log2_min_luma_coding_block_size_minus3 + 3; + // 7-11 + ctbLog2SizeY = minCbLog2SizeY + sps->log2_diff_max_min_luma_coding_block_size; + // 7-13 + ctbSizeY = 1 << ctbLog2SizeY; + // 7-15 + pps->picWidthInCtbsY = ceil((double)sps->pic_width_in_luma_samples / (double)ctbSizeY); + // 7-17 + pps->picHeightInCtbsY = ceil((double)sps->pic_height_in_luma_samples / (double)ctbSizeY); + + READ(pps->dependent_slice_segments_enabled_flag); + READ(pps->output_flag_present_flag); + READ_BITS(pps->num_extra_slice_header_bits, 3); + READ(pps->sign_data_hiding_enabled_flag); + READ(pps->cabac_init_present_flag); + CHECK_READ_UE(pps->num_ref_idx_l0_default_active_minus1, 0, 14); + CHECK_READ_UE(pps->num_ref_idx_l1_default_active_minus1, 0, 14); + READ_SE(pps->init_qp_minus26); + READ(pps->constrained_intra_pred_flag); + READ(pps->transform_skip_enabled_flag); + READ(pps->cu_qp_delta_enabled_flag); + if (pps->cu_qp_delta_enabled_flag) + READ_UE(pps->diff_cu_qp_delta_depth); + CHECK_READ_SE(pps->pps_cb_qp_offset, -12, 12); + CHECK_READ_SE(pps->pps_cr_qp_offset, -12, 12); + READ(pps->slice_chroma_qp_offsets_present_flag); + READ(pps->weighted_pred_flag); + READ(pps->weighted_bipred_flag); + READ(pps->transquant_bypass_enabled_flag); + READ(pps->tiles_enabled_flag); + READ(pps->entropy_coding_sync_enabled_flag); + if (pps->tiles_enabled_flag) { + CHECK_READ_UE(pps->num_tile_columns_minus1, 0, pps->picWidthInCtbsY - 1); + CHECK_READ_UE(pps->num_tile_rows_minus1, 0, pps->picHeightInCtbsY - 1); + READ(pps->uniform_spacing_flag); + if (pps->uniform_spacing_flag) { + uint8_t numCol = pps->num_tile_columns_minus1 + 1; + uint8_t numRow = pps->num_tile_rows_minus1 + 1; + for (uint32_t i = 0; i < numCol; i++) { + pps->column_width_minus1[i] = (i + 1) * pps->picWidthInCtbsY / numCol - i * pps->picWidthInCtbsY / numCol - 1; + } + for (uint32_t i = 0; i < numRow; i++) { + pps->row_height_minus1[i] = (i + 1) * pps->picHeightInCtbsY / numRow - i * pps->picHeightInCtbsY / numRow - 1; + } + } else { + pps->column_width_minus1[pps->num_tile_columns_minus1] = pps->picWidthInCtbsY - 1; + for (uint32_t i = 0; i < pps->num_tile_columns_minus1; i++) { + READ_UE(pps->column_width_minus1[i]); + pps->column_width_minus1[pps->num_tile_columns_minus1] -= (pps->column_width_minus1[i] + 1); + } + + pps->row_height_minus1[pps->num_tile_rows_minus1] = pps->picHeightInCtbsY - 1; + for (uint32_t i = 0; i < pps->num_tile_rows_minus1; i++) { + READ_UE(pps->row_height_minus1[i]); + pps->row_height_minus1[pps->num_tile_rows_minus1] -= (pps->row_height_minus1[i] + 1); + } + } + READ(pps->loop_filter_across_tiles_enabled_flag); + } + READ(pps->pps_loop_filter_across_slices_enabled_flag); + READ(pps->deblocking_filter_control_present_flag); + if (pps->deblocking_filter_control_present_flag) { + READ(pps->deblocking_filter_override_enabled_flag); + READ(pps->pps_deblocking_filter_disabled_flag); + if (!pps->pps_deblocking_filter_disabled_flag) { + CHECK_READ_SE(pps->pps_beta_offset_div2, -6, 6); + CHECK_READ_SE(pps->pps_tc_offset_div2, -6, 6); + } + } + READ(pps->pps_scaling_list_data_present_flag); + if (pps->pps_scaling_list_data_present_flag) { + if (!scalingListData(&pps->scaling_list, br)) + return false; + } + // When scaling_list_enabled_flag is equal to 1, + // sps_scaling_list_data_present_flag + // is equal to 0 and pps_scaling_list_data_present_flag is equal to 0, the + // default + // scaling list data are used to derive the array ScalingFactor as described + // in the + // scaling list data semantics as specified in clause 7.4.5. + if (sps->scaling_list_enabled_flag && !sps->sps_scaling_list_data_present_flag && !pps->pps_scaling_list_data_present_flag) { + uint8_t* dstList = NULL; + uint8_t* dstDcList = NULL; + for (uint32_t sizeId = 0; sizeId < 4; sizeId++) { + for (uint32_t matrixId = 0; matrixId < 6; + matrixId += (sizeId == 3) ? 3 : 1) { + switch (sizeId) { + case 0: // 4x4 + dstList = pps->scaling_list.scalingList4x4[matrixId]; + break; + case 1: // 8x8 + dstList = pps->scaling_list.scalingList8x8[matrixId]; + break; + case 2: // 16x16 + dstList = pps->scaling_list.scalingList16x16[matrixId]; + dstDcList = pps->scaling_list.scalingListDC16x16; + break; + case 3: // 32x32 + dstList = pps->scaling_list.scalingList32x32[matrixId]; + dstDcList = pps->scaling_list.scalingListDC32x32; + } + useDefaultScalingLists(dstList, dstDcList, sizeId, matrixId); + } + } + } + + READ(pps->lists_modification_present_flag); + READ_UE(pps->log2_parallel_merge_level_minus2); + READ(pps->slice_segment_header_extension_present_flag); + + READ(pps->pps_extension_present_flag); + if (pps->pps_extension_present_flag) { + READ(pps->pps_range_extension_flag); + READ(pps->pps_multilayer_extension_flag); + READ(pps->pps_3d_extension_flag); + READ_BITS(pps->pps_extension_5bits, 5); + } + + // 7.3.2.3.2 Picture parameter set range extension syntax + if (pps->pps_range_extension_flag) { + if (pps->transform_skip_enabled_flag) + READ_UE(pps->log2_max_transform_skip_block_size_minus2); + READ(pps->cross_component_prediction_enabled_flag); + READ(pps->chroma_qp_offset_list_enabled_flag); + if (pps->chroma_qp_offset_list_enabled_flag) { + CHECK_READ_UE(pps->diff_cu_chroma_qp_offset_depth, 0, sps->log2_diff_max_min_luma_coding_block_size); + CHECK_READ_UE(pps->chroma_qp_offset_list_len_minus1, 0, 5); + for (uint32_t i = 0; i <= pps->chroma_qp_offset_list_len_minus1; i++) { + CHECK_READ_SE(pps->cb_qp_offset_list[i], -12, 12); + CHECK_READ_SE(pps->cr_qp_offset_list[i], -12, 12); + } + } + + // 7-4 & 7-6 + int32_t bitDepthY = 8 + sps->bit_depth_luma_minus8; + int32_t bitDepthc = 8 + sps->bit_depth_chroma_minus8; + + int32_t maxValue = std::max(0, bitDepthY - 10); + CHECK_READ_UE(pps->log2_sao_offset_scale_luma, 0, maxValue); + maxValue = std::max(0, bitDepthc - 10); + CHECK_READ_UE(pps->log2_sao_offset_scale_chroma, 0, maxValue); + } + + m_pps[pps->pps_id] = pps; + + return true; +} + +// 7.3.6 Slice segment header syntax +bool Parser::parseSlice(const NalUnit* nalu, SliceHeader* slice) +{ + uint32_t nbits; + SharedPtr pps; + SharedPtr sps; + ShortTermRefPicSet* stRPS = NULL; + uint32_t UsedByCurrPicLt[16] = {0}; + int32_t numPicTotalCurr = 0; + + if (!nalu || !slice) { + ERROR("nalu or slice is NULL"); + return false; + } + + NalReader br(nalu->m_data + NalUnit::NALU_HEAD_SIZE, + nalu->m_size - NalUnit::NALU_HEAD_SIZE); + + READ(slice->first_slice_segment_in_pic_flag); + if (nalu->nal_unit_type >= NalUnit::BLA_W_LP && nalu->nal_unit_type <= NalUnit::RSV_IRAP_VCL23) + READ(slice->no_output_of_prior_pics_flag); + + CHECK_READ_UE(slice->pps_id, 0, MAXPPSCOUNT); + + pps = getPps(slice->pps_id); + if (!pps) + return false; + slice->pps = pps; + + sps = pps->sps; + if (!sps) + return false; + + // set default values + slice->pic_output_flag = 1; + slice->collocated_from_l0_flag = 1; + slice->beta_offset_div2 = pps->pps_beta_offset_div2; + slice->tc_offset_div2 = pps->pps_tc_offset_div2; + slice->loop_filter_across_slices_enabled_flag = pps->pps_loop_filter_across_slices_enabled_flag; + + if (!slice->first_slice_segment_in_pic_flag) { + nbits = ceil(log2(pps->picWidthInCtbsY * pps->picHeightInCtbsY)); + if (pps->dependent_slice_segments_enabled_flag) + READ(slice->dependent_slice_segment_flag); + READ_BITS(slice->slice_segment_address, nbits); + } + + if (!slice->dependent_slice_segment_flag) { + for (uint32_t i = 0; i < pps->num_extra_slice_header_bits; i++) + SKIP(1); // slice_reserved_flag + + // 0 for B slice, 1 for P slice and 2 for I slice + CHECK_READ_UE(slice->slice_type, 0, 2); + + if (pps->output_flag_present_flag) + READ(slice->pic_output_flag); + if (sps->separate_colour_plane_flag == 1) + READ_BITS(slice->colour_plane_id, 2); + if ((nalu->nal_unit_type != NalUnit::IDR_W_RADL) && (nalu->nal_unit_type != NalUnit::IDR_N_LP)) { + nbits = sps->log2_max_pic_order_cnt_lsb_minus4 + 4; + READ_BITS(slice->slice_pic_order_cnt_lsb, nbits); + READ(slice->short_term_ref_pic_set_sps_flag); + if (!slice->short_term_ref_pic_set_sps_flag) { + if (!stRefPicSet(&slice->short_term_ref_pic_sets, br, + sps->num_short_term_ref_pic_sets, sps.get())) + return false; + } + else if (sps->num_short_term_ref_pic_sets > 1) { + nbits = ceil(log2(sps->num_short_term_ref_pic_sets)); + READ_BITS(slice->short_term_ref_pic_set_idx, nbits); + } + if (sps->long_term_ref_pics_present_flag) { + if (sps->num_long_term_ref_pics_sps > 0) { + CHECK_READ_UE(slice->num_long_term_sps, 0, sps->num_long_term_ref_pics_sps); + } + READ_UE(slice->num_long_term_pics); + for (uint32_t i = 0; + i < slice->num_long_term_sps + slice->num_long_term_pics; i++) { + if (i < slice->num_long_term_sps) { + if (sps->num_long_term_ref_pics_sps > 1) { + nbits = ceil(log2(sps->num_long_term_ref_pics_sps)); + CHECK_READ_BITS(slice->lt_idx_sps[i], nbits, 0, sps->num_long_term_ref_pics_sps - 1); + } + } else { + nbits = sps->log2_max_pic_order_cnt_lsb_minus4 + 4; + READ_BITS(slice->poc_lsb_lt[i], nbits); + READ(slice->used_by_curr_pic_lt_flag[i]); + } + + if (i < slice->num_long_term_sps) + UsedByCurrPicLt[i] = sps->used_by_curr_pic_lt_sps_flag[slice->lt_idx_sps[i]]; + else + UsedByCurrPicLt[i] = slice->used_by_curr_pic_lt_flag[i]; + + READ(slice->delta_poc_msb_present_flag[i]); + if (slice->delta_poc_msb_present_flag[i]) + READ_UE(slice->delta_poc_msb_cycle_lt[i]); + } + } + if (sps->temporal_mvp_enabled_flag) + READ(slice->temporal_mvp_enabled_flag); + } + if (sps->sample_adaptive_offset_enabled_flag) { + READ(slice->sao_luma_flag); + if (sps->chroma_array_type) + READ(slice->sao_chroma_flag); + } + if (slice->isPSlice() || slice->isBSlice()) { + READ(slice->num_ref_idx_active_override_flag); + if (slice->num_ref_idx_active_override_flag) { + // shall be in the range of 0 to 14 + CHECK_READ_UE(slice->num_ref_idx_l0_active_minus1, 0, 14); + if (slice->isBSlice()) { + // shall be in the range of 0 to 14 + CHECK_READ_UE(slice->num_ref_idx_l1_active_minus1, 0, 14); + } + } else { + //When the current slice is a P or B slice and num_ref_idx_l0_active_minus1 + //is not present, num_ref_idx_l0_active_minus1 is inferred to be equal to + //num_ref_idx_l0_default_active_minus1, and num_ref_idx_l1_active_minus1 + //is inferred to be equal to num_ref_idx_l1_default_active_minus1. + slice->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1; + slice->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1; + } + + // according to 7-55 + if (!slice->short_term_ref_pic_set_sps_flag) + stRPS = &slice->short_term_ref_pic_sets; + else + stRPS = &sps->short_term_ref_pic_set[slice->short_term_ref_pic_set_idx]; + for (uint32_t i = 0; i < stRPS->NumNegativePics; i++) { + if (stRPS->UsedByCurrPicS0[i]) + numPicTotalCurr++; + } + for (uint32_t i = 0; i < stRPS->NumPositivePics; i++) { + if (stRPS->UsedByCurrPicS1[i]) + numPicTotalCurr++; + } + for (uint32_t i = 0; + i < (slice->num_long_term_sps + slice->num_long_term_pics); i++) { + if (UsedByCurrPicLt[i]) + numPicTotalCurr++; + } + + if (pps->lists_modification_present_flag && numPicTotalCurr > 1) { + if (!refPicListsModification(slice, br, numPicTotalCurr)) + return false; + } + + if (slice->isBSlice()) + READ(slice->mvd_l1_zero_flag); + if (pps->cabac_init_present_flag) + READ(slice->cabac_init_flag); + if (slice->temporal_mvp_enabled_flag) { + if (slice->isBSlice()) + READ(slice->collocated_from_l0_flag); + + if ((slice->collocated_from_l0_flag + && slice->num_ref_idx_l0_active_minus1 > 0) + || (!slice->collocated_from_l0_flag + && slice->num_ref_idx_l1_active_minus1 > 0)) { + READ_UE(slice->collocated_ref_idx); + } + } + if ((pps->weighted_pred_flag && slice->isPSlice()) || (pps->weighted_bipred_flag && slice->isBSlice())) { + if (!predWeightTable(slice, br)) + return false; + } + CHECK_READ_UE(slice->five_minus_max_num_merge_cand, 0, 4); + } + READ_SE(slice->qp_delta); + if (pps->slice_chroma_qp_offsets_present_flag) { + CHECK_READ_SE(slice->cb_qp_offset, -12, 12); + CHECK_READ_SE(slice->cr_qp_offset, -12, 12); + } + if (pps->chroma_qp_offset_list_enabled_flag) + READ(slice->cu_chroma_qp_offset_enabled_flag); + if (pps->deblocking_filter_override_enabled_flag) + READ(slice->deblocking_filter_override_flag); + if (slice->deblocking_filter_override_flag) { + READ(slice->deblocking_filter_disabled_flag); + if (!slice->deblocking_filter_disabled_flag) { + CHECK_READ_SE(slice->beta_offset_div2, -6, 6); + CHECK_READ_SE(slice->tc_offset_div2, -6, 6); + } + } + else { + slice->deblocking_filter_disabled_flag = pps->pps_deblocking_filter_disabled_flag; + if (!slice->deblocking_filter_disabled_flag) { + slice->beta_offset_div2 = pps->pps_beta_offset_div2; + slice->tc_offset_div2 = pps->pps_tc_offset_div2; + CHECK_RANGE_INT32(slice->beta_offset_div2, -6, 6); + CHECK_RANGE_INT32(slice->tc_offset_div2, -6, 6); + } + } + + if (pps->pps_loop_filter_across_slices_enabled_flag + && (slice->sao_luma_flag + || slice->sao_chroma_flag + || !slice->deblocking_filter_disabled_flag)) { + READ(slice->loop_filter_across_slices_enabled_flag); + } + } + + if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) { + READ_UE(slice->num_entry_point_offsets); + if (slice->num_entry_point_offsets > 0) { + // the value of offset_len_minus1 shall be in the range of [0, 31] + CHECK_READ_UE(slice->offset_len_minus1, 0, 31); + nbits = slice->offset_len_minus1 + 1; + slice->entry_point_offset_minus1.reserve(slice->num_entry_point_offsets); + for (uint32_t i = 0; i < slice->num_entry_point_offsets; i++) { + uint32_t tmp; + READ_BITS(tmp, nbits); + slice->entry_point_offset_minus1.push_back(tmp); + } + } + } + if (pps->slice_segment_header_extension_present_flag) { + CHECK_READ_UE(slice->slice_segment_header_extension_length, 0, 256); + for (uint32_t i = 0; i < slice->slice_segment_header_extension_length; i++) + SKIP(8); // slice_segment_header_extension_data_byte + } + + // byte_alignment() + SKIP(1); // alignment_bit_equal_to_one + while (br.getPos() & 7) + SKIP(1); + + slice->headerSize = br.getPos(); + slice->emulationPreventionBytes = br.getEpbCnt(); + + return true; +} + +} +} diff --git a/codecparsers/h265Parser.h b/codecparsers/h265Parser.h new file mode 100644 index 0000000..16f9e5a --- /dev/null +++ b/codecparsers/h265Parser.h @@ -0,0 +1,609 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * NOTES: + * The data structures defined below follow the ITU Recommendation + * H.265 (http://www.itu.int/rec/T-REC-H.265). The names are used + * exactly as in H.265, so struct fields which hold syntax elements are + * spelled in lowercase_with_underscores. Struct fields which hold variables + * are spelled in CamelCase. + */ + +#ifndef h265Parser_h +#define h265Parser_h + +#include "nalReader.h" +#include "VideoCommonDefs.h" + +#include +#include + +namespace YamiParser { +namespace H265 { + + const uint8_t MAXSUBLAYERS = 7; + const uint8_t MAXSPSCOUNT = 15; + const uint8_t MAXPPSCOUNT = 63; + const uint8_t MAXSHORTTERMRPSCOUNT = 64; + + //A.4 + const uint8_t MAXDPBSIZE = 16; + + const uint8_t UpperRightDiagonal4x4[16] = { + 0, 4, 1, 8, + 5, 2, 12, 9, + 6, 3, 13, 10, + 7, 14, 11, 15 + }; + + const uint8_t UpperRightDiagonal8x8[64] = { + 0, 8, 1, 16, 9, 2, 24, 17, + 10, 3, 32, 25, 18, 11, 4, 40, + 33, 26, 19, 12, 5, 48, 41, 34, + 27, 20, 13, 6, 56, 49, 42, 35, + 28, 21, 14, 7, 57, 50, 43, 36, + 29, 22, 15, 58, 51, 44, 37, 30, + 23, 59, 52, 45, 38, 31, 60, 53, + 46, 39, 61, 54, 47, 62, 55, 63 + }; + +#define UpperRightDiagonal16x16 UpperRightDiagonal8x8 +#define UpperRightDiagonal32x32 UpperRightDiagonal8x8 + + //7.3.3 + struct ProfileTierLevel { + uint8_t general_profile_space; + bool general_tier_flag; + uint8_t general_profile_idc; + bool general_profile_compatibility_flag[32]; + bool general_progressive_source_flag; + bool general_interlaced_source_flag; + bool general_non_packed_constraint_flag; + bool general_frame_only_constraint_flag; + bool general_max_12bit_constraint_flag; + bool general_max_10bit_constraint_flag; + bool general_max_8bit_constraint_flag; + bool general_max_422chroma_constraint_flag; + bool general_max_420chroma_constraint_flag; + bool general_max_monochrome_constraint_flag; + bool general_intra_constraint_flag; + bool general_one_picture_only_constraint_flag; + bool general_lower_bit_rate_constraint_flag; + //uint64_t general_reserved_zero_34bits; + //uint64_t general_reserved_zero_43bits; + bool general_inbld_flag; + //bool general_reserved_zero_bit; + uint8_t general_level_idc; + bool sub_layer_profile_present_flag[6]; + bool sub_layer_level_present_flag[6]; + //uint8_t reserved_zero_2bits[6]; + uint8_t sub_layer_profile_space[6]; + bool sub_layer_tier_flag[6]; + uint8_t sub_layer_profile_idc[6]; + bool sub_layer_profile_compatibility_flag[6][32]; + bool sub_layer_progressive_source_flag[6]; + bool sub_layer_interlaced_source_flag[6]; + bool sub_layer_non_packed_constraint_flag[6]; + bool sub_layer_frame_only_constraint_flag[6]; + bool sub_layer_max_12bit_constraint_flag[6]; + bool sub_layer_max_10bit_constraint_flag[6]; + bool sub_layer_max_8bit_constraint_flag[6]; + bool sub_layer_max_422chroma_constraint_flag[6]; + bool sub_layer_max_420chroma_constraint_flag[6]; + bool sub_layer_max_monochrome_constraint_flag[6]; + bool sub_layer_intra_constraint_flag[6]; + bool sub_layer_one_picture_only_constraint_flag[6]; + bool sub_layer_lower_bit_rate_constraint_flag[6]; + //uint64_t sub_layer_reserved_zero_34bits[6]; + //uint64_t sub_layer_reserved_zero_43bits[6]; + bool sub_layer_inbld_flag[6]; + //bool sub_layer_reserved_zero_bit[6]; + uint8_t sub_layer_level_idc[6]; + }; + + struct SubLayerHRDParameters { + uint32_t bit_rate_value_minus1[32]; + uint32_t cpb_size_value_minus1[32]; + uint32_t cpb_size_du_value_minus1[32]; + uint32_t bit_rate_du_value_minus1[32]; + bool cbr_flag[32]; + }; + + struct HRDParameters { + bool nal_hrd_parameters_present_flag; + bool vcl_hrd_parameters_present_flag; + bool sub_pic_hrd_params_present_flag; + uint8_t tick_divisor_minus2; + uint8_t du_cpb_removal_delay_increment_length_minus1; + bool sub_pic_cpb_params_in_pic_timing_sei_flag; + uint8_t dpb_output_delay_du_length_minus1; + uint8_t bit_rate_scale; + uint8_t cpb_size_scale; + uint8_t cpb_size_du_scale; + uint8_t initial_cpb_removal_delay_length_minus1; + uint8_t au_cpb_removal_delay_length_minus1; + uint8_t dpb_output_delay_length_minus1; + bool fixed_pic_rate_general_flag[MAXSUBLAYERS]; + bool fixed_pic_rate_within_cvs_flag[MAXSUBLAYERS]; + uint16_t elemental_duration_in_tc_minus1[MAXSUBLAYERS]; //[0, 2047] + bool low_delay_hrd_flag[MAXSUBLAYERS]; + uint8_t cpb_cnt_minus1[MAXSUBLAYERS]; //[0, 31] + + SubLayerHRDParameters sublayer_hrd_params[MAXSUBLAYERS]; + }; + + struct ShortTermRefPicSet { + bool inter_ref_pic_set_prediction_flag; + uint8_t delta_idx_minus1; + bool delta_rps_sign; + uint16_t abs_delta_rps_minus1; + bool used_by_curr_pic_flag[16]; + bool use_delta_flag[16]; + uint8_t num_negative_pics; + uint8_t num_positive_pics; + uint32_t delta_poc_s0_minus1[16]; + bool used_by_curr_pic_s0_flag[16]; + uint32_t delta_poc_s1_minus1[16]; + bool used_by_curr_pic_s1_flag[16]; + uint8_t NumDeltaPocs; + uint8_t NumNegativePics; + uint8_t NumPositivePics; + uint8_t UsedByCurrPicS0[16]; + uint8_t UsedByCurrPicS1[16]; + int32_t DeltaPocS0[16]; + int32_t DeltaPocS1[16]; + }; + + struct VuiParameters { + bool aspect_ratio_info_present_flag; + uint8_t aspect_ratio_idc; + uint16_t sar_width; + uint16_t sar_height; + bool overscan_info_present_flag; + bool overscan_appropriate_flag; + bool video_signal_type_present_flag; + uint8_t video_format; + bool video_full_range_flag; + bool colour_description_present_flag; + uint8_t colour_primaries; + uint8_t transfer_characteristics; + uint8_t matrix_coeffs; + bool chroma_loc_info_present_flag; + uint8_t chroma_sample_loc_type_top_field; //[0,5] + uint8_t chroma_sample_loc_type_bottom_field; //[0,5] + bool neutral_chroma_indication_flag; + bool field_seq_flag; + bool frame_field_info_present_flag; + bool default_display_window_flag; + uint32_t def_disp_win_left_offset; + uint32_t def_disp_win_right_offset; + uint32_t def_disp_win_top_offset; + uint32_t def_disp_win_bottom_offset; + bool vui_timing_info_present_flag; + uint32_t vui_num_units_in_tick; + uint32_t vui_time_scale; + bool vui_poc_proportional_to_timing_flag; + uint32_t vui_num_ticks_poc_diff_one_minus1; + bool vui_hrd_parameters_present_flag; + + HRDParameters hrd_params; + + bool bitstream_restriction_flag; + bool tiles_fixed_structure_flag; + bool motion_vectors_over_pic_boundaries_flag; + bool restricted_ref_pic_lists_flag; + uint16_t min_spatial_segmentation_idc; //[0, 4095] + uint8_t max_bytes_per_pic_denom; //[0, 16] + uint8_t max_bits_per_min_cu_denom; //[0, 16] + uint8_t log2_max_mv_length_horizontal; //[0, 16] + uint8_t log2_max_mv_length_vertical; //[0, 15] + }; + + struct ScalingList { + uint8_t scalingList4x4[6][16]; + uint8_t scalingList8x8[6][64]; + uint8_t scalingList16x16[6][64]; + // According to spec "7.3.4 Scaling list data syntax", + // we just use scalingList32x32[0] and scalingList32x32[3]; + // as spec "7.4.5 Scaling list data semantics", + // matrixId as the index of scalingList32x32 can be equal to 3; + // so we'd better define scalingList32x32[6][] other than scalingList32x32[2][]. + uint8_t scalingList32x32[6][64]; + uint8_t scalingListDC16x16[6]; + // scalingListDC32x32 is similar to scalingList32x32. + uint8_t scalingListDC32x32[6]; + }; + + struct RefPicListModification { + bool ref_pic_list_modification_flag_l0; + uint32_t list_entry_l0[15]; + bool ref_pic_list_modification_flag_l1; + uint32_t list_entry_l1[15]; + }; + + struct PredWeightTable { + uint8_t luma_log2_weight_denom; + int8_t delta_chroma_log2_weight_denom; + bool luma_weight_l0_flag[15]; + bool chroma_weight_l0_flag[15]; + int8_t delta_luma_weight_l0[15]; + int8_t luma_offset_l0[15]; + int8_t delta_chroma_weight_l0[15][2]; + int16_t delta_chroma_offset_l0[15][2]; + bool luma_weight_l1_flag[15]; + bool chroma_weight_l1_flag[15]; + int8_t delta_luma_weight_l1[15]; + int8_t luma_offset_l1[15]; + int8_t delta_chroma_weight_l1[15][2]; + int16_t delta_chroma_offset_l1[15][2]; + }; + + //video parameter set + struct VPS { + VPS(); + ~VPS(); + + uint8_t vps_id; //vps_video_parameter_set_id + bool vps_base_layer_internal_flag; + bool vps_base_layer_available_flag; + uint8_t vps_max_layers_minus1; + uint8_t vps_max_sub_layers_minus1; //[0, 6] + bool vps_temporal_id_nesting_flag; + //uint16_t vps_reserved_0xffff_16bits; + ProfileTierLevel profile_tier_level; + bool vps_sub_layer_ordering_info_present_flag; + uint8_t vps_max_dec_pic_buffering_minus1[MAXSUBLAYERS]; + uint8_t vps_max_num_reorder_pics[MAXSUBLAYERS]; + uint32_t vps_max_latency_increase_plus1[MAXSUBLAYERS]; + uint8_t vps_max_layer_id; + uint16_t vps_num_layer_sets_minus1; //[0, 1023] + //bool layer_id_included_flag[][]; + bool vps_timing_info_present_flag; + uint32_t vps_num_units_in_tick; + uint32_t vps_time_scale; + bool vps_poc_proportional_to_timing_flag; + uint32_t vps_num_ticks_poc_diff_one_minus1; + uint16_t vps_num_hrd_parameters; + HRDParameters hrd_parameters; + bool vps_extension_flag; + + //all non pod type should start here + std::vector hrd_layer_set_idx; + std::vector cprms_present_flag; + }; + + //Sequence parameter set + struct SPS { + SPS(); + + uint8_t vps_id; //sps_video_parameter_set_id + uint8_t sps_max_sub_layers_minus1; + bool sps_temporal_id_nesting_flag; + ProfileTierLevel profile_tier_level; + uint8_t sps_id; //sps_seq_parameter_set_id, [0, 15] + uint8_t chroma_format_idc; //[0, 3] + bool separate_colour_plane_flag; + uint8_t chroma_array_type; + uint16_t pic_width_in_luma_samples; + uint16_t pic_height_in_luma_samples; + bool conformance_window_flag; + uint32_t conf_win_left_offset; + uint32_t conf_win_right_offset; + uint32_t conf_win_top_offset; + uint32_t conf_win_bottom_offset; + int32_t width; + int32_t height; + //cropped frame + uint32_t croppedLeft; + uint32_t croppedTop; + uint32_t croppedWidth; + uint32_t croppedHeight; + uint8_t bit_depth_luma_minus8; //[0, 8] + uint8_t bit_depth_chroma_minus8; //[0, 8] + uint8_t log2_max_pic_order_cnt_lsb_minus4; //[0,12] + bool sps_sub_layer_ordering_info_present_flag; + uint8_t sps_max_dec_pic_buffering_minus1[MAXSUBLAYERS]; + uint8_t sps_max_num_reorder_pics[MAXSUBLAYERS]; + uint8_t sps_max_latency_increase_plus1[MAXSUBLAYERS]; + uint8_t log2_min_luma_coding_block_size_minus3; + uint8_t log2_diff_max_min_luma_coding_block_size; + uint8_t log2_min_transform_block_size_minus2; + uint8_t log2_diff_max_min_transform_block_size; + uint8_t max_transform_hierarchy_depth_inter; + uint8_t max_transform_hierarchy_depth_intra; + uint8_t scaling_list_enabled_flag; + bool sps_scaling_list_data_present_flag; + + ScalingList scaling_list; + + bool amp_enabled_flag; + bool sample_adaptive_offset_enabled_flag; + bool pcm_enabled_flag; + uint8_t pcm_sample_bit_depth_luma_minus1; + uint8_t pcm_sample_bit_depth_chroma_minus1; + uint8_t log2_min_pcm_luma_coding_block_size_minus3; + uint8_t log2_diff_max_min_pcm_luma_coding_block_size; + bool pcm_loop_filter_disabled_flag; + uint8_t num_short_term_ref_pic_sets; //[0,64] + + ShortTermRefPicSet short_term_ref_pic_set[64]; + + bool long_term_ref_pics_present_flag; + uint8_t num_long_term_ref_pics_sps; //[0,32] + uint16_t lt_ref_pic_poc_lsb_sps[32]; + bool used_by_curr_pic_lt_sps_flag[32]; + bool temporal_mvp_enabled_flag; + bool strong_intra_smoothing_enabled_flag; + bool vui_parameters_present_flag; + + VuiParameters vui_params; + + bool sps_extension_present_flag; + + //all non pod type should start here + SharedPtr vps; + }; + + //Picture parameter set + struct PPS { + PPS(); + + uint8_t pps_id; //pps_pic_parameter_set_id, [0, 63] + uint8_t sps_id; //pps_seq_parameter_set_id, [0, 15] + bool dependent_slice_segments_enabled_flag; + bool output_flag_present_flag; + uint8_t num_extra_slice_header_bits; + bool sign_data_hiding_enabled_flag; + bool cabac_init_present_flag; + uint8_t num_ref_idx_l0_default_active_minus1; //0, 14] + uint8_t num_ref_idx_l1_default_active_minus1; //0, 14] + int8_t init_qp_minus26; + bool constrained_intra_pred_flag; + bool transform_skip_enabled_flag; + bool cu_qp_delta_enabled_flag; + uint8_t diff_cu_qp_delta_depth; + int8_t pps_cb_qp_offset; //[-12, 12] + int8_t pps_cr_qp_offset; //[-12, 12] + bool slice_chroma_qp_offsets_present_flag; + bool weighted_pred_flag; + bool weighted_bipred_flag; + bool transquant_bypass_enabled_flag; + bool tiles_enabled_flag; + bool entropy_coding_sync_enabled_flag; + uint8_t num_tile_columns_minus1; + uint8_t num_tile_rows_minus1; + bool uniform_spacing_flag; + uint32_t column_width_minus1[19]; + uint32_t row_height_minus1[21]; + bool loop_filter_across_tiles_enabled_flag; + bool pps_loop_filter_across_slices_enabled_flag; + bool deblocking_filter_control_present_flag; + bool deblocking_filter_override_enabled_flag; + bool pps_deblocking_filter_disabled_flag; + int8_t pps_beta_offset_div2; //[-6, 6] + int8_t pps_tc_offset_div2; //[-6, 6] + bool pps_scaling_list_data_present_flag; + + ScalingList scaling_list; + + bool lists_modification_present_flag; + uint8_t log2_parallel_merge_level_minus2; + bool slice_segment_header_extension_present_flag; + bool pps_extension_present_flag; + bool pps_range_extension_flag; + bool pps_multilayer_extension_flag; + bool pps_3d_extension_flag; + uint8_t pps_extension_5bits; + bool pps_extension_data_flag; + //PPSRangeExtension pps_range_extension; + //7.3.2.3.2 Picture parameter set range extension syntax + uint32_t log2_max_transform_skip_block_size_minus2; + bool cross_component_prediction_enabled_flag; + bool chroma_qp_offset_list_enabled_flag; + uint32_t diff_cu_chroma_qp_offset_depth; + uint8_t chroma_qp_offset_list_len_minus1; //[0, 5] + int8_t cb_qp_offset_list[6]; //[-12, 12] + int8_t cr_qp_offset_list[6]; //[-12, 12] + uint8_t log2_sao_offset_scale_luma; + uint8_t log2_sao_offset_scale_chroma; + //used for parsing other syntax elements + uint32_t picWidthInCtbsY; + uint32_t picHeightInCtbsY; + + //all non pod type should start here + SharedPtr sps; + }; + + class NalUnit { + public: + enum { + NALU_HEAD_SIZE = 2, + NALU_MIN_SIZE = 4 + }; + + //Table 7-1 + enum NalUnitType { + //Coded slice segment of a non-TSA, non-STSA trailing picture + TRAIL_N, + TRAIL_R, + //Coded slice segment of a TSA picture + TSA_N, + TSA_R, + //Coded slice segment of an STSA picture + STSA_N, + STSA_R, + //Coded slice segment of a RADL picture + RADL_N, + RADL_R, + //Coded slice segment of a RASL picture + RASL_N, + RASL_R, + //10, 12, 14 Reserved non-IRAP SLNR VCL NAL unit types + RSV_VCL_N10 = 10, + RSV_VCL_N12 = 12, + RSV_VCL_N14 = 14, + //11, 13, 15 Reserved non-IRAP sub-layer reference VCL NAL unit types + //Coded slice segment of a BLA picture + BLA_W_LP = 16, + BLA_W_RADL, + BLA_N_LP, + //Coded slice segment of an IDR picture + IDR_W_RADL, + IDR_N_LP, + //Coded slice segment of a CRA picture + CRA_NUT, + //22 and 23 for Reserved IRAP VCL NAL unit types/ + RSV_IRAP_VCL22, + RSV_IRAP_VCL23, + //24 ... 31 for Reserved non-IRAP VCL NAL unit types + VPS_NUT = 32, //Video parameter set + SPS_NUT, //Sequence parameter set + PPS_NUT, //Picture parameter set + AUD_NUT, //Access unit delimiter + EOS_NUT, //End of sequence + EOB_NUT, //End of bitstream + FD_NUT, //Filler data + PREFIX_SEI_NUT, //Supplemental enhancement information + SUFFIX_SEI_NUT + //41 ... 47 Reserved + //48 ... 63 Unspecified + }; + + /* nal should be a complete nal unit without start code or length bytes */ + bool parseNaluHeader(const uint8_t* nal, size_t size); + + public: + const uint8_t* m_data; + uint32_t m_size; + + //defined in spec, keeping their original name + uint8_t nal_unit_type; + uint8_t nuh_layer_id; + uint8_t nuh_temporal_id_plus1; + }; + + struct SliceHeader { + SliceHeader(); + ~SliceHeader(); + + uint32_t getSliceDataByteOffset() const; + + bool isBSlice() const; + bool isPSlice() const; + bool isISlice() const; + + uint8_t pps_id; //slice_pic_parameter_set_id + bool first_slice_segment_in_pic_flag; + bool no_output_of_prior_pics_flag; + bool dependent_slice_segment_flag; + uint32_t slice_segment_address; + uint8_t slice_type; + bool pic_output_flag; + uint8_t colour_plane_id; + uint16_t slice_pic_order_cnt_lsb; + bool short_term_ref_pic_set_sps_flag; + uint8_t short_term_ref_pic_set_idx; //[0, 63] + ShortTermRefPicSet short_term_ref_pic_sets; + + uint8_t num_long_term_sps; //[0, 32] + uint8_t num_long_term_pics; + uint8_t lt_idx_sps[16]; //[0, 31] + uint32_t poc_lsb_lt[16]; + bool used_by_curr_pic_lt_flag[16]; + bool delta_poc_msb_present_flag[16]; + uint32_t delta_poc_msb_cycle_lt[16]; + bool temporal_mvp_enabled_flag; + bool sao_luma_flag; + bool sao_chroma_flag; + bool num_ref_idx_active_override_flag; + uint8_t num_ref_idx_l0_active_minus1; //[0, 14] + uint8_t num_ref_idx_l1_active_minus1; //[0, 14] + + RefPicListModification ref_pic_list_modification; + + bool mvd_l1_zero_flag; + bool cabac_init_flag; + bool collocated_from_l0_flag; + uint8_t collocated_ref_idx; + + PredWeightTable pred_weight_table; + + uint8_t five_minus_max_num_merge_cand; + int8_t qp_delta; + int8_t cb_qp_offset; //[-12, 12] + int8_t cr_qp_offset; //[-12, 12] + bool cu_chroma_qp_offset_enabled_flag; + bool deblocking_filter_override_flag; + bool deblocking_filter_disabled_flag; + int8_t beta_offset_div2; //[-6, 6] + int8_t tc_offset_div2; //[-6, 6] + bool loop_filter_across_slices_enabled_flag; + uint32_t num_entry_point_offsets; + uint8_t offset_len_minus1; //[0, 31] + uint16_t slice_segment_header_extension_length; //[0, 256] + + //Size of the slice_header() in bits + uint32_t headerSize; + //Number of emulation prevention bytes + uint32_t emulationPreventionBytes; + + //all none pod type should start here + SharedPtr pps; + std::vector entry_point_offset_minus1; + }; + + class Parser { + public: + bool parseVps(const NalUnit* nalu); + bool parseSps(const NalUnit* nalu); + bool parsePps(const NalUnit* nalu); + bool parseSlice(const NalUnit* nalu, SliceHeader* slice); + + private: + static uint8_t EXTENDED_SAR; + + bool profileTierLevel(ProfileTierLevel* ptl, NalReader& nr, uint8_t maxNumSubLayersMinus1); + bool subLayerHrdParameters(SubLayerHRDParameters* subParams, + NalReader& nr, uint32_t CpbCnt, uint8_t subPicParamsPresentFlag); + bool hrdParameters(HRDParameters* params, NalReader& nr, + uint8_t commonInfPresentFlag, uint8_t maxNumSubLayersMinus1); + bool vuiParameters(SPS* sps, NalReader& nr); + bool useDefaultScalingLists(uint8_t* dest, uint8_t* dstDcList, uint8_t sizeId, uint8_t matrixId); + bool scalingListData(ScalingList* dest_scaling_list, NalReader& nr); + bool stRefPicSet(ShortTermRefPicSet* stRPS, + NalReader& nr, uint8_t stRpsIdx, SPS* sps); + bool refPicListsModification(SliceHeader* slice, + NalReader& nr, int32_t numPicTotalCurr); + bool predWeightTable(SliceHeader* slice, NalReader& nr); + + typedef std::map > VpsMap; + typedef std::map > SpsMap; + typedef std::map > PpsMap; + + SharedPtr getVps(uint8_t id) const; + SharedPtr getSps(uint8_t id) const; + SharedPtr getPps(uint8_t id) const; + + VpsMap m_vps; + SpsMap m_sps; + PpsMap m_pps; + + friend class H265ParserTest; + }; +} +} +#endif diff --git a/codecparsers/h265Parser_unittest.cpp b/codecparsers/h265Parser_unittest.cpp new file mode 100644 index 0000000..1495176 --- /dev/null +++ b/codecparsers/h265Parser_unittest.cpp @@ -0,0 +1,212 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "h265Parser.h" + +// library headers +#include "common/Array.h" +#include "common/unittest.h" +#include "common/nalreader.h" + +namespace YamiParser { +namespace H265 { + + using YamiMediaCodec::NalReader; + + const static std::array g_SimpleH265 = { + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, + 0x99, 0x1b, 0x02, 0x40, 0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x01, 0x01, + 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x99, 0xa0, 0x0b, 0x08, 0x04, 0x85, 0xb1, 0xbb, 0xb6, 0xd2, 0x20, + 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03, 0x01, 0xe0, 0x80, + 0x00, 0x00, 0x00, 0x01, 0x44, 0x01, 0xc0, 0x61, 0xc3, 0xe0, 0x09, 0x00, + 0x00, 0x00, 0x01, 0x26, 0x01, 0xef, 0xc0, 0xb7, 0x5f, 0xc9, 0x39, 0xa9, + 0xe5, 0xd7, 0x40, 0x98, 0x5e, 0xf6, 0xb1, 0xe4, 0x38, 0x3a, 0x0f, 0x22, + 0xf5, 0xf1, 0xf6, 0xa5, 0x03, 0xd2, 0xa5, 0x4b, 0x53, 0x50, 0x24, 0x74, + 0x68, 0x82, 0x31, 0x54, 0x9f, 0x13, 0xca, 0x68, 0x70, 0x50, 0x3a, 0x49, + 0x9e, 0x4a, 0xb5, 0x0a, 0x9e, 0x36, 0x0d, 0x36, 0x72, 0x28, 0xc7, 0x91, + 0x27, 0x79, 0x3e, 0x08, 0x27, 0x64, 0x0a, 0xde, 0x89, 0x0f, 0x22, 0xb0, + 0x04, 0xe6, 0x59, 0xb3, 0x20, 0x1f, 0x26, 0x8d, 0xf0, 0xbd, 0x43, 0xf2, + 0xd9, 0x4a, 0x5b, 0x84, 0x46, 0x7b, 0x9b, 0xed, 0xee, 0x31, 0x50, 0x0a, + 0x0b, 0x6e, 0xb8, 0x80, 0x8a, 0x9e, 0xd7, 0xd0, 0x64, 0xe6, 0x66, 0x2a, + 0x18, 0x89, 0x85, 0xbf, 0xfd, 0xb9, 0x20, 0x86, 0x8a, 0x27, 0xa6, 0xc1, + 0xed, 0x5b, 0xb8, 0x67, 0xbe, 0x78, 0x0d, 0x0c, 0x0b, 0x6d, 0x89, 0x14, + 0x56, 0xb4, 0x55, 0xf2, 0xb7, 0xc5, 0x3e, 0xc8, 0x00, 0x1d, 0xd3, 0xef, + 0x8a, 0xeb, 0x47, 0xed, 0x1d, 0x0f, 0x34, 0x0e, 0x71, 0x28, 0xf6, 0xe5, + 0x07, 0xd2, 0xdd, 0x8a, 0xe0, 0xd8, 0x94, 0x4c, 0x98, 0xa3, 0xcc, 0x7f, + 0x63, 0x1e, 0xe1, 0xa6, 0x9b, 0xcd, 0x43, 0x8b, 0xd1, 0xaf, 0xe4, 0x2a, + 0x01, 0x91, 0xce, 0xae, 0x94, 0x6a, 0xed, 0x4a, 0xaf, 0x8d, 0x32, 0x05, + 0xa0, 0xa4, 0x5a, 0x00, 0x07, 0x1c, 0x9a, 0x1d, 0xdb, 0xba, 0x41, 0xd9, + 0xbd, 0xf4, 0x30, 0xbc, 0x06, 0x8a, 0xc7, 0xc7, 0x00, 0x00, 0x03, 0x00, + 0x06, 0x7b, 0x16, 0x08, 0x09, 0x28, 0x3b, 0xd6, 0xbc, 0xdb, 0xaa, 0xee, + 0x75, 0xa4, 0x10, 0x36, 0xb4, 0xfd, 0x71, 0x9d, 0xb9, 0xab, 0x11, 0x10, + 0x13, 0xe6, 0x74, 0x07, 0xf5, 0xa7, 0x7f, 0xae, 0x6a, 0xfd, 0xd1, 0x8a, + 0x14, 0x4a, 0x92, 0x57, 0x93, 0x68, 0xba, 0x9e, 0x88, 0xad, 0x96, 0x8a, + 0xf6, 0xa9, 0xc7, 0x87, 0xef, 0xd3, 0x89, 0x52, 0xb5, 0xe6, 0x41, 0x2d, + 0x9b, 0x8d, 0x33, 0x55, 0xf9, 0x32, 0x3d, 0x36, 0xfa, 0xe3, 0x43, 0x8f, + 0x99, 0x62, 0x46, 0x56, 0xdb, 0x04, 0xf9, 0x5b, 0xc3, 0xc6, 0x5d, 0x33, + 0x17, 0x61, 0xde, 0xef, 0xe8, 0xb9, 0x1f, 0x35, 0xf3, 0xbd, 0x69, 0xcb, + 0x4c, 0x56, 0x69, 0xaa, 0x8d, 0xc8, 0xd5, 0x32, 0x87, 0x20, 0xe7, 0xbd, + 0xeb, 0xc3, 0x68, 0xf3, 0x46, 0x70, 0x07, 0xf1, 0xf5, 0xc1, 0x45, 0x9b, + 0xb3, 0xa0, 0x65, 0xe2, 0xd9, 0xfa, 0x87, 0x70, 0x64, 0x87, 0xda, 0x6f, + 0x60, 0x5e, 0x30, 0x7d, 0x74, 0xd8, 0x68, 0xa2, 0x6c, 0xc5, 0x9b, 0x6c, + 0x31, 0x77, 0x96, 0x45, 0x41, 0x13, 0x60, 0x7e, 0xd2, 0x69, 0x96, 0x54, + 0x00, 0xb2, 0x0b, 0xf2, 0x7e, 0x34, 0x00, 0x9f, 0x36, 0x20, 0x0a, 0x53, + 0xcf, 0x3e, 0xaf, 0xb2, 0x1c, 0xa9, 0x4d, 0x90, 0x47, 0xf0, 0x7a, 0xe2, + 0x25, 0x62, 0x6b, 0xcd, 0x85, 0x37, 0x3e, 0x5c, 0x68, 0xac, 0x7f, 0xd9, + 0x95, 0x24, 0xd2, 0x77, 0x2e, 0x31, 0xf9, 0xa8, 0xf7, 0x27, 0xe4, 0x7c, + 0xf5, 0x4c, 0x3e, 0xd8, 0xda, 0x7f, 0xfa, 0x05, 0x7f, 0x1e, 0x3e, 0x6e, + 0x1a, 0x07, 0xe4, 0x22, 0xc4, 0x95, 0xaa, 0xb0, 0x25, 0xb0, 0x97, 0x02, + 0x3c, 0x0d, 0xb3, 0x5e, 0x9c, 0x49, 0x2a, 0xfb, 0x98, 0x5a, 0x3c, 0xef, + 0x50, 0x3c, 0x47, 0x7a, 0xe8, 0xac, 0xc0, 0x1c, 0x80, 0x6a, 0xe5, 0x87, + 0x98, 0x60, 0x7b, 0x0e, 0x71, 0xdc, 0x41, 0x55, 0x4d, 0xe8, 0x80, 0xa6, + 0x01, 0x61, 0xfb, 0x09, 0xd5, 0x44, 0x51, 0x61, 0x15, 0xeb, 0xe4, 0xa0, + 0x3d, 0x3b, 0x44, 0xa3, 0x8a, 0x74, 0xe9, 0xd3, 0xad, 0x9e, 0x82, 0x73, + 0x16, 0x21, 0xd7, 0x7a, 0xbe, 0x66, 0xe5, 0xde, 0x5b, 0xab, 0x44, 0x87, + 0x11, 0xb9, 0x1b, 0x27, 0x0f, 0xf9, 0x10, 0x84, 0x62, 0x31, 0xe5, 0x65, + 0xb0, 0xd7, 0x94, 0x66, 0xeb, 0x69, 0x76, 0x65, 0x5e, 0x87, 0xe3, 0x22, + 0x43, 0x71, 0x33, 0x52, 0x97, 0x76, 0x71, 0x0a, 0xe9, 0x5f, 0xbf, 0xf8, + 0xf6, 0x41, 0x17, 0xc2, 0x34, 0x8a, 0xa8, 0xda, 0xb0, 0x8d, 0x9e, 0xc2, + 0xbc, 0x54, 0xf5, 0xa2, 0x36, 0xef, 0x67, 0x15, 0xf2, 0xe2, 0xf9, 0xbe, + 0xfd, 0x9c, 0x86, 0x15, 0xed, 0xef, 0x6b, 0xf5, 0xc3, 0x5d, 0xe4, 0xa1, + 0x4d, 0xce, 0xcb, 0x1c, 0x10, 0xd3, 0xb3, 0x1f, 0x50, 0x85, 0x7d, 0x79, + 0x10, 0x9f, 0x10, 0xe5, 0xb4, 0x64, 0xce, 0x22, 0xaf, 0x6a, 0x2d, 0xb6, + 0x70, 0x46, 0x08, 0xf6, 0x6a, 0x35, 0xbc, 0x42, 0xf2, 0xf9, 0x8d, 0x92, + 0x06, 0x7c, 0xcf, 0x8c, 0xda, 0x1f, 0xa1, 0x63, 0x8f, 0x92, 0x70, 0x19, + 0x36, 0x69, 0x20, 0xba, 0x22, 0x4f, 0xf5, 0xd2, 0x85, 0xc7, 0x5f, 0x7c, + 0xda, 0x53, 0x09, 0x0c, 0xfa, 0x37, 0x70, 0x42, 0x79, 0x77, 0x83, 0x99, + 0xf8, 0x0e, 0xeb, 0x68, 0x25, 0x8d, 0xae, 0x96, 0x79, 0x70, 0xfb, 0x85, + 0xdb, 0xd0, 0x2f, 0x62, 0x9a, 0x61, 0xa8, 0xc5, 0x06, 0x29, 0x65, 0x82, + 0x2d, 0x2a, 0x07, 0x87, 0x72, 0x72, 0x11, 0xf1, 0x7a, 0x60, 0x95, 0x93, + 0x76, 0xba, 0x63, 0xd1, 0x19, 0xbe, 0x72, 0x54, 0xd1, 0x48, 0xb6, 0x33, + 0xb4, 0x31, 0x40, 0x79, 0xad, 0x93, 0x02, 0xc1, 0x11, 0xc0, 0x3a, 0x77, + 0x28, 0xe0, 0xdc, 0x38, 0xb4, 0xb8, 0xcc, 0xa7, 0x19, 0x3a, 0x16, 0x34, + 0x26, 0x5a, 0x4e, 0xa0, 0xfb, 0xc1, 0xa1, 0x37, 0x00, 0x5d, 0xf5, 0x39, + 0x8b, 0xc7, 0xc7, 0x33, 0xaf, 0xd3, 0xfa, 0x42, 0xe4, 0x73, 0xce, 0xf7, + 0x75, 0xdf, 0x9f, 0xdd, 0x7d, 0x4b, 0x6b, 0x46, 0xc2, 0x21, 0x96, 0x63, + 0x98, 0xec, 0x11, 0x10, 0x72, 0xa3, 0x77, 0xd9, 0x5b, 0xd9, 0x05, 0xfa, + 0x56, 0xdd, 0xa4, 0x47, 0xfd, 0xec, 0x72, 0x17, 0xfd, 0x3e, 0xb6, 0x3c, + 0x8e, 0xb3, 0x50, 0x02, 0x38, 0x43, 0x69, 0xff, 0x2d, 0x71, 0x93, 0xcb, + 0x15, 0xd4, 0x27, 0x2a, 0xae, 0x50, 0x3c, 0x91, 0xd6, 0xfc, 0xee, 0x6e, + 0x1c, 0x0f, 0xbe, 0xa8, 0x09, 0xe5, 0x84, 0x8e, 0x5d, 0x3a, 0x3e, 0xbb, + 0x8a, 0x6d, 0x0c, 0xd9, 0xa7, 0xc1, 0xed, 0xdd, 0x89, 0x7e, 0x59, 0xf4, + 0xed, 0x6f, 0x7b, 0xdc, 0x77, 0x77, 0xe5, 0x6c, 0x57, 0xff, 0xea, 0xb4, + 0x86, 0xf5, 0xc7, 0xe8, 0xf0, 0xca, 0xff, 0x31, 0x4b, 0x56, 0xed, 0xde, + 0x4d, 0x7d, 0xb8, 0xa3, 0x23, 0x67, 0xac, 0xca, 0xdd, 0x33, 0xb2, 0x1b, + 0xf6, 0xea, 0xfe, 0x43, 0x9b, 0x52, 0x22, 0xf4, 0x38, 0x5f, 0xd9, 0xee, + 0x75, 0x06, 0xc7, 0x63, 0x67, 0xba, 0x07, 0xce, 0x48, 0x9c, 0xc7, 0x63, + 0x6b, 0x4e, 0x61, 0x1b, 0xcd, 0x11, 0x62, 0x5f, 0x20, 0x2d, 0x24, 0x8f, + 0xfc, 0x16, 0xe3, 0xdf, 0x35, 0x2a, 0xd9, 0xec, 0xb4, 0xb7, 0x7c, 0xbb, + 0x56, 0xff, 0xa8, 0xf7, 0xda, 0x90, 0x86, 0xbf, 0xcc, 0xc5, 0x23, 0x41, + 0x44, 0xb6, 0xd5, 0xb2, 0x28, 0xa3, 0x8c, 0x96, 0x4a, 0x57, 0x5a, 0x80, + 0xd3, 0xd8, 0x68, 0xe3, 0x71, 0xf8, 0xfc, 0xd0, 0xe9, 0xbe, 0x3c, 0x7b, + 0xf8, 0x2c, 0x9e, 0xbd, 0x5b, 0xa6, 0xc4, 0xb5, 0x1f, 0x26, 0x17, 0x6e, + 0x2b, 0xd8, 0xbb, 0xe6, 0xe9, 0x53, 0xa0, 0x0d, 0x7a, 0x12, 0x34, 0x1e, + 0x0e, 0xef, 0x96, 0x51, 0x21, 0xed, 0x23, 0x1e, 0x56, 0xb7, 0x4e, 0x02, + 0x5f, 0x74, 0x59, 0xcc, 0xfe, 0x72, 0x5b, 0x3d, 0xe6, 0x86, 0x6d, 0xfe, + 0xce, 0x63, 0x34, 0x1a, 0x5d, 0xf5, 0x70, 0x3b, 0xe4, 0x33, 0x43, 0x06, + 0x46, 0xff, 0x35, 0x73, 0xa1, 0xe5, 0x2b, 0x38, 0x86, 0x4d, 0xc3, 0x16, + 0x07, 0x5f, 0x69, 0xdd, 0xdb, 0x51, 0x3f, 0x1d, 0x77, 0x9f, 0x58, 0x42, + 0x0f, 0xe6, 0x81, 0x52, 0xb6, 0x55, 0x0c, 0x57, 0x8e, 0x06, 0x5b, 0x11, + 0xf5, 0xa0, 0x34, 0x8b, 0x9d, 0x1c, 0xa7, 0xe6, 0x6d, 0x60, 0x7d, 0x14, + 0x40, 0xf7, 0x00, 0x8f, 0xae, 0xd2, 0xf1, 0x15, 0xdf, 0x19, 0x28, 0x3c, + 0x52, 0x5c, 0xf6, 0x2d, 0xd1, 0x59, 0x2e, 0x0d, 0xbf, 0x3f, 0xaf, 0x23, + 0x61, 0x1c, 0xda, 0xd7, 0xed, 0x95, 0xc3, 0x31, 0x91, 0x9f, 0xa2, 0x8d, + 0x0e, 0xe5, 0xd7, 0x38 + }; + + class H265ParserTest : public ::testing::Test { + + protected: + void checkH265Vps(Parser& parser, const NalUnit* nalu) + { + EXPECT_EQ(NalUnit::VPS_NUT, nalu->nal_unit_type); + EXPECT_EQ(true, parser.parseVps(nalu)); + SharedPtr vps = parser.getVps(0); + EXPECT_EQ(true, !!vps); + EXPECT_EQ(153, vps->profile_tier_level.general_level_idc); + EXPECT_EQ(5, vps->vps_max_dec_pic_buffering_minus1[0]); + } + + void checkH265Sps(Parser& parser, const NalUnit* nalu) + { + EXPECT_EQ(NalUnit::SPS_NUT, nalu->nal_unit_type); + EXPECT_EQ(true, parser.parseSps(nalu)); + SharedPtr sps = parser.getSps(0); + EXPECT_EQ(true, !!sps); + EXPECT_EQ(352, sps->pic_width_in_luma_samples); + EXPECT_EQ(288, sps->pic_height_in_luma_samples); + EXPECT_EQ(true, sps->vui_parameters_present_flag); + EXPECT_EQ(30u, sps->vui_params.vui_time_scale); + } + + void checkH265Pps(Parser& parser, const NalUnit* nalu) + { + EXPECT_EQ(NalUnit::PPS_NUT, nalu->nal_unit_type); + EXPECT_EQ(true, parser.parsePps(nalu)); + SharedPtr pps = parser.getPps(0); + EXPECT_EQ(true, !!pps); + EXPECT_EQ(14, pps->init_qp_minus26); + EXPECT_EQ(true, pps->slice_chroma_qp_offsets_present_flag); + } + + void checkH265SliceHeader(Parser& parser, NalUnit* nalu) + { + EXPECT_EQ(NalUnit::IDR_W_RADL, nalu->nal_unit_type); + SliceHeader slice; + EXPECT_EQ(true, parser.parseSlice(nalu, &slice)); + EXPECT_EQ(2, slice.slice_type); + EXPECT_EQ(0, slice.cr_qp_offset); + } + }; + +#define H265_PARSER_TEST(name) TEST_F(H265ParserTest, name) + + H265_PARSER_TEST(Parse_Simple) + { + const uint8_t* nal; + int32_t size; + NalUnit nalu; + NalReader nr(&g_SimpleH265[0], g_SimpleH265.size()); + Parser parser; + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNaluHeader(nal, size)); + checkH265Vps(parser, &nalu); + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNaluHeader(nal, size)); + checkH265Sps(parser, &nalu); + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNaluHeader(nal, size)); + checkH265Pps(parser, &nalu); + + ASSERT_TRUE(nr.read(nal, size)); + ASSERT_TRUE(nalu.parseNaluHeader(nal, size)); + checkH265SliceHeader(parser, &nalu); + + ASSERT_FALSE(HasFailure()); + } + +} // namespace H265 +} // namespace YamiParser diff --git a/codecparsers/jpegParser.cpp b/codecparsers/jpegParser.cpp new file mode 100644 index 0000000..e5cd4db --- /dev/null +++ b/codecparsers/jpegParser.cpp @@ -0,0 +1,816 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ---- + * + * Part of IJG's libjpeg library (primarily jdmarker.c) was used as a reference + * while implementing this parser. This implementation loosely reproduces some + * of the parsing logic found in the libjpeg jdmarker.c file. Although, this + * logic has been refactored using C++-style syntax and data structures and + * adjusted appropriately to fit into the overall libyami framework. Therefore, + * this implementation is considered to be partially derived from IJG's libjpeg. + * + * The following license preamble, below, is reproduced from libjpeg's + * jdmarker.c file. The README.ijg is also provided with this file: + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * Modified 2009-2013 by Guido Vollbeding. + * The jdmarker.c file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README.ijg file. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "jpegParser.h" + +// library headers +#include "common/log.h" + +// system headers +#include +#include + +namespace YamiParser { +namespace JPEG { + +#define INPUT_BYTE(var, action) \ + do { \ + if (m_input.end()) { \ + action; \ + } \ + var = m_input.read(8); \ + } while(0) + +#define INPUT_2BYTES(var, action) \ + do { \ + uint16_t b1, b2; \ + INPUT_BYTE(b1, action); \ + INPUT_BYTE(b2, action); \ + var = ((b1 << 8) | b2) & 0xffff; \ + } while(0) + +const Defaults Defaults::s_instance; + +Defaults::Defaults() + : m_acHuffTables() + , m_dcHuffTables() + , m_quantTables() +{ + // The following tables are from + // https://www.w3.org/Graphics/JPEG/itu-t81.pdf + + { // K.3.3.1 Luminance DC coefficients + std::array codes = { + 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + std::array values = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b + }; + + m_dcHuffTables[0].reset(new HuffTable()); + m_dcHuffTables[0]->codes.swap(codes); + m_dcHuffTables[0]->values.swap(values); + } + + { // K.3.3.1 Chrominance DC coefficients + std::array codes = { + 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + std::array values = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b + }; + + m_dcHuffTables[1].reset(new HuffTable()); + m_dcHuffTables[1]->codes.swap(codes); + m_dcHuffTables[1]->values.swap(values); + } + + { // K.3.3.2 Luminance AC coefficients + std::array codes = { + 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, + 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d + }; + std::array values = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, + 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, + 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa + }; + + m_acHuffTables[0].reset(new HuffTable()); + m_acHuffTables[0]->codes.swap(codes); + m_acHuffTables[0]->values.swap(values); + } + + { // K.3.3.2 Chrominance AC coefficients + std::array codes = { + 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, + 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77 + }; + std::array values = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, + 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, + 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, + 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, + 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa + }; + + m_acHuffTables[1].reset(new HuffTable()); + m_acHuffTables[1]->codes.swap(codes); + m_acHuffTables[1]->values.swap(values); + } + + static const std::array zigzag8x8 = { + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63 + }; + + { // Table K.1 Luminance quantization table values + std::array values = { + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99 + }; + + m_quantTables[0].reset(new QuantTable()); + for (size_t i(0); i < DCTSIZE2; ++i) + m_quantTables[0]->values[i] = values[zigzag8x8[i]]; + m_quantTables[0]->precision = 0; // 1-byte precision + } + + { // Table K.2 Chrominance quantization table values + std::array values = { + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + }; + + m_quantTables[1].reset(new QuantTable()); + for (size_t i(0); i < DCTSIZE2; ++i) + m_quantTables[1]->values[i] = values[zigzag8x8[i]]; + m_quantTables[1]->precision = 0; // 1-byte precision + } +} + +Parser::Parser(const uint8_t* data, const uint32_t size) + : m_input(data, size) + , m_data(data) + , m_size(size) + , m_current() + , m_frameHeader() + , m_scanHeader() + , m_quantTables() + , m_dcHuffTables() + , m_acHuffTables() + , m_arithDCL() + , m_arithDCU() + , m_arithACK() + , m_callbacks() + , m_sawSOI(false) + , m_sawEOI(false) + , m_sawSOS(false) + , m_restartInterval(0) +{ +} + +bool Parser::skipBytes(const uint32_t nBytes) +{ + if ((static_cast(nBytes) << 3) + > m_input.getRemainingBitsCount()) { + ERROR("Not enough bytes in stream"); + return false; + } + + // BitReader only supports skipping a max of CACHEBYTES at a time + // for each call to skip. + const uint32_t nSkips = nBytes / BitReader::CACHEBYTES; + const uint32_t rem = nBytes % BitReader::CACHEBYTES; + for (uint32_t i(0); i < nSkips; ++i) + m_input.skip(BitReader::CACHEBYTES << 3); + m_input.skip(rem << 3); + + return true; +} + +void Parser::registerCallback(const Marker& marker, const Callback& callback) +{ + m_callbacks[marker].push_back(callback); +} + +void Parser::registerStartOfFrameCallback(const Callback& callback) +{ + static const std::array sofMarkers = { + M_SOF0, M_SOF1 , M_SOF2 , M_SOF3 , M_SOF5 , M_SOF6 , M_SOF7, + M_SOF9, M_SOF10, M_SOF11, M_SOF13, M_SOF14, M_SOF15 }; + + for (size_t i(0); i < 13; ++i) + registerCallback(sofMarkers[i], callback); +} + +Parser::CallbackResult Parser::notifyCallbacks() const +{ + const Callbacks::const_iterator match(m_callbacks.find(m_current.marker)); + if (match != m_callbacks.end()) { + const CallbackList& callbacks = match->second; + const size_t nCallbacks = callbacks.size(); + for (size_t i(0); i < nCallbacks; ++i) + if (callbacks[i]() == ParseSuspend) + return ParseSuspend; + } + return ParseContinue; +} + +bool Parser::firstMarker() +{ + uint32_t c, c2; + + INPUT_BYTE(c, return false); + INPUT_BYTE(c2, return false); + if (c != 0xFF || c2 != M_SOI) { + ERROR("No SOI found. Not a JPEG"); + return false; + } + + m_current.marker = static_cast(c2); + m_current.position = currentBytePosition() - 1; + m_current.length = 0; // set by marker parse routines when appropriate + + return true; +} + +bool Parser::nextMarker() +{ + if (m_input.getRemainingBitsCount() == 0) + return false; + + const uint8_t* const end = m_data + m_size - 1; + const uint8_t* const start = m_data + currentBytePosition(); + const uint8_t* current = start; + const uint8_t* match; + + do { + match = std::find(current, end, 0xFF); + if (match == end) { + skipBytes(std::distance(start, match) + 1); + return false; + } + if (*(match + 1) < 0xFF && *(match + 1) >= M_SOF0) + break; + current = match + 1; + } while (true); + + skipBytes(std::distance(start, match) + 1); + + m_current.marker = static_cast(m_input.read(8)); + m_current.position = currentBytePosition() - 1; + m_current.length = 0; // set by marker parse routines when appropriate + + return true; +} + +bool Parser::parse() +{ + while (true) { + if (!m_sawSOI) { + if (!firstMarker()) { + return false; + } + } else if (!nextMarker()) { + if (m_sawSOS && !m_sawEOI) { + // NOTE: By standard, a missing EOI technically means the image + // is corrupt. However, there are many images in the wild where + // a missing EOI is the only corruption to the image (i.e. the + // entropy-coded data and headers are still intact). This can + // happen, for example, when the image was encoded by a buggy + // application that forgets to append the EOI to the final + // image. If a missing EOI is the only issue, then decoders can + // still successfully decode it. However, a missing EOI does + // not necessarily mean the rest of the image is intact. That + // is, there is no guarantee that the final decoded output will + // produce the desired result. Either way, we insert a fake + // EOI marker here to give decoders a chance to decode the + // image. + WARNING("No EOI marker found on input... inserting one now"); + m_current.marker = M_EOI; + m_current.position = currentBytePosition() - 1; + m_current.length = 0; + } else { + return m_sawEOI; + } + } + + DEBUG("%s (byte:0x%02x position:%u)", __func__, + m_current.marker, m_current.position); + + bool parseSegment = false; + + switch (m_current.marker) { + case M_SOI: + parseSegment = parseSOI(); + break; + case M_SOF0: // Baseline + parseSegment = parseSOF(true, false, false); + break; + case M_SOF1: // Extended sequential, Huffman + parseSegment = parseSOF(false, false, false); + break; + case M_SOF2: // Progressive, Huffman + parseSegment = parseSOF(false, true, false); + break; + case M_SOF9: // Extended sequential, arithmetic + parseSegment = parseSOF(false, false, true); + break; + case M_SOF10: // Progressive, arithmetic + parseSegment = parseSOF(false, true, true); + break; + case M_DAC: + parseSegment = parseDAC(); + break; + case M_DHT: + parseSegment = parseDHT(); + break; + case M_DQT: + parseSegment = parseDQT(); + break; + case M_DRI: + parseSegment = parseDRI(); + break; + case M_SOS: + parseSegment = parseSOS(); + break; + case M_EOI: + parseSegment = parseEOI(); + break; + + case M_APP0: + case M_APP1: + case M_APP2: + case M_APP3: + case M_APP4: + case M_APP5: + case M_APP6: + case M_APP7: + case M_APP8: + case M_APP9: + case M_APP10: + case M_APP11: + case M_APP12: + case M_APP13: + case M_APP14: + case M_APP15: + parseSegment = parseAPP(); + break; + + case M_COM: + case M_RST0: + case M_RST1: + case M_RST2: + case M_RST3: + case M_RST4: + case M_RST5: + case M_RST6: + case M_RST7: + parseSegment = true; + break; + + /* Currently unsupported SOFn types */ + case M_SOF3: // Lossless, Huffman + case M_SOF5: // Differential sequential, Huffman + case M_SOF6: // Differential progressive, Huffman + case M_SOF7: // Differential lossless, Huffman + case M_JPG: // Reserved for JPEG extensions + case M_SOF11: // Lossless, arithmetic + case M_SOF13: // Differential sequential, arithmetic + case M_SOF14: // Differential progressive, arithmetic + case M_SOF15: // Differential lossless, arithmetic + //unsupported + ERROR("Unsupported marker encountered: 0x%02x", m_current.marker); + return false; + + default: + // unknown or unhandled marker + ERROR("Unknown or unhandled marker: 0x%02x", m_current.marker); + return false; + } + + if (!parseSegment) + return false; + + if (notifyCallbacks() == ParseSuspend) + return true; + } +} + +bool Parser::parseSOI() +{ + if (m_sawSOI) { + ERROR("Duplicate SOI encountered"); + return false; + } + + m_sawSOI = true; + + return true; +} + +bool Parser::parseAPP() +{ + INPUT_2BYTES(m_current.length, return false); + + return skipBytes(m_current.length - 2); +} + +bool Parser::parseSOF(bool isBaseline, bool isProgressive, bool isArithmetic) +{ + if (m_frameHeader) { + ERROR("Duplicate SOF encountered"); + return false; + } + + INPUT_2BYTES(m_current.length, return false); + + m_frameHeader.reset(new FrameHeader); + + m_frameHeader->isBaseline = isBaseline; + m_frameHeader->isProgressive = isProgressive; + m_frameHeader->isArithmetic = isArithmetic; + + INPUT_BYTE(m_frameHeader->dataPrecision, return false); + INPUT_2BYTES(m_frameHeader->imageHeight, return false); + INPUT_2BYTES(m_frameHeader->imageWidth, return false); + + uint32_t numComponents; + + INPUT_BYTE(numComponents, return false); + + DEBUG("baseline : %d", m_frameHeader->isBaseline); + DEBUG("progressive : %d", m_frameHeader->isProgressive); + DEBUG("arithmetic : %d", m_frameHeader->isArithmetic); + DEBUG("precision : %d", m_frameHeader->dataPrecision); + DEBUG("image width : %u", m_frameHeader->imageWidth); + DEBUG("image height : %u", m_frameHeader->imageHeight); + DEBUG("num components: %d", numComponents); + + if (m_frameHeader->imageWidth <= 0 || m_frameHeader->imageHeight <= 0 + || numComponents <= 0) { + ERROR("Empty image"); + return false; + } + + if ((m_current.length - 8) != (numComponents * 3) + || numComponents > MAX_COMPS_IN_SCAN) { + ERROR("Bad length"); + return false; + } + + m_frameHeader->components.resize(numComponents); + m_frameHeader->maxHSampleFactor = 0; + m_frameHeader->maxVSampleFactor = 0; + + for (size_t index(0); index < numComponents; ++index) { + int factor; + Component::Shared& component = m_frameHeader->components[index]; + component.reset(new Component); + component->index = index; + + INPUT_BYTE(component->id, return false); + INPUT_BYTE(factor, return false); + + component->hSampleFactor = (factor >> 4) & 15; + component->vSampleFactor = factor & 15; + + if (component->hSampleFactor > m_frameHeader->maxHSampleFactor) + m_frameHeader->maxHSampleFactor = component->hSampleFactor; + + if (component->vSampleFactor > m_frameHeader->maxVSampleFactor) + m_frameHeader->maxVSampleFactor = component->vSampleFactor; + + INPUT_BYTE(component->quantTableNumber, return false); + } + + return true; +} + +static bool componentIdMatches(const int id, const Component::Shared& component) +{ + return id == component->id; +} + +bool Parser::parseSOS() +{ + using std::placeholders::_1; + + if (!m_frameHeader) { + ERROR("SOS Encountered before SOF"); + return false; + } + + INPUT_2BYTES(m_current.length, return false); + + size_t numComponents; + + INPUT_BYTE(numComponents, return false); + + if (m_current.length != (numComponents * 2 + 6) + || numComponents < 1 + || numComponents > MAX_COMPS_IN_SCAN) { + ERROR("Invalid SOS Length"); + return false; + } + + m_scanHeader.reset(new ScanHeader); + + m_scanHeader->numComponents = numComponents; + + for (size_t i(0); i < numComponents; ++i) + m_scanHeader->components[i].reset(); + + for (size_t i(0); i < numComponents; ++i) { + int id; + int c; + + INPUT_BYTE(id, return false); + + Components::iterator component = std::find_if( + m_frameHeader->components.begin(), + m_frameHeader->components.end(), + std::bind(&componentIdMatches, id, _1)); + + if (component == m_frameHeader->components.end() + || m_scanHeader->components[(*component)->index]) { + ERROR("Bad Component Id (%d)", id); + return false; + } + + INPUT_BYTE(c, return false); + + m_scanHeader->components[i] = *component; + (*component)->dcTableNumber = (c >> 4) & 15; + (*component)->acTableNumber = c & 15; + + /* This CSi (cc) should differ from the previous CSi */ + for (size_t pi(0); pi < i; ++pi) { + if (m_scanHeader->components[pi] == (*component)) { + ERROR("Bad Component Id (%d)", id); + return false; + } + } + } + + // The following are used only in progressive mode + // FIXME: validate these values according to JPEG specification + INPUT_BYTE(m_scanHeader->ss, return false); + INPUT_BYTE(m_scanHeader->se, return false); + INPUT_BYTE(m_scanHeader->ah, return false); + + m_scanHeader->al = m_scanHeader->ah & 15; + m_scanHeader->ah = (m_scanHeader->ah >> 4) & 15; + + m_sawSOS = true; + + return true; +} + +bool Parser::parseEOI() +{ + if (m_sawEOI) { + ERROR("Duplicate EOI encountered"); + return false; + } + + m_sawEOI = true; + + return true; +} + +bool Parser::parseDAC() +{ + INPUT_2BYTES(m_current.length, return false); + + long length = m_current.length - 2; + + while (length > 0) { + size_t index; + int value; + + INPUT_BYTE(index, return false); + INPUT_BYTE(value, return false); + + length -= 2; + + if (index < 0 || index >= (2 * NUM_ARITH_TBLS)) { + ERROR("Invalid DAC Index"); + return false; + } + + if (index >= NUM_ARITH_TBLS) { + m_arithACK[index - NUM_ARITH_TBLS] = value; + } else { + m_arithDCL[index] = value & 15; + m_arithDCU[index] = (value >> 4) & 15; + if (m_arithDCL[index] > m_arithDCU[index]) { + ERROR("Invalid DAC Value"); + return false; + } + } + } + + if (length != 0) { + ERROR("Invalid DAC Length"); + return false; + } + + return true; +} + +bool Parser::parseDQT() +{ + INPUT_2BYTES(m_current.length, return false); + + long length = m_current.length - 2; + + while (length > 0) { + int c; + + INPUT_BYTE(c, return false); + + const size_t index = c & 15; + const int precision = (c >> 4) & 15; + + if (index >= NUM_QUANT_TBLS) { + ERROR("Invalid quant table index encountered"); + return false; + } + + QuantTable::Shared& quantTable = m_quantTables[index]; + if (!quantTable) + quantTable.reset(new QuantTable); + + quantTable->precision = precision; + + for (size_t i(0); i < DCTSIZE2; ++i) { + if (precision) + INPUT_2BYTES(quantTable->values[i], return false); + else + INPUT_BYTE(quantTable->values[i], return false); + } + + const uint32_t nbytes = precision ? 2 : 1; + length -= (DCTSIZE2 * nbytes) + 1; + } + + if (length != 0) { + ERROR("Bad DQT length"); + return false; + } + + return true; +} + +bool Parser::parseDHT() +{ + INPUT_2BYTES(m_current.length, return false); + + long length = m_current.length - 2; + + while (length > 16) { + size_t index; + + INPUT_BYTE(index, return false); + + long count = 0; + std::vector codes(16, 0); + for (size_t i(0); i < 16; ++i) { + INPUT_BYTE(codes[i], return false); + count += codes[i]; + } + + length -= 1 + 16; + + if (count > 256 || count > length) { + ERROR("Bad Huff Table"); + return false; + } + + std::vector huffval(256, 0); + for (long i(0); i < count; ++i) + INPUT_BYTE(huffval[i], return false); + + length -= count; + + HuffTables* huffTables; + if (index & 0x10) { /* AC table definition */ + index -= 0x10; + huffTables = &m_acHuffTables; + } else { /* DC table definition */ + huffTables = &m_dcHuffTables; + } + + if (index < 0 || index >= NUM_HUFF_TBLS) { + ERROR("Bad Huff Table Index"); + return false; + } + + HuffTable::Shared& huffTable = (*huffTables)[index]; + if (!huffTable) + huffTable.reset(new HuffTable); + + std::memcpy(&huffTable->codes[0], &codes[0], + sizeof(huffTable->codes)); + std::memcpy(&huffTable->values[0], &huffval[0], + sizeof(huffTable->values)); + } + + if (length != 0) { + ERROR("Bad DHT Length"); + return false; + } + + return true; +} + +bool Parser::parseDRI() +{ + INPUT_2BYTES(m_current.length, return false); + + if (m_current.length != 4) { + ERROR("Bad DRI Length"); + return false; + } + + INPUT_2BYTES(m_restartInterval, return false); + + return true; +} + +} // namespace JPEG +} // namespace YamiParser diff --git a/codecparsers/jpegParser.h b/codecparsers/jpegParser.h new file mode 100644 index 0000000..9f3e3e9 --- /dev/null +++ b/codecparsers/jpegParser.h @@ -0,0 +1,267 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ---- + * + * Part of IJG's libjpeg library (primarily jdmarker.c) was used as a reference + * while implementing this parser. This implementation loosely reproduces some + * of the parsing logic found in the libjpeg jdmarker.c file. Although, this + * logic has been refactored using C++-style syntax and data structures and + * adjusted appropriately to fit into the overall libyami framework. Therefore, + * this implementation is considered to be partially derived from IJG's libjpeg. + * + * The following license preamble, below, is reproduced from libjpeg's + * jdmarker.c file. The README.ijg is also provided with this file: + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * Modified 2009-2013 by Guido Vollbeding. + * The jdmarker.c file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README.ijg file. + * + */ + +#ifndef jpegParser_h +#define jpegParser_h + +// library headers +#include "bitReader.h" +#include "common/Array.h" +#include "common/Functional.h" +#include "interface/VideoCommonDefs.h" + +// system headers +#include +#include + +namespace YamiParser { +namespace JPEG { + +const size_t DCTSIZE = 8; +const size_t DCTSIZE2 = 64; +const size_t NUM_QUANT_TBLS = 4; +const size_t NUM_HUFF_TBLS = 4; +const size_t NUM_ARITH_TBLS = 16; +const size_t MAX_COMPS_IN_SCAN = 4; + +/** + * JPEG marker codes + */ +enum Marker { + M_SOF0 = 0xc0, M_SOF1 = 0xc1, M_SOF2 = 0xc2, M_SOF3 = 0xc3, + M_SOF5 = 0xc5, M_SOF6 = 0xc6, M_SOF7 = 0xc7, M_JPG = 0xc8, + M_SOF9 = 0xc9, M_SOF10 = 0xca, M_SOF11 = 0xcb, M_SOF13 = 0xcd, + M_SOF14 = 0xce, M_SOF15 = 0xcf, M_DHT = 0xc4, M_DAC = 0xcc, + M_RST0 = 0xd0, M_RST1 = 0xd1, M_RST2 = 0xd2, M_RST3 = 0xd3, + M_RST4 = 0xd4, M_RST5 = 0xd5, M_RST6 = 0xd6, M_RST7 = 0xd7, + M_SOI = 0xd8, M_EOI = 0xd9, M_SOS = 0xda, M_DQT = 0xdb, + M_DNL = 0xdc, M_DRI = 0xdd, M_DHP = 0xde, M_EXP = 0xdf, + M_APP0 = 0xe0, M_APP1 = 0xe1, M_APP2 = 0xe2, M_APP3 = 0xe3, + M_APP4 = 0xe4, M_APP5 = 0xe5, M_APP6 = 0xe6, M_APP7 = 0xe7, + M_APP8 = 0xe8, M_APP9 = 0xe9, M_APP10 = 0xea, M_APP11 = 0xeb, + M_APP12 = 0xec, M_APP13 = 0xed, M_APP14 = 0xee, M_APP15 = 0xef, + M_JPG0 = 0xf0, M_JPG13 = 0xfd, M_COM = 0xfe, M_ERROR = 0x100 +}; + +struct QuantTable { + typedef std::shared_ptr Shared; + + std::array values; + int precision; +}; + +typedef std::array QuantTables; + +struct HuffTable { + typedef std::shared_ptr Shared; + + std::array codes; + std::array values; +}; + +typedef std::array HuffTables; + +struct Component { + typedef std::shared_ptr Shared; + + int id; + int index; + int hSampleFactor; + int vSampleFactor; + int quantTableNumber; + int dcTableNumber; + int acTableNumber; +}; + +typedef std::vector Components; +typedef std::array CurrComponents; + +struct Segment { + Segment() : marker(M_ERROR), position(0), length(0) { } + + Marker marker; + uint32_t position; + uint32_t length; +}; + +struct FrameHeader { + typedef std::shared_ptr Shared; + + bool isBaseline; + bool isProgressive; + bool isArithmetic; + int dataPrecision; + unsigned imageHeight; + unsigned imageWidth; + int maxVSampleFactor; + int maxHSampleFactor; + Components components; +}; + +struct ScanHeader { + typedef std::shared_ptr Shared; + + CurrComponents components; + size_t numComponents; + int ss; + int se; + int ah; + int al; +}; + +typedef std::array ArithmeticTable; + +class Defaults { +public: + static const Defaults& instance() { return s_instance; } + const HuffTables& acHuffTables() const { return m_acHuffTables; } + const HuffTables& dcHuffTables() const { return m_dcHuffTables; } + + /** + * @return the default luminance and chrominance quantization + * tables in zigzag order. + */ + const QuantTables& quantTables() const { return m_quantTables; } + +private: + Defaults(); + + static const Defaults s_instance; + + HuffTables m_acHuffTables; + HuffTables m_dcHuffTables; + QuantTables m_quantTables; +}; + +class Parser { +public: + typedef std::shared_ptr Shared; + + enum CallbackResult { + ParseContinue, + ParseSuspend + }; + + typedef std::function Callback; + typedef std::vector CallbackList; + typedef std::map Callbacks; + + Parser(const uint8_t* data, uint32_t size); + + virtual ~Parser() { } + + /** + * Parses the JPEG byte data. Notifies registered callbacks after each + * successfully parsed JPEG segment Marker. If a registered Callback + * returns ParseContinue, then this method continues parsing the JPEG byte + * data. If a Callback returns ParseSuspend, then this method returns + * control to the caller whom can call this method again to resume parsing + * the JPEG byte data. + * + * @retval true if parsing is successful + * @retval false if parsing is unsuccessful + */ + bool parse(); + + /** + * Register a Callback function for Marker. The Callback is called after + * the Marker is parsed by the parse() method. + */ + void registerCallback(const Marker&, const Callback&); + + /** + * Register a single Callback for all SOFn markers. + */ + void registerStartOfFrameCallback(const Callback&); + + /** + * @return the most current Segment parsed by the parse() method. + */ + const Segment& current() const { return m_current; } + const FrameHeader::Shared& frameHeader() const { return m_frameHeader; } + const ScanHeader::Shared& scanHeader() const { return m_scanHeader; } + const QuantTables& quantTables() const { return m_quantTables; } + const HuffTables& dcHuffTables() const { return m_dcHuffTables; } + const HuffTables& acHuffTables() const { return m_acHuffTables; } + unsigned restartInterval() const { return m_restartInterval; } + +private: + friend class JPEGParserTest; + + bool firstMarker(); + bool nextMarker(); + bool skipBytes(const uint32_t); + uint32_t currentBytePosition() const { return m_input.getPos() >> 3; } + CallbackResult notifyCallbacks() const; + + bool parseSOI(); + bool parseAPP(); + bool parseSOF(bool, bool, bool); + bool parseSOS(); + bool parseEOI(); + bool parseDAC(); + bool parseDQT(); + bool parseDHT(); + bool parseDRI(); + + BitReader m_input; + + const uint8_t* m_data; + uint32_t m_size; + + Segment m_current; + FrameHeader::Shared m_frameHeader; + ScanHeader::Shared m_scanHeader; + + QuantTables m_quantTables; + HuffTables m_dcHuffTables; + HuffTables m_acHuffTables; + + ArithmeticTable m_arithDCL; + ArithmeticTable m_arithDCU; + ArithmeticTable m_arithACK; + + Callbacks m_callbacks; + + bool m_sawSOI; + bool m_sawEOI; + bool m_sawSOS; + + unsigned m_restartInterval; +}; + +} // namespace JPEG +} // namespace YamiParser + +#endif // jpegParser_h diff --git a/codecparsers/jpegParser_unittest.cpp b/codecparsers/jpegParser_unittest.cpp new file mode 100644 index 0000000..ae87b29 --- /dev/null +++ b/codecparsers/jpegParser_unittest.cpp @@ -0,0 +1,540 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "jpegParser.h" + +// library headers +#include "common/unittest.h" + +// system headers +#include + +namespace YamiParser { +namespace JPEG { + +const static std::array g_SimpleJPEG = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x0a, 0x03, + 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, + 0x1f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, + 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, + 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, + 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, + 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, + 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, + 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc4, 0x00, + 0x1f, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, + 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, + 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, + 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, + 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, + 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, + 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, + 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, + 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, + 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xda, 0x00, + 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xfe, + 0x7b, 0xb4, 0xcd, 0x33, 0xee, 0xfc, 0xa7, 0x9c, 0x76, 0xfc, 0x7b, 0x8f, + 0xc3, 0x1f, 0xd7, 0x9a, 0xff, 0x00, 0x72, 0x7e, 0x90, 0xbf, 0x48, 0x3b, + 0xbc, 0x77, 0xfb, 0x6a, 0xff, 0x00, 0x97, 0x9b, 0x55, 0xd9, 0x59, 0xeb, + 0xf1, 0x34, 0x7f, 0x56, 0x7d, 0x1c, 0xbe, 0x8e, 0x97, 0xfa, 0x82, 0xfa, + 0x87, 0x4a, 0x7f, 0xf2, 0xeb, 0xc9, 0x2e, 0xdf, 0x77, 0xcb, 0xa6, 0xaf, + 0xad, 0x5d, 0x30, 0xe0, 0x7c, 0xa3, 0xa0, 0xee, 0x3d, 0x3e, 0xb5, 0xfe, + 0x62, 0x62, 0xbe, 0x90, 0xd1, 0xfa, 0xd6, 0x27, 0xfd, 0xb7, 0xfe, 0x62, + 0x2b, 0x7f, 0xcb, 0xc7, 0xff, 0x00, 0x3f, 0x24, 0x7f, 0xa9, 0x98, 0x5f, + 0xa3, 0xa4, 0x7e, 0xab, 0x86, 0xff, 0x00, 0x62, 0x5f, 0xee, 0xf4, 0x7f, + 0xe5, 0xd2, 0xff, 0x00, 0x9f, 0x71, 0xfe, 0xe8, 0x69, 0x8a, 0xbc, 0x70, + 0x3a, 0x0e, 0xc3, 0xd4, 0x55, 0xfd, 0x21, 0x31, 0x58, 0xaf, 0xf6, 0xef, + 0xf6, 0x9a, 0xff, 0x00, 0x15, 0x5f, 0xf9, 0x7d, 0x53, 0xfb, 0xdf, 0xde, + 0x23, 0xe8, 0xe3, 0x84, 0xc2, 0xdb, 0x2f, 0xff, 0x00, 0x66, 0xc3, 0xef, + 0x4b, 0xfe, 0x5c, 0xd3, 0xf2, 0xfe, 0xe9, 0xd5, 0xed, 0x5f, 0x41, 0xf9, + 0x0a, 0xff, 0x00, 0x31, 0x31, 0x58, 0xac, 0x4f, 0xd6, 0x71, 0x1f, 0xed, + 0x15, 0xff, 0x00, 0x8f, 0x5b, 0xfe, 0x5f, 0x54, 0xff, 0x00, 0x9f, 0x92, + 0xfe, 0xf1, 0xfe, 0xa5, 0xe1, 0x30, 0x98, 0x5f, 0xaa, 0xe1, 0xbf, 0xd9, + 0xb0, 0xff, 0x00, 0xee, 0xf4, 0x7f, 0xe5, 0xcd, 0x3f, 0xf9, 0xf7, 0x1f, + 0xee, 0x9f, 0xff, 0xd9 +}; + +class JPEGParserTest + : public ::testing::Test { + +protected: + +#define MEMBER_VARIABLE(result_type, var) \ + result_type& var(Parser& p) \ + { \ + return p.var; \ + } + + MEMBER_VARIABLE(BitReader, m_input); + MEMBER_VARIABLE(Segment, m_current); + MEMBER_VARIABLE(ScanHeader::Shared, m_scanHeader); + MEMBER_VARIABLE(FrameHeader::Shared, m_frameHeader); + MEMBER_VARIABLE(QuantTables, m_quantTables); + MEMBER_VARIABLE(HuffTables, m_dcHuffTables); + MEMBER_VARIABLE(HuffTables, m_acHuffTables); + MEMBER_VARIABLE(ArithmeticTable, m_arithDCL); + MEMBER_VARIABLE(ArithmeticTable, m_arithDCU); + MEMBER_VARIABLE(ArithmeticTable, m_arithACK); + MEMBER_VARIABLE(Parser::Callbacks, m_callbacks); + MEMBER_VARIABLE(bool, m_sawSOI); + MEMBER_VARIABLE(bool, m_sawEOI); + MEMBER_VARIABLE(bool, m_sawSOS); + MEMBER_VARIABLE(unsigned, m_restartInterval); + +#undef MEMBER_VARIABLE + +#define PARSE_MARKER(marker) \ + bool parse ## marker(Parser& p) \ + { \ + return p.parse ## marker(); \ + } + + PARSE_MARKER(SOI); + PARSE_MARKER(APP); + PARSE_MARKER(SOS); + PARSE_MARKER(EOI); + PARSE_MARKER(DAC); + PARSE_MARKER(DQT); + PARSE_MARKER(DHT); + PARSE_MARKER(DRI); + +#undef PARSE_MARKER + + bool parseSOF(Parser& p, bool isBaseline, bool isProgressive, bool isArithmetic) + { + return p.parseSOF(isBaseline, isProgressive, isArithmetic); + } + + void checkSimpleJPEG(const Parser& parser) + { + ASSERT_TRUE(parser.m_scanHeader.get() != NULL); + + EXPECT_TRUE(parser.m_input.end()); + EXPECT_EQ(M_EOI, parser.m_current.marker); + EXPECT_EQ(0u, parser.restartInterval()); + + ASSERT_TRUE(parser.m_frameHeader.get() != NULL); + EXPECT_EQ(10u, parser.m_frameHeader->imageWidth); + EXPECT_EQ(10u, parser.m_frameHeader->imageHeight); + EXPECT_EQ(8, parser.m_frameHeader->dataPrecision); + EXPECT_TRUE(parser.m_frameHeader->isBaseline); + EXPECT_FALSE(parser.m_frameHeader->isProgressive); + EXPECT_FALSE(parser.m_frameHeader->isArithmetic); + ASSERT_EQ(3u, parser.m_frameHeader->components.size()); + EXPECT_TRUE(parser.m_frameHeader->components[0].get() != NULL); + EXPECT_TRUE(parser.m_frameHeader->components[1].get() != NULL); + EXPECT_TRUE(parser.m_frameHeader->components[2].get() != NULL); + + EXPECT_TRUE(parser.quantTables()[0].get() != NULL); + EXPECT_TRUE(parser.quantTables()[1].get() != NULL); + EXPECT_TRUE(parser.quantTables()[2].get() == NULL); + EXPECT_TRUE(parser.quantTables()[3].get() == NULL); + + EXPECT_TRUE(parser.dcHuffTables()[0].get() != NULL); + EXPECT_TRUE(parser.dcHuffTables()[1].get() != NULL); + EXPECT_TRUE(parser.dcHuffTables()[2].get() == NULL); + EXPECT_TRUE(parser.dcHuffTables()[3].get() == NULL); + + EXPECT_TRUE(parser.acHuffTables()[0].get() != NULL); + EXPECT_TRUE(parser.acHuffTables()[1].get() != NULL); + EXPECT_TRUE(parser.acHuffTables()[2].get() == NULL); + EXPECT_TRUE(parser.acHuffTables()[3].get() == NULL); + } +}; + +#define JPEG_PARSER_TEST(name) \ + TEST_F(JPEGParserTest, name) + +JPEG_PARSER_TEST(Construct_Defaults) +{ + std::array data = {0x00}; + + Parser parser(&data[0], data.size()); + + EXPECT_FALSE(m_input(parser).end()); + EXPECT_EQ(m_current(parser).marker, M_ERROR); + + EXPECT_TRUE(m_frameHeader(parser).get() == NULL); + EXPECT_TRUE(m_scanHeader(parser).get() == NULL); + + EXPECT_EQ(m_quantTables(parser).size(), NUM_QUANT_TBLS); + for (size_t i(0); i < m_quantTables(parser).size(); ++i) + EXPECT_TRUE(m_quantTables(parser)[i].get() == NULL); + + EXPECT_EQ(m_dcHuffTables(parser).size(), NUM_HUFF_TBLS); + for (size_t i(0); i < m_dcHuffTables(parser).size(); ++i) + EXPECT_TRUE(m_dcHuffTables(parser)[i].get() == NULL); + + EXPECT_EQ(m_acHuffTables(parser).size(), NUM_HUFF_TBLS); + for (size_t i(0); i < m_acHuffTables(parser).size(); ++i) + EXPECT_TRUE(m_acHuffTables(parser)[i].get() == NULL); + + EXPECT_EQ(m_arithDCL(parser).size(), NUM_ARITH_TBLS); + EXPECT_EQ(m_arithDCU(parser).size(), NUM_ARITH_TBLS); + EXPECT_EQ(m_arithACK(parser).size(), NUM_ARITH_TBLS); + + EXPECT_EQ(m_callbacks(parser).size(), 0u); + + EXPECT_FALSE(m_sawSOI(parser)); + EXPECT_FALSE(m_sawEOI(parser)); + + EXPECT_EQ(m_restartInterval(parser), 0u); +} + +JPEG_PARSER_TEST(Construct_InvalidParams) +{ + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + + // invalid data pointer + EXPECT_DEATH(Parser(NULL, 10), ""); + + std::array data = {0x00}; + + // invalid size + Parser parser(&data[0], 0); + EXPECT_FALSE(parser.parse()); +} + +JPEG_PARSER_TEST(Parse_NoSOI) +{ + std::array data = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + Parser parser(&data[0], data.size()); + + EXPECT_FALSE(parser.parse()); + + EXPECT_EQ(parser.current().marker, M_ERROR); +} + +JPEG_PARSER_TEST(Parse_SOINotFirst) +{ + std::array data = { + 0x00, 0xFF, M_SOI, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + Parser parser(&data[0], data.size()); + + EXPECT_FALSE(parser.parse()); + + EXPECT_EQ(parser.current().marker, M_ERROR); +} + +JPEG_PARSER_TEST(Parse_SOIInvalid) +{ + std::array data = { + 0x00, M_SOI, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + Parser parser(&data[0], data.size()); + + EXPECT_FALSE(parser.parse()); + + EXPECT_EQ(parser.current().marker, M_ERROR); +} + +JPEG_PARSER_TEST(ParseSOI) +{ + std::array data = {0x00}; + + Parser parser(&data[0], data.size()); + + EXPECT_FALSE(m_sawSOI(parser)); + EXPECT_TRUE(parseSOI(parser)); + EXPECT_TRUE(m_sawSOI(parser)); + EXPECT_FALSE(parseSOI(parser)); +} + +JPEG_PARSER_TEST(ParseSOS_NoSOF) +{ + std::array data = {0x00}; + + Parser parser(&data[0], data.size()); + + EXPECT_TRUE(m_frameHeader(parser).get() == NULL); + EXPECT_FALSE(parseSOS(parser)); // returns false when SOF not seen +} + +JPEG_PARSER_TEST(ParseSOS_InvalidLength) +{ + std::array data = {0x00, 0x06, 0x00}; + + Parser parser(&data[0], data.size()); + + m_frameHeader(parser).reset(new FrameHeader); + + ASSERT_FALSE(m_input(parser).end()); + ASSERT_EQ(m_current(parser).length, 0u); + + EXPECT_FALSE(parseSOS(parser)); + EXPECT_TRUE(m_input(parser).end()); + EXPECT_EQ(m_current(parser).length, 6u); + + data[0] = 0x00; + data[1] = 0x0c; + data[2] = 0x00; + parser = Parser(&data[0], data.size()); + m_frameHeader(parser).reset(new FrameHeader); + + ASSERT_FALSE(m_input(parser).end()); + ASSERT_EQ(m_current(parser).length, 0u); + + EXPECT_FALSE(parseSOS(parser)); + EXPECT_TRUE(m_input(parser).end()); + EXPECT_EQ(m_current(parser).length, 12u); + + int nComponents = MAX_COMPS_IN_SCAN + 1; + unsigned length = nComponents * 2 + 6; + + ASSERT_LT(length, std::numeric_limits::max()); + + data[0] = 0x00; + data[1] = uint8_t(length); + data[2] = uint8_t(nComponents); + parser = Parser(&data[0], data.size()); + m_frameHeader(parser).reset(new FrameHeader); + + ASSERT_FALSE(m_input(parser).end()); + ASSERT_EQ(m_current(parser).length, 0u); + + EXPECT_FALSE(parseSOS(parser)); + EXPECT_TRUE(m_input(parser).end()); + EXPECT_EQ(m_current(parser).length, length); +} + +JPEG_PARSER_TEST(ParseSOS_BadComponentDescriptor) +{ + std::array data = {0x00, 0x0c, 0x3, 0x01}; + + Parser parser(&data[0], data.size()); + m_frameHeader(parser).reset(new FrameHeader); + + ASSERT_FALSE(m_input(parser).end()); + ASSERT_TRUE(m_scanHeader(parser).get() == NULL); + + EXPECT_FALSE(parseSOS(parser)); + EXPECT_TRUE(m_input(parser).end()); + ASSERT_TRUE(m_scanHeader(parser).get() != NULL); + EXPECT_EQ(m_scanHeader(parser)->numComponents, 3u); +} + +JPEG_PARSER_TEST(ParseSOS) +{ + std::array data = { + 0x00, 0x0c, + 0x03, 0x01, 0x11, 0x02, 0x10, 0x03, 0x01, 0x12, + 0x34, 0x56 + }; + + Parser parser(&data[0], data.size()); + + m_frameHeader(parser).reset(new FrameHeader); + m_frameHeader(parser)->components.resize(3); + for (size_t i(0); i < 3; ++i) { + m_frameHeader(parser)->components[i].reset(new Component); + m_frameHeader(parser)->components[i]->index = i; + m_frameHeader(parser)->components[i]->id = i + 1; + } + + ASSERT_FALSE(m_input(parser).end()); + ASSERT_TRUE(m_scanHeader(parser).get() == NULL); + ASSERT_EQ(m_current(parser).length, 0u); + + EXPECT_TRUE(parseSOS(parser)); + EXPECT_TRUE(m_input(parser).end()); + EXPECT_EQ(m_current(parser).length, 12u); + + ASSERT_TRUE(m_scanHeader(parser).get() != NULL); + EXPECT_EQ(m_scanHeader(parser)->numComponents, 3u); + ASSERT_TRUE(m_scanHeader(parser)->components[0].get() != NULL); + ASSERT_TRUE(m_scanHeader(parser)->components[1].get() != NULL); + ASSERT_TRUE(m_scanHeader(parser)->components[2].get() != NULL); + EXPECT_TRUE(m_scanHeader(parser)->components[3].get() == NULL); + + for (size_t i(0); i < 3; ++i) + EXPECT_EQ(m_scanHeader(parser)->components[i].get(), + m_frameHeader(parser)->components[i].get()); + + EXPECT_EQ(m_scanHeader(parser)->components[0]->dcTableNumber, 1); + EXPECT_EQ(m_scanHeader(parser)->components[0]->acTableNumber, 1); + + EXPECT_EQ(m_scanHeader(parser)->components[1]->dcTableNumber, 1); + EXPECT_EQ(m_scanHeader(parser)->components[1]->acTableNumber, 0); + + EXPECT_EQ(m_scanHeader(parser)->components[2]->dcTableNumber, 0); + EXPECT_EQ(m_scanHeader(parser)->components[2]->acTableNumber, 1); + + EXPECT_EQ(m_scanHeader(parser)->ss, 0x12); + EXPECT_EQ(m_scanHeader(parser)->se, 0x34); + EXPECT_EQ(m_scanHeader(parser)->ah, 0x5); + EXPECT_EQ(m_scanHeader(parser)->al, 0x6); +} + +JPEG_PARSER_TEST(Parse_Simple) +{ + Parser parser(&g_SimpleJPEG[0], g_SimpleJPEG.size()); + + EXPECT_TRUE(parser.parse()); + + checkSimpleJPEG(parser); + ASSERT_FALSE(HasFailure()); +} + +typedef std::map > Results; +Parser::CallbackResult simpleCallback(Results& results, const Parser& parser) +{ + results[parser.current().marker].push_back(parser.current()); + return Parser::ParseContinue; +} + +JPEG_PARSER_TEST(Parse_SimpleWithCallbacks) +{ + Parser parser(&g_SimpleJPEG[0], g_SimpleJPEG.size()); + Results results; + +#define registerCallback(id) \ + do { \ + parser.registerCallback(M_ ## id, \ + std::bind(&simpleCallback, std::ref(results), std::ref(parser))); \ + } while(0) + + registerCallback(SOI); + registerCallback(EOI); + registerCallback(APP0); + registerCallback(DQT); + registerCallback(SOF0); + registerCallback(DHT); + registerCallback(SOS); + +#undef registerCallback + + EXPECT_TRUE(parser.parse()); + + ASSERT_EQ(g_SimpleJPEG[1], M_SOI); + ASSERT_EQ(results[M_SOI].size(), 1u); + EXPECT_EQ(results[M_SOI][0].position, 1u); + EXPECT_EQ(results[M_SOI][0].length, 0u); + + ASSERT_EQ(g_SimpleJPEG[843], M_EOI); + ASSERT_EQ(results[M_EOI].size(), 1u); + EXPECT_EQ(results[M_EOI][0].position, 843u); + EXPECT_EQ(results[M_EOI][0].length, 0u); + + ASSERT_EQ(g_SimpleJPEG[3], M_APP0); + ASSERT_EQ(results[M_APP0].size(), 1u); + EXPECT_EQ(results[M_APP0][0].position, 3u); + EXPECT_EQ(results[M_APP0][0].length, 16u); + + ASSERT_EQ(g_SimpleJPEG[159], M_SOF0); + ASSERT_EQ(results[M_SOF0].size(), 1u); + EXPECT_EQ(results[M_SOF0][0].position, 159u); + EXPECT_EQ(results[M_SOF0][0].length, 17u); + + ASSERT_EQ(g_SimpleJPEG[610], M_SOS); + ASSERT_EQ(results[M_SOS].size(), 1u); + EXPECT_EQ(results[M_SOS][0].position, 610u); + EXPECT_EQ(results[M_SOS][0].length, 12u); + + ASSERT_EQ(g_SimpleJPEG[21], M_DQT); + ASSERT_EQ(g_SimpleJPEG[90], M_DQT); + ASSERT_EQ(results[M_DQT].size(), 2u); + EXPECT_EQ(results[M_DQT][0].position, 21u); + EXPECT_EQ(results[M_DQT][0].length, 67u); + EXPECT_EQ(results[M_DQT][1].position, 90u); + EXPECT_EQ(results[M_DQT][1].length, 67u); + + ASSERT_EQ(g_SimpleJPEG[178], M_DHT); + ASSERT_EQ(g_SimpleJPEG[211], M_DHT); + ASSERT_EQ(g_SimpleJPEG[394], M_DHT); + ASSERT_EQ(g_SimpleJPEG[427], M_DHT); + ASSERT_EQ(results[M_DHT].size(), 4u); + EXPECT_EQ(results[M_DHT][0].position, 178u); + EXPECT_EQ(results[M_DHT][0].length, 31u); + EXPECT_EQ(results[M_DHT][1].position, 211u); + EXPECT_EQ(results[M_DHT][1].length, 181u); + EXPECT_EQ(results[M_DHT][2].position, 394u); + EXPECT_EQ(results[M_DHT][2].length, 31u); + EXPECT_EQ(results[M_DHT][3].position, 427u); + EXPECT_EQ(results[M_DHT][3].length, 181u); + + checkSimpleJPEG(parser); + ASSERT_FALSE(HasFailure()); +} + +JPEG_PARSER_TEST(Parse_SimpleTruncated) +{ + const size_t size(g_SimpleJPEG.size()); + + for (size_t i(1); i < size; ++i) { + Parser parser(&g_SimpleJPEG[0], i); + + const bool result = parser.parse(); + + if (!m_sawSOS(parser)) { + EXPECT_FALSE(result) << i; + } else { + // If parser successfully parses an SOS but does not encounter an + // EOI marker at the end of the input, then it will insert a fake EOI + // marker and succeed to allow decoders to still attempt to decode + // the available entropy-coded data. + EXPECT_TRUE(result) << i; + } + } +} + +} // namespace JPEG +} // namespace YamiParser diff --git a/codecparsers/mpeg2_parser.cpp b/codecparsers/mpeg2_parser.cpp new file mode 100644 index 0000000..21032b1 --- /dev/null +++ b/codecparsers/mpeg2_parser.cpp @@ -0,0 +1,732 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This file contains an implementation of a Mpeg2 raw stream parser, +// as defined in ISO/IEC 13818-2 +// +// parser is highly influenced on the way other parsers are written in +// this project in particular vp8_parser. +// +// The parser is built under the logic that the client will separate the +// input stream in chunks of information separated by start codes. +// Client can decide if partial start_code streams are permitted and owns +// the decision to parse partial information + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// config.h defines macros for log.h to define log levels +#include "common/log.h" +#include "mpeg2_parser.h" +#include + +namespace YamiParser { +namespace MPEG2 { + +#define RETURN_ERROR(message) \ + do { \ + ERROR("Error while reading %s", #message); \ + bitReaderDeInit(); \ + return false; \ + } while (0) + +#define READ_MARKER_OR_RETURN(flag) \ + do { \ + if (!bitReaderReadMarker(flag)) \ + RETURN_ERROR(flag); \ + } while (0) + +#define READ_FLAG_OR_RETURN(flag) \ + do { \ + if (!bitReaderReadFlag(flag)) \ + RETURN_ERROR(flag); \ + } while (0) + +#define READ_BITS_OR_RETURN(bits, var) \ + do { \ + if (!bitReaderReadBits(bits, var)) \ + RETURN_ERROR(var); \ + } while (0) + +#define PEEK_BITS_OR_RETURN(bits, var) \ + do { \ + if (!bitReaderPeekBits(bits, var)) \ + RETURN_ERROR(var); \ + } while (0) + +#define PEEK_BOOL_OR_RETURN(var) \ + do { \ + if (!bitReaderPeekBool(var)) \ + RETURN_ERROR(var); \ + } while (0) + +#define SKIP_BITS_OR_RETURN(bits) \ + do { \ + if (!bitReaderSkipBits(bits)) \ + RETURN_ERROR("skip bits"); \ + } while (0) + +#define SKIP_BYTE_OR_RETURN() \ + do { \ + SKIP_BITS_OR_RETURN(8); \ + } while (0) + + // vlc increment values per code + // section B.1 table B-1 + + const uint8_t kVLCTable[][3] = { // num_of_bits, code, increment_value + { 1, 0x1, 1 }, + { 3, 0x3, 2 }, + { 3, 0x2, 3 }, + { 4, 0x3, 4 }, + { 4, 0x2, 5 }, + { 5, 0x3, 6 }, + { 5, 0x2, 7 }, + { 7, 0x7, 8 }, + { 7, 0x6, 9 }, + { 8, 0xb, 10 }, + { 8, 0xa, 11 }, + { 8, 0x9, 12 }, + { 8, 0x8, 13 }, + { 8, 0x7, 14 }, + { 8, 0x6, 15 }, + { 10, 0x17, 16 }, + { 10, 0x16, 17 }, + { 10, 0x15, 18 }, + { 10, 0x14, 19 }, + { 10, 0x13, 20 }, + { 10, 0x12, 21 }, + { 11, 0x23, 22 }, + { 11, 0x22, 23 }, + { 11, 0x21, 24 }, + { 11, 0x20, 25 }, + { 11, 0x1f, 26 }, + { 11, 0x1e, 27 }, + { 11, 0x1d, 28 }, + { 11, 0x1c, 29 }, + { 11, 0x1b, 30 }, + { 11, 0x1a, 31 }, + { 11, 0x19, 32 }, + { 11, 0x18, 33 }, + { 11, 0x8, 0xFF }, + }; + + // default matrix for intra blocks + // section 6.3.7 + const static uint8_t kDefaultIntraBlockMatrix[64] + = { 8, 16, 16, 19, 16, 19, 22, 22, 22, 22, 22, 22, 26, 24, 26, 27, + 27, 27, 26, 26, 26, 26, 27, 27, 27, 29, 29, 29, 34, 34, 34, 29, + 29, 29, 27, 27, 29, 29, 32, 32, 34, 34, 37, 38, 37, 35, 35, 34, + 35, 38, 38, 40, 40, 40, 48, 48, 46, 46, 56, 56, 58, 69, 69, 83 }; + + // default matrix for non-intra blocks + const static uint8_t kDefaultNonIntraBlockMatrix[64] + = { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; + + Slice::Slice() { memset(this, 0, sizeof(*this)); } + + QuantMatrices::QuantMatrices() { memset(this, 0, sizeof(*this)); } + + QuantMatrixExtension::QuantMatrixExtension() + { + memset(this, 0, sizeof(*this)); + } + + PictureCodingExtension::PictureCodingExtension() + { + memset(this, 0, sizeof(*this)); + } + + PictureHeader::PictureHeader() { memset(this, 0, sizeof(*this)); } + + GOPHeader::GOPHeader() { memset(this, 0, sizeof(*this)); } + + SeqExtension::SeqExtension() { memset(this, 0, sizeof(*this)); } + + SeqHeader::SeqHeader() { memset(this, 0, sizeof(*this)); } + + StreamHeader::StreamHeader() { memset(this, 0, sizeof(*this)); } + + Parser::Parser() + { + } + + Parser::~Parser() {} + + bool Parser::nextStartCode(const StreamHeader* shdr, StartCodeType& start_code) + { + start_code + = static_cast(shdr->nalData[kStartCodePrefixSize]); + return true; + } + + bool Parser::parseSlice(const StreamHeader* shdr) + { + uint32_t verticalSize; + int32_t nalSize = shdr->nalSize; + const uint8_t* nalData = shdr->nalData; + bool marker; + + if (shdr->nalSize < kStartCodeSize + 1) { + ERROR("Incomplete slice header"); + return false; + } + + m_slice = Slice(); + + m_slice.sliceData = nalData; + m_slice.sliceDataSize = nalSize; + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + m_slice.verticalPosition = nalData[0]; + + SKIP_BYTE_OR_RETURN(); // skip start code + + // parse one slice + + verticalSize = (m_sequenceExtension.vertical_size_extension & 0x3) + | (m_sequenceHdr.vertical_size_value & 0xFFF); + + if (verticalSize > 2800) { + // really big picture + READ_BITS_OR_RETURN( + 3, &(m_slice.slice_vertical_position_extension)); + m_slice.macroblockRow + = (m_slice.slice_vertical_position_extension << 7) + + m_slice.verticalPosition - 1; + } else { + m_slice.macroblockRow = m_slice.verticalPosition - 1; + } + + READ_BITS_OR_RETURN(5, &(m_slice.quantiser_scale_code)); + PEEK_BOOL_OR_RETURN(&marker); + if (marker) { + // read more intra bits + READ_FLAG_OR_RETURN(&(m_slice.intra_slice_flag)); + READ_FLAG_OR_RETURN(&(m_slice.intra_slice)); + READ_BITS_OR_RETURN(7, &(m_slice.reserved_bits)); + + PEEK_BOOL_OR_RETURN(&marker); + while (marker) { + // extra_information_slice + READ_FLAG_OR_RETURN(&(m_slice.extra_bit_slice)); + if (!m_slice.extra_bit_slice) { + ERROR("Bad extra bit slice"); + bitReaderDeInit(); + return false; + } + SKIP_BYTE_OR_RETURN(); + PEEK_BOOL_OR_RETURN(&marker); + } + } + + READ_FLAG_OR_RETURN(&(m_slice.extra_bit_slice)); + + if (m_slice.extra_bit_slice) { + ERROR("Bad extra bit slice"); + bitReaderDeInit(); + return false; + } + + // rest of slice is macro block information, decoder can process it + // as long as the first macroblock_icrement is known + + // sliceHeaderSize is given in bits + m_slice.sliceHeaderSize = bitReaderCurrentPosition(); + + if (!calculateMBColumn()) + return false; + + + DEBUG("slice header size : %" PRIu64 "", + m_slice.sliceHeaderSize); + DEBUG("slice number : %x", + m_slice.verticalPosition); + DEBUG("slice_vertical_position_extension : %x", + m_slice.slice_vertical_position_extension); + DEBUG("quantiser_scale_code : %x", + m_slice.quantiser_scale_code); + DEBUG("intra_slice_flag : %x", + m_slice.intra_slice_flag); + DEBUG("intra_slice : %x", + m_slice.intra_slice); + DEBUG("extra_bit_slice : %x", + m_slice.extra_bit_slice); + DEBUG("slice size : %" PRIu64 "", + m_slice.sliceDataSize); + DEBUG("size left on buffer : %d", nalSize); + DEBUG("slice data : %p", + m_slice.sliceData); + DEBUG("macroblockRow : %d", + m_slice.macroblockRow); + DEBUG("macroblockColumn : %d", + m_slice.macroblockColumn); + + bitReaderDeInit(); + return true; + } + + bool Parser::calculateMBColumn() + { + uint32_t bitsToParse; + uint32_t mbVLC, mbINC = 0, totalMBINC = 0; + do { + for (uint8_t i = 0; i < 34; i++) { + bitsToParse = kVLCTable[i][0]; + PEEK_BITS_OR_RETURN(bitsToParse, &mbVLC); + if (mbVLC == kVLCTable[i][1]) { + mbINC = kVLCTable[i][2]; + break; + } + } + if (mbINC == 255) + totalMBINC += 33; + else + totalMBINC += mbINC; + SKIP_BITS_OR_RETURN(bitsToParse); + } while (mbINC == 255); + + m_slice.macroblockColumn = totalMBINC - 1; + return true; + } + + bool Parser::parsePictureHeader(const StreamHeader* shdr) + { + PictureCodingType picture_type; + const uint8_t *nalData= shdr->nalData; + int32_t nalSize = shdr->nalSize; + + // minium length required on picture header buffer + if (nalSize < (kStartCodeSize + 3)) { + ERROR("Incomplete Picture Header"); + return false; + } + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + SKIP_BYTE_OR_RETURN(); + + READ_BITS_OR_RETURN(10, &(m_pictureHeader.temporal_reference)); + READ_BITS_OR_RETURN(3, &(m_pictureHeader.picture_coding_type)); + picture_type = static_cast( + m_pictureHeader.picture_coding_type); + READ_BITS_OR_RETURN(16, &(m_pictureHeader.vbv_delay)); + + if (picture_type == kPFrame || picture_type == kBFrame) { + READ_FLAG_OR_RETURN(&(m_pictureHeader.full_pel_forward_vector)); + READ_BITS_OR_RETURN(3, &(m_pictureHeader.forward_f_code)); + } + + if (picture_type == kBFrame) { + READ_FLAG_OR_RETURN(&(m_pictureHeader.full_pel_backward_vector)); + READ_BITS_OR_RETURN(3, &(m_pictureHeader.backward_f_code)); + } + + for (;;) { + READ_FLAG_OR_RETURN(&(m_pictureHeader.extra_bit_picture)); + if (m_pictureHeader.extra_bit_picture == 1) { + // decoder shall skip extra_information_picture byte + SKIP_BYTE_OR_RETURN(); + } else { + break; + } + } + + DEBUG("temporal_reference : %x", + m_pictureHeader.temporal_reference); + DEBUG("picture_coding_type : %x", + m_pictureHeader.picture_coding_type); + DEBUG("vbv_delay : %x", m_pictureHeader.vbv_delay); + DEBUG("full_pel_forward_vector : %x", + m_pictureHeader.full_pel_forward_vector); + DEBUG("forward_f_code : %x", m_pictureHeader.forward_f_code); + DEBUG("full_pel_backward_vector : %x", + m_pictureHeader.full_pel_backward_vector); + DEBUG("backward_f_code : %x", + m_pictureHeader.backward_f_code); + DEBUG("extra_bit_picture : %x", + m_pictureHeader.extra_bit_picture); + + bitReaderDeInit(); + + return true; + } + + bool Parser::parseGOPHeader(const StreamHeader* shdr) + { + const uint8_t *nalData= shdr->nalData; + int32_t nalSize = shdr->nalSize; + + if (nalSize < (kStartCodeSize + 3)) { + ERROR("Incomplete GOP Header"); + return false; + } + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + + SKIP_BYTE_OR_RETURN(); // skip start_sequence_code + + READ_FLAG_OR_RETURN(&(m_GOPHeader.drop_frame_flag)); + READ_BITS_OR_RETURN(5, &(m_GOPHeader.time_code_hours)); + READ_BITS_OR_RETURN(6, &(m_GOPHeader.time_code_minutes)); + + READ_MARKER_OR_RETURN(true); + + READ_BITS_OR_RETURN(6, &(m_GOPHeader.time_code_seconds)); + READ_BITS_OR_RETURN(6, &(m_GOPHeader.time_code_pictures)); + READ_FLAG_OR_RETURN(&(m_GOPHeader.closed_gop)); + READ_FLAG_OR_RETURN(&(m_GOPHeader.broken_link)); + // five marker bits all should be 0 + for (uint8_t i(0); i < 5; ++i) { + READ_MARKER_OR_RETURN(false); + } + + DEBUG("drop_frame_flag : %x", m_GOPHeader.drop_frame_flag); + DEBUG("time_code_hours : %x", m_GOPHeader.time_code_hours); + DEBUG("time_code_minutes : %x", m_GOPHeader.time_code_minutes); + DEBUG("time_code_seconds : %x", m_GOPHeader.time_code_seconds); + DEBUG("time_code_pictures : %x", m_GOPHeader.time_code_pictures); + DEBUG("closed_gop : %x", m_GOPHeader.closed_gop); + + bitReaderDeInit(); + + return true; + } + + bool Parser::readQuantMatrixOrDefault(bool& loadMatrix, uint8_t matrix[], + const uint8_t defaultMatrix[]) + { + if (!readQuantMatrix(loadMatrix, matrix)) + return false; + + if (!loadMatrix) { + memcpy(matrix, defaultMatrix, 64); + loadMatrix = true; + } + return true; + } + + bool Parser::readQuantMatrix(bool& loadMatrix, uint8_t matrix[]) + { + + READ_FLAG_OR_RETURN(&loadMatrix); + + if (loadMatrix) { + // read 8 bits *64 from the stream + uint32_t value; + for (uint8_t i(0); i < 64; ++i) { + READ_BITS_OR_RETURN(8, &value); + matrix[i] = value; + } + } + return true; + } + + bool Parser::parseQuantMatrixExtension(const StreamHeader* shdr) + { + ExtensionIdentifierType extID; + const uint8_t* nalData = shdr->nalData; + int32_t nalSize = shdr->nalSize; + QuantMatrices *quantMatrices = &m_quantMatrixExtension.quantizationMatrices; + + if (nalSize < kStartCodeSize) { + ERROR("Incomplete Quant Extension Header"); + return false; + } + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + SKIP_BYTE_OR_RETURN(); // skip start_sequence_code + + m_quantMatrixExtension = QuantMatrixExtension(); + + // extension_start_code_identifier + READ_BITS_OR_RETURN( + 4, &(m_quantMatrixExtension.extension_start_code_identifier)); + + extID = static_cast( + m_quantMatrixExtension.extension_start_code_identifier); + + if (extID != kQuantizationMatrix) { + ERROR("Wrong extension id type"); + bitReaderDeInit(); + return false; + } + + if (!readQuantMatrix(quantMatrices->load_intra_quantiser_matrix, + quantMatrices->intra_quantiser_matrix)) + return false; + + if (!readQuantMatrix(quantMatrices->load_non_intra_quantiser_matrix, + quantMatrices->non_intra_quantiser_matrix)) + return false; + + if (!readQuantMatrix(quantMatrices->load_chroma_intra_quantiser_matrix, + quantMatrices->chroma_intra_quantiser_matrix)) + return false; + + if (!readQuantMatrix( + quantMatrices->load_chroma_non_intra_quantiser_matrix, + quantMatrices->chroma_non_intra_quantiser_matrix)) + return false; + + DEBUG("load_intra_quantiser_matrix : %x", + quantMatrices->load_intra_quantiser_matrix); + DEBUG("load_non_intra_quantiser_matrix : %x", + quantMatrices->load_non_intra_quantiser_matrix); + DEBUG("load_chroma_intra_quantiser_matrix : %x", + quantMatrices->load_chroma_intra_quantiser_matrix); + DEBUG("load_chroma_non_intra_quantiser_matrix : %x", + quantMatrices->load_chroma_non_intra_quantiser_matrix); + + bitReaderDeInit(); + return true; + } + + bool Parser::parsePictureCodingExtension(const StreamHeader* shdr) + { + ExtensionIdentifierType extID; + const uint8_t *nalData= shdr->nalData; + int32_t nalSize = shdr->nalSize; + + if (nalSize < (kStartCodeSize + 4)) { + ERROR("Incomplete PictureCodingExtension Header"); + return false; + } + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + SKIP_BYTE_OR_RETURN(); // skip start_sequence_code + + // extension_start_code_identifier + READ_BITS_OR_RETURN( + 4, &(m_pictureCodingExtension.extension_start_code_identifier)); + + extID = static_cast( + m_pictureCodingExtension.extension_start_code_identifier); + + if (extID != kPictureCoding) { + ERROR("Wrong extension id type"); + bitReaderDeInit(); + return false; + } + + READ_BITS_OR_RETURN(4, &(m_pictureCodingExtension.f_code[0][0])); + READ_BITS_OR_RETURN(4, &(m_pictureCodingExtension.f_code[0][1])); + READ_BITS_OR_RETURN(4, &(m_pictureCodingExtension.f_code[1][0])); + READ_BITS_OR_RETURN(4, &(m_pictureCodingExtension.f_code[1][1])); + READ_BITS_OR_RETURN(2, &(m_pictureCodingExtension.intra_dc_precision)); + READ_BITS_OR_RETURN(2, &(m_pictureCodingExtension.picture_structure)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.top_field_first)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.frame_pred_frame_dct)); + READ_FLAG_OR_RETURN( + &(m_pictureCodingExtension.concealment_motion_vectors)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.q_scale_type)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.intra_vlc_format)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.alternate_scan)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.repeat_first_field)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.chrome_420_type)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.progressive_frame)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.composite_display_flag)); + + if (m_pictureCodingExtension.composite_display_flag) { + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.v_axis)); + READ_BITS_OR_RETURN(3, &(m_pictureCodingExtension.field_sequence)); + READ_FLAG_OR_RETURN(&(m_pictureCodingExtension.sub_carrier)); + READ_BITS_OR_RETURN(7, &(m_pictureCodingExtension.burst_amplitude)); + READ_BITS_OR_RETURN(8, + &(m_pictureCodingExtension.sub_carrier_phase)); + + } + + DEBUG("f_code_0_0 : %x", + m_pictureCodingExtension.f_code[0][0]); + DEBUG("f_code_0_1 : %x", + m_pictureCodingExtension.f_code[0][1]); + DEBUG("f_code_1_0 : %x", + m_pictureCodingExtension.f_code[1][0]); + DEBUG("f_code_1_1 : %x", + m_pictureCodingExtension.f_code[1][1]); + DEBUG("intra_dc_precision : %x", + m_pictureCodingExtension.intra_dc_precision); + DEBUG("picture_structure : %x", + m_pictureCodingExtension.picture_structure); + DEBUG("top_field_first : %x", + m_pictureCodingExtension.top_field_first); + DEBUG("frame_pred_frame_dct : %x", + m_pictureCodingExtension.frame_pred_frame_dct); + DEBUG("concealment_motion_vectors : %x", + m_pictureCodingExtension.concealment_motion_vectors); + DEBUG("q_scale_type : %x", + m_pictureCodingExtension.q_scale_type); + DEBUG("intra_vlc_format : %x", + m_pictureCodingExtension.intra_vlc_format); + DEBUG("alternate_scan : %x", + m_pictureCodingExtension.alternate_scan); + DEBUG("repeat_first_field : %x", + m_pictureCodingExtension.repeat_first_field); + DEBUG("chrome_420_type : %x", + m_pictureCodingExtension.chrome_420_type); + DEBUG("progressive_frame : %x", + m_pictureCodingExtension.progressive_frame); + DEBUG("composite_display_flag : %x", + m_pictureCodingExtension.composite_display_flag); + + bitReaderDeInit(); + + return true; + } + + bool Parser::parseSequenceExtension(const StreamHeader* shdr) + { + ExtensionIdentifierType extID; + const uint8_t *nalData= shdr->nalData; + int32_t nalSize = shdr->nalSize; + + if (nalSize < (kStartCodeSize + 5)) { + ERROR("Incomplete Sequence Extension"); + return false; + } + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + SKIP_BYTE_OR_RETURN(); + + READ_BITS_OR_RETURN( + 4, &(m_sequenceExtension.extension_start_code_identifier)); + + extID = static_cast( + m_sequenceExtension.extension_start_code_identifier); + + if (extID != kSequence) { + ERROR("Wrong extension id type %d", extID); + bitReaderDeInit(); + return false; + } + + READ_BITS_OR_RETURN(8, + &(m_sequenceExtension.profile_and_level_indication)); + READ_FLAG_OR_RETURN(&(m_sequenceExtension.progressive_sequence)); + READ_BITS_OR_RETURN(2, &(m_sequenceExtension.chroma_format)); + READ_BITS_OR_RETURN(2, &(m_sequenceExtension.horizontal_size_extension)); + READ_BITS_OR_RETURN(2, &(m_sequenceExtension.vertical_size_extension)); + READ_BITS_OR_RETURN(12, &(m_sequenceExtension.bit_rate_extension)); + + READ_MARKER_OR_RETURN(true); + + READ_BITS_OR_RETURN(8, &(m_sequenceExtension.vbv_buffer_size_extension)); + READ_FLAG_OR_RETURN(&(m_sequenceExtension.low_delay)); + READ_BITS_OR_RETURN(2, &(m_sequenceExtension.frame_rate_extension_n)); + READ_BITS_OR_RETURN(5, &(m_sequenceExtension.frame_rate_extension_d)); + + DEBUG("extension_start_code_identifier : %x", + m_sequenceExtension.extension_start_code_identifier); + DEBUG("profile_and_level_indication : %x", + m_sequenceExtension.profile_and_level_indication); + DEBUG("progressive_sequence : %x", + m_sequenceExtension.progressive_sequence); + DEBUG("chroma_format : %x", + m_sequenceExtension.chroma_format); + DEBUG("horizontal_size_extension : %x", + m_sequenceExtension.horizontal_size_extension); + DEBUG("vertical_size_extension : %x", + m_sequenceExtension.vertical_size_extension); + DEBUG("bit_rate_extension : %x", + m_sequenceExtension.bit_rate_extension); + DEBUG("vbv_buffer_size_extension : %x", + m_sequenceExtension.vbv_buffer_size_extension); + DEBUG("low_delay : %x", + m_sequenceExtension.low_delay); + DEBUG("frame_rate_extension_n : %x", + m_sequenceExtension.frame_rate_extension_n); + DEBUG("frame_rate_extension_d : %x", + m_sequenceExtension.frame_rate_extension_d); + + bitReaderDeInit(); + + return true; + } + + bool Parser::parseSequenceHeader(const StreamHeader* shdr) + { + const uint8_t* nalData = shdr->nalData; + int32_t nalSize = shdr->nalSize; + QuantMatrices* quantMatrices = &m_sequenceHdr.quantizationMatrices; + + if (nalSize < (kStartCodeSize + 7)) { + ERROR("Incomplete Sequence Header"); + return false; + } + + m_sequenceHdr = SeqHeader(); + + BitReader bitReader(nalData, nalSize); + bitReaderInit(&bitReader); + + SKIP_BYTE_OR_RETURN(); + + READ_BITS_OR_RETURN(12, &(m_sequenceHdr.horizontal_size_value)); + READ_BITS_OR_RETURN(12, &(m_sequenceHdr.vertical_size_value)); + READ_BITS_OR_RETURN(4, &(m_sequenceHdr.aspect_ratio_info)); + READ_BITS_OR_RETURN(4, &(m_sequenceHdr.frame_rate_code)); + READ_BITS_OR_RETURN(18, &(m_sequenceHdr.bit_rate_value)); + + READ_MARKER_OR_RETURN(true); + + READ_BITS_OR_RETURN(10, &(m_sequenceHdr.vbv_buffer_size_value)); + READ_FLAG_OR_RETURN(&(m_sequenceHdr.constrained_params_flag)); + + if (!readQuantMatrixOrDefault(quantMatrices->load_intra_quantiser_matrix, + quantMatrices->intra_quantiser_matrix, + &kDefaultIntraBlockMatrix[0])) + return false; + + if (!readQuantMatrixOrDefault(quantMatrices->load_non_intra_quantiser_matrix, + quantMatrices->non_intra_quantiser_matrix, + &kDefaultNonIntraBlockMatrix[0])); + + DEBUG("horizontal_size_value : %x", + m_sequenceHdr.horizontal_size_value); + DEBUG("vertical_size_value : %x", + m_sequenceHdr.vertical_size_value); + DEBUG("aspect_ratio_info : %x", + m_sequenceHdr.aspect_ratio_info); + DEBUG("frame_rate_code : %x", + m_sequenceHdr.frame_rate_code); + DEBUG("bit_rate_value : %x", + m_sequenceHdr.bit_rate_value); + DEBUG("vbv_buffer_size_value : %x", + m_sequenceHdr.vbv_buffer_size_value); + DEBUG("constrained_params_flag : %x", + m_sequenceHdr.constrained_params_flag); + DEBUG("load_intra_quantiser_matrix : %x", + quantMatrices->load_intra_quantiser_matrix); + DEBUG("load_non_intra_quantiser_matrix : %x", + quantMatrices->load_non_intra_quantiser_matrix); + + bitReaderDeInit(); + + return true; + } + +} // namespace MPEG2 +} // namespace YamiParser diff --git a/codecparsers/mpeg2_parser.h b/codecparsers/mpeg2_parser.h new file mode 100644 index 0000000..cb8304f --- /dev/null +++ b/codecparsers/mpeg2_parser.h @@ -0,0 +1,423 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This file contains an implementation of a Mpeg2 raw stream parser, +// as defined in ISO/IEC 13818-2 +// +// parser is highly influenced on the way other parsers are written in +// this project in particular vp8_parser. +// +// The parser is built under the logic that the client will separate the +// input stream in chunks of information separated by start codes. +// Client can decide if partial start_code streams are permitted and owns +// the decision to parse partial information + +#ifndef mpeg2_parser_h +#define mpeg2_parser_h + +// local headers +#include "common/NonCopyable.h" +#include "bitReader.h" +#include "VideoCommonDefs.h" + +// system headers +#include +#include + +namespace YamiParser { +namespace MPEG2 { + + // See spec for definitions of values/fields. + + enum PictureCodingType { + kIFrame = 1, + kPFrame, + kBFrame, + }; + + enum StartCodeSize { + kStartCodePrefixSize = 0, + kStartCodeSize, + }; + + enum ExtensionIdentifierType { + kSequence = 1, + kSequenceDisplay, + kQuantizationMatrix, + kSequenceScalable = 5, + kPictureDisplay = 7, + kPictureCoding, + kPictureSpatialScalable, + kPictureTempralScalable, + }; + + enum StartCodeType { + MPEG2_INVALID_START_CODE = -1, + MPEG2_PICTURE_START_CODE = 0x00, + MPEG2_SLICE_START_CODE_MIN, + MPEG2_SLICE_START_CODE_MAX = 0xaf, + MPEG2_RESERVED_CODE_0, + MPEG2_RESERVED_CODE_1, + MPEG2_USER_DATA_START_CODE, + MPEG2_SEQUENCE_HEADER_CODE, + MPEG2_SEQUENCE_ERROR_CODE, + MPEG2_EXTENSION_START_CODE, + MPEG2_RESERVED_CODE_2, + MPEG2_SEQUENCE_END_CODE, + MPEG2_GROUP_START_CODE, + }; + + enum SystemStartCodeType { + MPEG2_PROGRAM_END_CODE = 0xb9, + MPEG2_PACK_HEADER_CODE, + MPEG2_SYSTEM_HEADER_CODE, + MPEG2_PROGRAM_STREAM_MAP_CODE, + MPEG2_PRIVATE_STREAM_CODE_1, + MPEG2_PADDING_STREAM_CODE, + MPEG2_PRIVATE_STREAM_CODE_2, + MPEG2_AUDIO_PES_CODE_MIN = 0xc0, + MPEG2_AUDIO_PES_CODE_MAX = 0xdf, + MPEG2_VIDEO_PES_CODE_MIN = 0xe0, + MPEG2_VIDEO_PES_CODE_MAX = 0xef, + MPEG2_ECM_STREAM_CODE = 0xf0, + MPEG2_EMM_STREAM_CODE, + MPEG2_DSMCC_STREAM_CODE, + MPEG2_13522_STREAM_CODE, + MPEG2_H_222_TYPE_A_CODE, + MPEG2_H_222_TYPE_B_CODE, + MPEG2_H_222_TYPE_C_CODE, + MPEG2_H_222_TYPE_D_CODE, + MPEG2_H_222_TYPE_E_CODE, + + }; + + enum ParserResult { + MPEG2_PARSER_OK = 0, + MPEG2_PARSER_BROKEN_DATA, + MPEG2_PARSER_ERROR, + }; + + enum ProfileType { + MPEG2_PROFILE_HIGH = 1, + MPEG2_PROFILE_SPATIALLY_SCALABLE, + MPEG2_PROFILE_SNR_SCALABLE, + MPEG2_PROFILE_MAIN, + MPEG2_PROFILE_SIMPLE, + }; + + enum LevelType { + MPEG2_LEVEL_HIGH = 4, + MPEG2_LEVEL_HIGH_1440 = 6, + MPEG2_LEVEL_MAIN = 8, + MPEG2_LEVEL_LOW = 10, + }; + + struct StreamHeader { + StreamHeader(); + + const uint8_t* data; + off_t streamSize; + const uint8_t* nalData; + int32_t nalSize; + uint64_t time_stamp; + }; + + struct QuantMatrices { + QuantMatrices(); + + bool load_intra_quantiser_matrix; + uint8_t intra_quantiser_matrix[64]; + bool load_non_intra_quantiser_matrix; + uint8_t non_intra_quantiser_matrix[64]; + bool load_chroma_intra_quantiser_matrix; + uint8_t chroma_intra_quantiser_matrix[64]; + bool load_chroma_non_intra_quantiser_matrix; + uint8_t chroma_non_intra_quantiser_matrix[64]; + + }; + + // ISO/IEC spec section 6.2.2.1 + struct SeqHeader { + SeqHeader(); + + uint32_t horizontal_size_value; + uint32_t vertical_size_value; + uint32_t aspect_ratio_info; + uint32_t frame_rate_code; + uint32_t bit_rate_value; + bool marker_bit; + uint32_t vbv_buffer_size_value; + bool constrained_params_flag; + QuantMatrices quantizationMatrices; + }; + + // ISO/IEC spec section 6.2.2.3 + struct SeqExtension { + SeqExtension(); + + uint32_t extension_start_code_identifier; + uint32_t profile_and_level_indication; + bool progressive_sequence; + uint32_t chroma_format; + uint32_t horizontal_size_extension; + uint32_t vertical_size_extension; + uint32_t bit_rate_extension; + bool marker_bit; + uint32_t vbv_buffer_size_extension; + bool low_delay; + uint32_t frame_rate_extension_n; + uint32_t frame_rate_extension_d; + }; + + // ISO/IEC spec section 6.2.2.6 and 6.3.9 + struct GOPHeader { + GOPHeader(); + + bool drop_frame_flag; + uint32_t time_code_hours; + uint32_t time_code_minutes; + bool marker_bit; + uint32_t time_code_seconds; + uint32_t time_code_pictures; + bool closed_gop; + bool broken_link; + }; + + // ISO/IEC spec section 6.2.3 + struct PictureHeader { + PictureHeader(); + + uint32_t temporal_reference; + uint32_t picture_coding_type; + uint32_t vbv_delay; + bool full_pel_forward_vector; + uint32_t forward_f_code; + bool full_pel_backward_vector; + uint32_t backward_f_code; + bool extra_bit_picture; + }; + + // ISO/IEC spec section 6.2.3.1 + struct PictureCodingExtension { + PictureCodingExtension(); + + uint32_t extension_start_code_identifier; + uint32_t f_code[2][2]; // forward_horizontal + // forward_vertical + // backward_horizontal + // backward_vertical + uint32_t intra_dc_precision; + uint32_t picture_structure; + bool top_field_first; + bool frame_pred_frame_dct; + bool concealment_motion_vectors; + bool q_scale_type; + bool intra_vlc_format; + bool alternate_scan; + bool repeat_first_field; + bool chrome_420_type; + bool progressive_frame; + bool composite_display_flag; + bool v_axis; + uint32_t field_sequence; + bool sub_carrier; + uint32_t burst_amplitude; + uint32_t sub_carrier_phase; + }; + + // ISO/IEC spec section 6.2.3.2 + struct QuantMatrixExtension { + QuantMatrixExtension(); + + uint32_t extension_start_code_identifier; + QuantMatrices quantizationMatrices; + }; + + struct Slice { + Slice(); + + // helper variables + const uint8_t* sliceData; + uint64_t sliceDataSize; + uint64_t sliceHeaderSize; // in bits + uint32_t verticalPosition; + uint32_t macroblockRow; + uint32_t macroblockColumn; + // spec variables + uint32_t slice_vertical_position_extension; + uint32_t priority_breakpoint; + uint32_t quantiser_scale_code; + bool intra_slice_flag; + bool intra_slice; + uint32_t reserved_bits; + bool extra_bit_slice; + uint32_t extra_information_slice; + }; + + // A parser for raw Mpeg2 streams as specified in ISO/IEC 13818-2. + class Parser { + public: + Parser(); + ~Parser(); + + // Try to parse exactly the information of interest in a Mpeg2 raw + // stream + // Client can seek for the next start code and then parse it as required + + // parseSequenceHeader will parse a SequenceHeader according to the spec + // storing the information in the m_sequenceHdr structure and updating + // the position to the last bit parsed. information will be returned + bool parseSequenceHeader(const StreamHeader* shdr); + + // parseSequenceExtension will parse a SequenceExtension according to + // the + // spec + // storing the information in the sequence_extension structure and + // updating + // the position to the last bit parsed. + bool parseSequenceExtension(const StreamHeader* shdr); + + // parseGOPHeader will parse a GOPHeader according to the spec storing + // the information in the gop_header_ structure and updating the + // position + // to the last bit parsed. + bool parseGOPHeader(const StreamHeader* shdr); + + // parsePictureHeader will parse a PictureHeader according to the spec + // storing + // the information in the m_pictureHeader_ structure and updating the + // position + // to the last bit parsed. + bool parsePictureHeader(const StreamHeader* shdr); + + // parsePictureCodingExtension will parse a PictureHeader according to + // the + // spec storing the information in the picture_coding_extension_ + // structure + // and updating the position to the last bit parsed. + bool parsePictureCodingExtension(const StreamHeader* shdr); + + // parseQuantMatrixExtension will parse a Quant Matrix Extension ID + // within a Extension Start Code and keep it on the quantization + // Extension structure for later use + bool parseQuantMatrixExtension(const StreamHeader* shdr); + + // parseSlice will parse a Slice according to the spec storing the + // information + // in the Slice structure and updating the position to the last + // bit parsed. + bool parseSlice(const StreamHeader* shdr); + + // nextStartCodeNew will update with next start code and return true if one + // is found, + bool nextStartCode(const StreamHeader* shdr, StartCodeType& start_code); + + + const SeqHeader* getSequenceHeader() { return &m_sequenceHdr; } + const SeqExtension* getSequenceExtension() + { + return &m_sequenceExtension; + } + const GOPHeader* getGOPHeader() { return &m_GOPHeader; } + const PictureHeader* getPictureHeader() { return &m_pictureHeader; } + const PictureCodingExtension* getPictureCodingExtension() + { + return &m_pictureCodingExtension; + } + const QuantMatrixExtension* getQuantMatrixExtension() + { + return &m_quantMatrixExtension; + } + const Slice* getMPEG2Slice() { return &m_slice; } + + private: + friend class MPEG2ParserTest; + + bool readQuantMatrixOrDefault(bool& loadMatrix, uint8_t matrix[], + const uint8_t defaultMatrix[]); + + bool readQuantMatrix(bool& loadMatrix, uint8_t matrix[]); + bool calculateMBColumn(); + + // bitReader functions + + inline void bitReaderInit(const BitReader* bitReader) + { + m_bitReader = const_cast(bitReader); + } + + inline void bitReaderDeInit() { m_bitReader = NULL; } + + inline bool bitReaderSkipBits(uint32_t num_bits) const + { + return m_bitReader->skip(num_bits); + } + + inline bool bitReaderReadBits(uint32_t num_bits, uint32_t* out) const + { + return m_bitReader->readT(*out, num_bits); + } + + inline bool bitReaderPeekBits(uint32_t num_bits, uint32_t* out) const + { + return m_bitReader->peek(*out, num_bits); + } + + inline bool bitReaderPeekBool(bool* out) const + { + return m_bitReader->peek(*out, 1); + } + + inline bool bitReaderReadMarker(bool value) const + { + bool readMarker, ret; + // read 1 bit marker + ret = m_bitReader->readT(readMarker); + return ret && readMarker == value; + } + + inline bool bitReaderReadFlag(bool* flag) const + { + return m_bitReader->readT(*flag); + } + + inline uint64_t bitReaderCurrentPosition() const + { + return m_bitReader->getPos(); + } + + inline bool bitReaderIsByteAligned() const + { + return !(m_bitReader->getPos() % 8); + } + + BitReader* m_bitReader; + + SeqHeader m_sequenceHdr; + SeqExtension m_sequenceExtension; + GOPHeader m_GOPHeader; + PictureHeader m_pictureHeader; + PictureCodingExtension m_pictureCodingExtension; + QuantMatrixExtension m_quantMatrixExtension; + Slice m_slice; + + DISALLOW_COPY_AND_ASSIGN(Parser); + }; + +} // namespace MPEG2 +} // namespace YamiParser + +#endif // mpeg2_parser_h diff --git a/codecparsers/mpeg2_parser_unittest.cpp b/codecparsers/mpeg2_parser_unittest.cpp new file mode 100644 index 0000000..b0450b1 --- /dev/null +++ b/codecparsers/mpeg2_parser_unittest.cpp @@ -0,0 +1,203 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "mpeg2_parser.h" + +// library headers +#include "common/Array.h" +#include "common/log.h" +#include "common/unittest.h" + +// system headers +#include +#include //using rand + +namespace YamiParser { +namespace MPEG2 { + + const static std::array SequenceHeader + = { 0xb3, 0x20, 0x01, 0x20, 0x34, 0xff, 0xff, 0xe0, 0x18 }; + + const static std::array SequenceExtension + = { 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00 }; + + const static std::array GroupOfPicturesHeader + = { 0xb8, 0x00, 0x08, 0x06, 0x00 }; + + const static std::array PictureHeaderArray + = { 0x00, 0x00, 0x0f, 0xff, 0xf8 }; + + const static std::array PictureCodingExtensionArray + = { 0xb5, 0x8f, 0xff, 0xf3, 0x41, 0x80 }; + + const static std::array SliceArray + = { 0x01, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, + 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, + 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, + 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, + 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, + 0x52, 0x22, 0x00 }; + + class MPEG2ParserTest : public ::testing::Test { + protected: + +#define MEMBER_VARIABLE(result_type, var) \ + result_type& var(Parser& p) { return p.var; } + + MEMBER_VARIABLE(BitReader*, m_bitReader); + MEMBER_VARIABLE(SeqHeader, m_sequenceHdr); + MEMBER_VARIABLE(SeqExtension, m_sequenceExtension); + MEMBER_VARIABLE(GOPHeader, m_GOPHeader); + MEMBER_VARIABLE(PictureHeader, m_pictureHeader); + MEMBER_VARIABLE(PictureCodingExtension, m_pictureCodingExtension); + MEMBER_VARIABLE(Slice, m_slice); + +#undef MEMBER_VARIABLE + + void checkParamsSeqHeader(const Parser& parser) + { + EXPECT_EQ(0x200u, parser.m_sequenceHdr.horizontal_size_value); + EXPECT_EQ(0x120u, parser.m_sequenceHdr.vertical_size_value); + EXPECT_EQ(3u, parser.m_sequenceHdr.aspect_ratio_info); + EXPECT_EQ(4u, parser.m_sequenceHdr.frame_rate_code); + EXPECT_EQ(0x3ffffu, parser.m_sequenceHdr.bit_rate_value); + EXPECT_EQ(3u, parser.m_sequenceHdr.vbv_buffer_size_value); + } + + void checkParamsSeqExtension(const Parser& parser) + { + EXPECT_EQ( + kSequence, + parser.m_sequenceExtension.extension_start_code_identifier); + EXPECT_EQ(0x48u, + parser.m_sequenceExtension.profile_and_level_indication); + EXPECT_EQ(1, parser.m_sequenceExtension.progressive_sequence); + EXPECT_EQ(1u, parser.m_sequenceExtension.chroma_format); + } + + void checkParamsPictureHeader(const Parser& parser) + { + EXPECT_EQ(1u, parser.m_pictureHeader.picture_coding_type); + EXPECT_EQ(0xffffu, parser.m_pictureHeader.vbv_delay); + } + + void checkParamsPictureCodingExtension(const Parser& parser) + { + EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[0][0]); + EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[0][1]); + EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[1][0]); + EXPECT_EQ(0xfu, parser.m_pictureCodingExtension.f_code[1][1]); + EXPECT_EQ(0u, parser.m_pictureCodingExtension.intra_dc_precision); + EXPECT_EQ(3u, parser.m_pictureCodingExtension.picture_structure); + EXPECT_EQ(1, parser.m_pictureCodingExtension.frame_pred_frame_dct); + EXPECT_EQ(1, parser.m_pictureCodingExtension.chrome_420_type); + EXPECT_EQ(1, parser.m_pictureCodingExtension.progressive_frame); + } + + void checkParamsSlice(const Parser& parser) + { + EXPECT_EQ(14u, parser.m_slice.sliceHeaderSize); + EXPECT_EQ(0u, parser.m_slice.macroblockRow); + EXPECT_EQ(0u, parser.m_slice.macroblockColumn); + } + }; + +#define MPEG2_PARSER_TEST(name) TEST_F(MPEG2ParserTest, name) + + MPEG2_PARSER_TEST(ParseSequenceHeader) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &SequenceHeader[0]; + streamParser.nalSize = SequenceHeader.size(); + + EXPECT_TRUE(parser.parseSequenceHeader(&streamParser)); + checkParamsSeqHeader(parser); + } + + MPEG2_PARSER_TEST(ParseSequenceExtension) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &SequenceExtension[0]; + streamParser.nalSize = SequenceExtension.size(); + + EXPECT_TRUE(parser.parseSequenceExtension(&streamParser)); + checkParamsSeqExtension(parser); + } + + MPEG2_PARSER_TEST(ParseGOPHeader) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &GroupOfPicturesHeader[0]; + streamParser.nalSize = GroupOfPicturesHeader.size(); + + EXPECT_TRUE(parser.parseGOPHeader(&streamParser)); + //all params will be zero for this unittest + } + + MPEG2_PARSER_TEST(ParsePictureHeader) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &PictureHeaderArray[0]; + streamParser.nalSize = PictureHeaderArray.size(); + + EXPECT_TRUE(parser.parsePictureHeader(&streamParser)); + checkParamsPictureHeader(parser); + } + + MPEG2_PARSER_TEST(ParsePictureCodingExtension) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &PictureCodingExtensionArray[0]; + streamParser.nalSize = PictureCodingExtensionArray.size(); + + EXPECT_TRUE(parser.parsePictureCodingExtension(&streamParser)); + checkParamsPictureCodingExtension(parser); + } + + MPEG2_PARSER_TEST(ParseSlice) + { + Parser parser; + StreamHeader streamParser; + + streamParser.nalData = &SliceArray[0]; + streamParser.nalSize = SliceArray.size(); + + EXPECT_TRUE(parser.parseSlice(&streamParser)); + checkParamsSlice(parser); + } +} // namespace MPEG2 +} // namespace YamiParser diff --git a/codecparsers/nalReader.cpp b/codecparsers/nalReader.cpp new file mode 100644 index 0000000..df3c45e --- /dev/null +++ b/codecparsers/nalReader.cpp @@ -0,0 +1,146 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "nalReader.h" + +namespace YamiParser { + +/*get the smallest integer greater than or equal to half of n*/ +uint32_t getHalfCeil(uint32_t n) +{ + return ((n + 1) >> 1); +} + +NalReader::NalReader(const uint8_t *pdata, uint32_t size) + : BitReader(pdata, size) + , m_epb(0) +{ +} + +inline bool NalReader::isEmulationBytes(const uint8_t *p) const +{ + return *p == 0x03 + && (p - m_stream) >= 2 + && *(p - 1) == 0x00 && *(p - 2) == 0x00; +} + +void NalReader::loadDataToCache(uint32_t nbytes) +{ + const uint8_t *pStart = m_stream + m_loadBytes; + const uint8_t *p; + const uint8_t *pEnd = m_stream + m_size; + /*the numbers of emulation prevention three byte in current load block*/ + uint32_t epb = 0; + + unsigned long int tmp = 0; + uint32_t size = 0; + for (p = pStart; p < pEnd && size < nbytes; p++) { + if(!isEmulationBytes(p)) { + tmp <<= 8; + tmp |= *p; + size++; + } else { + epb++; + } + + } + m_cache = tmp; + m_loadBytes += p - pStart; + m_bitsInCache = size << 3; + m_epb += epb; +} + +/*according to 9.1 of h264 spec*/ +bool NalReader::readUe(uint32_t& v) +{ + int32_t leadingZeroBits = -1; + + for (uint32_t b = 0; !b; leadingZeroBits++) { + if (!read(b, 1)) + return false; + } + if (!read(v, leadingZeroBits)) + return false; + v = (1 << leadingZeroBits) - 1 + v; + return true; +} + +uint32_t NalReader::readUe() +{ + uint32_t res; + if (!readUe(res)) + res = 0; + return res; +} + +bool NalReader::readSe(int32_t& v) +{ + uint32_t codeNum; + if (!readUe(codeNum)) + return false; + uint32_t ceil = getHalfCeil(codeNum); + v = ((codeNum & 1) ? ceil : (-ceil)); + return true; +} + +/*according to 9.1.1*/ +int32_t NalReader::readSe() +{ + int32_t res; + if (!readSe(res)) + res = 0; + return res; +} + +bool NalReader::moreRbspData() const +{ + BitReader tmp(*this); + uint32_t remainingBits = (m_size << 3) - ((m_loadBytes << 3) - m_bitsInCache); + if(remainingBits == 0) + return false; + + /* If next bit is equal to 0, that means there is more data in RBSP before the + * rbsp_trailing_bits() syntax structure. + * If next bit is equal to 1 and existing another one bit equal to 1 in the + * remaining bits means more data, otherwise means no more data. + */ + uint8_t nextBit = tmp.read(1); + if(nextBit == 0) + return true; + + while(--remainingBits) { + nextBit = tmp.read(1); + if(nextBit) + return true; + } + + return false; +} + +void NalReader::rbspTrailingBits() +{ + /*rbsp_stop_one_bit, equal to 1*/ + skip(1); + while(getPos() & 7) + skip(1); /*rbsp_alignment_zero_bit, equal to 0*/ +} + +} /*namespace YamiParser*/ diff --git a/codecparsers/nalReader.h b/codecparsers/nalReader.h new file mode 100644 index 0000000..43ad5bf --- /dev/null +++ b/codecparsers/nalReader.h @@ -0,0 +1,88 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef nalReader_h +#define nalReader_h + +#include "common/log.h" +#include "bitReader.h" + +namespace YamiParser { + +class NalReader : public BitReader +{ +public: + NalReader(const uint8_t *data, uint32_t size); + + /*parse Exp-Golomb coding*/ + bool readUe(uint32_t& v); + inline bool readUe(uint8_t& v); + inline bool readUe(uint16_t& v); + uint32_t readUe(); + bool readSe(int32_t& v); + inline bool readSe(int8_t& v); + inline bool readSe(int16_t& v); + int32_t readSe(); + + bool moreRbspData() const; + void rbspTrailingBits(); + uint32_t getEpbCnt() { return m_epb; } +private: + void loadDataToCache(uint32_t nbytes); + inline bool isEmulationBytes(const uint8_t *p) const; + + uint32_t m_epb; /*the number of emulation prevention bytes*/ +}; + +bool NalReader::readUe(uint8_t& v) +{ + uint32_t tmp; + if (!readUe(tmp)) + return false; + v = tmp; + return true; +} + +bool NalReader::readUe(uint16_t& v) +{ + uint32_t tmp; + if (!readUe(tmp)) + return false; + v = tmp; + return true; +} + +bool NalReader::readSe(int8_t& v) +{ + int32_t tmp; + if (!readSe(tmp)) + return false; + v = tmp; + return true; +} + +bool NalReader::readSe(int16_t& v) +{ + int32_t tmp; + if (!readSe(tmp)) + return false; + v = tmp; + return true; +} + +} /*namespace YamiParser*/ + +#endif diff --git a/codecparsers/nalReader_unittest.cpp b/codecparsers/nalReader_unittest.cpp new file mode 100644 index 0000000..1f52bb8 --- /dev/null +++ b/codecparsers/nalReader_unittest.cpp @@ -0,0 +1,85 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * +3B * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "nalReader.h" + +// library headers +#include "common/unittest.h" + +namespace YamiParser { + +class NalReaderTest + : public ::testing::Test { +}; + +#define NALREADER_TEST(name) \ + TEST_F(NalReaderTest, name) + +NALREADER_TEST(ReadBeyondBoundary) +{ + uint8_t data = 0x55; + uint32_t u; + int32_t s; + NalReader reader(&data, 1); + EXPECT_EQ(0u, reader.read(1)); + EXPECT_EQ(1u, reader.read(1)); + EXPECT_TRUE(reader.readUe(u)); + EXPECT_EQ(1u, u); + EXPECT_TRUE(reader.readSe(s)); + EXPECT_EQ(0, s); + + EXPECT_FALSE(reader.end()); + EXPECT_FALSE(reader.read(u, 8)); + EXPECT_TRUE(reader.end()); + EXPECT_FALSE(reader.readUe(u)); + EXPECT_EQ(0u, reader.readUe()); + EXPECT_FALSE(reader.readSe(s)); + EXPECT_EQ(0, reader.readSe()); +} + +void checkBitreadEmpty(NalReader& reader) +{ + EXPECT_TRUE(reader.end()); + EXPECT_EQ(0u, reader.getPos()); + EXPECT_EQ(0u, + reader.getRemainingBitsCount()); + + uint32_t u; + int32_t s; + EXPECT_FALSE(reader.readUe(u)); + EXPECT_FALSE(reader.readSe(s)); + + EXPECT_TRUE(reader.end()); +} + +NALREADER_TEST(NullInit) +{ + uint8_t data = 0; + NalReader r1(&data, 0); + checkBitreadEmpty(r1); + + NalReader r2(NULL, 0); + checkBitreadEmpty(r2); + + EXPECT_DEATH(NalReader r3(NULL, 1), ""); +} + +} // namespace YamiParser diff --git a/codecparsers/unittest_main.cpp b/codecparsers/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/codecparsers/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/codecparsers/vc1Parser.cpp b/codecparsers/vc1Parser.cpp new file mode 100644 index 0000000..711b710 --- /dev/null +++ b/codecparsers/vc1Parser.cpp @@ -0,0 +1,1154 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vc1Parser.h" +#include "common/log.h" +#include "common/common_def.h" +#include +#include + +#define READ(f) \ + do { \ + if (!br->readT(f)) { \ + ERROR("failed to read %s", #f); \ + return false; \ + } \ + } while (0) + +#define READ_BITS(f, bits) \ + do { \ + if (!br->readT(f, bits)) { \ + ERROR("failed to read %d bits to %s", bits, #f); \ + return false; \ + } \ + } while (0) + +#define SKIP(bits) \ + do { \ + if (!br->skip(bits)) { \ + ERROR("failed to skip %d bits", bits); \ + return false; \ + } \ + } while (0) + +#define PEEK(f, bits) \ + do { \ + if (!br->peek(f, bits)) { \ + ERROR("failed to peek %d bits to %s", bits, #f); \ + return false; \ + } \ + } while (0) + +namespace YamiParser { +namespace VC1 { + + /* Table 36: PQINDEX to PQUANT/Quantizer Translation*/ + static const uint8_t QuantizerTranslationTable[32] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31 + }; + + /* Table 69: IMODE VLC Code table */ + static const VLCTable ImodeVLCTable[7] = { + { 2, 2 }, { 3, 2 }, { 2, 3 }, + { 3, 3 }, { 1, 3 }, { 1, 4 }, { 0, 4 } + }; + + /* Table 81: Code table for 3x2 and 2x3 tiles */ + static const VLCTable Norm6VLCTable[64] = { + { 1, 1 }, + { 2, 4 }, + { 3, 4 }, + { 0, 8 }, + { 4, 4 }, + { 1, 8 }, + { 2, 8 }, + { (2 << 5) | 7, (5 + 5) }, + { 5, 4 }, + { 3, 8 }, + { 4, 8 }, + { (2 << 5) | 11, (5 + 5) }, + { 5, 8 }, + { (2 << 5) | 13, (5 + 5) }, + { (2 << 5) | 14, (5 + 5) }, + { (3 << 8) | 14, (5 + 8) }, + { 6, 4 }, + { 6, 8 }, + { 7, 8 }, + { (2 << 5) | 19, (5 + 5) }, + { 8, 8 }, + { (2 << 5) | 21, (5 + 5) }, + { (2 << 5) | 22, (5 + 5) }, + { (3 << 8) | 13, (5 + 8) }, + { 9, 8 }, + { (2 << 5) | 25, (5 + 5) }, + { (2 << 5) | 26, (5 + 5) }, + { (3 << 8) | 12, (5 + 8) }, + { (2 << 5) | 28, (5 + 5) }, + { (3 << 8) | 11, (5 + 8) }, + { (3 << 8) | 10, (5 + 8) }, + { (3 << 4) | 7, (5 + 4) }, + { 7, 4 }, + { 10, 8 }, + { 11, 8 }, + { (2 << 5) | 3, (5 + 5) }, + { 12, 8 }, + { (2 << 5) | 5, (5 + 5) }, + { (2 << 5) | 6, (5 + 5) }, + { (3 << 8) | 9, (5 + 8) }, + { 13, 8 }, + { (2 << 5) | 9, (5 + 5) }, + { (2 << 5) | 10, (5 + 5) }, + { (3 << 8) | 8, (5 + 8) }, + { (2 << 5) | 12, (5 + 5) }, + { (3 << 8) | 7, (5 + 8) }, + { (3 << 8) | 6, (5 + 8) }, + { (3 << 4) | 6, (5 + 4) }, + { 14, 8 }, + { (2 << 5) | 17, (5 + 5) }, + { (2 << 5) | 18, (5 + 5) }, + { (3 << 8) | 5, (5 + 8) }, + { (2 << 5) | 20, (5 + 5) }, + { (3 << 8) | 4, (5 + 8) }, + { (3 << 8) | 3, (5 + 8) }, + { (3 << 4) | 5, (5 + 4) }, + { (2 << 5) | 24, (5 + 5) }, + { (3 << 8) | 2, (5 + 8) }, + { (3 << 8) | 1, (5 + 8) }, + { (3 << 4) | 4, (5 + 4) }, + { (3 << 8) | 0, (5 + 8) }, + { (3 << 4) | 3, (5 + 4) }, + { (3 << 4) | 2, (5 + 4) }, + { (3 << 1) | 1, (5 + 1) } + }; + + static const FrameType FrameTypeTable[2][8] = { + { + FRAME_I, FRAME_I, FRAME_P, FRAME_P, + FRAME_B, FRAME_B, FRAME_BI, FRAME_BI + }, + { + FRAME_P, FRAME_B, FRAME_I, FRAME_BI, + FRAME_SKIPPED + }, + }; + + /* Table 40: BFRACTION VLC Table */ + static const VLCTable BFractionVLCTable[] = { + {0x00, 3}, {0x01, 3}, + {0x02, 3}, {0x02, 3}, + {0x04, 3}, {0x05, 3}, + {0x06, 3}, {0x70, 7}, + {0x71, 7}, {0x72, 7}, + {0x73, 7}, {0x74, 7}, + {0x75, 7}, {0x76, 7}, + {0x77, 7}, {0x78, 7}, + {0x79, 7}, {0x7a, 7}, + {0x7b, 7}, {0x7c, 7}, + {0x7d, 7}, {0x7e, 7}, + {0x7f, 7} + }; + + Parser::Parser() + { + memset(&m_seqHdr, 0, sizeof(m_seqHdr)); + memset(&m_entryPointHdr, 0, sizeof(m_entryPointHdr)); + } + + Parser::~Parser() + { + } + + bool Parser::parseCodecData(uint8_t* data, uint32_t size) + { + int32_t offset; + offset = searchStartCode(data, size); + if (offset < 0) { + if (!parseSequenceHeader(data, size)) + return false; + } + else { + while (1) { + data += (offset + 4); + size -= (offset + 4); + if (data[-1] == 0xF) { + if (!parseSequenceHeader(data, size)) + return false; + } + else if (data[-1] == 0xE) { + if (!parseEntryPointHeader(data, size)) + return false; + } + offset = searchStartCode(data, size); + if (offset < 0) + break; + } + } + return true; + } + + bool Parser::parseFrameHeader(uint8_t*& data, uint32_t& size) + { + bool ret = false; + m_mbWidth = (m_seqHdr.coded_width + 15) >> 4; + m_mbHeight = (m_seqHdr.coded_height + 15) >> 4; + mallocBitPlanes(); + memset(&m_frameHdr, 0, sizeof(m_frameHdr)); + if (!convertToRbdu(data, size)) + return false; + BitReader bitReader(&m_rbdu[0], m_rbdu.size()); + if (m_seqHdr.profile != PROFILE_ADVANCED) { + ret = parseFrameHeaderSimpleMain(&bitReader); + } + else { + /* support advanced profile */ + ret = parseFrameHeaderAdvanced(&bitReader); + } + m_frameHdr.macroblock_offset = bitReader.getPos(); + return ret; + } + + int32_t Parser::searchStartCode(uint8_t* data, uint32_t size) + { + uint8_t* pos; + const uint8_t startCode[] = { 0x00, 0x00, 0x01 }; + pos = std::search(data, data + size, startCode, startCode + 3); + return (pos == data + size) ? (-1) : (pos - data); + } + + bool Parser::convertToRbdu(uint8_t*& data, uint32_t& size) + { + uint8_t* pos; + int32_t offset, i = 0; + const uint8_t startCode[] = { 0x00, 0x00, 0x03 }; + + if (m_seqHdr.profile == PROFILE_ADVANCED) { + while (1) { + /*skip for ununsed bdu types*/ + /*data and size are input and output parameters*/ + offset = searchStartCode(data, size); + if (offset >= 0) { + data += (offset + 4); + size -= (offset + 4); + } + if ((offset < 0) || (data[-1] == 0xD)) + break; + } + if (offset < 0) { + size = 0; + return false; + } + } + m_rbdu.clear(); + /*extraction of rbdu from ebdu*/ + while (1) { + pos = std::search(data + i, data + size, startCode, startCode + 3); + if (pos == data + size) { + m_rbdu.insert(m_rbdu.end(), data + i, pos); + break; + } + if (pos[3] <= 0x03) { + m_rbdu.insert(m_rbdu.end(), data + i, pos + 2); + } + else { + m_rbdu.insert(m_rbdu.end(), data + i, pos + 3); + } + i = pos - data + 3; + } + return (size > 0); + } + + /*Table 3: Sequence layer bitstream for Advanced Profile*/ + /*Table 263: Sequence Header Data Structure STRUCT_C for Simple and Main Profiles*/ + /*Table 264: Sequence Header Data Structure STRUCT_C for Advanced Profiles*/ + bool Parser::parseSequenceHeader(const uint8_t* data, uint32_t size) + { + uint32_t i; + BitReader bitReader(data, size); + BitReader* br = &bitReader; + READ_BITS(m_seqHdr.profile, 2); + if (m_seqHdr.profile != PROFILE_ADVANCED) { + /* skip reserved bits */ + SKIP(2); + READ_BITS(m_seqHdr.frmrtq_postproc, 3); + READ_BITS(m_seqHdr.bitrtq_postproc, 5); + READ(m_seqHdr.loop_filter); + /* skip reserved bits */ + SKIP(1); + READ(m_seqHdr.multires); + /* skip reserved bits */ + SKIP(1); + READ(m_seqHdr.fastuvmc); + READ(m_seqHdr.extended_mv); + READ_BITS(m_seqHdr.dquant, 2); + READ(m_seqHdr.variable_sized_transform_flag); + /* skip reserved bits */ + SKIP(1); + READ(m_seqHdr.overlap); + READ(m_seqHdr.syncmarker); + READ(m_seqHdr.rangered); + READ_BITS(m_seqHdr.max_b_frames, 3); + READ_BITS(m_seqHdr.quantizer, 2); + READ(m_seqHdr.finterpflag); + } + else { + READ_BITS(m_seqHdr.level, 3); + READ_BITS(m_seqHdr.colordiff_format, 2); + READ_BITS(m_seqHdr.frmrtq_postproc, 3); + READ_BITS(m_seqHdr.bitrtq_postproc, 5); + READ(m_seqHdr.postprocflag); + uint16_t tmp; + READ_BITS(tmp, 12); + m_seqHdr.coded_width = (tmp + 1) << 1; + READ_BITS(tmp, 12); + m_seqHdr.coded_height = (tmp + 1) << 1; + READ(m_seqHdr.pulldown); + READ(m_seqHdr.interlace); + READ(m_seqHdr.tfcntrflag); + READ(m_seqHdr.finterpflag); + /* skip reserved bits */ + SKIP(1); + READ(m_seqHdr.psf); + READ(m_seqHdr.display_ext); + if (m_seqHdr.display_ext) { + READ_BITS(m_seqHdr.disp_horiz_size, 14); + m_seqHdr.disp_horiz_size++; + READ_BITS(m_seqHdr.disp_vert_size, 14); + m_seqHdr.disp_vert_size++; + READ(m_seqHdr.aspect_ratio_flag); + if (m_seqHdr.aspect_ratio_flag) { + READ_BITS(m_seqHdr.aspect_ratio, 4); + if (m_seqHdr.aspect_ratio == 15) { + READ(m_seqHdr.aspect_horiz_size); + READ(m_seqHdr.aspect_vert_size); + } + } + READ(m_seqHdr.framerate_flag); + if (m_seqHdr.framerate_flag) { + READ(m_seqHdr.framerateind); + if (m_seqHdr.framerateind == 0) { + READ(m_seqHdr.frameratenr); + READ_BITS(m_seqHdr.frameratedr, 4); + } + else { + READ(m_seqHdr.framerateexp); + } + } + READ(m_seqHdr.color_format_flag); + + if (m_seqHdr.color_format_flag) { + READ(m_seqHdr.color_prim); + READ(m_seqHdr.transfer_char); + READ(m_seqHdr.matrix_coef); + } + } + READ(m_seqHdr.hrd_param_flag); + + /*Table 13: Syntax elements for HRD_PARAM structure*/ + if (m_seqHdr.hrd_param_flag) { + READ_BITS(m_seqHdr.hrd_param.hrd_num_leaky_buckets, 5); + READ_BITS(m_seqHdr.hrd_param.bit_rate_exponent, 4); + READ_BITS(m_seqHdr.hrd_param.buffer_size_exponent, 4); + for (i = 0; i < m_seqHdr.hrd_param.hrd_num_leaky_buckets; i++) { + READ(m_seqHdr.hrd_param.hrd_rate[i]); + READ(m_seqHdr.hrd_param.hrd_buffer[i]); + } + } + } + return true; + } + + /*Table 14: Entry-point layer bitstream for Advanced Profile*/ + bool Parser::parseEntryPointHeader(const uint8_t* data, uint32_t size) + { + uint8_t i; + BitReader bitReader(data, size); + BitReader* br = &bitReader; + READ(m_entryPointHdr.broken_link); + READ(m_entryPointHdr.closed_entry); + READ(m_entryPointHdr.panscan_flag); + READ(m_entryPointHdr.reference_distance_flag); + READ(m_entryPointHdr.loopfilter); + READ(m_entryPointHdr.fastuvmc); + READ(m_entryPointHdr.extended_mv); + READ_BITS(m_entryPointHdr.dquant, 2); + READ(m_entryPointHdr.variable_sized_transform_flag); + READ(m_entryPointHdr.overlap); + READ_BITS(m_entryPointHdr.quantizer, 2); + if (m_seqHdr.hrd_param_flag) { + for (i = 0; i < m_seqHdr.hrd_param.hrd_num_leaky_buckets; i++) + READ(m_entryPointHdr.hrd_full[i]); + } + + READ(m_entryPointHdr.coded_size_flag); + if (m_entryPointHdr.coded_size_flag) { + READ_BITS(m_entryPointHdr.coded_width, 12); + m_entryPointHdr.coded_width = (m_entryPointHdr.coded_width + 1) << 1; + READ_BITS(m_entryPointHdr.coded_height, 12); + m_entryPointHdr.coded_height = (m_entryPointHdr.coded_height + 1) << 1; + m_seqHdr.coded_width = m_entryPointHdr.coded_width; + m_seqHdr.coded_height = m_entryPointHdr.coded_height; + } + + if (m_entryPointHdr.extended_mv) + READ(m_entryPointHdr.extended_dmv_flag); + + READ(m_entryPointHdr.range_mapy_flag); + if (m_entryPointHdr.range_mapy_flag) + READ_BITS(m_entryPointHdr.range_mapy, 3); + + READ(m_entryPointHdr.range_mapuv_flag); + if (m_entryPointHdr.range_mapy_flag) + READ_BITS(m_entryPointHdr.range_mapuv, 3); + return true; + } + + bool Parser::parseSliceHeader(uint8_t* data, uint32_t size) + { + bool temp; + BitReader* br; + bool ret = true; + if (m_seqHdr.profile != PROFILE_ADVANCED) + return false; + BitReader bitReader(data, size); + br = &bitReader; + READ_BITS(m_sliceHdr.slice_addr, 9); + READ(temp); + if (temp) + ret = parseFrameHeaderAdvanced(&bitReader); + + m_sliceHdr.macroblock_offset = bitReader.getPos(); + return ret; + } + + void Parser::mallocBitPlanes() + { + uint32_t size = m_mbHeight * m_mbWidth; + m_bitPlanes.acpred.resize(size); + m_bitPlanes.fieldtx.resize(size); + m_bitPlanes.overflags.resize(size); + m_bitPlanes.mvtypemb.resize(size); + m_bitPlanes.skipmb.resize(size); + m_bitPlanes.directmb.resize(size); + m_bitPlanes.forwardmb.resize(size); + } + + bool Parser::decodeVLCTable(BitReader* br, uint16_t* out, + const VLCTable* table, uint32_t tableLen) + { + uint32_t i = 0; + uint16_t numberOfBits = 0; + uint16_t codeWord = 0; + while (i < tableLen) { + if (numberOfBits != table[i].codeLength) { + numberOfBits = table[i].codeLength; + PEEK(codeWord, numberOfBits); + } + if (codeWord == table[i].codeWord) { + *out = i; + SKIP(numberOfBits); + break; + } + i++; + } + return (i < tableLen) ? true : false; + } + + /* 8.7.3.6 Row-skip mode*/ + bool Parser::decodeRowskipMode(BitReader* br, uint8_t* data, uint32_t width, uint32_t height) + { + uint32_t i, j; + for (j = 0; j < height; j++) { + bool rowSkip; + READ(rowSkip); + if (rowSkip) { + for (i = 0; i < width; i++) + READ_BITS(data[i], 1); + } + else { + memset(data, 0, width); + } + data += m_mbWidth; + } + return true; + } + + /* 8.7.3.7 Column-skip mode*/ + bool Parser::decodeColskipMode(BitReader* br, uint8_t* data, uint32_t width, uint32_t height) + { + uint32_t i, j; + for (i = 0; i < width; i++) { + bool columnSkip; + READ(columnSkip); + if (columnSkip) { + for (j = 0; j < height; j++) + READ_BITS(data[j * m_mbWidth], 1); + } + else { + for (j = 0; j < height; j++) + data[j * m_mbWidth] = 0; + } + data++; + } + return true; + } + + /* Table 80: Norm-2/Diff-2 Code Table */ + bool Parser::decodeNorm2Mode(BitReader* br, uint8_t* data, uint32_t width, uint32_t height) + { + uint32_t i; + bool temp; + uint8_t* out = data; + if ((height * width) & 1) { + READ_BITS(*out, 1); + out++; + } + for (i = (height * width) & 1; i < height * width; i += 2) { + READ(temp); + if (temp == 0) { + *out++ = 0; + *out++ = 0; + } + else { + READ(temp); + if (temp) { + *out++ = 1; + *out++ = 1; + } + else { + READ(temp); + if (temp == 0) { + *out++ = 1; + *out++ = 0; + } + else { + *out++ = 0; + *out++ = 1; + } + } + } + } + return true; + } + + bool Parser::decodeNorm6Mode(BitReader* br, uint8_t* data, uint32_t width, uint32_t height) + { + uint32_t i = 0, j = 0; + uint16_t temp; + uint8_t* out = data; + bool is2x3Tiled = (((width % 3) != 0) && ((height % 3) == 0)); + if (is2x3Tiled) { + for (j = 0; j < height; j += 3) { + for (i = width & 1; i < width; i += 2) { + if (!decodeVLCTable(br, &temp, Norm6VLCTable, 64)) + return false; + out[i] = temp & 1; + out[i + 1] = (temp & 2) >> 1; + out[i + width] = (temp & 4) >> 2; + out[i + width + 1] = (temp & 8) >> 3; + out[i + width * 2] = (temp & 16) >> 4; + out[i + width * 2 + 1] = (temp & 32) >> 5; + } + out += 3 * width; + } + if (width & 1) + decodeColskipMode(br, data, width & 1, height); + } + else { + out += (height & 1) * width; + for (j = height & 1; j < height; j += 2) { + for (i = width % 3; i < width; i += 3) { + if (!decodeVLCTable(br, &temp, Norm6VLCTable, 64)) + return false; + out[i] = temp & 1; + out[i + 1] = (temp & 2) >> 1; + out[i + 2] = (temp & 4) >> 2; + out[i + width] = (temp & 8) >> 3; + out[i + width + 1] = (temp & 16) >> 4; + out[i + width + 2] = (temp & 32) >> 5; + } + out += 2 * width; + } + if (width % 3) + decodeColskipMode(br, data, width % 3, height); + if (height & 1) + decodeRowskipMode(br, data + (width % 3), width - (width % 3), height & 1); + } + return true; + } + + /* 8.7.3.8 Diff: Inverse differential decoding */ + void Parser::inverseDiff(uint8_t* data, uint32_t width, uint32_t height, uint32_t invert) + { + uint32_t i, j; + for (j = 0; j < height; j++) + for (i = 0; i < width; i++) { + if ((i == 0) && (j == 0)) { + data[j * width + i] ^= invert; + } + else if (i == 0) { + data[j * width + i] ^= data[(j - 1) * width]; + } + else if ((j > 0) && (data[(j - 1) * width + i] != data[j * width + i - 1])) { + data[j * width + i] ^= invert; + } + else { + data[j * width + i] ^= data[j * width + i - 1]; + } + } + } + + bool Parser::decodeBitPlane(BitReader* br, uint8_t* data, bool* isRaw) + { + uint32_t i, invert; + uint16_t mode; + *isRaw = false; + READ_BITS(invert, 1); + if (!decodeVLCTable(br, &mode, ImodeVLCTable, 7)) + return false; + if (mode == IMODE_RAW) { + *isRaw = true; + return true; + } + else if (mode == IMODE_NORM2) { + decodeNorm2Mode(br, data, m_mbWidth, m_mbHeight); + } + else if (mode == IMODE_NORM6) { + decodeNorm6Mode(br, data, m_mbWidth, m_mbHeight); + } + else if (mode == IMODE_DIFF2) { + decodeNorm2Mode(br, data, m_mbWidth, m_mbHeight); + inverseDiff(data, m_mbWidth, m_mbHeight, invert); + } + else if (mode == IMODE_DIFF6) { + decodeNorm6Mode(br, data, m_mbWidth, m_mbHeight); + inverseDiff(data, m_mbWidth, m_mbHeight, invert); + } + else if (mode == IMODE_ROWSKIP) { + decodeRowskipMode(br, data, m_mbWidth, m_mbHeight); + } + else if (mode == IMODE_COLSKIP) { + decodeColskipMode(br, data, m_mbWidth, m_mbHeight); + } + /*8.7.1 INVERT*/ + if ((mode != IMODE_DIFF2) && (mode != IMODE_DIFF6) && invert) { + for (i = 0; i < m_mbWidth * m_mbHeight; i++) + data[i] = !data[i]; + } + return true; + } + + /*Table 24: VOPDQUANT in picture header(Refer to 7.1.1.31)*/ + /*7.1.1.31.6 Picture Quantizer Differential(PQDIFF)(3 bits)*/ + bool Parser::parseVopdquant(BitReader* br, uint8_t dquant) + { + if (dquant == 2) { + m_frameHdr.dq_frame = 0; + READ_BITS(m_frameHdr.pq_diff, 3); + if (m_frameHdr.pq_diff != 7) { + m_frameHdr.alt_pic_quantizer = m_frameHdr.pquant + m_frameHdr.pq_diff + 1; + } + else { + READ_BITS(m_frameHdr.abs_pq, 5); + m_frameHdr.alt_pic_quantizer = m_frameHdr.abs_pq; + } + } + else { + READ(m_frameHdr.dq_frame); + if (m_frameHdr.dq_frame) { + READ_BITS(m_frameHdr.dq_profile, 2); + if (m_frameHdr.dq_profile == DQPROFILE_SINGLE_EDGE) { + READ_BITS(m_frameHdr.dq_sb_edge, 2); + } + else if (m_frameHdr.dq_profile == DQPROFILE_DOUBLE_EDGE) { + READ_BITS(m_frameHdr.dq_db_edge, 2); + } + else if (m_frameHdr.dq_profile == DQPROFILE_ALL_MACROBLOCKS) { + READ(m_frameHdr.dq_binary_level); + } + if (!((m_frameHdr.dq_profile == DQPROFILE_ALL_MACROBLOCKS) + && (m_frameHdr.dq_binary_level == 0))) { + READ_BITS(m_frameHdr.pq_diff, 3); + if (m_frameHdr.pq_diff != 7) { + m_frameHdr.alt_pic_quantizer = m_frameHdr.pquant + m_frameHdr.pq_diff + 1; + } + else { + READ_BITS(m_frameHdr.abs_pq, 5); + m_frameHdr.alt_pic_quantizer = m_frameHdr.abs_pq; + } + } + } + } + return true; + } + + int32_t Parser::getFirst01Bit(BitReader* br, bool val, uint32_t len) + { + uint32_t i = 0; + while (i < len) { + //TODO: check read beyond boundary here, it may need change so many functions + if (br->read(1) == val) + break; + i++; + } + return i; + } + + uint8_t Parser::getMVMode(BitReader* br, uint8_t pQuant, bool isMvMode2) + { + int32_t temp = 0; + uint8_t MVMode = 0; + temp = isMvMode2 ? getFirst01Bit(br, 1, 3) : getFirst01Bit(br, 1, 4); + switch (temp) { + case 0: + MVMode = (pQuant <= 12) ? MVMODE_1_MV : MVMODE_1_MV_HALF_PEL_BILINEAR; + break; + case 1: + MVMode = (pQuant <= 12) ? MVMODE_MIXED_MV : MVMODE_1_MV; + break; + case 2: + MVMode = MVMODE_1_MV_HALF_PEL; + break; + case 3: + if (isMvMode2) { + MVMode = (pQuant <= 12) ? MVMODE_1_MV_HALF_PEL_BILINEAR : MVMODE_MIXED_MV; + } + else { + MVMode = MVMODE_INTENSITY_COMPENSATION; + } + break; + case 4: + if (!isMvMode2) + MVMode = (pQuant <= 12) ? MVMODE_1_MV_HALF_PEL_BILINEAR : MVMODE_MIXED_MV; + break; + default: + break; + } + return MVMode; + } + + bool Parser::decodeBFraction(BitReader* br) + { + uint16_t bfraction; + if (!decodeVLCTable(br, &bfraction, BFractionVLCTable, N_ELEMENTS(BFractionVLCTable))) + return false; + + m_frameHdr.bfraction = bfraction; + if (m_frameHdr.bfraction == 22) { + m_frameHdr.picture_type = FRAME_BI; + } + return true; + } + + /*Table 16: Progressive I picture layer bitstream for Simple and Main Profile*/ + /*Table 17: Progressive BI picture layer bitstream for Main Profile*/ + /*Table 19: Progressive P picture layer bitstream for Simple and Main Profile*/ + /*Table 21: Progressive B picture layer bitstream for Main Profile*/ + bool Parser::parseFrameHeaderSimpleMain(BitReader* br) + { + bool temp; + m_frameHdr.interpfrm = 0; + if (m_seqHdr.finterpflag) + READ(m_frameHdr.interpfrm); + + SKIP(2); + m_frameHdr.range_reduction_frame = 0; + if (m_seqHdr.rangered) + READ(m_frameHdr.range_reduction_frame); + + READ(temp); + if (m_seqHdr.max_b_frames == 0) { + /* Table 33 Simple/Main Profile Picture Type VLC if MAXBFRAMES == 0 */ + if (!temp) + m_frameHdr.picture_type = FRAME_I; + else + m_frameHdr.picture_type = FRAME_P; + } + else { + /* Table 34 Main Profile Picture Type VLC if MAXBFRAMES > 0 */ + if (!temp) { + bool ptype; + READ(ptype); + if (ptype) + m_frameHdr.picture_type = FRAME_I; + else + m_frameHdr.picture_type = FRAME_B; + } + else { + m_frameHdr.picture_type = FRAME_P; + } + } + + if (m_frameHdr.picture_type == FRAME_B) { + if (!decodeBFraction(br)) + return false; + } + if (m_frameHdr.picture_type == FRAME_I + || m_frameHdr.picture_type == FRAME_BI) + SKIP(7); /* skip BF*/ + READ_BITS(m_frameHdr.pqindex, 5); + if (m_frameHdr.pqindex <= 8) + READ(m_frameHdr.halfqp); + if (m_seqHdr.quantizer == 0) { + m_frameHdr.pquant = QuantizerTranslationTable[m_frameHdr.pqindex]; + m_frameHdr.pquantizer = (m_frameHdr.pqindex <= 8) ? 1 : 0; + } + else { + m_frameHdr.pquant = m_frameHdr.pqindex; + if (m_seqHdr.quantizer == 1) + READ(m_frameHdr.pquantizer); + else if (m_seqHdr.quantizer == 2) + m_frameHdr.pquantizer = 0; + else if (m_seqHdr.quantizer == 3) + m_frameHdr.pquantizer = 1; + else + assert(0); + } + + if (m_seqHdr.extended_mv) + m_frameHdr.extended_mv_range = getFirst01Bit(br, 0, 3); + + if (m_seqHdr.multires + && ((m_frameHdr.picture_type == FRAME_I) + || (m_frameHdr.picture_type == FRAME_P))) { + READ_BITS(m_frameHdr.picture_resolution_index, 2); + } + + if ((m_frameHdr.picture_type == FRAME_I) + || (m_frameHdr.picture_type == FRAME_BI)) { + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + m_frameHdr.transacfrm2 = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + } + else if (m_frameHdr.picture_type == FRAME_P) { + m_frameHdr.mv_mode = getMVMode(br, m_frameHdr.pquant, false); + if (m_frameHdr.mv_mode == MVMODE_INTENSITY_COMPENSATION) { + m_frameHdr.mv_mode2 = getMVMode(br, m_frameHdr.pquant, true); + READ_BITS(m_frameHdr.lumscale, 6); + READ_BITS(m_frameHdr.lumshift, 6); + } + if (m_frameHdr.mv_mode == MVMODE_MIXED_MV + || (m_frameHdr.mv_mode == MVMODE_INTENSITY_COMPENSATION + && m_frameHdr.mv_mode2 == MVMODE_MIXED_MV)) { + if (!decodeBitPlane(br, &m_bitPlanes.mvtypemb[0], &m_frameHdr.mv_type_mb)) + return false; + } + if (!decodeBitPlane(br, &m_bitPlanes.skipmb[0], &m_frameHdr.skip_mb)) + return false; + + READ_BITS(m_frameHdr.mv_table, 2); + READ_BITS(m_frameHdr.cbp_table, 2); + if (m_seqHdr.dquant) + parseVopdquant(br, m_seqHdr.dquant); + + if (m_seqHdr.variable_sized_transform_flag) { + READ(m_frameHdr.mb_level_transform_type_flag); + if (m_frameHdr.mb_level_transform_type_flag) + READ_BITS(m_frameHdr.frame_level_transform_type, 2); + } + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + } + else if (m_frameHdr.picture_type == FRAME_B) { + READ_BITS(m_frameHdr.mv_mode, 1); + m_frameHdr.mv_mode = !(m_frameHdr.mv_mode); + if (!decodeBitPlane(br, &m_bitPlanes.directmb[0], &m_frameHdr.direct_mb)) + return false; + if (!decodeBitPlane(br, &m_bitPlanes.skipmb[0], &m_frameHdr.skip_mb)) + return false; + READ_BITS(m_frameHdr.mv_table, 2); + READ_BITS(m_frameHdr.cbp_table, 2); + if (m_seqHdr.dquant) + parseVopdquant(br, m_seqHdr.dquant); + if (m_seqHdr.variable_sized_transform_flag) { + READ(m_frameHdr.mb_level_transform_type_flag); + if (m_frameHdr.mb_level_transform_type_flag) + READ_BITS(m_frameHdr.frame_level_transform_type, 2); + } + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + } + return true; + } + + /* 9.1.1.43 P Reference Distance*/ + /* Table 106: REFDIST VLC Table*/ + bool Parser::getRefDist(BitReader* br, uint8_t& refDist) + { + uint32_t vlcSize; + PEEK(vlcSize, 2); + if (vlcSize != 3) { + READ_BITS(refDist, 2); + } + else { + //TODO: check read beyond boundary + refDist = getFirst01Bit(br, 0, 16) + 1; + } + return true; + } + + /*Table 18: Progressive I and BI picture layer bitstream for Advanced Profile*/ + /*Table 20: Progressive P picture layer bitstream for Advanced Profile*/ + /*Table 22: Progressive B picture layer bitstream for Advanced Profile*/ + /*Table 83: Interlaced Frame P picture layer bitstream for Advanced Profile*/ + /*Table 84: Interlaced Frame B picture layer bitstream for Advanced Profile*/ + /*Table 85: Picture Layer bitstream for Field 1 of Interlace Field Picture for Advanced Profile*/ + bool Parser::parseFrameHeaderAdvanced(BitReader* br) + { + uint32_t temp; + if (m_seqHdr.interlace) { + m_frameHdr.fcm = getFirst01Bit(br, 0, 2); + } + else { + m_frameHdr.fcm = PROGRESSIVE; + } + if (m_frameHdr.fcm == FIELD_INTERLACE) { + READ_BITS(temp, 3); + /* 9.1.1.42 Field Picture Type(FPTYPE) (3 bits) */ + m_frameHdr.picture_type = FrameTypeTable[0][temp]; + } + else { + /* Table 35 Advanced Profile Picture Type VLC */ + temp = getFirst01Bit(br, 0, 4); + m_frameHdr.picture_type = FrameTypeTable[1][temp]; + } + + /* skip tfcntr */ + if (m_seqHdr.tfcntrflag) + SKIP(8); + + if (m_seqHdr.pulldown) { + if (!(m_seqHdr.interlace) || m_seqHdr.psf) { + READ_BITS(m_frameHdr.rptfrm, 2); + } + else { + READ(m_frameHdr.tff); + READ(m_frameHdr.rff); + } + } + else { + m_frameHdr.tff = 1; + } + + if (m_frameHdr.picture_type == FRAME_SKIPPED) + return true; + + READ(m_frameHdr.rounding_control); + + if (m_seqHdr.interlace) { + READ(m_frameHdr.uvsamp); + if ((m_frameHdr.fcm == FIELD_INTERLACE) + && m_entryPointHdr.reference_distance_flag + && (m_frameHdr.picture_type != FRAME_B) + && (m_frameHdr.picture_type != FRAME_BI)) { + if (!getRefDist(br, m_frameHdr.refdist)) + return false; + } + } + if (m_seqHdr.finterpflag) + READ(m_frameHdr.interpfrm); + if ((m_frameHdr.fcm != FIELD_INTERLACE + && m_frameHdr.picture_type == FRAME_B) + || (m_frameHdr.fcm == FIELD_INTERLACE + && ((m_frameHdr.picture_type == FRAME_B) + || (m_frameHdr.picture_type == FRAME_BI)))) { + if (!decodeBFraction(br)) + return false; + } + READ_BITS(m_frameHdr.pqindex, 5); + if (m_frameHdr.pqindex <= 8) + READ(m_frameHdr.halfqp); + if (m_entryPointHdr.quantizer == 0) { + m_frameHdr.pquant = QuantizerTranslationTable[m_frameHdr.pqindex]; + m_frameHdr.pquantizer = (m_frameHdr.pqindex <= 8); + } + else { + m_frameHdr.pquant = m_frameHdr.pqindex; + if (m_entryPointHdr.quantizer == 1) + READ(m_frameHdr.pquantizer); + else if (m_entryPointHdr.quantizer == 2) + m_frameHdr.pquantizer = 0; + else if (m_entryPointHdr.quantizer == 3) + m_frameHdr.pquantizer = 1; + else + assert(0); + } + + if (m_seqHdr.postprocflag) + READ_BITS(m_frameHdr.post_processing, 2); + if ((m_frameHdr.picture_type == FRAME_I) + || (m_frameHdr.picture_type == FRAME_BI)) { + if (m_frameHdr.fcm == FRAME_INTERLACE) { + if (!decodeBitPlane(br, &m_bitPlanes.fieldtx[0], &m_frameHdr.fieldtx)) + return false; + } + if (!decodeBitPlane(br, &m_bitPlanes.acpred[0], &m_frameHdr.ac_pred)) + return false; + + if ((m_entryPointHdr.overlap) && m_frameHdr.pquant <= 8) { + m_frameHdr.condover = getFirst01Bit(br, 0, 2); + if (m_frameHdr.condover == 2) { + if (!decodeBitPlane(br, &m_bitPlanes.overflags[0], &m_frameHdr.overflags)) + return false; + } + } + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + m_frameHdr.transacfrm2 = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + + if (m_entryPointHdr.dquant) + parseVopdquant(br, m_entryPointHdr.dquant); + } + else if (m_frameHdr.picture_type == FRAME_P) { + if (m_frameHdr.fcm == FIELD_INTERLACE) { + READ(m_frameHdr.numref); + if (m_frameHdr.numref) + READ(m_frameHdr.reffield); + } + if (m_entryPointHdr.extended_mv) + m_frameHdr.extended_mv_range = getFirst01Bit(br, 0, 3); + if (m_frameHdr.fcm != PROGRESSIVE) { + if (m_entryPointHdr.extended_dmv_flag) + m_frameHdr.dmvrange = getFirst01Bit(br, 0, 3); + } + + if (m_frameHdr.fcm == FRAME_INTERLACE) { + READ(m_frameHdr.mvswitch4); + READ(m_frameHdr.intcomp); + if (m_frameHdr.intcomp) { + READ_BITS(m_frameHdr.lumscale, 6); + READ_BITS(m_frameHdr.lumshift, 6); + } + } + else { + m_frameHdr.mv_mode = getMVMode(br, m_frameHdr.pquant, false); + if (m_frameHdr.mv_mode == MVMODE_INTENSITY_COMPENSATION) { + m_frameHdr.mv_mode2 = getMVMode(br, m_frameHdr.pquant, true); + if (m_frameHdr.fcm == FIELD_INTERLACE) { + temp = getFirst01Bit(br, 1, 2); + m_frameHdr.intcompfield = temp ? (3 - temp) : temp; + } + READ_BITS(m_frameHdr.lumscale, 6); + READ_BITS(m_frameHdr.lumshift, 6); + if ((m_frameHdr.fcm == FIELD_INTERLACE) + && m_frameHdr.intcompfield) { + READ_BITS(m_frameHdr.lumscale2, 6); + READ_BITS(m_frameHdr.lumshift2, 6); + } + } + if (m_frameHdr.fcm == PROGRESSIVE) { + if (m_frameHdr.mv_mode == MVMODE_MIXED_MV + || (m_frameHdr.mv_mode == MVMODE_INTENSITY_COMPENSATION + && m_frameHdr.mv_mode2 == MVMODE_MIXED_MV)) { + if (!decodeBitPlane(br, &m_bitPlanes.mvtypemb[0], &m_frameHdr.mv_type_mb)) + return false; + } + } + } + + if (m_frameHdr.fcm != FIELD_INTERLACE) { + if (!decodeBitPlane(br, &m_bitPlanes.skipmb[0], &m_frameHdr.skip_mb)) + return false; + } + + if (m_frameHdr.fcm != PROGRESSIVE) { + READ_BITS(m_frameHdr.mbmodetab, 2); + READ_BITS(m_frameHdr.imvtab, 2); + READ_BITS(m_frameHdr.icbptab, 3); + if (m_frameHdr.fcm != FIELD_INTERLACE) { + READ_BITS(m_frameHdr.mvbptab2, 2); + if (m_frameHdr.mvswitch4) + READ_BITS(m_frameHdr.mvbptab4, 2); + } + else if (m_frameHdr.mv_mode == MVMODE_MIXED_MV) { + READ_BITS(m_frameHdr.mvbptab4, 2); + } + } + else { + READ_BITS(m_frameHdr.mv_table, 2); + READ_BITS(m_frameHdr.cbp_table, 2); + } + if (m_entryPointHdr.dquant) + parseVopdquant(br, m_entryPointHdr.dquant); + + if (m_entryPointHdr.variable_sized_transform_flag) { + READ(m_frameHdr.mb_level_transform_type_flag); + if (m_frameHdr.mb_level_transform_type_flag) + READ_BITS(m_frameHdr.frame_level_transform_type, 2); + } + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + } + else if (m_frameHdr.picture_type == FRAME_B) { + if (m_entryPointHdr.extended_mv) + m_frameHdr.extended_mv_range = getFirst01Bit(br, 0, 3); + if (m_frameHdr.fcm != PROGRESSIVE) { + if (m_entryPointHdr.extended_dmv_flag) + m_frameHdr.dmvrange = getFirst01Bit(br, 0, 3); + } + if (m_frameHdr.fcm == FRAME_INTERLACE) { + READ(m_frameHdr.intcomp); + } + else { + READ_BITS(m_frameHdr.mv_mode, 1); + m_frameHdr.mv_mode = !(m_frameHdr.mv_mode); + } + if (m_frameHdr.fcm == FIELD_INTERLACE) { + if (!decodeBitPlane(br, &m_bitPlanes.forwardmb[0], &m_frameHdr.forwardmb)) + return false; + } + else { + if (!decodeBitPlane(br, &m_bitPlanes.directmb[0], &m_frameHdr.direct_mb)) + return false; + if (!decodeBitPlane(br, &m_bitPlanes.skipmb[0], &m_frameHdr.skip_mb)) + return false; + } + if (m_frameHdr.fcm != PROGRESSIVE) { + READ_BITS(m_frameHdr.mbmodetab, 2); + READ_BITS(m_frameHdr.imvtab, 2); + READ_BITS(m_frameHdr.icbptab, 3); + + if (m_frameHdr.fcm == FRAME_INTERLACE) + READ_BITS(m_frameHdr.mvbptab2, 2); + + if ((m_frameHdr.fcm == FRAME_INTERLACE) + || ((m_frameHdr.fcm == FIELD_INTERLACE) + && (m_frameHdr.mv_mode == MVMODE_MIXED_MV))) + READ_BITS(m_frameHdr.mvbptab4, 2); + } + else { + READ_BITS(m_frameHdr.mv_table, 2); + READ_BITS(m_frameHdr.cbp_table, 2); + } + + if (m_entryPointHdr.dquant) + parseVopdquant(br, m_entryPointHdr.dquant); + if (m_entryPointHdr.variable_sized_transform_flag) { + READ(m_frameHdr.mb_level_transform_type_flag); + if (m_frameHdr.mb_level_transform_type_flag) + READ_BITS(m_frameHdr.frame_level_transform_type, 2); + } + m_frameHdr.transacfrm = getFirst01Bit(br, 0, 2); + READ(m_frameHdr.intra_transform_dc_table); + } + return true; + } +} +} diff --git a/codecparsers/vc1Parser.h b/codecparsers/vc1Parser.h new file mode 100644 index 0000000..743ed12 --- /dev/null +++ b/codecparsers/vc1Parser.h @@ -0,0 +1,277 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VC1_PARSER_H__ +#define __VC1_PARSER_H__ + +#include +#include +#include "bitReader.h" +#include + +namespace YamiParser { +namespace VC1 { + /*6.1.1 Profile(PROFILE)(2 bits)*/ + enum Profile { + PROFILE_SIMPLE = 0, + PROFILE_MAIN = 1, + PROFILE_ADVANCED = 3 + }; + + enum FrameType { + FRAME_I, + FRAME_P, + FRAME_B, + FRAME_BI, + FRAME_SKIPPED + }; + + enum BitPlaneMode { + IMODE_NORM2, + IMODE_NORM6, + IMODE_ROWSKIP, + IMODE_COLSKIP, + IMODE_DIFF2, + IMODE_DIFF6, + IMODE_RAW, + }; + + /*Table 43: Macroblock Quantization Profile(DQPROFILE) Code Table*/ + enum DQProfile { + DQPROFILE_ALL_FOUR_EDGES, + DQPROFILE_DOUBLE_EDGE, + DQPROFILE_SINGLE_EDGE, + DQPROFILE_ALL_MACROBLOCKS + }; + + enum MvMode { + MVMODE_1_MV, + MVMODE_1_MV_HALF_PEL, + MVMODE_1_MV_HALF_PEL_BILINEAR, + MVMODE_MIXED_MV, + MVMODE_INTENSITY_COMPENSATION + }; + + /*Table 13: Syntax elements for HRD_PARAM structure*/ + struct HrdParam { + uint8_t hrd_num_leaky_buckets; + uint8_t bit_rate_exponent; + uint8_t buffer_size_exponent; + uint16_t hrd_rate[31]; + uint16_t hrd_buffer[31]; + }; + + /*Table 14: Entry-point layer bitstream for Advanced Profile*/ + struct EntryPointHdr { + bool broken_link; + bool closed_entry; + bool panscan_flag; + bool reference_distance_flag; + bool loopfilter; + bool fastuvmc; + bool extended_mv; + uint8_t dquant; + bool variable_sized_transform_flag; + bool overlap; + uint8_t quantizer; + bool coded_size_flag; + uint16_t coded_width; + uint16_t coded_height; + bool extended_dmv_flag; + bool range_mapy_flag; + uint8_t range_mapy; + bool range_mapuv_flag; + uint8_t range_mapuv; + uint8_t hrd_full[31]; + }; + + /*Table 3: Sequence layer bitstream for Advanced Profile*/ + /*Table 263: Sequence Header Data Structure STRUCT_C for Simple and Main Profiles*/ + struct SeqHdr { + uint8_t profile; + uint16_t coded_width; + uint16_t coded_height; + uint8_t frmrtq_postproc; + uint8_t bitrtq_postproc; + bool loop_filter; + bool multires; + bool fastuvmc; + bool extended_mv; + uint8_t dquant; + bool variable_sized_transform_flag; + bool overlap; + bool syncmarker; + bool rangered; + uint8_t max_b_frames; + uint8_t quantizer; + bool finterpflag; + uint8_t level; + uint8_t colordiff_format; + bool postprocflag; + bool pulldown; + bool interlace; + bool tfcntrflag; + bool psf; + bool display_ext; + uint16_t disp_horiz_size; + uint16_t disp_vert_size; + bool aspect_ratio_flag; + uint8_t aspect_ratio; + uint8_t aspect_horiz_size; + uint8_t aspect_vert_size; + bool framerate_flag; + bool framerateind; + uint8_t frameratenr; + uint8_t frameratedr; + uint16_t framerateexp; + bool color_format_flag; + uint8_t color_prim; + uint8_t transfer_char; + uint8_t matrix_coef; + bool hrd_param_flag; + HrdParam hrd_param; + }; + + struct BitPlanes { + std::vector acpred; + std::vector fieldtx; + std::vector overflags; + std::vector mvtypemb; + std::vector skipmb; + std::vector directmb; + std::vector forwardmb; + }; + + struct FrameHdr { + uint8_t picture_type; + bool interpfrm; + bool halfqp; + uint8_t transacfrm; + bool intra_transform_dc_table; + uint8_t pqindex; + bool pquantizer; + uint8_t pquant; + uint8_t pq_diff; + uint8_t abs_pq; + bool dq_frame; + uint8_t dq_profile; + uint8_t dq_sb_edge; + uint8_t dq_db_edge; + bool dq_binary_level; + uint8_t alt_pic_quantizer; + uint8_t extended_mv_range; + bool range_reduction_frame; + uint8_t picture_resolution_index; + uint8_t transacfrm2; + uint8_t mv_mode; + uint8_t mv_table; + bool mb_level_transform_type_flag; + uint8_t mv_mode2; + uint8_t lumscale; + uint8_t lumshift; + uint8_t cbp_table; + uint8_t frame_level_transform_type; + bool mv_type_mb; + bool skip_mb; + bool direct_mb; + uint8_t fcm; + uint8_t rptfrm; + bool tff; + bool rff; + bool rounding_control; + bool uvsamp; + uint8_t post_processing; + uint8_t condover; + bool ac_pred; + bool overflags; + bool forwardmb; + bool fieldtx; + bool intcomp; + uint8_t dmvrange; + uint8_t mbmodetab; + uint8_t imvtab; + uint8_t icbptab; + uint8_t mvbptab2; + uint8_t mvbptab4; + bool mvswitch4; + uint8_t refdist; + uint8_t fptype; + bool numref; + bool reffield; + uint8_t lumscale2; + uint8_t lumshift2; + uint8_t intcompfield; + uint16_t bfraction; + uint32_t macroblock_offset; + }; + + struct VLCTable { + uint16_t codeWord; + uint16_t codeLength; + }; + + /*Table 41: Frame Coding Mode VLC */ + enum FrameCodingMode { + PROGRESSIVE, + FRAME_INTERLACE, + FIELD_INTERLACE + }; + + struct SliceHdr { + uint16_t slice_addr; + uint32_t macroblock_offset; + }; + + class Parser { + public: + Parser(); + ~Parser(); + bool parseCodecData(uint8_t*, uint32_t); + bool parseFrameHeader(uint8_t*&, uint32_t&); + bool parseSliceHeader(uint8_t*, uint32_t); + int32_t searchStartCode(uint8_t*, uint32_t); + SeqHdr m_seqHdr; + FrameHdr m_frameHdr; + SliceHdr m_sliceHdr; + EntryPointHdr m_entryPointHdr; + BitPlanes m_bitPlanes; + uint32_t m_mbWidth; + uint32_t m_mbHeight; + + private: + void mallocBitPlanes(); + bool getRefDist(BitReader*, uint8_t& refDist); + int32_t getFirst01Bit(BitReader*, bool, uint32_t); + uint8_t getMVMode(BitReader*, uint8_t, bool); + bool decodeBFraction(BitReader*); + bool convertToRbdu(uint8_t*&, uint32_t&); + bool decodeVLCTable(BitReader*, uint16_t*, const VLCTable*, uint32_t); + bool decodeRowskipMode(BitReader*, uint8_t*, uint32_t, uint32_t); + bool decodeColskipMode(BitReader*, uint8_t*, uint32_t, uint32_t); + bool decodeNorm2Mode(BitReader*, uint8_t*, uint32_t, uint32_t); + bool decodeNorm6Mode(BitReader*, uint8_t*, uint32_t, uint32_t); + bool decodeBitPlane(BitReader*, uint8_t*, bool*); + void inverseDiff(uint8_t*, uint32_t, uint32_t, uint32_t); + bool parseVopdquant(BitReader*, uint8_t); + bool parseSequenceHeader(const uint8_t*, uint32_t); + bool parseEntryPointHeader(const uint8_t*, uint32_t); + bool parseFrameHeaderSimpleMain(BitReader*); + bool parseFrameHeaderAdvanced(BitReader*); + std::vector m_rbdu; + }; +} +} +#endif diff --git a/codecparsers/vc1Parser_unittest.cpp b/codecparsers/vc1Parser_unittest.cpp new file mode 100644 index 0000000..8ed6bfb --- /dev/null +++ b/codecparsers/vc1Parser_unittest.cpp @@ -0,0 +1,667 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vc1Parser.h" + +// library headers +#include "common/Array.h" +#include "common/unittest.h" + +namespace YamiParser { +namespace VC1 { + + const static std::array SequenceHeader + = { 0x4e, 0x39, 0x0a, 0x81, 0x0 }; + + const static std::array g_MainVC1 = { + 0x80, 0x6b, 0x97, 0x00, 0xf3, 0xe3, 0xc1, 0x06, 0xdb, 0x3e, 0x88, 0x60, + 0x8c, 0xec, 0x31, 0x92, 0xa0, 0xaa, 0x42, 0xf6, 0x4d, 0xf7, 0x01, 0xcc, + 0x73, 0x00, 0x79, 0xea, 0xc8, 0x3a, 0xb9, 0x53, 0xb0, 0x1c, 0xb6, 0x21, + 0x99, 0x60, 0x95, 0x3f, 0x38, 0x53, 0x10, 0x79, 0xa5, 0x5a, 0x8b, 0x01, + 0xc1, 0x76, 0xe9, 0xf1, 0x03, 0xe6, 0xdd, 0xb1, 0x88, 0xf8, 0x70, 0x88, + 0xac, 0xce, 0x12, 0x99, 0x59, 0xd5, 0x42, 0x9c, 0xa5, 0x82, 0x83, 0xc7, + 0x54, 0xc5, 0xa4, 0x96, 0xf0, 0xbe, 0x05, 0x9d, 0x77, 0xa6, 0xfc, 0xe8, + 0x4e, 0x0a, 0xb0, 0x6c, 0xc2, 0x1b, 0xed, 0x0b, 0xc7, 0xcb, 0x57, 0x2e, + 0x0b, 0x11, 0xde, 0x61, 0x0d, 0x07, 0x06, 0xc6, 0x7b, 0x3b, 0x1f, 0x72, + 0x2f, 0x33, 0x09, 0xf1, 0x3f, 0xb9, 0x86, 0x01, 0x5e, 0xbe, 0xa0, 0x0b, + 0x8f, 0x21, 0x68, 0xe3, 0x01, 0x8b, 0x6d, 0x1b, 0x7b, 0x56, 0x7c, 0xba, + 0x69, 0x94, 0xc7, 0x35, 0xb3, 0x89, 0x89, 0xa1, 0x2d, 0x16, 0x5f, 0x2c, + 0x41, 0x8a, 0x22, 0x64, 0xdf, 0x26, 0x7a, 0x30, 0x2f, 0xce, 0x4f, 0x05, + 0xd8, 0x6c, 0x05, 0x23, 0xac, 0x62, 0xbc, 0x12, 0x32, 0x59, 0x1a, 0x4f, + 0x0a, 0xeb, 0x3c, 0x32, 0x00, 0xa2, 0x31, 0xbd, 0x77, 0x42, 0x49, 0xb1, + 0x6a, 0xc2, 0x07, 0x59, 0xe0, 0xd2, 0x88, 0x92, 0x6f, 0xfa, 0x13, 0x1b, + 0xec, 0x4b, 0xd8, 0x85, 0xc2, 0x7a, 0x36, 0xee, 0x8a, 0xbf, 0xa4, 0x91, + 0xb7, 0xb6, 0x5b, 0xe0, 0x45, 0x99, 0x80, 0x82, 0x26, 0xd0, 0x44, 0x7a, + 0x10, 0xc6, 0x48, 0x3f, 0x53, 0x8e, 0x30, 0x13, 0x87, 0xf6, 0x26, 0x34, + 0xfc, 0x8d, 0x89, 0x6c, 0xd2, 0x9a, 0xbc, 0x77, 0x1b, 0x80, 0x08, 0x18, + 0x62, 0x31, 0xb5, 0x79, 0xc7, 0x8f, 0xf3, 0x83, 0x12, 0x11, 0xd3, 0x84, + 0x5e, 0x18, 0x6e, 0xa1, 0x0c, 0xb6, 0xc1, 0x2b, 0x36, 0x02, 0x8d, 0x36, + 0x09, 0xe8, 0x95, 0x8a, 0xed, 0xb8, 0x0a, 0x70, 0xa0, 0x1e, 0xbb, 0xe8, + 0x85, 0xcd, 0xc5, 0xc5, 0x93, 0x31, 0x22, 0x73, 0x4a, 0xa0, 0xf4, 0x0b, + 0xd2, 0xee, 0xb7, 0x0b, 0x4d, 0x08, 0xbe, 0xfe, 0x5c, 0x33, 0x02, 0x10, + 0x63, 0xf8, 0xc1, 0x44, 0x36, 0x5a, 0x13, 0xa9, 0x72, 0x58, 0x47, 0x76, + 0x0f, 0xac, 0x16, 0x39, 0xe5, 0x28, 0x90, 0x0c, 0x7a, 0x4b, 0xc9, 0xad, + 0xb1, 0xf2, 0xb9, 0xd5, 0x62, 0x54, 0xb1, 0xa3, 0xc5, 0x38, 0x8c, 0xe4, + 0x90, 0x99, 0xe3, 0xa4, 0x58, 0xe6, 0x38, 0xec, 0xf0, 0x4e, 0x7d, 0xbc, + 0x55, 0x31, 0x82, 0x30, 0x4a, 0x0f, 0xa1, 0x2c, 0xd1, 0xce, 0x3b, 0x41, + 0xfe, 0xda, 0x1c, 0x98, 0x84, 0x2c, 0x19, 0x16, 0x94, 0x68, 0x16, 0x05, + 0x06, 0xe1, 0xf0, 0x28, 0xc4, 0x39, 0x43, 0xd9, 0x69, 0xbe, 0x08, 0x7f, + 0xca, 0xd0, 0xbc, 0x57, 0x05, 0x75, 0x07, 0xa8, 0x20, 0x93, 0xba, 0x23, + 0x47, 0x06, 0xb4, 0x19, 0xfb, 0x68, 0x73, 0xd5, 0x41, 0x1a, 0xc9, 0xa4, + 0xa6, 0x20, 0xdc, 0xcc, 0xaa, 0x6b, 0xfb, 0x75, 0x64, 0x7a, 0xaa, 0xb3, + 0xa8, 0x18, 0x51, 0x1b, 0xdc, 0x05, 0x7c, 0x61, 0x48, 0x74, 0x31, 0x64, + 0xca, 0x9a, 0xa5, 0x32, 0xeb, 0xb9, 0x50, 0x77, 0x9b, 0x70, 0x83, 0xaf, + 0x8c, 0xb0, 0x60, 0x19, 0xc4, 0x5f, 0xa3, 0xe0, 0x3e, 0x4b, 0x49, 0x72, + 0xac, 0x11, 0x95, 0x54, 0x59, 0x75, 0xe9, 0x5e, 0x6b, 0x9b, 0x5c, 0xe9, + 0x2e, 0xea, 0xa5, 0xf3, 0x5d, 0x57, 0x0f, 0x1c, 0x8f, 0xfb, 0x7e, 0x4f, + 0x8b, 0xcc, 0xf8, 0x2e, 0xb9, 0xe8, 0x09, 0x24, 0xdb, 0xf0, 0x46, 0x2a, + 0xa8, 0x64, 0xce, 0xe6, 0x8d, 0x1e, 0x83, 0x1a, 0x3d, 0x06, 0x87, 0x8c, + 0xe1, 0x31, 0x4c, 0xf4, 0xba, 0xc1, 0x00, 0x4b, 0xed, 0x10, 0x98, 0xe3, + 0x39, 0x14, 0x79, 0xaf, 0xc8, 0x30, 0x31, 0x9b, 0x26, 0x83, 0x4f, 0x89, + 0x54, 0x91, 0xcc, 0x13, 0x04, 0x61, 0xe1, 0x8f, 0xd6, 0xbe, 0xe9, 0xc5, + 0xed, 0xd0, 0xd4, 0xd8, 0xde, 0xf7, 0xef, 0x0c, 0x91, 0x65, 0xbd, 0x27, + 0xe5, 0xe2, 0xc7, 0x82, 0x1b, 0x7a, 0xb0, 0xa0, 0xe2, 0x1b, 0x61, 0xe3, + 0x88, 0xc2, 0xde, 0x25, 0x28, 0xc6, 0x73, 0x71, 0x8c, 0x1e, 0xf0, 0x33, + 0xb8, 0x63, 0x1c, 0x80, 0x9d, 0xfd, 0x8c, 0x64, 0x8e, 0x38, 0xc4, 0x40, + 0x70, 0x36, 0x98, 0x92, 0x1b, 0x68, 0xe3, 0x7d, 0xd1, 0x37, 0x50, 0x2d, + 0x91, 0x7d, 0x79, 0x94, 0x88, 0x42, 0x0f, 0x15, 0xaf, 0x21, 0x8c, 0x15, + 0x83, 0xb2, 0xc5, 0xd5, 0x13, 0x1e, 0xe2, 0x89, 0x6f, 0xef, 0x5d, 0x8b, + 0x66, 0xd5, 0xb6, 0xbc, 0xce, 0xda, 0x68, 0xf1, 0x75, 0x44, 0x61, 0xc5, + 0xc3, 0xea, 0xb4, 0x01, 0xf3, 0x66, 0x85, 0x14, 0xac, 0x17, 0xa0, 0xd5, + 0xd1, 0xd0, 0x17, 0x8d, 0xe0, 0xea, 0xb2, 0xd0, 0x28, 0xfa, 0xe3, 0xdc, + 0xea, 0x09, 0xf3, 0x45, 0x9b, 0xda, 0xa2, 0x82, 0x16, 0xe4, 0x1b, 0x50, + 0xb7, 0x3c, 0x91, 0xb7, 0xd5, 0x77, 0x98, 0x44, 0x27, 0xaf, 0xcc, 0xaa, + 0x8a, 0x85, 0x24, 0xc1, 0xb6, 0x59, 0x6c, 0x09, 0xbe, 0xe6, 0x83, 0xe9, + 0x69, 0x20, 0x73, 0x1b, 0x17, 0xfc, 0xc3, 0x99, 0x94, 0xfa, 0xba, 0x0b, + 0xe4, 0x6f, 0xd5, 0xa9, 0xb0, 0x66, 0xe6, 0x60, 0x0a, 0x14, 0x3c, 0x09, + 0x42, 0x7a, 0xfc, 0xca, 0xab, 0x42, 0x35, 0xd3, 0x02, 0xb7, 0x0d, 0x38, + 0x7b, 0xb0, 0xa9, 0x38, 0x50, 0x3e, 0xc7, 0xdd, 0x15, 0x31, 0x95, 0x10, + 0x00, 0x18, 0xe6, 0xc1, 0x41, 0xf8, 0xea, 0x88, 0xa5, 0x27, 0x26, 0xad, + 0x1d, 0x6a, 0x9b, 0xad, 0x31, 0xd6, 0x6a, 0x4a, 0xab, 0xbe, 0xa6, 0x6c, + 0x90, 0x3b, 0x67, 0xe4, 0xd0, 0x93, 0x54, 0x59, 0x38, 0x64, 0x64, 0x67, + 0x1a, 0x24, 0x3f, 0x20, 0x7c, 0x48, 0x38, 0xd4, 0xe2, 0x4d, 0x86, 0x26, + 0x41, 0xe9, 0x1b, 0xef, 0x09, 0x07, 0x00, 0xa7, 0x19, 0x73, 0xab, 0xdb, + 0x1c, 0x4b, 0x13, 0x25, 0xe6, 0x0a, 0x23, 0x75, 0x82, 0xc1, 0x06, 0xbc, + 0x77, 0x91, 0xc8, 0x76, 0x91, 0x2c, 0x49, 0xce, 0x8d, 0x17, 0xd7, 0x1b, + 0x37, 0x17, 0x1f, 0x15, 0x52, 0x89, 0xa5, 0x1b, 0x27, 0xb0, 0x26, 0xdc, + 0xca, 0x2e, 0x22, 0x30, 0xc0, 0xd8, 0x91, 0xc6, 0x27, 0x40, 0xca, 0x17, + 0x9c, 0x79, 0xac, 0x4e, 0xed, 0x43, 0x25, 0x77, 0x5b, 0x75, 0xfc, 0x43, + 0xef, 0x2f, 0x9a, 0x65, 0xbf, 0x60, 0x88, 0xdd, 0xc4, 0x24, 0x73, 0x09, + 0x26, 0xfc, 0x10, 0xb8, 0xca, 0xb3, 0x90, 0x58, 0xeb, 0xec, 0x81, 0x90, + 0x0e, 0x15, 0x3e, 0xb4, 0x34, 0x77, 0x81, 0x52, 0x04, 0x6c, 0xf0, 0x85, + 0xfd, 0xcd, 0x16, 0xde, 0x88, 0x7c, 0x68, 0x07, 0x89, 0x68, 0x85, 0x1e, + 0x03, 0x97, 0x4e, 0xb1, 0xad, 0x3c, 0x48, 0x03, 0x75, 0x2b, 0x54, 0x03, + 0x75, 0x1a, 0xd5, 0x07, 0x8a, 0xc3, 0xa2, 0xa9, 0x40, 0xa1, 0x21, 0xac, + 0xe5, 0xd1, 0x61, 0xba, 0x4c, 0xba, 0x2f, 0x66, 0xb0, 0x03, 0x9e, 0xa9, + 0x0c, 0x60, 0x9e, 0x15, 0xe1, 0xa0, 0x8d, 0xac, 0x34, 0xf8, 0x03, 0x08, + 0xd8, 0x1a, 0xc3, 0xcb, 0x5e, 0x91, 0xe9, 0x7a, 0x3e, 0x05, 0x1f, 0x0b, + 0x42, 0x7d, 0x51, 0x56, 0xbe, 0x46, 0x33, 0x43, 0x0c, 0x9a, 0xda, 0xe7, + 0xbe, 0x50, 0x10, 0x8e, 0xc6, 0xb4, 0xd1, 0x42, 0xbb, 0x09, 0x18, 0x65, + 0x1a, 0xdc, 0x0f, 0x82, 0x30, 0x34, 0xf8, 0xe9, 0xf8, 0x59, 0xf4, 0x9f, + 0x4c, 0xba, 0x1d, 0x16, 0xbf, 0xa2, 0xb0, 0x3b, 0xc4, 0xda, 0x7d, 0x65, + 0xcc, 0xaa, 0x0e, 0xe0, 0xcd, 0x2c, 0xb6, 0x01, 0x8d, 0x80, 0xa9, 0x04, + 0xa8, 0x43, 0x69, 0xa3, 0x37, 0xc1, 0xf0, 0x2f, 0x27, 0xf0, 0x83, 0x57, + 0x60, 0x17, 0x21, 0xe2, 0xe8, 0x71, 0x89, 0x83, 0x0e, 0xbb, 0x91, 0x84, + 0xb9, 0xf6, 0xc5, 0xd0, 0xd5, 0x68, 0xb2, 0xeb, 0xd9, 0x5c, 0x65, 0x37, + 0xd1, 0xcb, 0xab, 0x43, 0x4c, 0xd7, 0x55, 0x28, 0x44, 0x97, 0x7d, 0x4d, + 0x7a, 0xeb, 0x47, 0x3c, 0x49, 0x53, 0x1f, 0x22, 0x12, 0x8b, 0x83, 0xd1, + 0x4f, 0x72, 0x35, 0x71, 0xf1, 0x47, 0xa9, 0xb9, 0xd4, 0x49, 0xd5, 0xe4, + 0xd2, 0xdc, 0xee, 0x90, 0x82, 0xe6, 0xe8, 0x47, 0xa9, 0xfb, 0x3c, 0x9e, + 0x8d, 0xa3, 0xe6, 0x1a, 0x19, 0x29, 0x08, 0x68, 0x85, 0x10, 0xb2, 0x3f, + 0x12, 0x3b, 0x89, 0x7c, 0x78, 0x64, 0x20, 0x09, 0x24, 0x69, 0xc4, 0xf1, + 0x0b, 0x27, 0xba, 0xd0, 0x3f, 0xb9, 0x08, 0x80, 0x76, 0x10, 0x23, 0x7a, + 0xa7, 0xb6, 0xc8, 0x30, 0x27, 0xbf, 0x42, 0xcc, 0x28, 0x27, 0x37, 0x35, + 0x13, 0x32, 0xcd, 0x19, 0xdc, 0x63, 0xa2, 0x5f, 0x0a, 0xc8, 0xf1, 0x69, + 0x08, 0x7e, 0x05, 0x20, 0x2d, 0xff, 0xf1, 0x70, 0x8a, 0x41, 0xed, 0x87, + 0x13, 0x7a, 0x87, 0x90, 0x2e, 0x14, 0xc6, 0x4b, 0x19, 0x40, 0xdc, 0x4f, + 0xb1, 0x13, 0x80, 0xf2, 0x90, 0xd7, 0x27, 0x11, 0x85, 0x5e, 0x16, 0x6a, + 0x01, 0x6f, 0x7b, 0x5e, 0x88, 0x91, 0x02, 0x94, 0x88, 0x32, 0x3d, 0x45, + 0xd2, 0xe7, 0xbd, 0xaa, 0xff, 0xd8, 0x0e, 0x50, 0xa4, 0xf7, 0x85, 0x18, + 0xb3, 0x04, 0x0e, 0xca, 0x60, 0xe4, 0x61, 0x44, 0x2b, 0x0f, 0xa8, 0x7a, + 0x57, 0x57, 0x6c, 0x04, 0xbb, 0x95, 0x5b, 0x94, 0x21, 0xb5, 0x50, 0x14, + 0x67, 0xce, 0x0d, 0xae, 0xfd, 0xa9, 0xf8, 0x36, 0x66, 0xda, 0x04, 0x94, + 0x49, 0xc3, 0x19, 0xd9, 0x86, 0xad, 0xd0, 0xd1, 0x65, 0xc1, 0x92, 0x46, + 0x1e, 0x04, 0xfe, 0xad, 0xc1, 0x68, 0x12, 0xe8, 0x79, 0x82, 0x3b, 0x2e, + 0x31, 0x14, 0x26, 0x98, 0xcf, 0x87, 0xb8, 0x08, 0xab, 0x23, 0x05, 0x6e, + 0x20, 0xe0, 0x57, 0x81, 0x81, 0x55, 0x07, 0xbf, 0x16, 0xf4, 0xb1, 0x86, + 0x64, 0x45, 0x54, 0xf0, 0x15, 0xf1, 0x8e, 0x38, 0xd8, 0xf8, 0x8e, 0x19, + 0xb9, 0x86, 0x0c, 0x05, 0xb7, 0x09, 0x6e, 0x91, 0xda, 0x07, 0xbf, 0xf4, + 0x61, 0x6f, 0xdb, 0x65, 0x09, 0x92, 0xd9, 0x2e, 0x18, 0x15, 0x3a, 0x78, + 0x19, 0x80, 0x25, 0x99, 0x3d, 0x49, 0x0a, 0xe2, 0x48, 0x5d, 0xc8, 0x01, + 0x33, 0xf8, 0x08, 0x54, 0x2c, 0x4c, 0x38, 0x66, 0x69, 0x2b, 0x27, 0x19, + 0xc5, 0xad, 0xaf, 0x5d, 0x5b, 0x8e, 0x3a, 0xa8, 0xb2, 0xea, 0xa1, 0xb5, + 0x5a, 0x2c, 0xba, 0xdd, 0x89, 0x6b, 0x5b, 0x10, 0xbb, 0x67, 0x20, 0x00, + 0xc9, 0x73, 0x51, 0x52, 0x00, 0x99, 0xf1, 0xb4, 0x8a, 0x97, 0x49, 0x24, + 0x4b, 0xb6, 0x8b, 0x1e, 0x01, 0x35, 0xf2, 0xc2, 0x91, 0x8b, 0x84, 0x7f, + 0x8d, 0x70, 0x83, 0x3c, 0x08, 0x50, 0x3e, 0xf8, 0xd9, 0x31, 0x92, 0x35, + 0x3d, 0x3f, 0xda, 0x90, 0xf4, 0x10, 0xfd, 0x5d, 0x99, 0x7a, 0xa2, 0x67, + 0x7b, 0x6f, 0x6d, 0x64, 0xa1, 0x5c, 0x05, 0x8a, 0x57, 0x67, 0x81, 0x9e, + 0xdb, 0x01, 0x73, 0x5e, 0x4f, 0x2e, 0x8f, 0xd7, 0x90, 0xc4, 0x4d, 0xe3, + 0x6d, 0x12, 0x84, 0x94, 0xc5, 0x1d, 0x59, 0x91, 0xea, 0x4a, 0x76, 0x24, + 0x80, 0x89, 0x23, 0x6d, 0x06, 0x1c, 0xcb, 0x80, 0xc2, 0x5b, 0x43, 0xa8, + 0xf0, 0x09, 0x78, 0x96, 0xfb, 0x47, 0x8f, 0x30, 0x39, 0x24, 0x63, 0xee, + 0x22, 0x03, 0x68, 0x08, 0x45, 0x23, 0x8f, 0xe4, 0xf6, 0x19, 0xd0, 0x30, + 0x16, 0x1f, 0xda, 0x48, 0x79, 0xaf, 0x5a, 0x62, 0x19, 0x07, 0x1f, 0x7e, + 0x0f, 0x73, 0x3c, 0x34, 0xd9, 0x31, 0xe0, 0xca, 0xfb, 0x53, 0x09, 0x02, + 0xc4, 0x9a, 0x5b, 0x88, 0x7c, 0x63, 0x07, 0x91, 0xc5, 0x0a, 0x6f, 0x41, + 0x1b, 0x20, 0x69, 0x19, 0xde, 0x1d, 0x71, 0x8b, 0xe2, 0x0c, 0x6d, 0xb6, + 0xa2, 0x3f, 0xcb, 0x79, 0x91, 0x02, 0x2c, 0xfc, 0xea, 0x70, 0x5c, 0x67, + 0x9b, 0x63, 0xc0, 0x4f, 0x0f, 0x6e, 0x14, 0x7c, 0x11, 0x90, 0x54, 0x04, + 0x51, 0xbe, 0x22, 0x81, 0x31, 0x90, 0x49, 0x9c, 0xdd, 0x1d, 0x40, 0xd0, + 0x43, 0x00, 0x6b, 0xea, 0x78, 0x26, 0xd6, 0x09, 0x83, 0x61, 0x3b, 0xc9, + 0x76, 0xeb, 0xc4, 0x01, 0x08, 0x46, 0xe1, 0xfb, 0xd7, 0x7d, 0xba, 0x62, + 0xeb, 0xeb, 0xb3, 0x0a, 0x8a, 0xed, 0xe5, 0x0b, 0xaf, 0x62, 0x5e, 0x6d, + 0x47, 0x11, 0xde, 0xce, 0x93, 0x60, 0x00, 0x2e, 0x47, 0x52, 0x38, 0xd3, + 0x49, 0x5c, 0x6c, 0x1b, 0xdc, 0xdd, 0x86, 0x93, 0x38, 0x2e, 0x42, 0x0e, + 0xc7, 0x32, 0x41, 0x0e, 0xbb, 0x56, 0x57, 0x11, 0x9a, 0xfb, 0x58, 0x13, + 0xa4, 0x5a, 0x9f, 0x7e, 0x42, 0x3e, 0x3e, 0x98, 0x43, 0xae, 0x4c, 0x86, + 0xb0, 0xed, 0x51, 0x21, 0x09, 0xa6, 0x08, 0x36, 0x13, 0x97, 0xaf, 0x5f, + 0xd7, 0x67, 0x8d, 0xdc, 0x1a, 0x08, 0xcd, 0xf9, 0xc0, 0xac, 0x12, 0xfa, + 0x90, 0x5a, 0xef, 0x17, 0xf5, 0xb5, 0x37, 0xd7, 0xed, 0x20, 0xf4, 0x24, + 0x93, 0xa3, 0x42, 0xed, 0xad, 0x54, 0x23, 0x4b, 0x30, 0x15, 0x0f, 0x04, + 0x61, 0xdd, 0xa1, 0xc6, 0x69, 0xde, 0xfd, 0x87, 0x51, 0xd2, 0x8b, 0x23, + 0x8d, 0x0c, 0xf4, 0x3b, 0x4f, 0x07, 0xc9, 0xda, 0xd0, 0x41, 0x38, 0x88, + 0xb9, 0x90, 0x4f, 0x72, 0x92, 0x44, 0x04, 0x62, 0x0f, 0x18, 0xf9, 0x89, + 0xe1, 0x06, 0xc8, 0x84, 0x50, 0xc9, 0x43, 0x5d, 0x8c, 0xac, 0x38, 0xd7, + 0x90, 0x36, 0x6b, 0x91, 0x2e, 0xcd, 0x96, 0xcd, 0x8b, 0x13, 0xd8, 0x85, + 0x13, 0x99, 0x79, 0xd4, 0x0a, 0x74, 0x8f, 0xa6, 0x26, 0x19, 0xa2, 0x20, + 0xd8, 0x5d, 0xc0, 0xe4, 0xf7, 0xa3, 0x5d, 0x21, 0x22, 0xbf, 0xd3, 0x05, + 0x86, 0x60, 0xf6, 0xd5, 0x00, 0x36, 0x5e, 0x5a, 0xb9, 0xa8, 0xc7, 0xf3, + 0xdc, 0xea, 0x83, 0x08, 0x57, 0x24, 0x56, 0xf7, 0x2b, 0x40, 0x2a, 0x0d, + 0x56, 0x8e, 0x31, 0x50, 0xb9, 0xd6, 0x57, 0x44, 0x72, 0x09, 0x44, 0x79, + 0xe7, 0x7f, 0xb1, 0x83, 0xa9, 0xc4, 0xbb, 0xcd, 0x20, 0x06, 0x4b, 0xae, + 0xf1, 0xe0, 0x13, 0x9a, 0x54, 0x72, 0xef, 0xbc, 0x5c, 0x24, 0x75, 0x87, + 0x49, 0x1b, 0xb2, 0xc9, 0x97, 0x0f, 0x49, 0x37, 0x71, 0x93, 0x56, 0x59, + 0x34, 0x03, 0x26, 0x58, 0xc3, 0xdd, 0x98, 0x30, 0x2d, 0x54, 0x8f, 0xdc, + 0x75, 0xf6, 0xaf, 0x25, 0x04, 0xe8, 0xce, 0x70, 0x00, 0xc4, 0x45, 0x09, + 0xdc, 0x68, 0x3a, 0x65, 0x03, 0x41, 0xfd, 0x09, 0xc4, 0x3f, 0xe1, 0x31, + 0x78, 0xb0, 0x0c, 0x37, 0x10, 0xf6, 0xa7, 0x14, 0x3a, 0xe9, 0xa9, 0xcf, + 0xb2, 0x5d, 0xfc, 0x9d, 0xe4, 0x1a, 0xa2, 0xff, 0xc4, 0x65, 0x5b, 0x3c, + 0xbe, 0x8f, 0x12, 0xfa, 0x13, 0x42, 0xeb, 0x82, 0x16, 0xf1, 0x12, 0xc4, + 0xcf, 0x45, 0xaa, 0xfe, 0x70, 0xd0, 0xb0, 0x14, 0xf9, 0xc8, 0xc4, 0xe7, + 0x50, 0x86, 0xc8, 0x8d, 0x31, 0x65, 0xbd, 0xa2, 0x4d, 0x1a, 0xec, 0x8c, + 0x62, 0x28, 0xa2, 0x69, 0x14, 0x24, 0xb4, 0xc3, 0x34, 0x25, 0x80, 0xc8, + 0x29, 0x71, 0xdf, 0x8a, 0xe1, 0x0d, 0xe3, 0x15, 0xe6, 0xbe, 0x74, 0x1a, + 0xbb, 0x66, 0xbb, 0xa3, 0x30, 0x76, 0x22, 0x7b, 0xef, 0xdb, 0x19, 0x13, + 0xb9, 0x84, 0x14, 0xa3, 0x98, 0xb8, 0x60, 0x00, 0x2d, 0xdb, 0x04, 0x81, + 0x12, 0x8f, 0xb8, 0x81, 0x48, 0x36, 0x18, 0x08, 0x93, 0x7d, 0x04, 0x16, + 0x73, 0xe3, 0xbc, 0x41, 0x7b, 0x22, 0x1b, 0x23, 0xba, 0x24, 0xe9, 0x3a, + 0x25, 0x31, 0x90, 0xaf, 0xc5, 0x80, 0xff, 0xf5, 0x84, 0xad, 0x8d, 0x67, + 0x13, 0x2f, 0x9e, 0x4d, 0x8f, 0x46, 0x07, 0x03, 0xbe, 0xb4, 0xb4, 0xe8, + 0xcd, 0x23, 0x2e, 0x97, 0x7e, 0x36, 0x05, 0x7c, 0x25, 0x5c, 0x1e, 0x72, + 0xa0, 0x74, 0xfa, 0x92, 0x97, 0x66, 0x3d, 0xfb, 0x51, 0xa8, 0x9b, 0xee, + 0x2a, 0xf9, 0x6c, 0xc9, 0xa6, 0xc2, 0x03, 0x9b, 0x52, 0x05, 0x95, 0xb7, + 0x29, 0xb4, 0xd1, 0xac, 0x0b, 0x78, 0x0a, 0x30, 0xd1, 0x41, 0xee, 0x7d, + 0xaa, 0x9b, 0x85, 0xad, 0x1d, 0x55, 0x05, 0xaa, 0x38, 0x9c, 0x39, 0xe7, + 0x70, 0xa8, 0xb2, 0x19, 0x5c, 0x5d, 0x16, 0x06, 0x83, 0xdd, 0xc0, 0xe8, + 0x4d, 0x2f, 0x88, 0x9f, 0xe9, 0xb0, 0x20, 0x38, 0x96, 0x96, 0x22, 0x5a, + 0x5d, 0xea, 0xc6, 0x9a, 0x3c, 0x8c, 0x71, 0x31, 0xb5, 0xf4, 0xe7, 0x48, + 0x02, 0x21, 0x4a, 0x5c, 0x1c, 0x07, 0x37, 0x29, 0xa7, 0x2a, 0xd6, 0x8e, + 0x83, 0x8e, 0x16, 0x46, 0x03, 0x38, 0x8b, 0xfe, 0x03, 0xd8, 0x38, 0x9e, + 0x57, 0x59, 0x79, 0x89, 0x03, 0x7b, 0x90, 0xad, 0xff, 0x26, 0x86, 0x50, + 0x0a, 0x71, 0xa9, 0x71, 0xd6, 0xc6, 0x76, 0xf4, 0x1c, 0x7d, 0x9d, 0x73, + 0xc8, 0xbe, 0x8e, 0x94, 0x61, 0x09, 0x49, 0x87, 0x3c, 0x0b, 0x9c, 0x98, + 0xb6, 0x92, 0xe3, 0x8c, 0x90, 0xe4, 0xed, 0xd3, 0x9f, 0x23, 0x12, 0x89, + 0xf6, 0x14, 0x68, 0x0e, 0xd2, 0x4f, 0x9b, 0x9c, 0x33, 0x89, 0xa2, 0x80, + 0xd1, 0xdc, 0x93, 0x39, 0x76, 0xb0, 0x7b, 0x42, 0x94, 0x32, 0x2c, 0x04, + 0xfe, 0xfb, 0x2d, 0x88, 0x98, 0xfc, 0x32, 0x82, 0x62, 0x11, 0x09, 0x11, + 0x10, 0xb8, 0x63, 0x1d, 0xf7, 0xa9, 0x03, 0x6a, 0x3b, 0x97, 0x49, 0x64, + 0x13, 0xa2, 0xb7, 0xb8, 0xb4, 0x96, 0xdb, 0x68, 0xe6, 0x2e, 0xec, 0x9a, + 0x18, 0xc1, 0x08, 0x98, 0x04, 0x71, 0x18, 0x24, 0x40, 0xa3, 0x32, 0x05, + 0xe6, 0x84, 0x42, 0xc3, 0xa2, 0x4c, 0x67, 0x49, 0x14, 0x43, 0xe5, 0xe2, + 0x36, 0x1f, 0x51, 0x61, 0x59, 0x88, 0x5e, 0x6f, 0xb8, 0xc6, 0xfb, 0xb6, + 0x1a, 0x75, 0xc3, 0xad, 0x25, 0x3c, 0x10, 0x90, 0xf8, 0xe8, 0x64, 0x9a, + 0x7d, 0x6b, 0x5f, 0xfa, 0x6c, 0x08, 0xa0, 0x53, 0x4e, 0x0f, 0xab, 0x81, + 0x0a, 0x0e, 0x9a, 0x13, 0x2e, 0x54, 0x10, 0xd1, 0x07, 0x02, 0xf2, 0xaf, + 0xb0, 0x05, 0xf5, 0xd4, 0xd2, 0x94, 0x15, 0x17, 0x93, 0x2d, 0x4c, 0x3e, + 0x3e, 0x16, 0x61, 0x62, 0xb5, 0xb6, 0xe7, 0x3c, 0x86, 0x34, 0xaf, 0xa8, + 0x0c, 0xd7, 0x8c, 0x79, 0xc9, 0xc3, 0xad, 0xeb, 0xa8, 0x75, 0x5d, 0x03, + 0x54, 0x5e, 0xc4, 0xbf, 0xba, 0x1d, 0x75, 0x05, 0xed, 0x64, 0x4d, 0x84, + 0xe7, 0xe1, 0x3f, 0x6a, 0x61, 0xd5, 0xe2, 0x90, 0xe7, 0xf3, 0xff, 0xe7, + 0xba, 0xee, 0x5f, 0x94, 0x2a, 0x17, 0x36, 0xec, 0x13, 0x5d, 0xea, 0x7e, + 0x86, 0xb5, 0x47, 0x13, 0xf6, 0x31, 0x70, 0xbc, 0x13, 0xe4, 0xcd, 0x2e, + 0x50, 0xb6, 0x32, 0xf0, 0x1c, 0xdd, 0xc1, 0xac, 0xd8, 0xd8, 0xe9, 0xd4, + 0x44, 0xb0, 0x3e, 0x62, 0x69, 0x46, 0x0a, 0x5f, 0xa4, 0xb8, 0x01, 0x5b, + 0x03, 0xdc, 0xc1, 0xb3, 0xf1, 0x27, 0x0e, 0xbc, 0x21, 0xae, 0x3d, 0x7a, + 0xce, 0xb3, 0x40, 0x61, 0xb2, 0xe4, 0xc2, 0x13, 0x11, 0xfb, 0x9c, 0x29, + 0x21, 0x5e, 0x41, 0xdb, 0x8e, 0x20, 0xdb, 0x87, 0x70, 0x88, 0x25, 0xa5, + 0x52, 0x08, 0xeb, 0x21, 0x06, 0x85, 0x4b, 0xbb, 0x0c, 0x37, 0x18, 0x94, + 0xb8, 0x72, 0xb8, 0x11, 0xdc, 0x8c, 0x08, 0x85, 0x61, 0x8c, 0xd0, 0x26, + 0x18, 0x86, 0x50, 0xba, 0x03, 0xc6, 0xbb, 0x0b, 0x88, 0x93, 0x43, 0x32, + 0x53, 0x42, 0x89, 0x92, 0x50, 0x6e, 0xd1, 0xb1, 0xa0, 0x95, 0xdc, 0xf8, + 0x46, 0x35, 0xdc, 0xd2, 0x8d, 0x5c, 0x01, 0x56, 0x84, 0x22, 0xe1, 0x49, + 0x24, 0x70, 0x75, 0xc2, 0xbf, 0xa8, 0x7a, 0xa0, 0xe3, 0x09, 0x2e, 0x15, + 0x7e, 0x90, 0x84, 0xba, 0xe7, 0xdc, 0x85, 0xc4, 0x01, 0x8b, 0xef, 0x0a, + 0x71, 0xea, 0x38, 0x01, 0x1d, 0x63, 0x6b, 0xb1, 0x22, 0x57, 0xa4, 0x75, + 0x10, 0x85, 0xda, 0x77, 0xbd, 0x30, 0x24, 0xf4, 0x62, 0xe1, 0x15, 0x56, + 0xf4, 0x96, 0x86, 0xb4, 0x8b, 0x88, 0xc6, 0x87, 0xee, 0xc9, 0x89, 0x61, + 0x69, 0xb9, 0x27, 0xa1, 0xf3, 0x6a, 0x0c, 0x91, 0xf9, 0xf8, 0x78, 0x91, + 0x82, 0xa0, 0x50, 0x9b, 0x97, 0x84, 0xdd, 0xc3, 0x10, 0xc1, 0x3e, 0xf6, + 0xf1, 0x9c, 0x64, 0x21, 0x00, 0xa6, 0x43, 0xc6, 0xe2, 0x05, 0xfe, 0xfc, + 0x4b, 0x63, 0x18, 0xe2, 0x02, 0x2d, 0x94, 0x24, 0x35, 0x77, 0xc0, 0x89, + 0x0a, 0x53, 0x85, 0x9b, 0x6e, 0xbf, 0x7b, 0xd1, 0xeb, 0x15, 0xd3, 0x91, + 0x31, 0xb1, 0xa2, 0x44, 0x65, 0x08, 0x3f, 0x32, 0xb3, 0xc1, 0xd6, 0x0a, + 0x0d, 0x9f, 0x58, 0xec, 0xc4, 0xcd, 0x6c, 0x4d, 0x3d, 0x67, 0x13, 0x88, + 0x1d, 0x79, 0x4a, 0x21, 0xa2, 0x69, 0xc9, 0x93, 0x2f, 0x2c, 0x27, 0xf7, + 0x1d, 0x0d, 0x52, 0x68, 0x98, 0x98, 0xda, 0x66, 0x9a, 0x03, 0x2d, 0x9d, + 0x6e, 0x0b, 0x7e, 0x0c, 0x29, 0x88, 0x67, 0x62, 0x77, 0x0c, 0xcd, 0x26, + 0x87, 0xa3, 0x39, 0xca, 0x7e, 0xc7, 0x0c, 0x06, 0x3b, 0x6b, 0x10, 0x07, + 0x9c, 0x97, 0x26, 0xf4, 0x72, 0x12, 0xcd, 0xc8, 0x8c, 0x76, 0x1b, 0x4c, + 0x76, 0x73, 0xc0, 0x4b, 0xc7, 0xa6, 0x10, 0x1f, 0x16, 0x17, 0x5a, 0x5e, + 0xd9, 0x8c, 0xdd, 0x14, 0x33, 0x30, 0xa1, 0x15, 0x86, 0x1b, 0x73, 0x7e, + 0x9b, 0xf9, 0x28, 0x1f, 0x42, 0xc0, 0x56, 0x46, 0x18, 0x4a, 0x8c, 0xaf, + 0x2b, 0x98, 0x51, 0xf6, 0xa2, 0xeb, 0xca, 0x4f, 0xa2, 0x25, 0x52, 0xeb, + 0xeb, 0xc3, 0x10, 0x38, 0x29, 0xaf, 0x1b, 0xd1, 0xda, 0x73, 0xe9, 0x16, + 0x83, 0xba, 0x69, 0x45, 0xf5, 0xd5, 0xd9, 0xa6, 0x5f, 0x53, 0xa6, 0x54, + 0x75, 0x36, 0x2c, 0xba, 0xbc, 0xbc, 0x2b, 0x95, 0x8a, 0x1a, 0x6e, 0x78, + 0x70, 0xda, 0xf6, 0x23, 0x82, 0xc3, 0xb7, 0x5e, 0x06, 0x7d, 0x88, 0x24, + 0x66, 0xe8, 0x69, 0x92, 0x87, 0xf1, 0x31, 0xb4, 0x83, 0x8c, 0xf3, 0x5f, + 0x25, 0x0e, 0xff, 0x94, 0x14, 0x50, 0x8f, 0x0d, 0xc1, 0xe1, 0x4f, 0x25, + 0x7b, 0x2d, 0xf0, 0xdb, 0x56, 0xe2, 0x10, 0xc8, 0x10, 0xa3, 0x64, 0x33, + 0xb8, 0xd1, 0x42, 0x7f, 0xc2, 0x54, 0xe3, 0x38, 0x4d, 0x14, 0xb0, 0x80, + 0x9c, 0xa8, 0x15, 0x79, 0x4c, 0xdc, 0xf3, 0x4e, 0x26, 0x2b, 0x37, 0x17, + 0x17, 0xf1, 0x9b, 0x87, 0x3a, 0xcf, 0x4e, 0xc9, 0x50, 0x67, 0xb1, 0x9b, + 0x23, 0x88, 0x29, 0x3d, 0x5d, 0xcc, 0xd9, 0x2b, 0xa9, 0xad, 0x08, 0xdb, + 0x05, 0x25, 0xf7, 0x73, 0x19, 0xcb, 0xdd, 0xe3, 0x65, 0xfd, 0x40, 0xed, + 0x30, 0xb6, 0x01, 0x7b, 0x82, 0x19, 0xbe, 0x39, 0x86, 0x8a, 0xa0, 0x05, + 0xd0, 0x4a, 0x1e, 0xdf, 0x08, 0xa6, 0xe2, 0x62, 0x8f, 0xb2, 0xd1, 0x89, + 0x08, 0xe0, 0xbe, 0x36, 0x90, 0x86, 0x89, 0x20, 0xa2, 0x13, 0x37, 0xe7, + 0x78, 0x61, 0x05, 0x03, 0xba, 0xeb, 0xda, 0x90, 0x7c, 0x70, 0x4c, 0x47, + 0x1e, 0x8d, 0x24, 0x21, 0x37, 0x39, 0x9a, 0x26, 0x4b, 0x61, 0xcc, 0x4d, + 0x31, 0x93, 0x0b, 0x81, 0x7b, 0x1a, 0x59, 0x26, 0x5a, 0x63, 0x13, 0xf0, + 0x32, 0xe3, 0x80, 0x11, 0x24, 0x85, 0x74, 0xc5, 0x21, 0x00, 0x32, 0x23, + 0xf3, 0xf2, 0x62, 0x8c, 0xa8, 0xea, 0xfd, 0xd9, 0x3e, 0xfd, 0x3d, 0x6f, + 0x15, 0xe8, 0xa9, 0x27, 0x3d, 0x89, 0x0d, 0x1d, 0x28, 0x28, 0x6a, 0x23, + 0x8f, 0x18, 0xb0, 0x96, 0xcb, 0xd6, 0x24, 0xce, 0x0e, 0x5f, 0x12, 0x8f, + 0xe0, 0x86, 0x87, 0xdd, 0xc3, 0x14, 0x69, 0x44, 0xb2, 0x3f, 0x8b, 0xb2, + 0x7b, 0x85, 0x1b, 0xdc, 0x82, 0x98, 0xce, 0x90, 0x91, 0xdd, 0x64, 0xd5, + 0x3b, 0x48, 0xfb, 0xb3, 0xfe, 0xf4, 0x66, 0x3e, 0x0b, 0x26, 0xc4, 0xe7, + 0x20, 0x5f, 0x70, 0xa7, 0x3f, 0xf4, 0x19, 0xfb, 0x8e, 0xa9, 0x5f, 0xc1, + 0x16, 0x62, 0x3c, 0x28, 0x10, 0x20, 0x81, 0x45, 0x1e, 0x05, 0xde, 0xa6, + 0x48, 0x94, 0xe3, 0x25, 0x5d, 0x7f, 0x72, 0x15, 0x0d, 0x62, 0x51, 0x68, + 0xc6, 0x21, 0x93, 0x8f, 0xb9, 0x7d, 0x8b, 0x8d, 0x21, 0x91, 0x28, 0xd6, + 0x98, 0x79, 0xa1, 0xc5, 0x88, 0x86, 0x42, 0x9c, 0x11, 0xc1, 0xb6, 0x40, + 0xe2, 0x11, 0xd6, 0x22, 0x4e, 0x80, 0x09, 0xee, 0x0b, 0xd8, 0xd6, 0x60, + 0x88, 0x48, 0xdd, 0x24, 0x70, 0x18, 0x57, 0xf4, 0x33, 0xa8, 0x1e, 0xa6, + 0xd0, 0xd8, 0xd8, 0x58, 0x6d, 0xa3, 0x4b, 0xac, 0x4a, 0x88, 0x41, 0x45, + 0x51, 0x0c, 0x8f, 0x1c, 0x22, 0x1f, 0xea, 0xed, 0x56, 0x2b, 0x6a, 0x06, + 0x35, 0x10, 0xda, 0xb1, 0x09, 0x3e, 0xc8, 0x31, 0xc9, 0xa6, 0x1f, 0xc2, + 0x44, 0x34, 0x7a, 0xe1, 0x34, 0xe8, 0x17, 0x3e, 0x11, 0xf4, 0x1f, 0xd9, + 0x38, 0xc1, 0xc7, 0x2a, 0x68, 0xc4, 0x2e, 0x61, 0x04, 0xf3, 0xa0, 0x4d, + 0x3d, 0x7d, 0x70, 0x3b, 0x98, 0x91, 0x72, 0xa3, 0x51, 0x49, 0xf1, 0x31, + 0xd0, 0x9a, 0xc4, 0x8e, 0xcb, 0x90, 0xc6, 0x00, 0xa8, 0xaf, 0xc8, 0x90, + 0x37, 0xfa, 0x0a, 0x94, 0xe6, 0x1a, 0x77, 0x5f, 0x52, 0x0d, 0x2e, 0xab, + 0x8e, 0x6b, 0xaf, 0xa6, 0x08, 0x4a, 0xfb, 0xe4, 0x2e, 0xd3, 0x4d, 0x0c, + 0x91, 0xf9, 0x49, 0x25, 0x16, 0xc6, 0x97, 0x09, 0xf1, 0x88, 0xd9, 0x9d, + 0xc1, 0x88, 0xd9, 0x92, 0x39, 0xbd, 0xc5, 0xba, 0xe3, 0x49, 0xd0, 0x78, + 0x50, 0x20, 0x65, 0xb6, 0x3f, 0xc0, 0x31, 0xc6, 0xb1, 0x49, 0x1e, 0x28, + 0xfd, 0x9a, 0x71, 0xb1, 0x0c, 0x8b, 0xae, 0x7f, 0xc3, 0xb7, 0x21, 0xb4, + 0x19, 0x8e, 0xe6, 0x2a, 0x16, 0xc2, 0x9f, 0xd9, 0x82, 0x23, 0x34, 0x14, + 0x60, 0xe8, 0xb6, 0x65, 0x66, 0x24, 0xbb, 0xf3, 0x13, 0x52, 0x1b, 0x07, + 0x83, 0xd8, 0x4e, 0x9d, 0x83, 0xf6, 0x36, 0x31, 0x36, 0x31, 0xa1, 0x88, + 0xb3, 0x78, 0x3c, 0x80, 0x19, 0xab, 0x51, 0x5e, 0xac, 0x9e, 0x34, 0x64, + 0xb4, 0x0f, 0x8b, 0xde, 0x7a, 0x22, 0x01, 0x5b, 0x6c, 0xdb, 0x09, 0x89, + 0x06, 0x62, 0xb9, 0x77, 0x9e, 0x8c, 0x40, 0x8a, 0x80, 0x06, 0x0e, 0xd7, + 0x4d, 0xab, 0x98, 0x8b, 0xe7, 0x01, 0xee, 0x93, 0x4c, 0xb2, 0x61, 0xf1, + 0xfb, 0x71, 0xc6, 0xbf, 0xdf, 0x0b, 0x57, 0xfb, 0x87, 0xc4, 0xc7, 0x68, + 0x20, 0x38, 0x67, 0x07, 0x0d, 0x07, 0x0b, 0x08, 0x8b, 0xba, 0x1e, 0xec, + 0x5b, 0x78, 0x2a, 0x49, 0x0f, 0x0e, 0x90, 0x42, 0xe1, 0xdf, 0x27, 0x02, + 0x98, 0x8e, 0x1c, 0x7a, 0x71, 0x31, 0x8a, 0x4e, 0x21, 0x09, 0xe4, 0x7e, + 0x88, 0xe3, 0x4b, 0xf6, 0xb5, 0x7b, 0x40, 0xa9, 0x14, 0x33, 0xad, 0x34, + 0x92, 0x43, 0x3b, 0x08, 0xc8, 0x5f, 0xa0, 0xef, 0xc5, 0x89, 0x18, 0x79, + 0x62, 0x3a, 0xa0, 0x79, 0xeb, 0x37, 0x8c, 0x86, 0xcd, 0xa2, 0xbc, 0x0c, + 0x90, 0x9a, 0x04, 0x6c, 0x88, 0xce, 0xf6, 0x0d, 0x8d, 0x08, 0x43, 0x99, + 0x61, 0xb3, 0x23, 0x28, 0x82, 0xdf, 0x8d, 0xa5, 0xa3, 0x89, 0x2b, 0x86, + 0x21, 0x07, 0x0a, 0xf1, 0x8d, 0x76, 0x06, 0x83, 0x60, 0x40, 0xff, 0xec, + 0x40, 0xab, 0x22, 0xec, 0x39, 0xd3, 0x71, 0x2e, 0x0f, 0x0c, 0xcf, 0x29, + 0x7a, 0xec, 0xfa, 0x45, 0xed, 0xc8, 0x3a, 0xf4, 0x42, 0x47, 0x1c, 0xc0, + 0xdd, 0xb0, 0x42, 0x2c, 0xa7, 0x12, 0x37, 0x8d, 0x08, 0x80, 0x22, 0x97, + 0x54, 0xce, 0x5e, 0x65, 0x6d, 0xe6, 0x0d, 0x26, 0x1b, 0xfc, 0x0a, 0x5f, + 0x53, 0xac, 0x61, 0x2d, 0x1b, 0x3e, 0x5f, 0xd4, 0xca, 0x8f, 0x01, 0x30, + 0x7c, 0x04, 0x68, 0xb8, 0x0c, 0x87, 0x57, 0x84, 0x36, 0x0d, 0x81, 0x8c, + 0x1d, 0x8d, 0x35, 0x28, 0xde, 0x50, 0x59, 0x47, 0xb7, 0x6e, 0xe1, 0x29, + 0x60, 0x01, 0x9a, 0x5c, 0x0a, 0xa2, 0x5a, 0x22, 0x62, 0x06, 0xa3, 0x74, + 0x15, 0x2a, 0x16, 0xf6, 0xe9, 0x5a, 0x56, 0xbc, 0x27, 0x27, 0xb8, 0x1b, + 0x9c, 0xcb, 0x6e, 0x7f, 0x70, 0xbc, 0x72, 0x13, 0xfe, 0x9e, 0x9e, 0x89, + 0x1d, 0xdd, 0x21, 0x51, 0xdb, 0x71, 0xce, 0xf3, 0x68, 0xe9, 0xb0, 0x83, + 0xd0, 0x2d, 0x90, 0x54, 0x2e, 0x91, 0x19, 0x47, 0xcb, 0x86, 0x89, 0xa7, + 0x3d, 0x98, 0x2e, 0xb4, 0x28, 0xbd, 0x33, 0xfe, 0x6e, 0x0a, 0x56, 0x2c, + 0x5e, 0x17, 0xc1, 0x17, 0x62, 0x17, 0x1d, 0x67, 0xeb, 0x9d, 0xa9, 0x74, + 0x9d, 0x8d, 0xbc, 0xa4, 0x6e, 0x6b, 0xbe, 0xfc, 0x6a, 0x8b, 0xdf, 0x2b, + 0x00, 0xe5, 0x51, 0x5e, 0xd0, 0x56, 0x68, 0xe6, 0xe7, 0x40, 0xfc, 0x6b, + 0x51, 0xf7, 0xc7, 0xaa, 0x26, 0x5f, 0xe2, 0x6a, 0xe6, 0xf1, 0x0c, 0x47, + 0x48, 0x9c, 0x75, 0x10, 0xac, 0x2b, 0x08, 0xa2, 0x95, 0x99, 0xfc, 0x0d, + 0x78, 0xd6, 0xfd, 0x02, 0x45, 0x19, 0x0b, 0x47, 0x78, 0x8e, 0xa4, 0x3b, + 0x85, 0x7f, 0x0e, 0xec, 0x62, 0x8c, 0x49, 0xca, 0x4d, 0x70, 0x09, 0xb4, + 0x98, 0x87, 0xac, 0x48, 0xe8, 0xa7, 0x06, 0x36, 0x8a, 0x1f, 0x49, 0x0d, + 0x71, 0x79, 0x93, 0xae, 0x12, 0x91, 0x15, 0xe9, 0xda, 0x44, 0xad, 0x38, + 0x10, 0x4d, 0xa3, 0xf0, 0xc2, 0xfd, 0xd0, 0xf8, 0x9c, 0x41, 0x4e, 0x2e, + 0x28, 0x4e, 0xff, 0xaf, 0x35, 0x0c, 0x10, 0x82, 0x01, 0x57, 0x08, 0x92, + 0x75, 0x8c, 0x77, 0x12, 0x3b, 0x88, 0x64, 0x34, 0x4d, 0x0a, 0x0a, 0x84, + 0x40, 0xc6, 0xf8, 0x1d, 0xc4, 0x48, 0x65, 0xe4, 0x11, 0x5c, 0x3a, 0xce, + 0x0c, 0x6f, 0xe6, 0x14, 0x25, 0x5a, 0x5c, 0x00, 0xaf, 0x12, 0x87, 0x5b, + 0x89, 0x48, 0xfa, 0x42, 0x12, 0xe0, 0x33, 0xeb, 0x9e, 0x80, 0x91, 0x58, + 0x25, 0x40, 0xb1, 0x1c, 0xef, 0xa3, 0x22, 0x83, 0x11, 0x70, 0xdd, 0xe7, + 0x04, 0xda, 0xeb, 0x94, 0x52, 0x90, 0xcd, 0xc8, 0x13, 0x01, 0x2e, 0xdb, + 0x13, 0x15, 0xe7, 0xab, 0x5c, 0x25, 0xdc, 0x89, 0x56, 0x31, 0x21, 0x02, + 0xf7, 0x24, 0xd6, 0xd2, 0xf8, 0xc3, 0x08, 0x25, 0x76, 0x71, 0x20, 0xdd, + 0x42, 0x84, 0x72, 0xaa, 0x71, 0x63, 0x4b, 0x31, 0xe7, 0xfe, 0x83, 0x44, + 0xf5, 0x0b, 0x19, 0x1a, 0x71, 0x0d, 0x86, 0x8c, 0x40, 0x63, 0x66, 0x45, + 0xe4, 0x4a, 0x19, 0x96, 0x36, 0x22, 0x18, 0x12, 0x12, 0x45, 0x01, 0xc6, + 0xb1, 0x67, 0x89, 0x8d, 0x04, 0xa5, 0x25, 0x37, 0x11, 0xe2, 0x86, 0x30, + 0xdd, 0x44, 0xdc, 0x35, 0xcd, 0xf7, 0x3e, 0xc8, 0xfc, 0x1d, 0xdc, 0x26, + 0xe1, 0xb4, 0xaf, 0x0c, 0x29, 0x20, 0xe2, 0xd7, 0xa5, 0x58, 0x45, 0x87, + 0x3d, 0x32, 0x82, 0x66, 0x4f, 0x4c, 0x2a, 0x90, 0x17, 0x2d, 0x41, 0x3b, + 0x84, 0x07, 0x18, 0xed, 0x8b, 0xb0, 0x17, 0xd0, 0x4d, 0x43, 0x84, 0x56, + 0x8f, 0x56, 0x61, 0x02, 0x3b, 0x39, 0xb8, 0x74, 0x0e, 0x4b, 0x75, 0x0d, + 0x9d, 0x07, 0xb4, 0x15, 0x54, 0xc7, 0x9c, 0x50, 0x64, 0xb8, 0x80, 0xf3, + 0x4b, 0xc8, 0xcf, 0x86, 0xa9, 0x1b, 0x84, 0x06, 0xd4, 0xe8, 0xb5, 0x06, + 0x03, 0x21, 0x98, 0xd8, 0xca, 0xfa, 0x2e, 0xa0, 0x18, 0xbc, 0xe7, 0x2d, + 0xf3, 0x2b, 0xf4, 0x0b, 0xae, 0x2f, 0x07, 0x9a, 0x59, 0x0e, 0x3e, 0x1b, + 0x33, 0xe2, 0xec, 0x7b, 0xdd, 0x99, 0xf8, 0x99, 0x77, 0x31, 0x43, 0xc5, + 0x05, 0x1d, 0x22, 0x35, 0xdb, 0x66, 0xd4, 0x9f, 0x14, 0x98, 0x18, 0xa0, + 0x20, 0x40, 0x34, 0x41, 0x57, 0x1f, 0x89, 0x96, 0xe3, 0x5f, 0x31, 0xcc, + 0x41, 0x27, 0xa7, 0x11, 0x23, 0xd0, 0xe5, 0x97, 0x0d, 0x2e, 0x3c, 0xa9, + 0x4f, 0x90, 0x0c, 0xf1, 0xf1, 0x95, 0x2e, 0x26, 0x0e, 0xa1, 0x3c, 0x63, + 0xed, 0xba, 0x55, 0x67, 0xa2, 0x71, 0x85, 0x74, 0x44, 0x97, 0x86, 0xfd, + 0xe5, 0x64, 0xe6, 0xd6, 0x7f, 0xed, 0xad, 0xe3, 0x42, 0x5c, 0xef, 0xe7, + 0xbf, 0xba, 0x4c, 0xdc, 0x92, 0x2a, 0xb3, 0x4d, 0x4d, 0xff, 0xef, 0xe3, + 0x79, 0x85, 0x0b, 0x2e, 0x67, 0x06, 0xc6, 0x4a, 0x21, 0xb1, 0x12, 0x83, + 0x8b, 0x9e, 0xb4, 0x3a, 0x10, 0x16, 0x31, 0xde, 0x31, 0x6b, 0x5c, 0x63, + 0xc7, 0x78, 0xbb, 0x2e, 0xe7, 0x55, 0x7f, 0xe2, 0x4b, 0x2c, 0x25, 0xff, + 0x67, 0xba, 0x17, 0x1e, 0x9c, 0xe1, 0x08, 0x6f, 0x10, 0x6f, 0xa6, 0xfe, + 0x99, 0x3d, 0x16, 0xff, 0xf7, 0x7f, 0x96, 0x47, 0xb1, 0x91, 0xae, 0xf5, + 0xdc, 0x82, 0x19, 0x2e, 0xee, 0x05, 0x2e, 0xa4, 0xed, 0x2d, 0x21, 0xa1, + 0x85, 0x7d, 0xc8, 0x99, 0xa1, 0xa2, 0x55, 0x4e, 0xa8, 0xed, 0x10, 0x81, + 0x7e, 0x26, 0x4a, 0x68, 0x93, 0xb8, 0x32, 0x7c, 0x0b, 0x12, 0xf0, 0x71, + 0xa2, 0x26, 0xfe, 0xd4, 0x65, 0x01, 0x79, 0x92, 0x98, 0xcd, 0xcf, 0x8c, + 0x7c, 0x38, 0x81, 0x1e, 0x3c, 0xdf, 0x37, 0x1b, 0x42, 0x12, 0x4b, 0x75, + 0xa4, 0x97, 0x72, 0x7f, 0x7b, 0x0c, 0x5d, 0xea, 0xa8, 0x91, 0xc6, 0x3f, + 0xf5, 0x91, 0xa8, 0x3b, 0xb9, 0x00, 0x27, 0x2c, 0x2c, 0x85, 0xa4, 0x91, + 0x97, 0xe1, 0x4b, 0xcd, 0x24, 0x42, 0x21, 0x3d, 0x16, 0x0a, 0x3a, 0x16, + 0xd2, 0x9d, 0xcc, 0x83, 0xf7, 0x90, 0x63, 0x16, 0xad, 0xcc, 0xd7, 0xe4, + 0x3c, 0xdd, 0x28, 0x58, 0x23, 0x59, 0x64, 0xb1, 0x9c, 0xf2, 0x9e, 0xcf, + 0x57, 0x40, 0x12, 0x19, 0xc0, 0x38, 0x1e, 0xb0, 0xe6, 0x39, 0xf0, 0x64, + 0x19, 0x4c, 0x63, 0x27, 0x74, 0xa6, 0x32, 0x84, 0xdb, 0x88, 0xb6, 0x65, + 0x33, 0x21, 0x2e, 0x83, 0x58, 0x9d, 0xe8, 0x7d, 0xd9, 0xc1, 0xdf, 0x3b, + 0x10, 0xa3, 0x7d, 0x73, 0xd1, 0x39, 0xf3, 0xd7, 0x62, 0xdd, 0xdd, 0xd1, + 0x91, 0x10, 0xdd, 0xd9, 0x97, 0xb1, 0x06, 0xeb, 0xcf, 0x47, 0x7f, 0x3f, + 0xc0, 0x44, 0x09, 0x76, 0x4a, 0xe0, 0x9d, 0x79, 0xba, 0x50, 0x65, 0xde, + 0xec, 0xe2, 0x25, 0xa0, 0xde, 0x2c, 0x89, 0xc6, 0x25, 0x59, 0xd8, 0xbe, + 0xb4, 0xa1, 0x89, 0x14, 0xf7, 0xd7, 0x84, 0x8b, 0x3b, 0xf2, 0xe2, 0x49, + 0x28, 0x8a, 0x43, 0x48, 0x16, 0x2d, 0x0c, 0xfa, 0xe0, 0x44, 0x8f, 0x5a, + 0xba, 0xd0, 0x9b, 0x80, 0x98, 0xaf, 0xd6, 0xae, 0x10, 0x56, 0x68, 0x3f, + 0x74, 0xb3, 0xc7, 0x05, 0xd8, 0x97, 0x66, 0x3e, 0x2f, 0xf6, 0xee, 0xa2, + 0x2d, 0x06, 0x8e, 0xd9, 0x22, 0x4d, 0x3f, 0xec, 0xf8, 0x13, 0x1c, 0x4d, + 0x1e, 0x64, 0x26, 0xd8, 0xd6, 0x32, 0x22, 0x10, 0xcd, 0x2f, 0x11, 0x00, + 0x29, 0x60, 0x42, 0x9d, 0xc1, 0x03, 0xc6, 0x15, 0x89, 0x89, 0xf7, 0x20, + 0x66, 0xd9, 0xcc, 0x09, 0x8d, 0xbe, 0xdd, 0xc8, 0xb3, 0xef, 0xbe, 0xee, + 0x0f, 0x13, 0x64, 0x0b, 0xd6, 0x82, 0x8a, 0x72, 0xf2, 0x74, 0x48, 0x82, + 0x39, 0xa4, 0x84, 0x34, 0x6a, 0x21, 0x6a, 0x68, 0x57, 0xb2, 0x41, 0xcc, + 0x64, 0x85, 0x1c, 0x81, 0xed, 0x94, 0x57, 0x63, 0x5e, 0x53, 0x24, 0x37, + 0x67, 0xf4, 0x27, 0x0d, 0x71, 0xdb, 0xee, 0xa1, 0x86, 0x26, 0xb0, 0xbf, + 0x8b, 0x88, 0xf5, 0x8e, 0x21, 0x24, 0x49, 0xaf, 0x2c, 0x4e, 0x0d, 0x10, + 0xee, 0x85, 0x93, 0xde, 0xf5, 0xfa, 0xca, 0x31, 0xef, 0x65, 0xcd, 0x9f, + 0xc8, 0xcd, 0x06, 0x26, 0xf8, 0xa1, 0x68, 0x12, 0x26, 0xf3, 0x5c, 0x4c, + 0xc2, 0xaa, 0x4e, 0x2f, 0x7f, 0x25, 0x4c, 0x98, 0x17, 0x0e, 0xe6, 0x11, + 0x8e, 0x30, 0x97, 0x56, 0x77, 0x6e, 0x14, 0x18, 0xcc, 0x40, 0x90, 0x59, + 0x0d, 0x12, 0x33, 0xf4, 0x3a, 0x5d, 0x9f, 0x50, 0x5e, 0xbf, 0x84, 0xa0, + 0xa7, 0x35, 0x71, 0x28, 0xb8, 0x83, 0xad, 0x2b, 0x67, 0x10, 0x87, 0x25, + 0xca, 0x7f, 0x4c, 0xf3, 0x15, 0xe3, 0xec, 0x7e, 0x38, 0x5a, 0xfa, 0xb7, + 0xe8, 0xa4, 0x6d, 0x89, 0x48, 0x7f, 0x00, 0x18, 0x64, 0x48, 0xb8, 0x41, + 0xe4, 0x6f, 0xe7, 0xc2, 0x84, 0x7e, 0xce, 0x50, 0x6d, 0x85, 0x63, 0x05, + 0xfa, 0x86, 0x05, 0xc0, 0xc8, 0x05, 0x65, 0xb6, 0x2c, 0xcb, 0xc4, 0x39, + 0xd2, 0x09, 0x94, 0xe9, 0x3a, 0xe7, 0xc5, 0xeb, 0x11, 0x24, 0x42, 0x85, + 0x0e, 0x6b, 0xa6, 0xa6, 0x08, 0xcd, 0x77, 0xbb, 0x34, 0x89, 0x1c, 0x4b, + 0xa0, 0xd0, 0x03, 0xf8, 0x08, 0x79, 0xf1, 0xf9, 0x1d, 0x8d, 0x30, 0x50, + 0x70, 0x02, 0x30, 0x36, 0xc1, 0x02, 0x7d, 0x36, 0x40, 0x8e, 0x85, 0x55, + 0x4e, 0xb9, 0x47, 0x39, 0x13, 0x13, 0x19, 0x43, 0x0c, 0x10, 0xf8, 0xd0, + 0xca, 0x0c, 0xea, 0xc2, 0x33, 0x10, 0x65, 0x07, 0xf0, 0x49, 0x10, 0xb1, + 0x3b, 0x52, 0x7d, 0xd2, 0x71, 0x0f, 0xb8, 0xc5, 0xdc, 0xe2, 0x3f, 0x14, + 0x61, 0xfb, 0x2c, 0x4c, 0x7a, 0x4b, 0x14, 0xe0, 0x99, 0xc7, 0xde, 0xee, + 0x75, 0x3b, 0xe9, 0x96, 0x06, 0x5f, 0xc1, 0x88, 0xa0, 0x5c, 0x13, 0x45, + 0x28, 0x94, 0x49, 0x03, 0x62, 0x0c, 0x18, 0x86, 0x74, 0xd9, 0x95, 0x4a, + 0xd0, 0xdc, 0xe3, 0x48, 0xb4, 0x08, 0xd8, 0x86, 0xcf, 0x42, 0x63, 0x07, + 0x09, 0x35, 0x73, 0x68, 0x55, 0x19, 0x9a, 0xfc, 0x34, 0x42, 0xe5, 0x1f, + 0x0b, 0x59, 0xae, 0x49, 0xae, 0x38, 0xf1, 0x75, 0x59, 0x05, 0xc4, 0xbe, + 0x70, 0x08, 0xb1, 0x53, 0x15, 0xc4, 0x15, 0x1a, 0x36, 0xba, 0xa8, 0x49, + 0x9a, 0xd0, 0xaf, 0xa4, 0x01, 0x61, 0x3e, 0x78, 0x65, 0xd1, 0x99, 0x00, + 0xb7, 0x14, 0xef, 0xdf, 0x6c, 0x24, 0x30, 0x98, 0x6c, 0xd3, 0x36, 0x0d, + 0x53, 0xcf, 0xfc, 0xdf, 0x18, 0x2c, 0xe1, 0xc7, 0xd2, 0x09, 0x1c, 0x60, + 0x33, 0x66, 0x40, 0x53, 0xec, 0xe1, 0xb0, 0xc0, 0xc1, 0xae, 0x65, 0xbd, + 0x20, 0x9e, 0x88, 0x38, 0xda, 0xd6, 0x26, 0xf8, 0x4c, 0x92, 0x3b, 0xe8, + 0xc5, 0xc2, 0xca, 0x0d, 0xdb, 0x48, 0xf1, 0xac, 0x44, 0x62, 0xcc, 0x56, + 0xa8, 0x33, 0x80, 0x88, 0x98, 0x87, 0xde, 0x34, 0xe2, 0x7d, 0x99, 0x22, + 0x15, 0xd2, 0xb1, 0x8b, 0x0b, 0xea, 0x4b, 0xcd, 0x89, 0xde, 0xce, 0x08, + 0x1e, 0x2e, 0x32, 0x04, 0x24, 0xe1, 0xb5, 0x96, 0x18, 0x89, 0x88, 0x9f, + 0x2e, 0x1a, 0x8f, 0x09, 0xe2, 0x64, 0x93, 0xc4, 0x34, 0x29, 0x45, 0xd9, + 0x3e, 0xbf, 0x01, 0x25, 0xe4, 0x24, 0x43, 0x43, 0x16, 0x45, 0xbd, 0xc4, + 0x84, 0x34, 0xdd, 0xe8, 0x7d, 0xd0, 0xd0, 0xe5, 0x37, 0x25, 0xfc, 0xb3, + 0x1d, 0xe3, 0x73, 0x10, 0x61, 0xe1, 0x31, 0xcb, 0x3a, 0x54, 0x00, 0x53, + 0x1f, 0xb1, 0x36, 0x42, 0x16, 0x7c, 0xf7, 0x69, 0x1b, 0xbe, 0xbf, 0x18, + 0x00, 0x98, 0x05, 0xd9, 0x80, 0x40, 0x7f, 0x58, 0x39, 0xd6, 0x40, 0xf4, + 0x78, 0x90, 0x34, 0xae, 0x80, 0x0b, 0x91, 0x41, 0xa9, 0xac, 0x03, 0xdf, + 0xc7, 0x03, 0x09, 0x89, 0xde, 0xb5, 0x4a, 0x66, 0x6c, 0x1c, 0x9a, 0x7b, + 0xe1, 0x1f, 0x28, 0xbe, 0xdf, 0x09, 0x00, 0x2e, 0x09, 0xe0, 0xfc, 0xd2, + 0x0c, 0xe4, 0x00, 0x4b, 0xe2, 0x12, 0xe0, 0xa1, 0x10, 0x05, 0xc8, 0xde, + 0x09, 0xab, 0x3c, 0x39, 0x3d, 0x42, 0xfe, 0x4c, 0x76, 0x02, 0xb1, 0xd4, + 0x82, 0x20, 0x03, 0x0c, 0x5e, 0x04, 0x0e, 0x0b, 0x0d, 0x3c, 0xcb, 0x2c, + 0xfa, 0x50, 0x88, 0xe4, 0x24, 0x08, 0x84, 0x4c, 0x67, 0x3f, 0x63, 0xf7, + 0x65, 0x97, 0xb0, 0x32, 0x45, 0x90, 0x55, 0x06, 0x08, 0x6f, 0xdf, 0x5d, + 0x6a, 0x58, 0xc0, 0x9a, 0x61, 0x41, 0xad, 0x74, 0xa0, 0xa5, 0x71, 0x47, + 0x21, 0x34, 0x3c, 0x31, 0x36, 0x10, 0x9a, 0x9a, 0xcc, 0x06, 0xae, 0xcf, + 0x94, 0x82, 0x35, 0xd9, 0x69, 0xf0, 0x28, 0x8b, 0xfd, 0xaa, 0x66, 0x95, + 0x90, 0x2c, 0x9f, 0xb3, 0xcf, 0x62, 0x1b, 0x86, 0x33, 0xca, 0x5b, 0x8e, + 0x05, 0x9b, 0x91, 0xda, 0x1a, 0x37, 0xa0, 0xcc, 0xab, 0x06, 0x29, 0x4a, + 0x51, 0x16, 0x05, 0xc6, 0x00, 0xc1, 0xc0, 0x44, 0xb1, 0xe3, 0x70, 0x5e, + 0x85, 0xa3, 0xb0, 0x07, 0x10, 0xc8, 0x0e, 0x98, 0xf5, 0xf3, 0x86, 0x31, + 0x50, 0x26, 0x48, 0x89, 0x80, 0x25, 0xe0, 0x26, 0x5d, 0x89, 0x72, 0x5e, + 0xd1, 0x94, 0xac, 0xb0, 0x49, 0x54, 0xef, 0xec, 0x12, 0xa0, 0x1a, 0x66, + 0xe4, 0x86, 0x93, 0x85, 0xec, 0x11, 0x7b, 0x86, 0x9a, 0x02, 0x81, 0x97, + 0xfd, 0x3a, 0x0b, 0x86, 0x95, 0xcb, 0xb9, 0x5e, 0xd1, 0x2b, 0xd4, 0xb7, + 0x7d, 0x25, 0xaa, 0x48, 0x55, 0x5c, 0xee, 0x69, 0xaa, 0xfd, 0xf2, 0xe3, + 0x6c, 0xc9, 0x13, 0xdb, 0x1c, 0x45, 0x17, 0x8c, 0xd8, 0x27, 0x93, 0xda, + 0xa2, 0x1a, 0xa8, 0x99, 0x68, 0xe3, 0xd8, 0xd2, 0x4c, 0xe3, 0x48, 0x3b, + 0x6a, 0x55, 0x04, 0x71, 0xeb, 0x7e, 0xd0, 0x2a, 0x71, 0x68, 0xbf, 0x82, + 0x43, 0xb8, 0x5a, 0xd8, 0x91, 0x02, 0xba, 0x82, 0x16, 0xfc, 0x17, 0x75, + 0xa1, 0xa4, 0xc4, 0x21, 0x1b, 0x08, 0x93, 0x73, 0xa1, 0x9c, 0x82, 0xd6, + 0x3b, 0x88, 0xed, 0x0e, 0x14, 0xc1, 0x0a, 0xed, 0x79, 0x5c, 0x15, 0x10, + 0x96, 0xc0, 0x87, 0xbf, 0xec, 0xd2, 0x92, 0x4d, 0xd1, 0xec, 0x73, 0x12, + 0x78, 0x21, 0xae, 0x2d, 0x8c, 0x48, 0x86, 0x26, 0x83, 0x47, 0x71, 0x13, + 0x13, 0x50, 0x60, 0x05, 0x83, 0x55, 0x4d, 0xcf, 0xb7, 0x2e, 0xe4, 0xc8, + 0xb8, 0x8e, 0x41, 0x18, 0xda, 0x1c, 0x85, 0x4e, 0x62, 0x28, 0x6d, 0x63, + 0x1b, 0x64, 0xd6, 0x77, 0x55, 0xb0, 0x72, 0x3b, 0x7c, 0xee, 0x60, 0xce, + 0x29, 0x2e, 0xde, 0x4b, 0x33, 0xf7, 0x13, 0x38, 0x93, 0xf9, 0x66, 0x01, + 0xaa, 0xbf, 0x51, 0x36, 0x0a, 0x19, 0x41, 0x38, 0xb8, 0x67, 0x1f, 0x14, + 0x62, 0x24, 0x3a, 0x2c, 0x43, 0x9c, 0x43, 0x22, 0xe1, 0xe2, 0x46, 0xe8, + 0xbd, 0x60, 0xf2, 0x5a, 0xb9, 0x48, 0xfb, 0xf1, 0x8d, 0xfa, 0x71, 0x1d, + 0x19, 0x03, 0x0c, 0x43, 0x17, 0x39, 0xbb, 0xd0, 0x22, 0x28, 0x19, 0x06, + 0x81, 0xe3, 0x02, 0x92, 0x6e, 0x29, 0x8d, 0x77, 0xe8, 0x15, 0x25, 0x3b, + 0x52, 0x1e, 0x34, 0x50, 0x9d, 0xd8, 0xf0, 0x65, 0x3c, 0x02, 0x82, 0x0b, + 0xfa, 0x86, 0xad, 0xd2, 0x7b, 0x3d, 0x3b, 0x8a, 0x2c, 0xf1, 0xae, 0x4b, + 0xe5, 0x03, 0xbe, 0xf2, 0x46, 0xdb, 0x7c, 0xd0, 0xcd, 0x89, 0x12, 0x83, + 0x50, 0x52, 0x13, 0xa0, 0x0a, 0x2d, 0x82, 0x25, 0xa3, 0x5f, 0xfc, 0x77, + 0x46, 0x4d, 0xcc, 0xe9, 0x22, 0x11, 0x9f, 0xd9, 0x15, 0xde, 0x64, 0x77, + 0xb9, 0x89, 0x9e, 0x6f, 0xba, 0x56, 0xe8, 0xfe, 0x99, 0x87, 0x7e, 0x93, + 0xbb, 0xc0, 0xf2, 0x98, 0xbd, 0xa0, 0x97, 0x05, 0x2c, 0xb8, 0x90, 0xb2, + 0x34, 0x0a, 0x24, 0x4a, 0x18, 0x88, 0x77, 0x15, 0xfe, 0xae, 0x80, 0xbe, + 0xf8, 0x44, 0x03, 0xe9, 0x42, 0x67, 0xe0, 0xaf, 0x01, 0x74, 0x63, 0x68, + 0x26, 0x46, 0x95, 0xcd, 0x20, 0x2e, 0x0c, 0xa5, 0x67, 0x96, 0xf4, 0xab, + 0x71, 0xa9, 0xdf, 0x34, 0x02, 0x68, 0x3b, 0x8f, 0x0e, 0x04, 0x4c, 0x11, + 0x33, 0xdc, 0xc8, 0xa3, 0x41, 0xa1, 0x45, 0x41, 0xe6, 0x94, 0xd3, 0x0b, + 0x95, 0x90, 0x7e, 0x89, 0xf6, 0xe3, 0x6a, 0x56, 0x94, 0x0f, 0xda, 0x84, + 0xd0, 0xa6, 0xae, 0x59, 0xb8, 0x2c, 0x2d, 0xf5, 0xd3, 0x21, 0xd2, 0xff, + 0xd6, 0x31, 0x31, 0x64, 0x28, 0x3c, 0xe9, 0x6f, 0x4b, 0x9f, 0x0a, 0xc0, + 0x82, 0x40, 0x8b, 0x0a, 0xd2, 0x91, 0x7e, 0xde, 0xf8, 0x14, 0xd0, 0xff, + 0x87, 0xb6, 0x3e, 0x90, 0x2a, 0x78, 0xd3, 0x7d, 0x98, 0x64, 0x59, 0x42, + 0x77, 0xcc, 0x49, 0xe8, 0xb1, 0x0c, 0x00, 0xfc, 0xf8, 0xad, 0x08, 0xa7, + 0x6f, 0x9f, 0xbe, 0x84, 0x8a, 0x36, 0x87, 0x8f, 0x73, 0xff, 0xfd, 0x39, + 0xca, 0x09, 0x26, 0x8f, 0xff, 0x6f, 0xfd, 0xe9, 0x40, 0x42, 0x9e, 0x9b, + 0x00 + }; + + class VC1ParserTest : public ::testing::Test { + protected: + void checkParamsSeqHeader(const Parser& parser) + { + EXPECT_EQ(0x1, parser.m_seqHdr.profile); + EXPECT_EQ(0x7, parser.m_seqHdr.frmrtq_postproc); + EXPECT_EQ(0x3, parser.m_seqHdr.bitrtq_postproc); + EXPECT_EQ(0x1, parser.m_seqHdr.loop_filter); + EXPECT_EQ(0x0, parser.m_seqHdr.multires); + EXPECT_FALSE(parser.m_seqHdr.fastuvmc); + EXPECT_FALSE(parser.m_seqHdr.extended_mv); + EXPECT_EQ(0x0, parser.m_seqHdr.dquant); + EXPECT_TRUE(parser.m_seqHdr.variable_sized_transform_flag); + EXPECT_EQ(0x1, parser.m_seqHdr.overlap); + EXPECT_EQ(0x0, parser.m_seqHdr.syncmarker); + EXPECT_EQ(0x1, parser.m_seqHdr.rangered); + EXPECT_EQ(0x0, parser.m_seqHdr.max_b_frames); + EXPECT_EQ(0x0, parser.m_seqHdr.quantizer); + EXPECT_FALSE(parser.m_seqHdr.finterpflag); + EXPECT_EQ(0x0, parser.m_seqHdr.level); + EXPECT_EQ(0x0, parser.m_seqHdr.colordiff_format); + EXPECT_FALSE(parser.m_seqHdr.postprocflag); + EXPECT_EQ(0x0, parser.m_seqHdr.pulldown); + EXPECT_EQ(0x0, parser.m_seqHdr.interlace); + EXPECT_FALSE(parser.m_seqHdr.tfcntrflag); + EXPECT_EQ(0x0, parser.m_seqHdr.psf); + EXPECT_EQ(0x0, parser.m_seqHdr.display_ext); + EXPECT_EQ(0x0, parser.m_seqHdr.disp_horiz_size); + EXPECT_EQ(0x0, parser.m_seqHdr.disp_vert_size); + EXPECT_FALSE(parser.m_seqHdr.aspect_ratio_flag); + EXPECT_EQ(0x0, parser.m_seqHdr.aspect_ratio); + EXPECT_EQ(0x0, parser.m_seqHdr.aspect_horiz_size); + EXPECT_EQ(0x0, parser.m_seqHdr.aspect_vert_size); + EXPECT_FALSE(parser.m_seqHdr.framerate_flag); + EXPECT_EQ(0x0, parser.m_seqHdr.framerateind); + EXPECT_EQ(0x0, parser.m_seqHdr.frameratenr); + EXPECT_EQ(0x0, parser.m_seqHdr.frameratedr); + EXPECT_EQ(0x0, parser.m_seqHdr.framerateexp); + EXPECT_FALSE(parser.m_seqHdr.color_format_flag); + EXPECT_EQ(0x0, parser.m_seqHdr.color_prim); + EXPECT_EQ(0x0, parser.m_seqHdr.transfer_char); + EXPECT_EQ(0x0, parser.m_seqHdr.matrix_coef); + EXPECT_FALSE(parser.m_seqHdr.hrd_param_flag); + EXPECT_EQ(0x0, parser.m_seqHdr.hrd_param.hrd_num_leaky_buckets); + EXPECT_EQ(0x0, parser.m_seqHdr.hrd_param.bit_rate_exponent); + EXPECT_EQ(0x0, parser.m_seqHdr.hrd_param.buffer_size_exponent); + for (uint32_t i = 0; i < 31; i++) { + EXPECT_EQ(0x0, parser.m_seqHdr.hrd_param.hrd_rate[i]); + EXPECT_EQ(0x0, parser.m_seqHdr.hrd_param.hrd_buffer[i]); + } + } + + void checkParamsFrameHeader(const Parser& parser) + { + EXPECT_EQ(0x0, parser.m_frameHdr.picture_type); + EXPECT_EQ(0x0, parser.m_frameHdr.interpfrm); + EXPECT_EQ(0x0, parser.m_frameHdr.halfqp); + EXPECT_EQ(0x1, parser.m_frameHdr.transacfrm); + EXPECT_EQ(0x1, parser.m_frameHdr.intra_transform_dc_table); + EXPECT_EQ(0xb, parser.m_frameHdr.pqindex); + EXPECT_EQ(0x0, parser.m_frameHdr.pquantizer); + EXPECT_EQ(0x8, parser.m_frameHdr.pquant); + EXPECT_EQ(0x0, parser.m_frameHdr.pq_diff); + EXPECT_EQ(0x0, parser.m_frameHdr.abs_pq); + EXPECT_EQ(0x0, parser.m_frameHdr.dq_frame); + EXPECT_EQ(0x0, parser.m_frameHdr.dq_profile); + EXPECT_EQ(0x0, parser.m_frameHdr.dq_sb_edge); + EXPECT_EQ(0x0, parser.m_frameHdr.dq_db_edge); + EXPECT_EQ(0x0, parser.m_frameHdr.dq_binary_level); + EXPECT_EQ(0x0, parser.m_frameHdr.alt_pic_quantizer); + EXPECT_EQ(0x0, parser.m_frameHdr.extended_mv_range); + EXPECT_EQ(0x0, parser.m_frameHdr.range_reduction_frame); + EXPECT_EQ(0x0, parser.m_frameHdr.picture_resolution_index); + EXPECT_EQ(0x0, parser.m_frameHdr.transacfrm2); + EXPECT_EQ(0x0, parser.m_frameHdr.mv_mode); + EXPECT_EQ(0x0, parser.m_frameHdr.mv_table); + EXPECT_FALSE(parser.m_frameHdr.mb_level_transform_type_flag); + EXPECT_EQ(0x0, parser.m_frameHdr.mv_mode2); + EXPECT_EQ(0x0, parser.m_frameHdr.lumscale); + EXPECT_EQ(0x0, parser.m_frameHdr.lumshift); + EXPECT_EQ(0x0, parser.m_frameHdr.cbp_table); + EXPECT_EQ(0x0, parser.m_frameHdr.frame_level_transform_type); + EXPECT_FALSE(parser.m_frameHdr.mv_type_mb); + EXPECT_FALSE(parser.m_frameHdr.skip_mb); + EXPECT_FALSE(parser.m_frameHdr.direct_mb); + EXPECT_EQ(0x0, parser.m_frameHdr.fcm); + EXPECT_EQ(0x0, parser.m_frameHdr.rptfrm); + EXPECT_FALSE(parser.m_frameHdr.tff); + EXPECT_FALSE(parser.m_frameHdr.rff); + EXPECT_EQ(0x0, parser.m_frameHdr.rounding_control); + EXPECT_EQ(0x0, parser.m_frameHdr.uvsamp); + EXPECT_EQ(0x0, parser.m_frameHdr.post_processing); + EXPECT_EQ(0x0, parser.m_frameHdr.condover); + EXPECT_FALSE(parser.m_frameHdr.ac_pred); + EXPECT_FALSE(parser.m_frameHdr.overflags); + EXPECT_FALSE(parser.m_frameHdr.forwardmb); + EXPECT_FALSE(parser.m_frameHdr.fieldtx); + EXPECT_EQ(0x0, parser.m_frameHdr.intcomp); + EXPECT_EQ(0x0, parser.m_frameHdr.dmvrange); + EXPECT_EQ(0x0, parser.m_frameHdr.mbmodetab); + EXPECT_EQ(0x0, parser.m_frameHdr.imvtab); + EXPECT_EQ(0x0, parser.m_frameHdr.icbptab); + EXPECT_EQ(0x0, parser.m_frameHdr.mvbptab2); + EXPECT_EQ(0x0, parser.m_frameHdr.mvbptab4); + EXPECT_EQ(0x0, parser.m_frameHdr.mvswitch4); + EXPECT_EQ(0x0, parser.m_frameHdr.refdist); + EXPECT_EQ(0x0, parser.m_frameHdr.fptype); + EXPECT_EQ(0x0, parser.m_frameHdr.numref); + EXPECT_EQ(0x0, parser.m_frameHdr.reffield); + EXPECT_EQ(0x0, parser.m_frameHdr.lumscale2); + EXPECT_EQ(0x0, parser.m_frameHdr.lumshift2); + EXPECT_EQ(0x0, parser.m_frameHdr.intcompfield); + EXPECT_EQ(0x14u, parser.m_frameHdr.macroblock_offset); + } + }; + +#define VC1_PARSER_TEST(name) TEST_F(VC1ParserTest, name) + + VC1_PARSER_TEST(ParseSequenceHeader) + { + Parser parser; + uint8_t* data = const_cast(SequenceHeader.data()); + uint32_t size = SequenceHeader.size(); + memset(&(parser.m_seqHdr), 0, sizeof(parser.m_seqHdr)); + ASSERT_TRUE(parser.parseCodecData(data, size)); + + checkParamsSeqHeader(parser); + } + + VC1_PARSER_TEST(ParseFrameHeader) + { + Parser parser; + uint8_t* data; + uint32_t size; + memset(&(parser.m_seqHdr), 0, sizeof(parser.m_seqHdr)); + memset(&(parser.m_entryPointHdr), 0, sizeof(parser.m_entryPointHdr)); + data = const_cast(SequenceHeader.data()); + size = SequenceHeader.size(); + ASSERT_TRUE(parser.parseCodecData(data, size)); + + data = const_cast(g_MainVC1.data()); + size = g_MainVC1.size(); + ASSERT_TRUE(parser.parseFrameHeader(data, size)); + checkParamsFrameHeader(parser); + } + +} // namespace VC1 +} // namespace YamiParser diff --git a/codecparsers/vp8_bool_decoder.cpp b/codecparsers/vp8_bool_decoder.cpp new file mode 100644 index 0000000..302727e --- /dev/null +++ b/codecparsers/vp8_bool_decoder.cpp @@ -0,0 +1,240 @@ +/* + * Copyright 2015 The Chromium Authors. All rights reserved. + * Copyright 2016 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Copyright (c) 2010, The WebM Project authors. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This file is modified from the dboolhuff.{c,h} from the WebM's libvpx +// project. (http://www.webmproject.org/code) +// It is used to decode bits from a vp8 stream. + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "vp8_bool_decoder.h" + +namespace YamiParser { + +#define CHAR_BIT 8 + +#define VP8_BD_VALUE_BIT \ + static_cast(sizeof(Vp8BoolDecoder::value_) * CHAR_BIT) + +static const int kDefaultProbability = 0x80; // 0x80 / 256 = 0.5 + +// This is meant to be a large, positive constant that can still be efficiently +// loaded as an immediate (on platforms like ARM, for example). Even relatively +// modest values like 100 would work fine. +#define VP8_LOTS_OF_BITS (0x40000000) + +// The number of leading zeros. +static const unsigned char kVp8Norm[256] = { + 0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; + +Vp8BoolDecoder::Vp8BoolDecoder() + : user_buffer_(NULL), + user_buffer_end_(NULL), + value_(0), + count_(-8), + range_(255) { +} + +bool Vp8BoolDecoder::Initialize(const uint8_t* data, size_t size) { + if (data == NULL || size == 0) + return false; + user_buffer_start_ = data; + user_buffer_ = data; + user_buffer_end_ = data + size; + value_ = 0; + count_ = -8; + range_ = 255; + return true; +} + +void Vp8BoolDecoder::FillDecoder() { + // DCHECK(user_buffer_ != NULL); + int shift = VP8_BD_VALUE_BIT - CHAR_BIT - (count_ + CHAR_BIT); + size_t bytes_left = user_buffer_end_ - user_buffer_; + size_t bits_left = bytes_left * CHAR_BIT; + int x = static_cast(shift + CHAR_BIT - bits_left); + int loop_end = 0; + + if (x >= 0) { + count_ += VP8_LOTS_OF_BITS; + loop_end = x; + } + + if (x < 0 || bits_left) { + while (shift >= loop_end) { + count_ += CHAR_BIT; + value_ |= static_cast(*user_buffer_) << shift; + ++user_buffer_; + shift -= CHAR_BIT; + } + } +} + +int Vp8BoolDecoder::ReadBit(int probability) { + int bit = 0; + size_t split = 1 + (((range_ - 1) * probability) >> 8); + if (count_ < 0) + FillDecoder(); + size_t bigsplit = static_cast(split) << (VP8_BD_VALUE_BIT - 8); + + if (value_ >= bigsplit) { + range_ -= split; + value_ -= bigsplit; + bit = 1; + } else { + range_ = split; + } + + size_t shift = kVp8Norm[range_]; + range_ <<= shift; + value_ <<= shift; + count_ -= shift; + + //DCHECK_EQ(1U, (range_ >> 7)); // In the range [128, 255]. + + return bit; +} + +bool Vp8BoolDecoder::ReadLiteral(size_t num_bits, int* out) { + //DCHECK_LE(num_bits, sizeof(int) * CHAR_BIT); + *out = 0; + for (; num_bits > 0; --num_bits) + *out = (*out << 1) | ReadBit(kDefaultProbability); + return !OutOfBuffer(); +} + +bool Vp8BoolDecoder::ReadBool(bool* out, uint8_t probability) { + *out = !!ReadBit(probability); + return !OutOfBuffer(); +} + +bool Vp8BoolDecoder::ReadBool(bool* out) { + return ReadBool(out, kDefaultProbability); +} + +bool Vp8BoolDecoder::ReadLiteralWithSign(size_t num_bits, int* out) { + ReadLiteral(num_bits, out); + // Read sign. + if (ReadBit(kDefaultProbability)) + *out = -*out; + return !OutOfBuffer(); +} + +size_t Vp8BoolDecoder::BitOffset() { + int bit_count = count_ + 8; + if (bit_count > VP8_BD_VALUE_BIT) + // Capped at 0 to ignore buffer underrun. + bit_count = std::max(0, bit_count - VP8_LOTS_OF_BITS); + return (user_buffer_ - user_buffer_start_) * 8 - bit_count; +} + +uint8_t Vp8BoolDecoder::GetRange() { + return (range_); +} + +uint8_t Vp8BoolDecoder::GetBottom() { + if (count_ < 0) + FillDecoder(); + return static_cast(value_ >> (VP8_BD_VALUE_BIT - 8)); +} + +inline bool Vp8BoolDecoder::OutOfBuffer() { + // Check if we have reached the end of the buffer. + // + // Variable |count_| stores the number of bits in the |value_| buffer, minus + // 8. The top byte is part of the algorithm and the remainder is buffered to + // be shifted into it. So, if |count_| == 8, the top 16 bits of |value_| are + // occupied, 8 for the algorithm and 8 in the buffer. + // + // When reading a byte from the user's buffer, |count_| is filled with 8 and + // one byte is filled into the |value_| buffer. When we reach the end of the + // data, |count_| is additionally filled with VP8_LOTS_OF_BITS. So when + // |count_| == VP8_LOTS_OF_BITS - 1, the user's data has been exhausted. + return (count_ > VP8_BD_VALUE_BIT) && (count_ < VP8_LOTS_OF_BITS); +} + +} // namespace YamiParser diff --git a/codecparsers/vp8_bool_decoder.h b/codecparsers/vp8_bool_decoder.h new file mode 100644 index 0000000..b914b66 --- /dev/null +++ b/codecparsers/vp8_bool_decoder.h @@ -0,0 +1,163 @@ +/* + * Copyright 2015 The Chromium Authors. All rights reserved. + * Copyright 2016 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Copyright (c) 2010, The WebM Project authors. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This file is modified from the dboolhuff.{c,h} from the WebM's libvpx +// project. (http://www.webmproject.org/code) +// It is used to decode bits from a vp8 stream. +// +// This file is taken from Chromium Project and adapted to libyami + +#ifndef VP8_BOOL_DECODER_H_ +#define VP8_BOOL_DECODER_H_ + +#include "common/NonCopyable.h" +#include "VideoCommonDefs.h" +#include +#include + +namespace YamiParser { + +// A class to decode the VP8's boolean entropy coded stream. It's a variant of +// arithmetic coding. See RFC 6386 - Chapter 7. Boolean Entropy Decoder. +class Vp8BoolDecoder { + public: + Vp8BoolDecoder(); + + // Initializes the decoder to start decoding |data|, |size| being size + // of |data| in bytes. Returns false if |data| is NULL or empty. + bool Initialize(const uint8_t* data, size_t size); + + // Reads a boolean from the coded stream. Returns false if it has reached the + // end of |data| and failed to read the boolean. The probability of |out| to + // be true is |probability| / 256, e.g., when |probability| is 0x80, the + // chance is 1/2 (i.e., 0x80 / 256). + bool ReadBool(bool* out, uint8_t probability); + + // Reads a boolean from the coded stream with the default probability 1/2. + // Returns false if it has reached the end of |data| and failed to read the + // boolean. + bool ReadBool(bool* out); + + // Reads a "literal", that is, a "num_bits"-wide unsigned value whose bits + // come high- to low-order, with each bit encoded at probability 1/2. + // Returns false if it has reached the end of |data| and failed to read the + // literal. + bool ReadLiteral(size_t num_bits, int* out); + + // Reads a literal with sign from the coded stream. This is similar to + // the ReadListeral(), it first read a "num_bits"-wide unsigned value, and + // then read an extra bit as the sign of the literal. Returns false if it has + // reached the end of |data| and failed to read the literal or the sign. + // This is different from the "read_signed_literal(d, n)" defined in RFC 6386. + bool ReadLiteralWithSign(size_t num_bits, int* out); + + // The following methods are used to get the internal states of the decoder. + + // Returns the bit offset to the current top bit of the coded stream. It is + // also the number of bits that have been written in the corresponding + // encoding state. More specifically, we have the following constraint: + // w + (bottom * S) <= v < w + (bottom + range) * S, + // where "w" is for the bits already written, + // "v" is for the possible values of the coded number. + // "S" is the scale for the current bit position, + // i.e., S = pow(2, -(n + 8)), where "n" is the bit number of "w". + // BitOffset() returns the bit count of "w", i.e., "n". + size_t BitOffset(); + + // Gets the "bottom" of the current coded value. See BitOffset() for + // more details. + uint8_t GetBottom(); + + // Gets the "range" of the current coded value. See BitOffset() for + // more details. + uint8_t GetRange(); + + private: + // Reads the next bit from the coded stream. The probability of the bit to + // be one is |probability| / 256. + int ReadBit(int probability); + + // Fills more bits from |user_buffer_| to |value_|. We shall keep at least 8 + // bits of the current |user_buffer_| in |value_|. + void FillDecoder(); + + // Returns true iff we have ran out of bits. + bool OutOfBuffer(); + + const uint8_t* user_buffer_; + const uint8_t* user_buffer_start_; + const uint8_t* user_buffer_end_; + size_t value_; + int count_; + size_t range_; + + DISALLOW_COPY_AND_ASSIGN(Vp8BoolDecoder); +}; + +} // namespace YamiParser + +#endif // VP8_BOOL_DECODER_H_ diff --git a/codecparsers/vp8_bool_decoder_unittest.cpp b/codecparsers/vp8_bool_decoder_unittest.cpp new file mode 100644 index 0000000..b03d7d2 --- /dev/null +++ b/codecparsers/vp8_bool_decoder_unittest.cpp @@ -0,0 +1,161 @@ +/* + * Copyright 2015 The Chromium Authors. All rights reserved. + * Copyright 2016 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This file is taken from Chromium Project and adapted to libyami + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vp8_bool_decoder.h" + +#include +#include + +#include + +#include "common/unittest.h" + +namespace YamiParser { + +const static size_t NUM_BITS_TO_TEST = 100; + +namespace { + +// 100 zeros with probability of 0x80. +const uint8_t kDataZerosAndEvenProbabilities[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00}; + +// 100 ones with probability of 0x80. +const uint8_t kDataOnesAndEvenProbabilities[] = { + 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xf0, 0x20}; + +// [0, 1, 0, 1, ..., 1] with probability [0, 1, 2, 3, ..., 99]. +const uint8_t kDataParitiesAndIncreasingProbabilities[] = { + 0x00, 0x02, 0x08, 0x31, 0x8e, 0xca, 0xab, 0xe2, 0xc8, 0x31, 0x12, + 0xb3, 0x2c, 0x19, 0x90, 0xc6, 0x6a, 0xeb, 0x17, 0x52, 0x30}; + +} // namespace + +class Vp8BoolDecoderTest : public ::testing::Test { + public: + Vp8BoolDecoderTest() {} + + protected: + // Fixture member, the bool decoder to be tested. + Vp8BoolDecoder bd_; + + private: + DISALLOW_COPY_AND_ASSIGN(Vp8BoolDecoderTest); +}; + +#define INITIALIZE(data) ASSERT_TRUE(bd_.Initialize(data, sizeof(data))); + +TEST_F(Vp8BoolDecoderTest, DecodeBoolsWithZerosAndEvenProbabilities) { + INITIALIZE(kDataZerosAndEvenProbabilities); + ASSERT_EQ(0u, bd_.BitOffset()); + for (size_t i = 0; i < NUM_BITS_TO_TEST; ++i) { + bool out = true; + ASSERT_TRUE(bd_.ReadBool(&out, 0x80)); + ASSERT_FALSE(out); + ASSERT_EQ(i, bd_.BitOffset()); + } +} + +TEST_F(Vp8BoolDecoderTest, DecodeLiteralsWithZerosAndEvenProbabilities) { + INITIALIZE(kDataZerosAndEvenProbabilities); + + int value = 1; + ASSERT_TRUE(bd_.ReadLiteral(1, &value)); + ASSERT_EQ(0, value); + + value = 1; + ASSERT_TRUE(bd_.ReadLiteral(32, &value)); + ASSERT_EQ(0, value); + + value = 1; + ASSERT_TRUE(bd_.ReadLiteralWithSign(1, &value)); + ASSERT_EQ(0, value); + + value = 1; + ASSERT_TRUE(bd_.ReadLiteralWithSign(31, &value)); + ASSERT_EQ(0, value); +} + +TEST_F(Vp8BoolDecoderTest, DecodeBoolsWithOnesAndEvenProbabilities) { + INITIALIZE(kDataOnesAndEvenProbabilities); + + ASSERT_EQ(0u, bd_.BitOffset()); + for (size_t i = 0; i < NUM_BITS_TO_TEST; ++i) { + bool out = false; + ASSERT_TRUE(bd_.ReadBool(&out, 0x80)); + ASSERT_TRUE(out); + ASSERT_EQ(i + 1, bd_.BitOffset()); + } +} + +TEST_F(Vp8BoolDecoderTest, DecodeLiteralsWithOnesAndEvenProbabilities) { + INITIALIZE(kDataOnesAndEvenProbabilities); + + int value = 0; + ASSERT_TRUE(bd_.ReadLiteral(1, &value)); + EXPECT_EQ(1, value); + + value = 0; + ASSERT_TRUE(bd_.ReadLiteral(31, &value)); + EXPECT_EQ(0x7FFFFFFF, value); + + value = 0; + ASSERT_TRUE(bd_.ReadLiteralWithSign(1, &value)); + EXPECT_EQ(-1, value); + + value = 0; + ASSERT_TRUE(bd_.ReadLiteralWithSign(31, &value)); + EXPECT_EQ(-0x7FFFFFFF, value); +} + +TEST_F(Vp8BoolDecoderTest, DecodeBoolsWithParitiesAndIncreasingProbabilities) { + INITIALIZE(kDataParitiesAndIncreasingProbabilities); + + for (size_t i = 0; i < NUM_BITS_TO_TEST; ++i) { + bool out = !(i & 1); + ASSERT_LE(i, std::numeric_limits::max()); + ASSERT_TRUE(bd_.ReadBool(&out, static_cast(i))); + EXPECT_EQ(out, !!(i & 1)); + } +} + +} // namespace YamiParser diff --git a/codecparsers/vp8_parser.cpp b/codecparsers/vp8_parser.cpp new file mode 100644 index 0000000..aee31b4 --- /dev/null +++ b/codecparsers/vp8_parser.cpp @@ -0,0 +1,913 @@ +/* + * Copyright 2015 The Chromium Authors. All rights reserved. + * Copyright 2016 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// This file contains an implementation of a VP8 raw stream parser, +// as defined in RFC 6386. +// +// This file is taken from Chromium Project and adapted to libyami + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vp8_parser.h" +#include "common/log.h" +#include + +namespace YamiParser { + +#define ERROR_RETURN(what) \ + do { \ + return false; \ + } while (0) + +#define BD_READ_BOOL_OR_RETURN(out) \ + do { \ + if (!bd_.ReadBool(out)) \ + ERROR_RETURN(out); \ + } while (0) + +#define BD_READ_BOOL_WITH_PROB_OR_RETURN(out, prob) \ + do { \ + if (!bd_.ReadBool(out, prob)) \ + ERROR_RETURN(out); \ + } while (0) + +#define BD_READ_UNSIGNED_OR_RETURN(num_bits, out) \ + do { \ + int _out; \ + if (!bd_.ReadLiteral(num_bits, &_out)) \ + ERROR_RETURN(out); \ + *out = _out; \ + } while (0) + +#define BD_READ_SIGNED_OR_RETURN(num_bits, out) \ + do { \ + int _out; \ + if (!bd_.ReadLiteralWithSign(num_bits, &_out)) \ + ERROR_RETURN(out); \ + *out = _out; \ + } while (0) + +Vp8FrameHeader::Vp8FrameHeader() { + memset(this, 0, sizeof(*this)); +} + +Vp8Parser::Vp8Parser() : stream_(NULL), bytes_left_(0) { + memset(&curr_segmentation_hdr_, 0, offsetof(Vp8SegmentationHeader, segment_feature_mode)); + memset(&curr_loopfilter_hdr_, 0, offsetof(Vp8LoopFilterHeader, type)); + memset(&curr_entropy_hdr_, 0, sizeof(curr_entropy_hdr_)); +} + +Vp8Parser::~Vp8Parser() { +} + +Vp8ParserResult Vp8Parser::ParseFrame(const uint8_t* ptr, + size_t frame_size, + Vp8FrameHeader* fhdr) { + stream_ = ptr; + bytes_left_ = frame_size; + + *fhdr = Vp8FrameHeader(); + fhdr->data = stream_; + fhdr->frame_size = bytes_left_; + + if (!ParseFrameTag(fhdr)) + return VP8_PARSER_ERROR; + + fhdr->first_part_offset = stream_ - fhdr->data; + + if (!ParseFrameHeader(fhdr)) + return VP8_PARSER_ERROR; + + if (!ParsePartitions(fhdr)) + return VP8_PARSER_ERROR; + + return VP8_PARSER_OK; +} + +static inline uint32_t GetBitsAt(uint32_t data, size_t shift, size_t num_bits) { + return ((data >> shift) & ((1 << num_bits) - 1)); +} + +bool Vp8Parser::ParseFrameTag(Vp8FrameHeader* fhdr) { + const size_t kFrameTagSize = 3; + if (bytes_left_ < kFrameTagSize) + return false; + + uint32_t frame_tag = (stream_[2] << 16) | (stream_[1] << 8) | stream_[0]; + fhdr->key_frame = + static_cast(GetBitsAt(frame_tag, 0, 1)); + fhdr->version = GetBitsAt(frame_tag, 1, 2); + fhdr->is_experimental = !!GetBitsAt(frame_tag, 3, 1); + fhdr->show_frame =!!GetBitsAt(frame_tag, 4, 1); + fhdr->first_part_size = GetBitsAt(frame_tag, 5, 19); + + stream_ += kFrameTagSize; + bytes_left_ -= kFrameTagSize; + + if (fhdr->IsKeyframe()) { + const size_t kKeyframeTagSize = 7; + if (bytes_left_ < kKeyframeTagSize) + return false; + + static const uint8_t kVp8StartCode[] = {0x9d, 0x01, 0x2a}; + if (memcmp(stream_, kVp8StartCode, sizeof(kVp8StartCode)) != 0) { + DEBUG("Not a valid vp8 frame"); + return false; + } + + stream_ += sizeof(kVp8StartCode); + bytes_left_ -= sizeof(kVp8StartCode); + + uint16_t data = (stream_[1] << 8) | stream_[0]; + fhdr->width = data & 0x3fff; + fhdr->horizontal_scale = data >> 14; + + data = (stream_[3] << 8) | stream_[2]; + fhdr->height = data & 0x3fff; + fhdr->vertical_scale = data >> 14; + + stream_ += 4; + bytes_left_ -= 4; + } + + return true; +} + +bool Vp8Parser::ParseFrameHeader(Vp8FrameHeader* fhdr) { + if (!bd_.Initialize(stream_, bytes_left_)) + return false; + + bool keyframe = fhdr->IsKeyframe(); + if (keyframe) { + unsigned int data; + BD_READ_UNSIGNED_OR_RETURN(1, &data); // color_space + BD_READ_UNSIGNED_OR_RETURN(1, &data); // clamping_type + } + + if (!ParseSegmentationHeader(keyframe)) + return false; + + fhdr->segmentation_hdr = curr_segmentation_hdr_; + + if (!ParseLoopFilterHeader(keyframe)) + return false; + + fhdr->loopfilter_hdr = curr_loopfilter_hdr_; + + int log2_nbr_of_dct_partitions; + BD_READ_UNSIGNED_OR_RETURN(2, &log2_nbr_of_dct_partitions); + fhdr->num_of_dct_partitions = + static_cast(1 << log2_nbr_of_dct_partitions); + + if (!ParseQuantizationHeader(&fhdr->quantization_hdr)) + return false; + + if (keyframe) { + BD_READ_BOOL_OR_RETURN(&fhdr->refresh_entropy_probs); + } else { + BD_READ_BOOL_OR_RETURN(&fhdr->refresh_golden_frame); + BD_READ_BOOL_OR_RETURN(&fhdr->refresh_alternate_frame); + + int refresh_mode; + if (!fhdr->refresh_golden_frame) { + BD_READ_UNSIGNED_OR_RETURN(2, &refresh_mode); + fhdr->copy_buffer_to_golden = + static_cast(refresh_mode); + } + + if (!fhdr->refresh_alternate_frame) { + BD_READ_UNSIGNED_OR_RETURN(2, &refresh_mode); + fhdr->copy_buffer_to_alternate = + static_cast(refresh_mode); + } + + BD_READ_UNSIGNED_OR_RETURN(1, &fhdr->sign_bias_golden); + BD_READ_UNSIGNED_OR_RETURN(1, &fhdr->sign_bias_alternate); + BD_READ_BOOL_OR_RETURN(&fhdr->refresh_entropy_probs); + BD_READ_BOOL_OR_RETURN(&fhdr->refresh_last); + } + + if (keyframe) + ResetProbs(); + + fhdr->entropy_hdr = curr_entropy_hdr_; + + if (!ParseTokenProbs(&fhdr->entropy_hdr, fhdr->refresh_entropy_probs)) + return false; + + BD_READ_BOOL_OR_RETURN(&fhdr->mb_no_skip_coeff); + if (fhdr->mb_no_skip_coeff) + BD_READ_UNSIGNED_OR_RETURN(8, &fhdr->prob_skip_false); + + if (!keyframe) { + BD_READ_UNSIGNED_OR_RETURN(8, &fhdr->prob_intra); + BD_READ_UNSIGNED_OR_RETURN(8, &fhdr->prob_last); + BD_READ_UNSIGNED_OR_RETURN(8, &fhdr->prob_gf); + } + + if (!ParseIntraProbs(&fhdr->entropy_hdr, fhdr->refresh_entropy_probs, + keyframe)) + return false; + + if (!keyframe) { + if (!ParseMVProbs(&fhdr->entropy_hdr, fhdr->refresh_entropy_probs)) + return false; + } + + fhdr->macroblock_bit_offset = bd_.BitOffset(); + fhdr->bool_dec_range = bd_.GetRange(); + fhdr->bool_dec_value = bd_.GetBottom(); + fhdr->bool_dec_count = 7 - (bd_.BitOffset() + 7) % 8; + + return true; +} + +bool Vp8Parser::ParseSegmentationHeader(bool keyframe) { + Vp8SegmentationHeader* shdr = &curr_segmentation_hdr_; + + if (keyframe) + memset(shdr, 0, sizeof(*shdr)); + + BD_READ_BOOL_OR_RETURN(&shdr->segmentation_enabled); + if (!shdr->segmentation_enabled) + return true; + + BD_READ_BOOL_OR_RETURN(&shdr->update_mb_segmentation_map); + BD_READ_BOOL_OR_RETURN(&shdr->update_segment_feature_data); + if (shdr->update_segment_feature_data) { + int mode; + BD_READ_UNSIGNED_OR_RETURN(1, &mode); + shdr->segment_feature_mode = + static_cast(mode); + + for (size_t i = 0; i < kMaxMBSegments; ++i) { + bool quantizer_update; + BD_READ_BOOL_OR_RETURN(&quantizer_update); + if (quantizer_update) + BD_READ_SIGNED_OR_RETURN(7, &shdr->quantizer_update_value[i]); + else + shdr->quantizer_update_value[i] = 0; + } + + for (size_t i = 0; i < kMaxMBSegments; ++i) { + bool loop_filter_update; + BD_READ_BOOL_OR_RETURN(&loop_filter_update); + if (loop_filter_update) + BD_READ_SIGNED_OR_RETURN(6, &shdr->lf_update_value[i]); + else + shdr->lf_update_value[i] = 0; + } + } + + if (shdr->update_mb_segmentation_map) { + for (size_t i = 0; i < kNumMBFeatureTreeProbs; ++i) { + bool segment_prob_update; + BD_READ_BOOL_OR_RETURN(&segment_prob_update); + if (segment_prob_update) + BD_READ_UNSIGNED_OR_RETURN(8, &shdr->segment_prob[i]); + else + shdr->segment_prob[i] = Vp8SegmentationHeader::kDefaultSegmentProb; + } + } + + return true; +} + +bool Vp8Parser::ParseLoopFilterHeader(bool keyframe) { + Vp8LoopFilterHeader* lfhdr = &curr_loopfilter_hdr_; + + if (keyframe) + memset(lfhdr, 0, sizeof(*lfhdr)); + + int type; + BD_READ_UNSIGNED_OR_RETURN(1, &type); + lfhdr->type = static_cast(type); + BD_READ_UNSIGNED_OR_RETURN(6, &lfhdr->level); + BD_READ_UNSIGNED_OR_RETURN(3, &lfhdr->sharpness_level); + BD_READ_BOOL_OR_RETURN(&lfhdr->loop_filter_adj_enable); + + if (lfhdr->loop_filter_adj_enable) { + BD_READ_BOOL_OR_RETURN(&lfhdr->mode_ref_lf_delta_update); + if (lfhdr->mode_ref_lf_delta_update) { + for (size_t i = 0; i < kNumBlockContexts; ++i) { + bool ref_frame_delta_update_flag; + BD_READ_BOOL_OR_RETURN(&ref_frame_delta_update_flag); + if (ref_frame_delta_update_flag) + BD_READ_SIGNED_OR_RETURN(6, &lfhdr->ref_frame_delta[i]); + } + + for (size_t i = 0; i < kNumBlockContexts; ++i) { + bool mb_mode_delta_update_flag; + BD_READ_BOOL_OR_RETURN(&mb_mode_delta_update_flag); + if (mb_mode_delta_update_flag) + BD_READ_SIGNED_OR_RETURN(6, &lfhdr->mb_mode_delta[i]); + } + } + } + + return true; +} + +bool Vp8Parser::ParseQuantizationHeader(Vp8QuantizationHeader* qhdr) { + // If any of the delta values is not present, the delta should be zero. + memset(qhdr, 0, sizeof(*qhdr)); + + BD_READ_UNSIGNED_OR_RETURN(7, &qhdr->y_ac_qi); + + bool delta_present; + + BD_READ_BOOL_OR_RETURN(&delta_present); + if (delta_present) + BD_READ_SIGNED_OR_RETURN(4, &qhdr->y_dc_delta); + + BD_READ_BOOL_OR_RETURN(&delta_present); + if (delta_present) + BD_READ_SIGNED_OR_RETURN(4, &qhdr->y2_dc_delta); + + BD_READ_BOOL_OR_RETURN(&delta_present); + if (delta_present) + BD_READ_SIGNED_OR_RETURN(4, &qhdr->y2_ac_delta); + + BD_READ_BOOL_OR_RETURN(&delta_present); + if (delta_present) + BD_READ_SIGNED_OR_RETURN(4, &qhdr->uv_dc_delta); + + BD_READ_BOOL_OR_RETURN(&delta_present); + if (delta_present) + BD_READ_SIGNED_OR_RETURN(4, &qhdr->uv_ac_delta); + + return true; +} + +// See spec for details on these values. +const uint8_t kCoeffUpdateProbs[kNumBlockTypes][kNumCoeffBands] + [kNumPrevCoeffContexts][kNumEntropyNodes] = { + { + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255}, + {250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255}, + {234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255}, + }, + { + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255}, + {234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255}, + {251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255}, + }, + { + {255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, + { + { + {248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255}, + {248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255}, + {248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255}, + {250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + { + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + }, + }, +}; + +const uint8_t kKeyframeYModeProbs[kNumYModeProbs] = {145, 156, 163, 128}; +const uint8_t kKeyframeUVModeProbs[kNumUVModeProbs] = {142, 114, 183}; + +const uint8_t kDefaultYModeProbs[kNumYModeProbs] = {112, 86, 140, 37}; +const uint8_t kDefaultUVModeProbs[kNumUVModeProbs] = {162, 101, 204}; + +const uint8_t kDefaultCoeffProbs[kNumBlockTypes][kNumCoeffBands] + [kNumPrevCoeffContexts][kNumEntropyNodes] = { + { + { + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128}, + {189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128}, + {106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128}, + }, + { + { 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128}, + {181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128}, + { 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128}, + }, + { + { 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128}, + {184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128}, + { 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128}, + }, + { + { 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128}, + {170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128}, + { 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128}, + }, + { + { 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128}, + {207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128}, + {102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128}, + }, + { + { 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128}, + {177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128}, + { 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128}, + }, + { + { 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + } + }, + { + { + {198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62}, + {131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1}, + { 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128}, + }, + { + { 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128}, + {184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128}, + { 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128}, + }, + { + { 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128}, + { 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128}, + { 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128}, + }, + { + { 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128}, + {109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128}, + { 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128}, + }, + { + { 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128}, + { 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128}, + { 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128}, + }, + { + { 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128}, + {124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128}, + { 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128}, + }, + { + { 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128}, + {121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128}, + { 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128}, + }, + { + { 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128}, + {203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + {137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128}, + } + }, + { + { + {253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128}, + {175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128}, + { 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128}, + }, + { + { 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128}, + {239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128}, + {155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128}, + }, + { + { 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128}, + {201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128}, + { 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128}, + }, + { + { 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128}, + {223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128}, + {141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + }, + { + { 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128}, + {190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128}, + {149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + { 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + { 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128}, + {213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128}, + { 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + { + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + {128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, + } + }, + { + { + {202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255}, + {126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128}, + { 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128}, + }, + { + { 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128}, + {166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128}, + { 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128}, + }, + { + { 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128}, + {124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128}, + { 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128}, + }, + { + { 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128}, + {149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128}, + { 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128} + }, + { + { 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128}, + {123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128}, + { 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128}, + }, + { + { 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128}, + {168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128}, + { 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128}, + }, + { + { 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128}, + {141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128}, + { 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128}, + }, + { + { 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + {238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128}, + }, + }, +}; + +const uint8_t kMVUpdateProbs[kNumMVContexts][kNumMVProbs] = +{ + { + 237, 246, 253, 253, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + }, + { + 231, 243, 245, 253, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, + }, +}; + +const uint8_t kDefaultMVProbs[kNumMVContexts][kNumMVProbs] = { + { + 162, 128, 225, 146, 172, 147, 214, 39, 156, + 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + }, + { + 164, 128, 204, 170, 119, 235, 140, 230, 228, + 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, + }, +}; + +void Vp8Parser::ResetProbs() { + // Memcpy's below are preceded by a static_assert. The static_assert + // is complying as both sizes of the comparison use the same values + // defined in the header file. Commenting out static_assert as it is + // c++11 feature. + + // static_assert( + // sizeof(curr_entropy_hdr_.coeff_probs) == sizeof(kDefaultCoeffProbs), + // "coeff_probs_arrays_must_be_of_correct_size"); + memcpy(curr_entropy_hdr_.coeff_probs, kDefaultCoeffProbs, + sizeof(curr_entropy_hdr_.coeff_probs)); + + // static_assert(sizeof(curr_entropy_hdr_.mv_probs) == sizeof(kDefaultMVProbs), + // "mv_probs_arrays_must_be_of_correct_size"); + memcpy(curr_entropy_hdr_.mv_probs, kDefaultMVProbs, + sizeof(curr_entropy_hdr_.mv_probs)); + + // static_assert( + // sizeof(curr_entropy_hdr_.y_mode_probs) == sizeof(kDefaultYModeProbs), + // "y_probs_arrays_must_be_of_correct_size"); + memcpy(curr_entropy_hdr_.y_mode_probs, kDefaultYModeProbs, + sizeof(curr_entropy_hdr_.y_mode_probs)); + + // static_assert( + // sizeof(curr_entropy_hdr_.uv_mode_probs) == sizeof(kDefaultUVModeProbs), + // "uv_probs_arrays_must_be_of_correct_size"); + memcpy(curr_entropy_hdr_.uv_mode_probs, kDefaultUVModeProbs, + sizeof(curr_entropy_hdr_.uv_mode_probs)); +} + +bool Vp8Parser::ParseTokenProbs(Vp8EntropyHeader* ehdr, + bool update_curr_probs) { + for (size_t i = 0; i < kNumBlockTypes; ++i) { + for (size_t j = 0; j < kNumCoeffBands; ++j) { + for (size_t k = 0; k < kNumPrevCoeffContexts; ++k) { + for (size_t l = 0; l < kNumEntropyNodes; ++l) { + bool coeff_prob_update_flag; + BD_READ_BOOL_WITH_PROB_OR_RETURN(&coeff_prob_update_flag, + kCoeffUpdateProbs[i][j][k][l]); + if (coeff_prob_update_flag) + BD_READ_UNSIGNED_OR_RETURN(8, &ehdr->coeff_probs[i][j][k][l]); + } + } + } + } + + if (update_curr_probs) { + memcpy(curr_entropy_hdr_.coeff_probs, ehdr->coeff_probs, + sizeof(curr_entropy_hdr_.coeff_probs)); + } + + return true; +} + +bool Vp8Parser::ParseIntraProbs(Vp8EntropyHeader* ehdr, + bool update_curr_probs, + bool keyframe) { + if (keyframe) { + // static_assert( + // sizeof(ehdr->y_mode_probs) == sizeof(kKeyframeYModeProbs), + // "y_probs_arrays_must_be_of_correct_size"); + memcpy(ehdr->y_mode_probs, kKeyframeYModeProbs, + sizeof(ehdr->y_mode_probs)); + + // static_assert( + // sizeof(ehdr->uv_mode_probs) == sizeof(kKeyframeUVModeProbs), + // "uv_probs_arrays_must_be_of_correct_size"); + memcpy(ehdr->uv_mode_probs, kKeyframeUVModeProbs, + sizeof(ehdr->uv_mode_probs)); + } else { + bool intra_16x16_prob_update_flag; + BD_READ_BOOL_OR_RETURN(&intra_16x16_prob_update_flag); + if (intra_16x16_prob_update_flag) { + for (size_t i = 0; i < kNumYModeProbs; ++i) + BD_READ_UNSIGNED_OR_RETURN(8, &ehdr->y_mode_probs[i]); + + if (update_curr_probs) { + memcpy(curr_entropy_hdr_.y_mode_probs, ehdr->y_mode_probs, + sizeof(curr_entropy_hdr_.y_mode_probs)); + } + } + + bool intra_chroma_prob_update_flag; + BD_READ_BOOL_OR_RETURN(&intra_chroma_prob_update_flag); + if (intra_chroma_prob_update_flag) { + for (size_t i = 0; i < kNumUVModeProbs; ++i) + BD_READ_UNSIGNED_OR_RETURN(8, &ehdr->uv_mode_probs[i]); + + if (update_curr_probs) { + memcpy(curr_entropy_hdr_.uv_mode_probs, ehdr->uv_mode_probs, + sizeof(curr_entropy_hdr_.uv_mode_probs)); + } + } + } + + return true; +} + +bool Vp8Parser::ParseMVProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs) { + for (size_t mv_ctx = 0; mv_ctx < kNumMVContexts; ++mv_ctx) { + for (size_t p = 0; p < kNumMVProbs; ++p) { + bool mv_prob_update_flag; + BD_READ_BOOL_WITH_PROB_OR_RETURN(&mv_prob_update_flag, + kMVUpdateProbs[mv_ctx][p]); + if (mv_prob_update_flag) { + uint8_t prob; + BD_READ_UNSIGNED_OR_RETURN(7, &prob); + ehdr->mv_probs[mv_ctx][p] = prob ? (prob << 1) : 1; + } + } + } + + if (update_curr_probs) { + memcpy(curr_entropy_hdr_.mv_probs, ehdr->mv_probs, + sizeof(curr_entropy_hdr_.mv_probs)); + } + + return true; +} + +bool Vp8Parser::ParsePartitions(Vp8FrameHeader* fhdr) { + CHECK_GE(fhdr->num_of_dct_partitions, 1u); + CHECK_LE(fhdr->num_of_dct_partitions, kMaxDCTPartitions); + + // DCT partitions start after the first partition and partition size values + // that follow it. There are num_of_dct_partitions - 1 sizes stored in the + // stream after the first partition, each 3 bytes long. The size of last + // DCT partition is not stored in the stream, but is instead calculated by + // taking the remainder of the frame size after the penultimate DCT partition. + size_t first_dct_pos = fhdr->first_part_offset + fhdr->first_part_size + + (fhdr->num_of_dct_partitions - 1) * 3; + + // Make sure we have enough data for the first partition and partition sizes. + if (fhdr->frame_size < first_dct_pos) + return false; + + // Total size of all DCT partitions. + size_t bytes_left = fhdr->frame_size - first_dct_pos; + + // Position ourselves at the beginning of partition size values. + const uint8_t* ptr = + fhdr->data + fhdr->first_part_offset + fhdr->first_part_size; + + // Read sizes from the stream (if present). + for (size_t i = 0; i < fhdr->num_of_dct_partitions - 1; ++i) { + fhdr->dct_partition_sizes[i] = (ptr[2] << 16) | (ptr[1] << 8) | ptr[0]; + + // Make sure we have enough data in the stream for ith partition and + // subtract its size from total. + if (bytes_left < fhdr->dct_partition_sizes[i]) + return false; + + bytes_left -= fhdr->dct_partition_sizes[i]; + + // Move to the position of the next partition size value. + ptr += 3; + } + + // The remainder of the data belongs to the last DCT partition. + fhdr->dct_partition_sizes[fhdr->num_of_dct_partitions - 1] = bytes_left; + + return true; +} + +} // namespace YamiParser diff --git a/codecparsers/vp8_parser.h b/codecparsers/vp8_parser.h new file mode 100644 index 0000000..44a4944 --- /dev/null +++ b/codecparsers/vp8_parser.h @@ -0,0 +1,242 @@ +/* + * Copyright 2015 The Chromium Authors. All rights reserved. + * Copyright 2016 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Google, nor the WebM Project, nor the names + * of its contributors may be used to endorse or promote products + * derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// +// This file contains an implementation of a VP8 raw stream parser, +// as defined in RFC 6386. +// This is taken from Chromium Project and adapted to use within libyami + +#ifndef VP8_PARSER_H_ +#define VP8_PARSER_H_ + +#include "common/NonCopyable.h" +#include "VideoCommonDefs.h" +#include +#include +#include "vp8_bool_decoder.h" + +#define CHECK_GE(X, Y) assert(X >= Y) +#define CHECK_LE(X, Y) assert(X <= Y) + +namespace YamiParser { + +// See spec for definitions of values/fields. +const size_t kMaxMBSegments = 4; +const size_t kNumMBFeatureTreeProbs = 3; +enum Vp8ParserResult { + VP8_PARSER_OK = 0, + VP8_PARSER_BROKEN_DATA, + VP8_PARSER_ERROR, +}; + +// Member of Vp8FrameHeader and will be 0-initialized +// in Vp8FrameHeader's constructor. +struct Vp8SegmentationHeader { + enum SegmentFeatureMode { FEATURE_MODE_DELTA = 0, FEATURE_MODE_ABSOLUTE = 1 }; + + bool segmentation_enabled; + bool update_mb_segmentation_map; + bool update_segment_feature_data; + + int8_t quantizer_update_value[kMaxMBSegments]; + int8_t lf_update_value[kMaxMBSegments]; + static const int kDefaultSegmentProb = 255; + uint8_t segment_prob[kNumMBFeatureTreeProbs]; + SegmentFeatureMode segment_feature_mode; + //Because these variables is non pod type, it can not use memset and use offsetof to weed out it +}; + +const size_t kNumBlockContexts = 4; + +// Member of Vp8FrameHeader and will be 0-initialized +// in Vp8FrameHeader's constructor. +struct Vp8LoopFilterHeader { + enum Type { LOOP_FILTER_TYPE_NORMAL = 0, LOOP_FILTER_TYPE_SIMPLE = 1 }; + uint8_t level; + uint8_t sharpness_level; + bool loop_filter_adj_enable; + bool mode_ref_lf_delta_update; + + int8_t ref_frame_delta[kNumBlockContexts]; + int8_t mb_mode_delta[kNumBlockContexts]; + Type type; + //Because these variables is non pod type, it can not use memset and use offsetof to weed out it +}; + +// Member of Vp8FrameHeader and will be 0-initialized +// in Vp8FrameHeader's constructor. +struct Vp8QuantizationHeader { + uint8_t y_ac_qi; + int8_t y_dc_delta; + int8_t y2_dc_delta; + int8_t y2_ac_delta; + int8_t uv_dc_delta; + int8_t uv_ac_delta; +}; + +const size_t kNumBlockTypes = 4; +const size_t kNumCoeffBands = 8; +const size_t kNumPrevCoeffContexts = 3; +const size_t kNumEntropyNodes = 11; + +const size_t kNumMVContexts = 2; +const size_t kNumMVProbs = 19; + +const size_t kNumYModeProbs = 4; +const size_t kNumUVModeProbs = 3; + +// Member of Vp8FrameHeader and will be 0-initialized +// in Vp8FrameHeader's constructor. +struct Vp8EntropyHeader { + uint8_t coeff_probs[kNumBlockTypes][kNumCoeffBands][kNumPrevCoeffContexts] + [kNumEntropyNodes]; + + uint8_t y_mode_probs[kNumYModeProbs]; + uint8_t uv_mode_probs[kNumUVModeProbs]; + + uint8_t mv_probs[kNumMVContexts][kNumMVProbs]; +}; + +const size_t kMaxDCTPartitions = 8; + +struct Vp8FrameHeader { + Vp8FrameHeader(); + + enum FrameType { KEYFRAME = 0, INTERFRAME = 1 }; + bool IsKeyframe() const { return key_frame == KEYFRAME; } + + enum GoldenRefreshMode { + COPY_LAST_TO_GOLDEN = 1, + COPY_ALT_TO_GOLDEN = 2, + }; + + enum AltRefreshMode { + COPY_LAST_TO_ALT = 1, + COPY_GOLDEN_TO_ALT = 2, + }; + + FrameType key_frame; + uint8_t version; + bool is_experimental; + bool show_frame; + size_t first_part_size; + + uint16_t width; + uint8_t horizontal_scale; + uint16_t height; + uint8_t vertical_scale; + + Vp8SegmentationHeader segmentation_hdr; + Vp8LoopFilterHeader loopfilter_hdr; + Vp8QuantizationHeader quantization_hdr; + + size_t num_of_dct_partitions; + + Vp8EntropyHeader entropy_hdr; + + bool refresh_entropy_probs; + bool refresh_golden_frame; + bool refresh_alternate_frame; + GoldenRefreshMode copy_buffer_to_golden; + AltRefreshMode copy_buffer_to_alternate; + uint8_t sign_bias_golden; + uint8_t sign_bias_alternate; + bool refresh_last; + + bool mb_no_skip_coeff; + uint8_t prob_skip_false; + uint8_t prob_intra; + uint8_t prob_last; + uint8_t prob_gf; + + const uint8_t* data; + size_t frame_size; + + size_t dct_partition_sizes[kMaxDCTPartitions]; + // Offset in bytes from data. + off_t first_part_offset; + // Offset in bits from first_part_offset. + off_t macroblock_bit_offset; + + // Bool decoder state + uint8_t bool_dec_range; + uint8_t bool_dec_value; + uint8_t bool_dec_count; +}; + +// A parser for raw VP8 streams as specified in RFC 6386. +class Vp8Parser { + public: + Vp8Parser(); + ~Vp8Parser(); + + // Try to parse exactly one VP8 frame starting at |ptr| and of size |size|, + // filling the parsed data in |fhdr|. Return true on success. + // Size has to be exactly the size of the frame and coming from the caller, + // who needs to acquire it from elsewhere (normally from a container). + Vp8ParserResult ParseFrame(const uint8_t* ptr, size_t size, Vp8FrameHeader* fhdr); + + private: + friend class Vp8ParserTest; + + bool ParseFrameTag(Vp8FrameHeader* fhdr); + bool ParseFrameHeader(Vp8FrameHeader* fhdr); + + bool ParseSegmentationHeader(bool keyframe); + bool ParseLoopFilterHeader(bool keyframe); + bool ParseQuantizationHeader(Vp8QuantizationHeader* qhdr); + bool ParseTokenProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs); + bool ParseIntraProbs(Vp8EntropyHeader* ehdr, + bool update_curr_probs, + bool keyframe); + bool ParseMVProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs); + bool ParsePartitions(Vp8FrameHeader* fhdr); + void ResetProbs(); + + // These persist across calls to ParseFrame() and may be used and/or updated + // for subsequent frames if the stream instructs us to do so. + Vp8SegmentationHeader curr_segmentation_hdr_; + Vp8LoopFilterHeader curr_loopfilter_hdr_; + Vp8EntropyHeader curr_entropy_hdr_; + + const uint8_t* stream_; + size_t bytes_left_; + Vp8BoolDecoder bd_; + + DISALLOW_COPY_AND_ASSIGN(Vp8Parser); +}; + +} // namespace YamiParser + +#endif // MEDIA_FILTERS_VP8_PARSER_H_ diff --git a/codecparsers/vp9parser.cpp b/codecparsers/vp9parser.cpp new file mode 100644 index 0000000..c0a945d --- /dev/null +++ b/codecparsers/vp9parser.cpp @@ -0,0 +1,660 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * SECTION:vp9parser + * @short_description: Convenience library for parsing vp9 video bitstream. + * + * For more details about the structures, you can refer to the + * specifications: + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "bitReader.h" +#include "vp9quant.h" +#include "vp9parser.h" +#include +#include +#include "common/log.h" + +using YamiParser::BitReader; + +#define MAX_LOOP_FILTER 63 +#define MAX_PROB 255 + +typedef struct _ReferenceSize { + uint32_t width; + uint32_t height; +} ReferenceSize; + +typedef struct _Vp9ParserPrivate { + int8_t y_dc_delta_q; + int8_t uv_dc_delta_q; + int8_t uv_ac_delta_q; + + int16_t y_dequant[QINDEX_RANGE][2]; + int16_t uv_dequant[QINDEX_RANGE][2]; + + /* for loop filters */ + int8_t ref_deltas[VP9_MAX_REF_LF_DELTAS]; + int8_t mode_deltas[VP9_MAX_MODE_LF_DELTAS]; + + BOOL segmentation_abs_delta; + Vp9SegmentationInfoData segmentation[VP9_MAX_SEGMENTS]; + + ReferenceSize reference[VP9_REF_FRAMES]; +} Vp9ParserPrivate; + +void init_dequantizer(Vp9Parser* parser); + +static void init_vp9_parser(Vp9Parser* parser, VP9_BIT_DEPTH bit_depth) +{ + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + memset(parser, 0, sizeof(Vp9Parser)); + memset(priv, 0, sizeof(Vp9ParserPrivate)); + parser->priv = priv; + parser->bit_depth = bit_depth; + init_dequantizer(parser); +} + +Vp9Parser* vp9_parser_new() +{ + Vp9Parser* parser = (Vp9Parser*)malloc(sizeof(Vp9Parser)); + if (!parser) + return NULL; + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)malloc(sizeof(Vp9ParserPrivate)); + if (!priv) { + free(parser); + return NULL; + } + parser->priv = priv; + init_vp9_parser(parser, VP9_BITS_8); + return parser; +} + +void vp9_parser_free(Vp9Parser* parser) +{ + if (parser) { + if (parser->priv) + free(parser->priv); + free(parser); + } +} + +#define vp9_read_bit(br) br->read(1) +#define vp9_read_bits(br, bits) br->read(bits) + +static int32_t vp9_read_signed_bits(BitReader* br, int bits) +{ + assert(bits < 32); + const int32_t value = vp9_read_bits(br, bits); + return vp9_read_bit(br) ? -value : value; +} + +static BOOL verify_frame_marker(BitReader* br) +{ +#define VP9_FRAME_MARKER 2 + uint8_t frame_marker = vp9_read_bits(br, 2); + if (frame_marker != VP9_FRAME_MARKER) + return FALSE; + return TRUE; +} + +static BOOL verify_sync_code(BitReader* const br) +{ +#define VP9_SYNC_CODE_0 0x49 +#define VP9_SYNC_CODE_1 0x83 +#define VP9_SYNC_CODE_2 0x42 + return vp9_read_bits(br, 8) == VP9_SYNC_CODE_0 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_1 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_2; +} + +static VP9_PROFILE read_profile(BitReader* br) +{ + uint8_t profile = vp9_read_bit(br); + profile |= vp9_read_bit(br) << 1; + if (profile > 2) + profile += vp9_read_bit(br); + return (VP9_PROFILE)profile; +} + +static void read_frame_size(BitReader* br, + uint32_t* width, uint32_t* height) +{ + const uint32_t w = vp9_read_bits(br, 16) + 1; + const uint32_t h = vp9_read_bits(br, 16) + 1; + *width = w; + *height = h; +} + +static void read_display_frame_size(Vp9FrameHdr* frame_hdr, BitReader* br) +{ + frame_hdr->display_size_enabled = vp9_read_bit(br); + if (frame_hdr->display_size_enabled) { + read_frame_size(br, &frame_hdr->display_width, &frame_hdr->display_height); + } +} + +static void read_frame_size_from_refs(const Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br) +{ + BOOL found = FALSE; + int i; + const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + for (i = 0; i < VP9_REFS_PER_FRAME; i++) { + found = vp9_read_bit(br); + if (found) { + uint8_t idx = frame_hdr->ref_frame_indices[i]; + frame_hdr->size_from_ref[i] = TRUE; + frame_hdr->width = priv->reference[idx].width; + frame_hdr->height = priv->reference[idx].height; + break; + } + } + if (!found) { + read_frame_size(br, &frame_hdr->width, &frame_hdr->height); + } +} + +static VP9_INTERP_FILTER read_interp_filter(BitReader* br) +{ + const VP9_INTERP_FILTER filter_map[] = { VP9_EIGHTTAP_SMOOTH, + VP9_EIGHTTAP, + VP9_EIGHTTAP_SHARP, + VP9_BILINEAR }; + return vp9_read_bit(br) ? VP9_SWITCHABLE + : filter_map[vp9_read_bits(br, 2)]; +} + +static void read_loopfilter(Vp9LoopFilter* lf, BitReader* br) +{ + lf->filter_level = vp9_read_bits(br, 6); + lf->sharpness_level = vp9_read_bits(br, 3); + + lf->mode_ref_delta_update = 0; + + lf->mode_ref_delta_enabled = vp9_read_bit(br); + if (lf->mode_ref_delta_enabled) { + lf->mode_ref_delta_update = vp9_read_bit(br); + if (lf->mode_ref_delta_update) { + int i; + for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) { + lf->update_ref_deltas[i] = vp9_read_bit(br); + if (lf->update_ref_deltas[i]) + lf->ref_deltas[i] = vp9_read_signed_bits(br, 6); + } + + for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) { + lf->update_mode_deltas[i] = vp9_read_bit(br); + if (lf->update_mode_deltas[i]) + lf->mode_deltas[i] = vp9_read_signed_bits(br, 6); + } + } + } +} + +static int8_t read_delta_q(BitReader* br) +{ + return vp9_read_bit(br) ? vp9_read_signed_bits(br, 4) : 0; +} + +static void read_quantization(Vp9FrameHdr* frame_hdr, BitReader* br) +{ + frame_hdr->base_qindex = vp9_read_bits(br, QINDEX_BITS); + frame_hdr->y_dc_delta_q = read_delta_q(br); + frame_hdr->uv_dc_delta_q = read_delta_q(br); + frame_hdr->uv_ac_delta_q = read_delta_q(br); +} + +static void read_segmentation(Vp9SegmentationInfo* seg, BitReader* br) +{ + int i; + + seg->update_map = FALSE; + seg->update_data = FALSE; + + seg->enabled = vp9_read_bit(br); + if (!seg->enabled) + return; + seg->update_map = vp9_read_bit(br); + if (seg->update_map) { + for (i = 0; i < VP9_SEG_TREE_PROBS; i++) { + seg->update_tree_probs[i] = vp9_read_bit(br); + seg->tree_probs[i] = seg->update_tree_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB; + } + seg->temporal_update = vp9_read_bit(br); + if (seg->temporal_update) { + for (i = 0; i < VP9_PREDICTION_PROBS; i++) { + seg->update_pred_probs[i] = vp9_read_bit(br); + seg->pred_probs[i] = seg->update_pred_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB; + } + } + else { + for (i = 0; i < VP9_PREDICTION_PROBS; i++) { + seg->pred_probs[i] = MAX_PROB; + } + } + } + + seg->update_data = vp9_read_bit(br); + + if (seg->update_data) { + /* clear all features */ + memset(seg->data, 0, sizeof(seg->data)); + + seg->abs_delta = vp9_read_bit(br); + for (i = 0; i < VP9_MAX_SEGMENTS; i++) { + Vp9SegmentationInfoData* seg_data = seg->data + i; + uint8_t data; + /* SEG_LVL_ALT_Q */ + seg_data->alternate_quantizer_enabled = vp9_read_bit(br); + if (seg_data->alternate_quantizer_enabled) { + data = vp9_read_bits(br, 8); + seg_data->alternate_quantizer = vp9_read_bit(br) ? -data : data; + } + /* SEG_LVL_ALT_LF */ + seg_data->alternate_loop_filter_enabled = vp9_read_bit(br); + if (seg_data->alternate_loop_filter_enabled) { + data = vp9_read_bits(br, 6); + seg_data->alternate_loop_filter = vp9_read_bit(br) ? -data : data; + } + /* SEG_LVL_REF_FRAME */ + seg_data->reference_frame_enabled = vp9_read_bit(br); + if (seg_data->reference_frame_enabled) { + seg_data->reference_frame = vp9_read_bits(br, 2); + } + seg_data->reference_skip = vp9_read_bit(br); + } + } +} + +#define MIN_TILE_WIDTH_B64 4 +#define MAX_TILE_WIDTH_B64 64 +uint32_t get_max_lb_tile_cols(uint32_t sb_cols) +{ + int log2 = 0; + while ((sb_cols >> log2) >= MIN_TILE_WIDTH_B64) + ++log2; + if (log2) + log2--; + return log2; +} + +uint32_t get_min_lb_tile_cols(uint32_t sb_cols) +{ + uint32_t log2 = 0; + while ((uint64_t)(MAX_TILE_WIDTH_B64 << log2) < sb_cols) + ++log2; + return log2; +} + +/* align to 64, follow specification 6.2.6 Compute image size syntax */ +#define SB_ALIGN(w) (((w) + 63) >> 6) +static BOOL read_tile_info(Vp9FrameHdr* frame_hdr, BitReader* br) +{ + const uint32_t sb_cols = SB_ALIGN(frame_hdr->width); + uint32_t min_lb_tile_cols = get_min_lb_tile_cols(sb_cols); + uint32_t max_lb_tile_cols = get_max_lb_tile_cols(sb_cols); + uint32_t max_ones = max_lb_tile_cols - min_lb_tile_cols; + + /* columns */ + frame_hdr->log2_tile_columns = min_lb_tile_cols; + while (max_ones-- && vp9_read_bit(br)) + frame_hdr->log2_tile_columns++; + + /* row */ + frame_hdr->log2_tile_rows = vp9_read_bit(br); + if (frame_hdr->log2_tile_rows) + frame_hdr->log2_tile_rows += vp9_read_bit(br); + return TRUE; +} + +static void loop_filter_update(Vp9Parser* parser, const Vp9LoopFilter* lf) +{ + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + int i; + + for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) { + if (lf->update_ref_deltas[i]) + priv->ref_deltas[i] = lf->ref_deltas[i]; + } + + for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) { + if (lf->update_mode_deltas[i]) + priv->mode_deltas[i] = lf->mode_deltas[i]; + } +} + +BOOL compare_and_set(int8_t* dest, const int8_t src) +{ + const int8_t old = *dest; + *dest = src; + return old != src; +} + +void init_dequantizer(Vp9Parser* parser) +{ + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + int q; + for (q = 0; q < QINDEX_RANGE; q++) { + priv->y_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->y_dc_delta_q); + priv->y_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, 0); + priv->uv_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->uv_dc_delta_q); + priv->uv_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, priv->uv_ac_delta_q); + } +} +static void quantization_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) +{ + BOOL update = FALSE; + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + update |= compare_and_set(&priv->y_dc_delta_q, frame_hdr->y_dc_delta_q); + update |= compare_and_set(&priv->uv_dc_delta_q, frame_hdr->uv_dc_delta_q); + update |= compare_and_set(&priv->uv_ac_delta_q, frame_hdr->uv_ac_delta_q); + if (update) { + init_dequantizer(parser); + } + parser->lossless_flag = frame_hdr->base_qindex == 0 && frame_hdr->y_dc_delta_q == 0 && frame_hdr->uv_dc_delta_q == 0 && frame_hdr->uv_ac_delta_q == 0; +} + +uint8_t seg_get_base_qindex(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid) +{ + int seg_base = frame_hdr->base_qindex; + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + const Vp9SegmentationInfoData* seg = priv->segmentation + segid; + /* DEBUG("id = %d, seg_base = %d, seg enable = %d, alt eanble = %d, abs = %d, alt= %d\n",segid, + seg_base, frame_hdr->segmentation.enabled, seg->alternate_quantizer_enabled, priv->segmentation_abs_delta, seg->alternate_quantizer); + */ + if (frame_hdr->segmentation.enabled && seg->alternate_quantizer_enabled) { + if (priv->segmentation_abs_delta) + seg_base = seg->alternate_quantizer; + else + seg_base += seg->alternate_quantizer; + } + return clamp(seg_base, 0, MAXQ); +} + +uint8_t seg_get_filter_level(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid) +{ + int seg_filter = frame_hdr->loopfilter.filter_level; + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + const Vp9SegmentationInfoData* seg = priv->segmentation + segid; + + if (frame_hdr->segmentation.enabled && seg->alternate_loop_filter_enabled) { + if (priv->segmentation_abs_delta) + seg_filter = seg->alternate_loop_filter; + else + seg_filter += seg->alternate_loop_filter; + } + return clamp(seg_filter, 0, MAX_LOOP_FILTER); +} + +/*save segmentation info from frame header to parser*/ +static void segmentation_save(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) +{ + const Vp9SegmentationInfo* info = &frame_hdr->segmentation; + if (!info->enabled) + return; + if (info->update_map) { + ASSERT(sizeof(parser->mb_segment_tree_probs) == sizeof(info->tree_probs)); + ASSERT(sizeof(parser->segment_pred_probs) == sizeof(info->pred_probs)); + memcpy(parser->mb_segment_tree_probs, info->tree_probs, sizeof(info->tree_probs)); + memcpy(parser->segment_pred_probs, info->pred_probs, sizeof(info->pred_probs)); + } + if (info->update_data) { + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + priv->segmentation_abs_delta = info->abs_delta; + ASSERT(sizeof(priv->segmentation) == sizeof(info->data)); + memcpy(priv->segmentation, info->data, sizeof(info->data)); + } +} + +static void segmentation_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) +{ + int i = 0; + const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + const Vp9LoopFilter* lf = &frame_hdr->loopfilter; + int default_filter = lf->filter_level; + const int scale = 1 << (default_filter >> 5); + + segmentation_save(parser, frame_hdr); + + for (i = 0; i < VP9_MAX_SEGMENTS; i++) { + uint8_t q = seg_get_base_qindex(parser, frame_hdr, i); + + Vp9Segmentation* seg = parser->segmentation + i; + const Vp9SegmentationInfoData* info = priv->segmentation + i; + + seg->luma_dc_quant_scale = priv->y_dequant[q][0]; + seg->luma_ac_quant_scale = priv->y_dequant[q][1]; + seg->chroma_dc_quant_scale = priv->uv_dequant[q][0]; + seg->chroma_ac_quant_scale = priv->uv_dequant[q][1]; + + if (lf->filter_level) { + uint8_t filter = seg_get_filter_level(parser, frame_hdr, i); + + if (!lf->mode_ref_delta_enabled) { + memset(seg->filter_level, filter, sizeof(seg->filter_level)); + } + else { + int ref, mode; + const int intra_filter = filter + priv->ref_deltas[VP9_INTRA_FRAME] * scale; + seg->filter_level[VP9_INTRA_FRAME][0] = clamp(intra_filter, 0, MAX_LOOP_FILTER); + for (ref = VP9_LAST_FRAME; ref < VP9_MAX_REF_FRAMES; ++ref) { + for (mode = 0; mode < VP9_MAX_MODE_LF_DELTAS; ++mode) { + const int inter_filter = filter + priv->ref_deltas[ref] * scale + + priv->mode_deltas[mode] * scale; + seg->filter_level[ref][mode] = clamp(inter_filter, 0, MAX_LOOP_FILTER); + } + } + } + } + seg->reference_frame_enabled = info->reference_frame_enabled; + ; + seg->reference_frame = info->reference_frame; + seg->reference_skip = info->reference_skip; + } +} + +static void reference_update(Vp9Parser* parser, const Vp9FrameHdr* const frame_hdr) +{ + uint8_t flag = 1; + uint8_t refresh_frame_flags; + int i; + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + ReferenceSize* reference = priv->reference; + if (frame_hdr->frame_type == VP9_KEY_FRAME) { + refresh_frame_flags = 0xff; + } + else { + refresh_frame_flags = frame_hdr->refresh_frame_flags; + } + for (i = 0; i < VP9_REF_FRAMES; i++) { + if (refresh_frame_flags & flag) { + reference[i].width = frame_hdr->width; + reference[i].height = frame_hdr->height; + } + flag <<= 1; + } +} + +static inline int key_or_intra_only(const Vp9FrameHdr* frame_hdr) +{ + return frame_hdr->frame_type == VP9_KEY_FRAME || frame_hdr->intra_only; +} + +static void set_default_lf_deltas(Vp9Parser* parser) +{ + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + priv->ref_deltas[VP9_INTRA_FRAME] = 1; + priv->ref_deltas[VP9_LAST_FRAME] = 0; + priv->ref_deltas[VP9_GOLDEN_FRAME] = -1; + priv->ref_deltas[VP9_ALTREF_FRAME] = -1; + + priv->mode_deltas[0] = 0; + priv->mode_deltas[1] = 0; +} + +static void set_default_segmentation_info(Vp9Parser* parser) +{ + Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; + + memset(priv->segmentation, 0, sizeof(priv->segmentation)); + priv->segmentation_abs_delta = FALSE; +} + +static void setup_past_independence(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) +{ + set_default_lf_deltas(parser); + set_default_segmentation_info(parser); + memset(frame_hdr->ref_frame_sign_bias, 0, sizeof(frame_hdr->ref_frame_sign_bias)); +} + +static Vp9ParseResult vp9_parser_update(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) +{ + if (frame_hdr->frame_type == VP9_KEY_FRAME) { + init_vp9_parser(parser, frame_hdr->bit_depth); + } + if (key_or_intra_only(frame_hdr) || frame_hdr->error_resilient_mode) { + setup_past_independence(parser, frame_hdr); + } + loop_filter_update(parser, &frame_hdr->loopfilter); + quantization_update(parser, frame_hdr); + segmentation_update(parser, frame_hdr); + reference_update(parser, frame_hdr); + return VP9_PARSER_OK; +} + +static Vp9ParseResult vp9_color_config(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br) +{ + if (frame_hdr->profile >= VP9_PROFILE_2) { + frame_hdr->bit_depth = vp9_read_bit(br) ? VP9_BITS_12 : VP9_BITS_10; + if (VP9_BITS_12 == frame_hdr->bit_depth) { + ERROR("vp9 12 bits-depth is unsupported by now!"); + return VP9_PARSER_UNSUPPORTED; + } + } + else { + frame_hdr->bit_depth = VP9_BITS_8; + } + + frame_hdr->color_space = (VP9_COLOR_SPACE)vp9_read_bits(br, 3); + if (frame_hdr->color_space != VP9_SRGB) { + vp9_read_bit(br); //color_range + if (frame_hdr->profile == VP9_PROFILE_1 || frame_hdr->profile == VP9_PROFILE_3) { + frame_hdr->subsampling_x = vp9_read_bit(br); + frame_hdr->subsampling_y = vp9_read_bit(br); + + if (vp9_read_bit(br)) { //reserved_zero + ERROR("reserved bit"); + return VP9_PARSER_ERROR; + } + } + else { + frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1; + } + } + else { + ERROR("do not support SRGB"); + return VP9_PARSER_UNSUPPORTED; + } + + return VP9_PARSER_OK; +} + +Vp9ParseResult +vp9_parse_frame_header(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, const uint8_t* data, uint32_t size) +{ +#define FRAME_CONTEXTS_BITS 2 + BitReader bit_reader(data, size); + BitReader* br = &bit_reader; + memset(frame_hdr, 0, sizeof(*frame_hdr)); + /* Uncompressed Data Chunk */ + if (!verify_frame_marker(br)) + goto error; + frame_hdr->profile = read_profile(br); + if (frame_hdr->profile > MAX_VP9_PROFILES) + goto error; + frame_hdr->show_existing_frame = vp9_read_bit(br); + if (frame_hdr->show_existing_frame) { + frame_hdr->frame_to_show = vp9_read_bits(br, VP9_REF_FRAMES_LOG2); + return VP9_PARSER_OK; + } + frame_hdr->frame_type = (VP9_FRAME_TYPE)vp9_read_bit(br); + frame_hdr->show_frame = vp9_read_bit(br); + frame_hdr->error_resilient_mode = vp9_read_bit(br); + if (frame_hdr->frame_type == VP9_KEY_FRAME) { + if (!verify_sync_code(br)) + goto error; + if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK) + goto error; + read_frame_size(br, &frame_hdr->width, &frame_hdr->height); + read_display_frame_size(frame_hdr, br); + } + else { + frame_hdr->intra_only = frame_hdr->show_frame ? 0 : vp9_read_bit(br); + frame_hdr->reset_frame_context = frame_hdr->error_resilient_mode ? 0 : vp9_read_bits(br, 2); + if (frame_hdr->intra_only) { + if (!verify_sync_code(br)) + goto error; + if (frame_hdr->profile > VP9_PROFILE_0) { + if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK) + goto error; + } + else { + frame_hdr->color_space = VP9_BT_601; + frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1; + frame_hdr->bit_depth = VP9_BITS_8; + } + + frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES); + read_frame_size(br, &frame_hdr->width, &frame_hdr->height); + read_display_frame_size(frame_hdr, br); + } + else { + int i; + frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES); + for (i = 0; i < VP9_REFS_PER_FRAME; i++) { + frame_hdr->ref_frame_indices[i] = vp9_read_bits(br, VP9_REF_FRAMES_LOG2); + frame_hdr->ref_frame_sign_bias[i] = vp9_read_bit(br); + } + read_frame_size_from_refs(parser, frame_hdr, br); + read_display_frame_size(frame_hdr, br); + frame_hdr->allow_high_precision_mv = vp9_read_bit(br); + frame_hdr->mcomp_filter_type = read_interp_filter(br); + } + } + if (!frame_hdr->error_resilient_mode) { + frame_hdr->refresh_frame_context = vp9_read_bit(br); + frame_hdr->frame_parallel_decoding_mode = vp9_read_bit(br); + } + else { + frame_hdr->frame_parallel_decoding_mode = TRUE; + } + frame_hdr->frame_context_idx = vp9_read_bits(br, FRAME_CONTEXTS_BITS); + read_loopfilter(&frame_hdr->loopfilter, br); + read_quantization(frame_hdr, br); + read_segmentation(&frame_hdr->segmentation, br); + if (!read_tile_info(frame_hdr, br)) + goto error; + frame_hdr->first_partition_size = vp9_read_bits(br, 16); + if (!frame_hdr->first_partition_size) + goto error; + frame_hdr->frame_header_length_in_bytes = (br->getPos() + 7) / 8; + return vp9_parser_update(parser, frame_hdr); +error: + return VP9_PARSER_ERROR; +} diff --git a/codecparsers/vp9parser.h b/codecparsers/vp9parser.h new file mode 100644 index 0000000..18fdac5 --- /dev/null +++ b/codecparsers/vp9parser.h @@ -0,0 +1,248 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VP9_PARSER_H__ +#define __VP9_PARSER_H__ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#include +#include "common/common_def.h" + +#define VP9_REFS_PER_FRAME 3 + +#define VP9_REF_FRAMES_LOG2 3 +#define VP9_REF_FRAMES (1 << VP9_REF_FRAMES_LOG2) + +#define VP9_MAX_LOOP_FILTER 63 +#define VP9_MAX_SHARPNESS 7 + +#define VP9_MAX_REF_LF_DELTAS 4 +#define VP9_MAX_MODE_LF_DELTAS 2 + +#define VP9_SEGMENT_DELTADATA 0 +#define VP9_SEGMENT_ABSDATA 1 + +#define VP9_MAX_SEGMENTS 8 +#define VP9_SEG_TREE_PROBS (VP9_MAX_SEGMENTS - 1) + +#define VP9_PREDICTION_PROBS 3 + +typedef struct _Vp9FrameHdr Vp9FrameHdr; +typedef struct _Vp9Parser Vp9Parser; +typedef struct _Vp9LoopFilter Vp9LoopFilter; +typedef struct _Vp9Segmentation Vp9Segmentation; +typedef struct _Vp9SegmentationInfo Vp9SegmentationInfo; +typedef struct _Vp9SegmentationInfoData Vp9SegmentationInfoData; + +/** + * Vp9ParseResult: + * @VP9_PARSER_OK: The parsing went well + * @VP9_PARSER_NO_PACKET_ERROR: An error accured durint the parsing + * + * Result type of any parsing function. + */ +typedef enum { + VP9_PARSER_OK, + VP9_PARSER_ERROR, + VP9_PARSER_UNSUPPORTED +} Vp9ParseResult; + +typedef enum VP9_PROFILE { + VP9_PROFILE_0, + VP9_PROFILE_1, + VP9_PROFILE_2, + VP9_PROFILE_3, + MAX_VP9_PROFILES +} VP9_PROFILE; + +typedef enum VP9_BIT_DEPTH { + VP9_BITS_8, + VP9_BITS_10, + VP9_BITS_12 +} VP9_BIT_DEPTH; + +typedef enum { + VP9_UNKNOW_COLOR_SPACE = 0, + VP9_BT_601 = 1, + VP9_BT_709 = 2, + VP9_SMPTE_170 = 3, + VP9_SMPTE_240 = 4, + VP9_RESERVED_1 = 5, + VP9_RESERVED_2 = 6, + VP9_SRGB = 7, +} VP9_COLOR_SPACE; + +typedef enum { + VP9_KEY_FRAME = 0, + VP9_INTER_FRAME = 1, +} VP9_FRAME_TYPE; + +typedef enum { + VP9_EIGHTTAP = 0, + VP9_EIGHTTAP_SMOOTH = 1, + VP9_EIGHTTAP_SHARP = 2, + VP9_BILINEAR = 3, + VP9_SWITCHABLE = 4 +} VP9_INTERP_FILTER; + +typedef enum { + VP9_INTRA_FRAME = 0, + VP9_LAST_FRAME = 1, + VP9_GOLDEN_FRAME = 2, + VP9_ALTREF_FRAME = 3, + VP9_MAX_REF_FRAMES = 4 +} VP9_MV_REFERENCE_FRAME; + +struct _Vp9LoopFilter { + uint8_t filter_level; + uint8_t sharpness_level; + + BOOL mode_ref_delta_enabled; + BOOL mode_ref_delta_update; + BOOL update_ref_deltas[VP9_MAX_REF_LF_DELTAS]; + int8_t ref_deltas[VP9_MAX_REF_LF_DELTAS]; + BOOL update_mode_deltas[VP9_MAX_MODE_LF_DELTAS]; + int8_t mode_deltas[VP9_MAX_MODE_LF_DELTAS]; +}; + +struct _Vp9SegmentationInfoData { + /* SEG_LVL_ALT_Q */ + BOOL alternate_quantizer_enabled; + int16_t alternate_quantizer; + + /* SEG_LVL_ALT_LF */ + BOOL alternate_loop_filter_enabled; + int8_t alternate_loop_filter; + + /* SEG_LVL_REF_FRAME */ + BOOL reference_frame_enabled; + uint8_t reference_frame; + + BOOL reference_skip; +}; + +struct _Vp9SegmentationInfo { + /* segmetation */ + /* enable in setup_segmentation*/ + BOOL enabled; + /* update_map in setup_segmentation*/ + BOOL update_map; + /* tree_probs exist or not*/ + BOOL update_tree_probs[VP9_SEG_TREE_PROBS]; + uint8_t tree_probs[VP9_SEG_TREE_PROBS]; + /* pred_probs exist or not*/ + BOOL update_pred_probs[VP9_PREDICTION_PROBS]; + uint8_t pred_probs[VP9_PREDICTION_PROBS]; + + /* abs_delta in setup_segmentation */ + BOOL abs_delta; + /* temporal_update in setup_segmentation */ + BOOL temporal_update; + + /* update_data in setup_segmentation*/ + BOOL update_data; + Vp9SegmentationInfoData data[VP9_MAX_SEGMENTS]; +}; + +struct _Vp9FrameHdr { + VP9_PROFILE profile; + BOOL show_existing_frame; + uint8_t frame_to_show; + VP9_FRAME_TYPE frame_type; + BOOL show_frame; + BOOL error_resilient_mode; + BOOL subsampling_x; + BOOL subsampling_y; + uint32_t width; + uint32_t height; + BOOL display_size_enabled; + uint32_t display_width; + uint32_t display_height; + uint8_t frame_context_idx; + + VP9_BIT_DEPTH bit_depth; + VP9_COLOR_SPACE color_space; + + BOOL intra_only; + uint8_t reset_frame_context; + uint8_t refresh_frame_flags; + + uint8_t ref_frame_indices[VP9_REFS_PER_FRAME]; + BOOL ref_frame_sign_bias[VP9_REFS_PER_FRAME]; + BOOL size_from_ref[VP9_REFS_PER_FRAME]; + BOOL allow_high_precision_mv; + VP9_INTERP_FILTER mcomp_filter_type; + + BOOL refresh_frame_context; + /* frame_parallel_decoding_mode in vp9 code*/ + BOOL frame_parallel_decoding_mode; + + //quant + uint8_t base_qindex; + int8_t y_dc_delta_q; + int8_t uv_dc_delta_q; + int8_t uv_ac_delta_q; + + Vp9LoopFilter loopfilter; + Vp9SegmentationInfo segmentation; + + uint8_t log2_tile_rows; + uint8_t log2_tile_columns; + + uint32_t first_partition_size; + uint32_t frame_header_length_in_bytes; +}; + +struct _Vp9Segmentation { + uint8_t filter_level[4][2]; + int16_t luma_ac_quant_scale; + int16_t luma_dc_quant_scale; + int16_t chroma_ac_quant_scale; + int16_t chroma_dc_quant_scale; + + BOOL reference_frame_enabled; + uint8_t reference_frame; + + BOOL reference_skip; +}; + +struct _Vp9Parser { + BOOL lossless_flag; + VP9_BIT_DEPTH bit_depth; + + uint8_t mb_segment_tree_probs[VP9_SEG_TREE_PROBS]; + uint8_t segment_pred_probs[VP9_PREDICTION_PROBS]; + Vp9Segmentation segmentation[VP9_MAX_SEGMENTS]; + + /* private data */ + void* priv; +}; + +Vp9ParseResult +vp9_parse_frame_header(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, const uint8_t* data, uint32_t size); + +Vp9Parser* vp9_parser_new(); + +void vp9_parser_free(Vp9Parser* parser); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __VP9_PARSER_H__ */ diff --git a/codecparsers/vp9quant.AUTHORS b/codecparsers/vp9quant.AUTHORS new file mode 100644 index 0000000..a9aa481 --- /dev/null +++ b/codecparsers/vp9quant.AUTHORS @@ -0,0 +1,100 @@ +# This file is automatically generated from the git commit history +# by tools/gen_authors.sh. + +Aaron Watry +Abo Talib Mahfoodh +Adrian Grange +Ahmad Sharif +Alexander Voronov +Alex Converse +Alexis Ballier +Alok Ahuja +Alpha Lam +A.Mahfoodh +Ami Fischman +Andoni Morales Alastruey +Andres Mejia +Aron Rosenberg +Attila Nagy +changjun.yang +chm +Christian Duvivier +Daniel Kang +Deb Mukherjee +Dmitry Kovalev +Dragan Mrdjan +Erik Niemeyer +Fabio Pedretti +Frank Galligan +Fredrik Söderquist +Fritz Koenig +Gaute Strokkenes +Giuseppe Scrivano +Guillaume Martres +Guillermo Ballester Valor +Hangyu Kuang +Henrik Lundin +Hui Su +Ivan Maltz +James Berry +James Zern +Jan Kratochvil +Janne Salonen +Jeff Faust +Jeff Muizelaar +Jeff Petkau +Jim Bankoski +Jingning Han +Johann Koenig +John Koleszar +Joshua Bleecher Snyder +Joshua Litt +Justin Clift +Justin Lebar +KO Myung-Hun +Lou Quillio +Luca Barbato +Makoto Kato +Mans Rullgard +Marco Paniconi +Mark Mentovai +Martin Ettl +Martin Storsjo +Matthew Heaney +Michael Kohler +Mike Frysinger +Mike Hommey +Mikhal Shemer +Morton Jonuschat +Parag Salasakar +Pascal Massimino +Patrik Westin +Paul Wilkins +Pavol Rusnak +Paweł Hajdan +Philip Jägenstedt +Priit Laes +Rafael Ávila de Espíndola +Rafaël Carré +Ralph Giles +Rob Bradford +Ronald S. Bultje +Sami Pietilä +Scott Graham +Scott LaVarnway +Shimon Doodkin +Stefan Holmer +Suman Sunkara +Taekhyun Kim +Takanori MATSUURA +Tamar Levy +Tero Rintaluoma +Thijs Vermeir +Timothy B. Terriberry +Tom Finegan +Vignesh Venkatasubramanian +Yaowu Xu +Yunqing Wang +Google Inc. +The Mozilla Foundation +The Xiph.Org Foundation diff --git a/codecparsers/vp9quant.LICENSE b/codecparsers/vp9quant.LICENSE new file mode 100644 index 0000000..83ef339 --- /dev/null +++ b/codecparsers/vp9quant.LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2010, The WebM Project authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google, nor the WebM Project, nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/codecparsers/vp9quant.PATENTS b/codecparsers/vp9quant.PATENTS new file mode 100644 index 0000000..4414d83 --- /dev/null +++ b/codecparsers/vp9quant.PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer, and otherwise run, modify and propagate the contents of this +implementation of VP8, where such license applies only to those patent +claims, both currently owned by Google and acquired in the future, +licensable by Google that are necessarily infringed by this +implementation of VP8. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of VP8 or any code incorporated within this +implementation of VP8 constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of VP8 +shall terminate as of the date such litigation is filed. diff --git a/codecparsers/vp9quant.c b/codecparsers/vp9quant.c new file mode 100644 index 0000000..6b5f476 --- /dev/null +++ b/codecparsers/vp9quant.c @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2010 The WebM project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "vp9quant.h" + +#define BIT_DEPTH_MODE_COUNT 3 +#define MODE_8BITS_DEPTH 0 +#define MODE_12BITS_DEPTH 2 + +static const int16_t dc_qlookup[BIT_DEPTH_MODE_COUNT][QINDEX_RANGE] = { + { + 4, 8, 8, 9, 10, 11, 12, 12, + 13, 14, 15, 16, 17, 18, 19, 19, + 20, 21, 22, 23, 24, 25, 26, 26, + 27, 28, 29, 30, 31, 32, 32, 33, + 34, 35, 36, 37, 38, 38, 39, 40, + 41, 42, 43, 43, 44, 45, 46, 47, + 48, 48, 49, 50, 51, 52, 53, 53, + 54, 55, 56, 57, 57, 58, 59, 60, + 61, 62, 62, 63, 64, 65, 66, 66, + 67, 68, 69, 70, 70, 71, 72, 73, + 74, 74, 75, 76, 77, 78, 78, 79, + 80, 81, 81, 82, 83, 84, 85, 85, + 87, 88, 90, 92, 93, 95, 96, 98, + 99, 101, 102, 104, 105, 107, 108, 110, + 111, 113, 114, 116, 117, 118, 120, 121, + 123, 125, 127, 129, 131, 134, 136, 138, + 140, 142, 144, 146, 148, 150, 152, 154, + 156, 158, 161, 164, 166, 169, 172, 174, + 177, 180, 182, 185, 187, 190, 192, 195, + 199, 202, 205, 208, 211, 214, 217, 220, + 223, 226, 230, 233, 237, 240, 243, 247, + 250, 253, 257, 261, 265, 269, 272, 276, + 280, 284, 288, 292, 296, 300, 304, 309, + 313, 317, 322, 326, 330, 335, 340, 344, + 349, 354, 359, 364, 369, 374, 379, 384, + 389, 395, 400, 406, 411, 417, 423, 429, + 435, 441, 447, 454, 461, 467, 475, 482, + 489, 497, 505, 513, 522, 530, 539, 549, + 559, 569, 579, 590, 602, 614, 626, 640, + 654, 668, 684, 700, 717, 736, 755, 775, + 796, 819, 843, 869, 896, 925, 955, 988, + 1022, 1058, 1098, 1139, 1184, 1232, 1282, 1336, + }, + { + 4, 9, 10, 13, 15, 17, 20, 22, + 25, 28, 31, 34, 37, 40, 43, 47, + 50, 53, 57, 60, 64, 68, 71, 75, + 78, 82, 86, 90, 93, 97, 101, 105, + 109, 113, 116, 120, 124, 128, 132, 136, + 140, 143, 147, 151, 155, 159, 163, 166, + 170, 174, 178, 182, 185, 189, 193, 197, + 200, 204, 208, 212, 215, 219, 223, 226, + 230, 233, 237, 241, 244, 248, 251, 255, + 259, 262, 266, 269, 273, 276, 280, 283, + 287, 290, 293, 297, 300, 304, 307, 310, + 314, 317, 321, 324, 327, 331, 334, 337, + 343, 350, 356, 362, 369, 375, 381, 387, + 394, 400, 406, 412, 418, 424, 430, 436, + 442, 448, 454, 460, 466, 472, 478, 484, + 490, 499, 507, 516, 525, 533, 542, 550, + 559, 567, 576, 584, 592, 601, 609, 617, + 625, 634, 644, 655, 666, 676, 687, 698, + 708, 718, 729, 739, 749, 759, 770, 782, + 795, 807, 819, 831, 844, 856, 868, 880, + 891, 906, 920, 933, 947, 961, 975, 988, + 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105, + 1120, 1137, 1153, 1170, 1186, 1202, 1218, 1236, + 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379, + 1398, 1416, 1436, 1456, 1476, 1496, 1516, 1537, + 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717, + 1741, 1766, 1791, 1817, 1844, 1871, 1900, 1929, + 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197, + 2236, 2276, 2319, 2363, 2410, 2458, 2508, 2561, + 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102, + 3188, 3280, 3375, 3478, 3586, 3702, 3823, 3953, + 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347, + }, + { + 4, 12, 18, 25, 33, 41, 50, 60, + 70, 80, 91, 103, 115, 127, 140, 153, + 166, 180, 194, 208, 222, 237, 251, 266, + 281, 296, 312, 327, 343, 358, 374, 390, + 405, 421, 437, 453, 469, 484, 500, 516, + 532, 548, 564, 580, 596, 611, 627, 643, + 659, 674, 690, 706, 721, 737, 752, 768, + 783, 798, 814, 829, 844, 859, 874, 889, + 904, 919, 934, 949, 964, 978, 993, 1008, + 1022, 1037, 1051, 1065, 1080, 1094, 1108, 1122, + 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234, + 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342, + 1368, 1393, 1419, 1444, 1469, 1494, 1519, 1544, + 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741, + 1765, 1789, 1814, 1838, 1862, 1885, 1909, 1933, + 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199, + 2233, 2267, 2300, 2334, 2367, 2400, 2434, 2467, + 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788, + 2830, 2872, 2913, 2954, 2995, 3036, 3076, 3127, + 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517, + 3565, 3621, 3677, 3733, 3788, 3843, 3897, 3951, + 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420, + 4479, 4546, 4612, 4677, 4742, 4807, 4871, 4942, + 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517, + 5591, 5665, 5745, 5825, 5905, 5984, 6063, 6149, + 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867, + 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, + 7832, 7958, 8085, 8214, 8352, 8492, 8635, 8788, + 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, + 10465, 10702, 10946, 11210, 11482, 11776, 12081, 12409, + 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, + 16356, 16943, 17575, 18237, 18949, 19718, 20521, 21387, + } +}; + +static const int16_t ac_qlookup[BIT_DEPTH_MODE_COUNT][QINDEX_RANGE] = { + { + 4, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, + 47, 48, 49, 50, 51, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, 62, + 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, + 79, 80, 81, 82, 83, 84, 85, 86, + 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, 102, + 104, 106, 108, 110, 112, 114, 116, 118, + 120, 122, 124, 126, 128, 130, 132, 134, + 136, 138, 140, 142, 144, 146, 148, 150, + 152, 155, 158, 161, 164, 167, 170, 173, + 176, 179, 182, 185, 188, 191, 194, 197, + 200, 203, 207, 211, 215, 219, 223, 227, + 231, 235, 239, 243, 247, 251, 255, 260, + 265, 270, 275, 280, 285, 290, 295, 300, + 305, 311, 317, 323, 329, 335, 341, 347, + 353, 359, 366, 373, 380, 387, 394, 401, + 408, 416, 424, 432, 440, 448, 456, 465, + 474, 483, 492, 501, 510, 520, 530, 540, + 550, 560, 571, 582, 593, 604, 615, 627, + 639, 651, 663, 676, 689, 702, 715, 729, + 743, 757, 771, 786, 801, 816, 832, 848, + 864, 881, 898, 915, 933, 951, 969, 988, + 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151, + 1173, 1196, 1219, 1243, 1267, 1292, 1317, 1343, + 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567, + 1597, 1628, 1660, 1692, 1725, 1759, 1793, 1828, + }, + { + 4, 9, 11, 13, 16, 18, 21, 24, + 27, 30, 33, 37, 40, 44, 48, 51, + 55, 59, 63, 67, 71, 75, 79, 83, + 88, 92, 96, 100, 105, 109, 114, 118, + 122, 127, 131, 136, 140, 145, 149, 154, + 158, 163, 168, 172, 177, 181, 186, 190, + 195, 199, 204, 208, 213, 217, 222, 226, + 231, 235, 240, 244, 249, 253, 258, 262, + 267, 271, 275, 280, 284, 289, 293, 297, + 302, 306, 311, 315, 319, 324, 328, 332, + 337, 341, 345, 349, 354, 358, 362, 367, + 371, 375, 379, 384, 388, 392, 396, 401, + 409, 417, 425, 433, 441, 449, 458, 466, + 474, 482, 490, 498, 506, 514, 523, 531, + 539, 547, 555, 563, 571, 579, 588, 596, + 604, 616, 628, 640, 652, 664, 676, 688, + 700, 713, 725, 737, 749, 761, 773, 785, + 797, 809, 825, 841, 857, 873, 889, 905, + 922, 938, 954, 970, 986, 1002, 1018, 1038, + 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198, + 1218, 1242, 1266, 1290, 1314, 1338, 1362, 1386, + 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603, + 1631, 1663, 1695, 1727, 1759, 1791, 1823, 1859, + 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159, + 2199, 2239, 2283, 2327, 2371, 2415, 2459, 2507, + 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915, + 2971, 3027, 3083, 3143, 3203, 3263, 3327, 3391, + 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952, + 4028, 4104, 4184, 4264, 4348, 4432, 4516, 4604, + 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372, + 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, + 6388, 6512, 6640, 6768, 6900, 7036, 7172, 7312, + }, + { + 4, 13, 19, 27, 35, 44, 54, 64, + 75, 87, 99, 112, 126, 139, 154, 168, + 183, 199, 214, 230, 247, 263, 280, 297, + 314, 331, 349, 366, 384, 402, 420, 438, + 456, 475, 493, 511, 530, 548, 567, 586, + 604, 623, 642, 660, 679, 698, 716, 735, + 753, 772, 791, 809, 828, 846, 865, 884, + 902, 920, 939, 957, 976, 994, 1012, 1030, + 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175, + 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317, + 1335, 1352, 1370, 1387, 1405, 1422, 1440, 1457, + 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595, + 1627, 1660, 1693, 1725, 1758, 1791, 1824, 1856, + 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118, + 2150, 2183, 2216, 2248, 2281, 2313, 2346, 2378, + 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750, + 2798, 2847, 2895, 2943, 2992, 3040, 3088, 3137, + 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619, + 3684, 3748, 3812, 3876, 3941, 4005, 4069, 4149, + 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791, + 4871, 4967, 5064, 5160, 5256, 5352, 5448, 5544, + 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410, + 6522, 6650, 6778, 6906, 7034, 7162, 7290, 7435, + 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635, + 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, + 10220, 10412, 10604, 10812, 11020, 11228, 11437, 11661, + 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565, + 13821, 14093, 14365, 14637, 14925, 15213, 15502, 15806, + 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414, + 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, + 21902, 22334, 22766, 23214, 23662, 24126, 24590, 25070, + 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247, + } +}; + +int clamp(int value, int low, int high) +{ + return value < low ? low : (value > high ? high : value); +} + +int16_t vp9_dc_quant(int bit_depth, int qindex, int delta) +{ + if (bit_depth > MODE_12BITS_DEPTH || bit_depth < MODE_8BITS_DEPTH) { + bit_depth = MODE_8BITS_DEPTH; + printf("WARNING: bit depth of vp9 should be in the range 8bitS(0),10bits(1) and 12bits(2).\n"); + } + const uint8_t q = clamp(qindex + delta, 0, MAXQ); + return dc_qlookup[bit_depth][q]; +} + +int16_t vp9_ac_quant(int bit_depth, int qindex, int delta) +{ + if (bit_depth > MODE_12BITS_DEPTH || bit_depth < MODE_8BITS_DEPTH) { + bit_depth = MODE_8BITS_DEPTH; + printf("WARNING: bit depth of vp9 should be in the range 8bitS(0),10bits(1) and 12bits(2).\n"); + } + const uint8_t q = clamp(qindex + delta, 0, MAXQ); + return ac_qlookup[bit_depth][q]; +} diff --git a/codecparsers/vp9quant.h b/codecparsers/vp9quant.h new file mode 100644 index 0000000..5900616 --- /dev/null +++ b/codecparsers/vp9quant.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2010 The WebM project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ +#ifndef __VP9_QUANT_H__ +#define __VP9_QUANT_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MAXQ 255 +#define QINDEX_RANGE 256 +#define QINDEX_BITS 8 + +int clamp(int value, int low, int high); + +int16_t vp9_dc_quant(int bit_depth, int qindex, int delta); + +int16_t vp9_ac_quant(int bit_depth, int qindex, int delta); + +#ifdef __cplusplus +}; +#endif + +#endif //__VP9_QUANT_H__ diff --git a/common.mk b/common.mk new file mode 100644 index 0000000..c6f8697 --- /dev/null +++ b/common.mk @@ -0,0 +1,4 @@ +LOCAL_CFLAGS := -D__ENABLE_DEBUG__ -Wno-sign-compare -Wno-unused-parameter -O2 +LOCAL_CPPFLAGS := -D__ENABLE_DEBUG__ -Wno-sign-compare -Wno-unused-parameter -O2 -std=c++11 + +ENABLE-V4L2-OPS=true diff --git a/common/Android.mk b/common/Android.mk new file mode 100644 index 0000000..f5ada52 --- /dev/null +++ b/common/Android.mk @@ -0,0 +1,32 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +ROOT := $(LOCAL_PATH)/../ +GEN := $(ROOT)/interface/YamiVersion.h +$(GEN) : $(ROOT)/interface/YamiVersion.h.in $(ROOT)/configure.ac + @python3 $(ROOT)/build/GenVer.py + +LOCAL_GENERATED_SOURCES += $(GEN) + +LOCAL_SRC_FILES := \ + log.cpp \ + utils.cpp \ + nalreader.cpp \ + surfacepool.cpp \ + PooledFrameAllocator.cpp \ + YamiVersion.cpp \ + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva \ + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libva + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_common +include $(BUILD_STATIC_LIBRARY) diff --git a/common/Array.h b/common/Array.h new file mode 100644 index 0000000..ee00e95 --- /dev/null +++ b/common/Array.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Array_h +#define Array_h + +#if __cplusplus > 199711L + #include +#else + #include + namespace std { + using std::tr1::array; + } +#endif // __cplusplus > 199711L + +#endif // Array_h diff --git a/common/Functional.h b/common/Functional.h new file mode 100644 index 0000000..8f860f4 --- /dev/null +++ b/common/Functional.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* orignal version of this file have been defined in VideoCommonDefs.h, + but it will introduce compile error in gtest, so we define it here. + it's reasonable since not all files need bind + */ + +#ifndef Functional_h +#define Functional_h + +#if __cplusplus > 199711L + #include +#else + #include + namespace std { + using std::tr1::bind; + using std::tr1::function; + using std::tr1::ref; + namespace placeholders { + using std::tr1::placeholders::_1; + using std::tr1::placeholders::_2; + } + } +#endif // __cplusplus > 199711L + +#endif // Functional_h diff --git a/common/Makefile.am b/common/Makefile.am new file mode 100644 index 0000000..1a788e5 --- /dev/null +++ b/common/Makefile.am @@ -0,0 +1,63 @@ +libyami_common_source_c = \ + log.cpp \ + utils.cpp \ + nalreader.cpp \ + surfacepool.cpp \ + PooledFrameAllocator.cpp \ + YamiVersion.cpp \ + Thread.cpp \ + $(NULL) + +libyami_common_source_h = \ + ../interface/YamiVersion.h \ + $(NULL) + +libyami_common_source_h_priv = \ + Array.h \ + NonCopyable.h \ + Functional.h \ + log.h \ + utils.h \ + common_def.h \ + nalreader.h \ + videopool.h \ + surfacepool.h \ + Thread.h \ + $(NULL) + +libyami_common_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + -lpthread \ + $(NULL) + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_common_cppflags = \ + $(LIBVA_CFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_builddir)/interface \ + $(extra_includes) \ + $(NULL) + +noinst_LTLIBRARIES = libyami_common.la +libyami_commonincludedir = ${includedir}/libyami +libyami_commoninclude_HEADERS = $(libyami_common_source_h) +libyami_common_la_SOURCES = $(libyami_common_source_c) +libyami_common_la_LDFLAGS = $(libyami_common_ldflags) $(AM_LDFLAGS) +libyami_common_la_CPPFLAGS = $(libyami_common_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in\ + YamiVersion.h \ + $(NULL) + + diff --git a/common/Makefile.unittest b/common/Makefile.unittest new file mode 100644 index 0000000..caeb3a6 --- /dev/null +++ b/common/Makefile.unittest @@ -0,0 +1,36 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + factory_unittest.cpp \ + nalreader_unittest.cpp \ + utils_unittest.cpp \ + Thread_unittest.cpp \ + $(NULL) + + + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest + $(builddir)/unittest + diff --git a/common/NonCopyable.h b/common/NonCopyable.h new file mode 100644 index 0000000..63b8751 --- /dev/null +++ b/common/NonCopyable.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NoCopyable_h +#define NoCopyable_h + +#ifndef DISALLOW_COPY_AND_ASSIGN +#define DISALLOW_COPY_AND_ASSIGN(className) \ + className(const className&); \ + className& operator=(const className&); +#endif + +#endif //NoCopyable_h diff --git a/common/PooledFrameAllocator.cpp b/common/PooledFrameAllocator.cpp new file mode 100644 index 0000000..1e87e5f --- /dev/null +++ b/common/PooledFrameAllocator.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "PooledFrameAllocator.h" +#include +#include + +namespace YamiMediaCodec { + +struct SurfaceDestoryer +{ +private: + SharedPtr m_display; + std::vector m_surfaces; +public: + SurfaceDestoryer(const SharedPtr& display, std::vector& surfaces) + :m_display(display) + { + m_surfaces.swap(surfaces); + } + void operator()(VideoPool* pool) + { + if (m_surfaces.size()) + vaDestroySurfaces(*m_display, &m_surfaces[0], m_surfaces.size()); + delete pool; + } + +}; + + +PooledFrameAllocator::PooledFrameAllocator(const SharedPtr& display, int poolsize) + :m_display(display) + , m_poolsize(poolsize) +{ +} +bool PooledFrameAllocator::setFormat(uint32_t fourcc, int width, int height) +{ + std::vector surfaces; + surfaces.resize(m_poolsize); + + uint32_t rtFormat = getRtFormat(fourcc); + if (!rtFormat) { + return false; + } + + uint32_t vaFourcc = fourcc; + if (fourcc == YAMI_FOURCC_R210) { + //workaround for libva, currently libva will use ARGB as fourcc for 10 bits RGB + //it's not good, we need change this. add dedicate fourcc for 10 bits + vaFourcc = YAMI_FOURCC_ARGB; + } + + VASurfaceAttrib attrib; + attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; + attrib.type = VASurfaceAttribPixelFormat; + attrib.value.type = VAGenericValueTypeInteger; + attrib.value.value.i = vaFourcc; + + VAStatus status = vaCreateSurfaces(*m_display, rtFormat, width, height, + &surfaces[0], surfaces.size(), + &attrib, 1); + + if (status != VA_STATUS_SUCCESS) { + ERROR("create surface failed, %s", vaErrorStr(status)); + return false; + } + std::deque > buffers; + for (size_t i = 0; i < surfaces.size(); i++) { + SharedPtr f(new VideoFrame); + memset(f.get(), 0, sizeof(VideoFrame)); + f->crop.width = width; + f->crop.height = height; + f->surface = (intptr_t)surfaces[i]; + f->fourcc = fourcc; + buffers.push_back(f); + } + m_pool.reset(new VideoPool(buffers), SurfaceDestoryer(m_display, surfaces)); + return true; +} + +SharedPtr PooledFrameAllocator::alloc() +{ + return m_pool->alloc(); +} + +} //namespace diff --git a/common/PooledFrameAllocator.h b/common/PooledFrameAllocator.h new file mode 100644 index 0000000..6a5338c --- /dev/null +++ b/common/PooledFrameAllocator.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PooledFrameAllocator_h +#define PooledFrameAllocator_h + +#include +#include +#include +#include "common/videopool.h" + + +namespace YamiMediaCodec { + +class FrameAllocator +{ +public: + virtual bool setFormat(uint32_t fourcc, int width, int height) = 0; + virtual SharedPtr alloc() = 0; + virtual ~FrameAllocator() {} +}; + +class PooledFrameAllocator : public FrameAllocator +{ +public: + PooledFrameAllocator(const SharedPtr& display, int poolsize); + bool setFormat(uint32_t fourcc, int width, int height); + SharedPtr alloc(); + +private: + SharedPtr m_display; + SharedPtr > m_pool; + int m_poolsize; +}; +}; + +#endif diff --git a/common/Thread.cpp b/common/Thread.cpp new file mode 100644 index 0000000..f24e94b --- /dev/null +++ b/common/Thread.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "Thread.h" +#include "Functional.h" +#include "log.h" + +#include + +namespace YamiMediaCodec { + +Thread::Thread(const char* name) + : m_name(name) + , m_started(false) + , m_thread(INVALID_ID) + , m_cond(m_lock) + , m_sent(m_lock) +{ +} + +bool Thread::start() +{ + AutoLock lock(m_lock); + if (m_started) + return false; + if (pthread_create(&m_thread, NULL, init, this)) { + ERROR("create thread %s failed", m_name.c_str()); + m_thread = INVALID_ID; + return false; + } + m_started = true; + return true; +} + +void* Thread::init(void* thread) +{ + Thread* t = (Thread*)thread; + t->loop(); + return NULL; +} + +void Thread::loop() +{ + while (1) { + AutoLock lock(m_lock); + if (m_queue.empty()) { + if (!m_started) + return; + m_cond.wait(); + } + else { + Job& r = m_queue.front(); + m_lock.release(); + r(); + m_lock.acquire(); + m_queue.pop_front(); + } + } +} + +void Thread::enqueue(const Job& r) +{ + m_queue.push_back(r); + m_cond.signal(); +} + +void Thread::post(const Job& r) +{ + AutoLock lock(m_lock); + if (!m_started) { + ERROR("%s: post job after stop()", m_name.c_str()); + return; + } + enqueue(r); +} + +void Thread::sendJob(const Job& r, bool& flag) +{ + r(); + + //flag need protect here since we check it in other thread + AutoLock lock(m_lock); + flag = true; + m_sent.broadcast(); +} + +bool Thread::send(const Job& c) +{ + bool flag = false; + + AutoLock lock(m_lock); + if (!m_started) { + ERROR("%s: sent job after stop()", m_name.c_str()); + return false; + } + enqueue(std::bind(&Thread::sendJob, this, std::ref(c), std::ref(flag))); + //wait for result; + while (!flag) { + m_sent.wait(); + } + return true; +} + +void Thread::stop() +{ + { + AutoLock lock(m_lock); + if (!m_started) + return; + m_started = false; + m_cond.signal(); + } + pthread_join(m_thread, NULL); + m_thread = INVALID_ID; + assert(m_queue.empty()); +} + +bool Thread::isCurrent() +{ + return pthread_self() == m_thread; +} + +Thread::~Thread() +{ + stop(); +} +} diff --git a/common/Thread.h b/common/Thread.h new file mode 100644 index 0000000..526ac79 --- /dev/null +++ b/common/Thread.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef Thread_h +#define Thread_h + +#include "condition.h" +#include "lock.h" +#include "Functional.h" + +#include +#include +#include + +namespace YamiMediaCodec { + +typedef std::function Job; + +class Thread { +public: + explicit Thread(const char* name = ""); + ~Thread(); + bool start(); + //stop thread, this will waiting all post/sent job done + void stop(); + //post job to this thread + void post(const Job&); + //send job and wait it done + bool send(const Job&); + bool isCurrent(); + +private: + //thread loop + static void* init(void*); + void loop(); + void enqueue(const Job& r); + void sendJob(const Job& r, bool& flag); + + std::string m_name; + bool m_started; + pthread_t m_thread; + + Lock m_lock; + Condition m_cond; + Condition m_sent; + std::deque m_queue; + + static const pthread_t INVALID_ID = (pthread_t)-1; + + DISALLOW_COPY_AND_ASSIGN(Thread); +}; +}; + +#endif diff --git a/common/Thread_unittest.cpp b/common/Thread_unittest.cpp new file mode 100644 index 0000000..17253e1 --- /dev/null +++ b/common/Thread_unittest.cpp @@ -0,0 +1,102 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "Thread.h" + +#include "common/unittest.h" +#include "common/log.h" + +namespace YamiMediaCodec { + +using namespace std; + +#define THREAD_TEST(name) \ + TEST(ThreadTest, name) + +void add(int& v) +{ + v++; +} + +void sleepAndAdd(Thread& t, int seconds, int& v) +{ + sleep(seconds); + EXPECT_FALSE(t.isCurrent()); + t.post(bind(add, ref(v))); +} + +void checkSum(int& v, int expected) +{ + EXPECT_EQ(expected, v); +} + +void isCurrent(Thread& t) +{ + EXPECT_TRUE(t.isCurrent()); +} + +void emptyJob() +{ + /* nothing */ +} + +void sendJob(Thread& t, Job job) +{ + t.send(job); +} + +THREAD_TEST(FullTest) +{ + std::cout << "this may take some time" << std::endl; + + Thread t[3]; + + //check start + for (int i = 0; i < 3; i++) { + EXPECT_TRUE(t[i].start()); + } + + //post + int v = 0; + for (int i = 0; i < 5; i++) { + t[0].post(bind(sleepAndAdd, ref(t[2]), 1, ref(v))); + } + for (int i = 0; i < 5; i++) { + t[1].post(bind(sleepAndAdd, ref(t[2]), 2, ref(v))); + } + + //make sure we can send message from diffrent thread + t[0].send(bind(sendJob, ref(t[2]), emptyJob)); + t[1].send(bind(sendJob, ref(t[2]), emptyJob)); + + //is current + t[2].send(bind(isCurrent, ref(t[2]))); + + for (int i = 0; i < 3; i++) { + EXPECT_TRUE(t[i].send(bind(isCurrent, ref(t[i])))); + t[i].stop(); + } + EXPECT_EQ(10, v); + + //send after stop + EXPECT_FALSE(t[2].send(bind(checkSum, ref(v), 11))); +} +} diff --git a/common/YamiVersion.cpp b/common/YamiVersion.cpp new file mode 100644 index 0000000..2a51c87 --- /dev/null +++ b/common/YamiVersion.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "YamiVersion.h" + +void yamiGetApiVersion(uint32_t *apiVersion) +{ + *apiVersion = YAMI_API_VERSION; +} diff --git a/common/basesurfaceallocator.h b/common/basesurfaceallocator.h new file mode 100644 index 0000000..482e38a --- /dev/null +++ b/common/basesurfaceallocator.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef basesurfaceallocator_h +#define basesurfaceallocator_h +#include "VideoCommonDefs.h" + +namespace YamiMediaCodec{ + +namespace details { + +YamiStatus allocatSurfaces(SurfaceAllocator* thiz, SurfaceAllocParams* params); +YamiStatus freeSurfaces (SurfaceAllocator* thiz, SurfaceAllocParams* params); +void unrefAllocator (SurfaceAllocator* thiz); + +}; +/// base class for surface allocator. +/// hide details on function hooks +class BaseSurfaceAllocator : public SurfaceAllocator +{ +friend YamiStatus details::allocatSurfaces(SurfaceAllocator* thiz, SurfaceAllocParams* params); +friend YamiStatus details::freeSurfaces (SurfaceAllocator* thiz, SurfaceAllocParams* params); +friend void details::unrefAllocator (SurfaceAllocator* thiz); + +public: + BaseSurfaceAllocator() + { + //hook function and data + alloc = details::allocatSurfaces; + free = details::freeSurfaces; + unref = details::unrefAllocator; + } + virtual ~BaseSurfaceAllocator() {} +protected: + virtual YamiStatus doAlloc(SurfaceAllocParams* params) = 0; + virtual YamiStatus doFree(SurfaceAllocParams* params) = 0; + virtual void doUnref() = 0; +}; + +namespace details { + +inline YamiStatus allocatSurfaces(SurfaceAllocator* thiz, SurfaceAllocParams* params) +{ + if (!thiz || !params) + return YAMI_INVALID_PARAM; + BaseSurfaceAllocator* p = (BaseSurfaceAllocator*)thiz; + return p->doAlloc(params); +} + + +inline YamiStatus freeSurfaces(SurfaceAllocator* thiz, SurfaceAllocParams* params) +{ + if (!thiz || !params) + return YAMI_INVALID_PARAM; + BaseSurfaceAllocator* p = (BaseSurfaceAllocator*)thiz; + return p->doFree(params); +} + +inline void unrefAllocator (SurfaceAllocator* thiz) +{ + if (!thiz) + return; + BaseSurfaceAllocator* p = (BaseSurfaceAllocator*)thiz; + p->doUnref(); +} + +} //details + +} //YamiMediaCodec + +#endif //basesurfaceallocator_h diff --git a/common/common_def.h b/common/common_def.h new file mode 100644 index 0000000..c72f5f7 --- /dev/null +++ b/common/common_def.h @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __COMMON_DEF_H__ +#define __COMMON_DEF_H__ + +#ifndef BOOL +#define BOOL int +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef CHAR_BIT +#define CHAR_BIT 8 +#endif + + +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#ifndef MAX +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif + +#define CLIP(a, min, max) do { \ + a = (MIN(max, MAX(a, min))); \ +} while (0) + +#ifndef N_ELEMENTS +#define N_ELEMENTS(array) (sizeof(array)/sizeof(array[0])) +#endif + +#ifndef ALIGN_POW2 +#define ALIGN_POW2(a, b) ((a + (b - 1)) & ~(b - 1)) +#endif + +#ifndef ALIGN2 +#define ALIGN2(a) ALIGN_POW2(a, 2) +#endif + +#ifndef ALIGN8 +#define ALIGN8(a) ALIGN_POW2(a, 8) +#endif + +#ifndef ALIGN16 +#define ALIGN16(a) ALIGN_POW2(a, 16) +#endif + +#ifndef ALIGN32 +#define ALIGN32(a) ALIGN_POW2(a, 32) +#endif + +#ifndef RETURN_IF_FAIL +#define RETURN_IF_FAIL(condition) \ +do{ \ + if (!(condition)) \ + return; \ +}while(0) +#endif + +#ifndef RETURN_VAL_IF_FAIL +#define RETURN_VAL_IF_FAIL(condition, value) \ +do{ \ + if (!(condition)) \ + return (value); \ +}while(0) +#endif + +#define PARAMETER_ASSIGN(a, b) memcpy(&(a), &(b), sizeof(b)) +#endif //__COMMON_DEF_H__ diff --git a/common/condition.h b/common/condition.h new file mode 100644 index 0000000..61a7432 --- /dev/null +++ b/common/condition.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef condition_h +#define condition_h + +#include "NonCopyable.h" +#include "VideoCommonDefs.h" + +#include "lock.h" + +namespace YamiMediaCodec{ + +class Condition +{ +public: + explicit Condition(Lock& lock):m_lock(lock) + { + pthread_cond_init(&m_cond, NULL); + } + + ~Condition() + { + pthread_cond_destroy(&m_cond); + } + + void wait() + { + pthread_cond_wait(&m_cond, &m_lock.m_lock); + } + + void signal() + { + pthread_cond_signal(&m_cond); + } + + void broadcast() + { + pthread_cond_broadcast(&m_cond); + } + +private: + Lock& m_lock; + pthread_cond_t m_cond; + DISALLOW_COPY_AND_ASSIGN(Condition); + +}; + +}; + +#endif diff --git a/common/factory.h b/common/factory.h new file mode 100644 index 0000000..2a64f7b --- /dev/null +++ b/common/factory.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __COMMON_FACTORY_H__ +#define __COMMON_FACTORY_H__ + +#include +#include +#include + +template < class T > +class Factory { +public: + typedef T* Type; + typedef Type (*Creator) (void); + typedef std::string KeyType; + typedef std::vector Keys; + typedef std::map Creators; + typedef typename Creators::iterator iterator; + typedef typename Creators::const_iterator const_iterator; + + /** + * Register class C with @param key. Returns true if class C is + * successfully registered using @param key. If @param key is already + * registered, returns false and does not register class C with + * @param key. + */ + template < class C > + static bool register_(const KeyType& key) + { + std::pair result = + getCreators().insert(std::make_pair(key, create)); + return result.second; + } + + /** + * Create and return a new object that is registered with @param key. + * If @param key does not exist, then returns NULL. The caller is + * responsible for managing the lifetime of the returned object. + */ + static Type create(const KeyType& key) + { + Creators& creators = getCreators(); + const const_iterator creator(creators.find(key)); + if (creator != creators.end()) + return creator->second(); + return NULL; + } + + static Keys keys() + { + Keys result; + const Creators& creators = getCreators(); + const const_iterator endIt(creators.end()); + for (const_iterator it(creators.begin()); it != endIt; ++it) + result.push_back(it->first); + return result; + } + +private: + template < class C > + static Type create() + { + return new C; + } + static Creators& getCreators() + { + static Creators creators; + return creators; + } +}; + +#endif // __COMMON_FACTORY_H__ diff --git a/common/factory_unittest.cpp b/common/factory_unittest.cpp new file mode 100644 index 0000000..11210e8 --- /dev/null +++ b/common/factory_unittest.cpp @@ -0,0 +1,67 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "factory.h" + +// library headers +#include "common/unittest.h" + +#define FACTORY_TEST(name) \ + TEST(FactoryTest, name) + +class Base { +public: + virtual ~Base() { } +}; + +class A : public Base { }; +class B : public Base { }; +class C : public Base { }; + +// Attempt to expose what is commonly referred to as the +// "static initialization order fiasco". +// If the unittest program segfaults during pre-main static +// initialization, then we've likely introduced an initialization +// order bug. +const bool rA = Factory::register_("A"); + +FACTORY_TEST(Register) { + EXPECT_TRUE(rA); + EXPECT_TRUE(Factory::register_("B")); + EXPECT_TRUE(Factory::register_("B2")); + EXPECT_TRUE(Factory::register_("C")); + EXPECT_FALSE(Factory::register_("A")); + EXPECT_FALSE(Factory::register_("B")); + EXPECT_FALSE(Factory::register_("C")); +} + +FACTORY_TEST(Create) { + Base* a = Factory::create("A"); + Base* z = Factory::create("Z"); + + EXPECT_TRUE(a != NULL); + EXPECT_TRUE(z == NULL); + EXPECT_TRUE(dynamic_cast(a) != NULL); + EXPECT_TRUE(dynamic_cast(a) == NULL); + + delete a; + delete z; +} diff --git a/common/factory_unittest.h b/common/factory_unittest.h new file mode 100644 index 0000000..3032202 --- /dev/null +++ b/common/factory_unittest.h @@ -0,0 +1,57 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// primary header +#include "common/factory.h" + +// library headers +#include "common/unittest.h" + +// system headers +#include + +template +class FactoryTest + : public ::testing::Test { +protected: + typedef std::vector::KeyType> FactoryKeys; + + void doFactoryTest(const FactoryKeys& keys) { + ::testing::StaticAssertTypeEq::Type>(); + + EXPECT_TRUE(Derived::s_registered); + + const typename FactoryKeys::const_iterator end(keys.end()); + for ( typename FactoryKeys::const_iterator key(keys.begin()); + key != end; ++key) { + SCOPED_TRACE("key: " + *key); + + ASSERT_FALSE(Factory::template register_(*key)); + + Base* object(NULL); + + ASSERT_TRUE(object == NULL); + + object = Factory::create(*key); + + EXPECT_TRUE(object != NULL); + + EXPECT_TRUE(dynamic_cast(object)); + + delete object; + } + } +}; diff --git a/common/lock.h b/common/lock.h new file mode 100644 index 0000000..8869775 --- /dev/null +++ b/common/lock.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef lock_h +#define lock_h + +#include "NonCopyable.h" +#include + +namespace YamiMediaCodec{ + +class Lock +{ +public: + Lock() + { + pthread_mutex_init(&m_lock, NULL); + } + + ~Lock() + { + pthread_mutex_destroy(&m_lock); + } + + void acquire() + { + pthread_mutex_lock(&m_lock); + } + + void release() + { + pthread_mutex_unlock(&m_lock); + } + + void tryLock() + { + pthread_mutex_trylock(&m_lock); + } + + friend class Condition; + +private: + pthread_mutex_t m_lock; + DISALLOW_COPY_AND_ASSIGN(Lock); +}; + +class AutoLock +{ +public: + explicit AutoLock(Lock& lock) : m_lock(lock) + { + m_lock.acquire(); + } + ~AutoLock() + { + m_lock.release(); + } + Lock& m_lock; +private: + DISALLOW_COPY_AND_ASSIGN(AutoLock); +}; + +}; + +#endif diff --git a/common/log.cpp b/common/log.cpp new file mode 100644 index 0000000..e8eb8dc --- /dev/null +++ b/common/log.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2011-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* log.cpp is to enable debug log with LIBYAMI_LOG_LEVEL and LIBYAMI_TRACE: + * LIBYAMI_LOG_LEVEL=log_level: the record will be printed if the log_level larger than (Error, 0), (Warning, 1), (Info, 2)(Debug & Debug_, 3). + * LIBYAMI_LOG=log_file: the libyami log saved into log_file; + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "log.h" +#include +#include +#include +#include +#include "common/lock.h" + +int yamiLogFlag; +FILE* yamiLogFn; +int isInit = 0; +static YamiMediaCodec::Lock g_traceLock; + +void yamiTraceInit(); + +class TraceInitor { + public: + TraceInitor() { yamiTraceInit(); } + ~TraceInitor() {} +}; +static class TraceInitor g_initor; + +void yamiTraceInit() +{ + YamiMediaCodec::AutoLock locker(g_traceLock); + if(!isInit){ + char* libyamiLogLevel = getenv("LIBYAMI_LOG_LEVEL"); + char* libyamLog = getenv("LIBYAMI_LOG"); + FILE* tmp; + + yamiLogFn = stderr; + if (libyamiLogLevel){ + yamiLogFlag = atoi(libyamiLogLevel); + if (libyamLog){ + time_t now; + struct tm* curtime; + char filename[80]; + + time(&now); + + if ((curtime = localtime(&now))) { + snprintf(filename, sizeof(filename), "%s_%2d_%02d_%02d_%02d_%02d", libyamLog, + curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday, + curtime->tm_hour, curtime->tm_sec); + } else { + snprintf(filename, sizeof(filename), "%s", libyamLog); + } + + if ((tmp = fopen(filename, "w"))){ + yamiLogFn = tmp; + ERROR("Libyami_Trace is on, save log into %s.\n", filename); + } else { + ERROR("Open file %s failed.\n", filename); + } + } + } + else { + yamiLogFlag = YAMI_LOG_ERROR; + } + isInit = 1; + } +#ifndef __ENABLE_DEBUG__ + if (yamiLogFlag > YAMI_LOG_ERROR) + fprintf(stderr, "yami log isn't enabled (--enable-debug)\n"); + #endif +} diff --git a/common/log.h b/common/log.h new file mode 100644 index 0000000..96330e5 --- /dev/null +++ b/common/log.h @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2013 Intel Coperation.. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __LOG_H__ +#define __LOG_H__ + +#if (defined(ANDROID) && defined(__USE_LOGCAT__)) +#include +#define ERROR(...) +#define INFO(...) +#define WARNING(...) +#define DEBUG(...) + +#ifndef PRINT_FOURCC +#define DEBUG_FOURCC(promptStr, fourcc) +#endif + +#else + +#include +#include +#include +#include +#include +#include +#define GETTID() syscall(__NR_gettid) + +extern int yamiLogFlag; +extern FILE* yamiLogFn; +extern int isInit; + +#ifndef YAMIMESSAGE +#define yamiMessage(stream, format, ...) do {\ + fprintf(stream, format, ##__VA_ARGS__); \ +}while (0) +#endif + +#define YAMI_DEBUG_MESSAGE(LEVEL, prefix, format, ...) \ + do {\ + if (yamiLogFlag >= YAMI_LOG_##LEVEL) { \ + const char* name = strrchr(__FILE__, '/'); \ + name = (name ? (name + 1) : __FILE__); \ + yamiMessage(yamiLogFn, "libyami %s %ld (%s, %d): " format "\n", #prefix, (long int)GETTID(), name, __LINE__, ##__VA_ARGS__); \ + } \ + } while (0) + +#ifndef ERROR +#define ERROR(format, ...) YAMI_DEBUG_MESSAGE(ERROR, error, format, ##__VA_ARGS__) +#endif + +#ifdef __ENABLE_DEBUG__ + +#ifndef WARNING +#define WARNING(format, ...) YAMI_DEBUG_MESSAGE(WARNING, warning, format, ##__VA_ARGS__) +#endif + +#ifndef INFO +#define INFO(format, ...) YAMI_DEBUG_MESSAGE(INFO, info, format, ##__VA_ARGS__) +#endif + +#ifndef DEBUG +#define DEBUG(format, ...) YAMI_DEBUG_MESSAGE(DEBUG, debug, format, ##__VA_ARGS__) +#endif + +#ifndef DEBUG_ +#define DEBUG_(format, ...) DEBUG(format, ##__VA_ARGS__) +#endif + +#ifndef DEBUG_FOURCC +#define DEBUG_FOURCC(promptStr, fourcc) do { \ + if (yamiLogFlag >= YAMI_LOG_DEBUG) { \ + uint32_t i_fourcc = fourcc; \ + char *ptr = (char*)(&(i_fourcc)); \ + DEBUG("%s, fourcc: 0x%x, %c%c%c%c\n", promptStr, i_fourcc, *(ptr), *(ptr+1), *(ptr+2), *(ptr+3)); \ + } \ +} while(0) +#endif + +#else //__ENABLE_DEBUG__ +#ifndef INFO +#define INFO(format, ...) +#endif + +#ifndef WARNING +#define WARNING(format, ...) +#endif + +#ifndef DEBUG +#define DEBUG(format, ...) +#endif + +#ifndef PRINT_FOURCC +#define DEBUG_FOURCC(promptStr, fourcc) +#endif + +#endif //__ENABLE_DEBUG__ +#endif //__ANDROID + +#ifndef ASSERT +#define ASSERT(expr) \ + do { \ + if (!(expr)) { \ + ERROR("assert fails"); \ + assert(0 && (expr)); \ + } \ + } while (0) +#endif + +#define YAMI_LOG_ERROR 0x1 +#define YAMI_LOG_WARNING 0x2 +#define YAMI_LOG_INFO 0x3 +#define YAMI_LOG_DEBUG 0x4 + +#endif //__LOG_H__ diff --git a/common/nalreader.cpp b/common/nalreader.cpp new file mode 100755 index 0000000..8a7cecb --- /dev/null +++ b/common/nalreader.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "nalreader.h" + +namespace YamiMediaCodec{ + +NalReader::NalReader(const uint8_t* buf, int32_t size, uint32_t nalLengthSize, bool asWhole) +{ + m_begin = buf; + m_next = buf; + m_end = buf + size; + m_asWhole = asWhole; + + m_nalLengthSize = nalLengthSize; + m_size = 0; + + searchNalStart(); +} + +bool NalReader::read(const uint8_t*& nal, int32_t& nalSize) +{ + if (m_next == m_end) + return false; + + nal = m_next; + const uint8_t* nalEnd; + if (m_asWhole) { + nalEnd = m_end; + m_next = m_end; + } else { + nalEnd = searchNalStart(); + } + nalSize = nalEnd - nal; + return true; +} + +static const uint8_t START_CODE[] = { 0, 0, 1 }; +static const int START_CODE_SIZE = 3; +static const uint8_t* START_CODE_END = START_CODE + START_CODE_SIZE; + +const uint8_t* NalReader::searchStartCode() +{ + m_begin = std::search(m_next, m_end, START_CODE, START_CODE_END); + + if (m_begin != m_end) { + m_next = m_begin + START_CODE_SIZE; + } else { + m_next = m_end; + } + return m_begin; +} + +const uint8_t* NalReader::searchNalStart() +{ + if (!m_nalLengthSize) + return searchStartCode(); + + if (m_end > m_begin + m_size + m_nalLengthSize) { + m_begin += m_size; + } else { + m_begin = m_next = m_end; + return m_begin; + } + + uint32_t i, size; + m_next = m_begin + m_nalLengthSize; + + for (i = 0, size = 0; i < m_nalLengthSize; i++) + size = (size << 8) | m_begin[i]; + + m_size = m_nalLengthSize + size; + + return m_begin; +} +} //namespace YamiMediaCodec diff --git a/common/nalreader.h b/common/nalreader.h new file mode 100755 index 0000000..1779db9 --- /dev/null +++ b/common/nalreader.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +namespace YamiMediaCodec{ + +class NalReader +{ +public: + NalReader(const uint8_t* buf, int32_t size, uint32_t nalLengthSize = 0, bool asWhole = false); + + /*nal point to the nal unit without start code or length bytes*/ + bool read(const uint8_t*& nal, int32_t& nalSize); + +private: + const uint8_t* searchNalStart(); + const uint8_t* searchStartCode(); + const uint8_t* m_begin; + const uint8_t* m_next; + const uint8_t* m_end; + bool m_asWhole; + uint32_t m_nalLengthSize; + uint32_t m_size; +}; + +} //namespace YamiMediaCodec diff --git a/common/nalreader_unittest.cpp b/common/nalreader_unittest.cpp new file mode 100644 index 0000000..95da493 --- /dev/null +++ b/common/nalreader_unittest.cpp @@ -0,0 +1,124 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "nalreader.h" + +// library headers +#include "common/Array.h" +#include "common/unittest.h" + +namespace YamiMediaCodec { + +#define NALREADER_TEST(name) \ + TEST(NalReaderTest, name) + +const std::array g_data = { + 0x02, // junk + + 0x00, 0x00, 0x01, // start code prefix + 0xff, 0xfe, 0xfd, + 0xfc, 0xfb, 0xfa, + + 0x00, 0x00, 0x01, // start code prefix + 0xaa, + + 0x00, 0x00, 0x01, // start code prefix + 0xfd, 0xaf, 0x24, + + 0x00, 0x00, 0x01, // start code prefix + 0x01, 0x00, 0x00, + 0x1a, 0x01, 0x01, + 0x00, 0x01, 0xbd, + + 0x00, 0x00, 0x01, // start code prefix + 0x56, 0x01, 0x84, + 0x12 +}; + +const std::array g_nsizes = { 6, 1, 3, 9, 4 }; + +NALREADER_TEST(ReadAsUnits) { + const uint8_t* nal; + const uint32_t start(3); //start code size + int32_t size; //NAL unit size + int32_t offset(1); //to skip 1 junk byte in g_data + + NalReader reader(&g_data[0], g_data.size(), 0, false); + + for (unsigned n(0); n < g_nsizes.size(); ++n) { + //For unit reads, the NalReader returns buffer contents between each + //start code prefix, start code prefix is not included in read result; + //"nal": buffer contents; + //"size": buffer length; + EXPECT_TRUE(reader.read(nal, size)); + EXPECT_EQ(size, g_nsizes[n]); + for (int32_t i(0); i < size; ++i) + EXPECT_EQ(nal[i], g_data[i + offset + start]); + offset += (size + start); + } + + EXPECT_FALSE(reader.read(nal, size)); +} + +NALREADER_TEST(ReadAsWhole) { + const uint8_t* nal; + int32_t size; + const int32_t offset = 4; // 1 initial junk byte + first start code + + NalReader reader(&g_data[0], g_data.size(), 0, true); + //For whole read, the NalReader returns entire buffer contents after + //first start code. That is, the first start code prefix is not included + //in the result. + EXPECT_TRUE(reader.read(nal, size)); + EXPECT_EQ((size_t)(size + offset), g_data.size()); + + for (int32_t i(0); i < size; ++i) + EXPECT_EQ(nal[i], g_data[i + offset]); + + EXPECT_FALSE(reader.read(nal, size)); +} + +NALREADER_TEST(ReadEmptyBuf) { + const uint8_t data[] = {}; + const uint8_t* nal; + int32_t size; + + NalReader reader(data, 0, false); + EXPECT_FALSE(reader.read(nal, size)); + + reader = NalReader(data, 0, true); + EXPECT_FALSE(reader.read(nal, size)); +} + +NALREADER_TEST(ReadNoPrefix) { + const std::array data = { + 0x00, 0x01, 0x00, + 0x10, 0x01, 0xfe, + 0x01, 0x00, 0x00 + }; + const uint8_t* nal; + int32_t size; + + NalReader reader(&data[0], data.size(), false); + EXPECT_FALSE(reader.read(nal, size)); +} + +} diff --git a/common/scopedlogger.h b/common/scopedlogger.h new file mode 100644 index 0000000..352423f --- /dev/null +++ b/common/scopedlogger.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef scopedlogger_h +#define scopedlogger_h + +/*it's expensive, disable it by default*/ +#define DISABLE_SCOPED_LOGGER +#ifndef DISABLE_SCOPED_LOGGER +#include "log.h" + +class ScopedLogger { + public: + ScopedLogger(const char *str) + { + m_str = str; + INFO("+%s", m_str); + } + ~ScopedLogger() + { + INFO("-%s", m_str); + } + + private: + const char *m_str; +}; + +#define FUNC_ENTER() ScopedLogger __func_loggger__(__func__) +#else +#define FUNC_ENTER() +#endif + +#endif //scopedlogger_h diff --git a/common/surfacepool.cpp b/common/surfacepool.cpp new file mode 100644 index 0000000..929a55f --- /dev/null +++ b/common/surfacepool.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "surfacepool.h" + +#include "common/log.h" + +namespace YamiMediaCodec{ + +SharedPtr +SurfacePool::create(const SharedPtr& alloc, + uint32_t fourcc, uint32_t width, uint32_t height, uint32_t size) +{ + SharedPtr pool(new SurfacePool); + if (YAMI_SUCCESS != pool->init(alloc, fourcc, width, height, size)) + pool.reset(); + return pool; +} + +SurfacePool::SurfacePool() +{ + memset(&m_params, 0, sizeof(m_params)); +} + +YamiStatus SurfacePool::init(const SharedPtr& alloc, + uint32_t fourcc, uint32_t width, uint32_t height, uint32_t size) +{ + m_params.fourcc = fourcc; + m_params.width = width; + m_params.height = height; + m_params.size = size; + YamiStatus status = alloc->alloc(alloc.get(), &m_params); + if (status != YAMI_SUCCESS) + return status; + + //prepare surfaces for pool + std::deque surfaces; + for (uint32_t i = 0; i < m_params.size; i++) { + SurfacePtr s(new VaapiSurface(m_params.surfaces[i], width, height, fourcc)); + surfaces.push_back(s); + } + m_pool.reset(new VideoPool(surfaces)); + if (!m_pool) { + ERROR("failed to create Surface Pool"); + return YAMI_OUT_MEMORY; + } + + m_alloc = alloc; + return YAMI_SUCCESS; +} + +SurfacePool::~SurfacePool() +{ + if (m_alloc) { + m_alloc->free(m_alloc.get(), &m_params); + } +} + +SurfacePtr SurfacePool::alloc() +{ + return m_pool->alloc(); +} + +} //YamiMediaCodec diff --git a/common/surfacepool.h b/common/surfacepool.h new file mode 100644 index 0000000..7abaef1 --- /dev/null +++ b/common/surfacepool.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef surfacepool_h +#define surfacepool_h + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "common/videopool.h" +#include "VideoCommonDefs.h" +/* we should not include vaapi surface here, + * but we have no choose before we make VaapiSurface more generic, + * and rename it to Surface + */ +#include "vaapi/vaapiptrs.h" +#include "vaapi/VaapiSurface.h" +#include + +namespace YamiMediaCodec{ + +class SurfacePool +{ +public: + static SharedPtr + create(const SharedPtr& alloc, + uint32_t fourcc, uint32_t width, uint32_t height, uint32_t size); + + /** + * allocator surface from pool, if no avaliable surface it will return NULL + */ + SurfacePtr alloc(); + + /** + * peek surfaces from surface pool. + */ + template + void peekSurfaces(std::vector& surfaces); + ~SurfacePool(); +private: + SurfacePool(); + + YamiStatus init(const SharedPtr& alloc, + uint32_t fourcc, uint32_t width, uint32_t height, uint32_t size); + + SharedPtr m_alloc; + SurfaceAllocParams m_params; + SharedPtr > m_pool; + DISALLOW_COPY_AND_ASSIGN(SurfacePool) + +}; + +template +void SurfacePool::peekSurfaces(std::vector& surfaces) +{ + ASSERT(surfaces.size() == 0); + ASSERT(m_alloc); + for (uint32_t i = 0; i < m_params.size; i++) { + surfaces.push_back((S)m_params.surfaces[i]); + } +} + +} //YamiMediaCodec + +#endif //#define surfacepool_h diff --git a/common/unittest.h b/common/unittest.h new file mode 100644 index 0000000..5ee5c1a --- /dev/null +++ b/common/unittest.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef unittest_h +#define unittest_h + +/* + * The following #define prevents gtest from using it's own tr1 tuple + * implementation. This is necessary since we use C++11 and/or the system + * provided tr1/tuple[.h] in this project. The gtest header appears to + * incorrectly detect the availability of the system tr1/tuple[.h] and thus + * tries to use it's own implementation of it... and thus will cause compile + * failures due to duplicate definitions of tr1::tuple. + */ +#define GTEST_USE_OWN_TR1_TUPLE 0 + +#include + +#endif // unittest_h diff --git a/common/unittest_main.cpp b/common/unittest_main.cpp new file mode 100644 index 0000000..19f9823 --- /dev/null +++ b/common/unittest_main.cpp @@ -0,0 +1,27 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/common/utils.cpp b/common/utils.cpp new file mode 100644 index 0000000..2c9c29f --- /dev/null +++ b/common/utils.cpp @@ -0,0 +1,303 @@ +/* + * Copyright (C) 2011-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "utils.h" + +#include "common/common_def.h" +#include "common/log.h" + +#define __STDC_FORMAT_MACROS +#include + +#include +#include +#include +#include +#include +#include + +namespace YamiMediaCodec{ + +uint32_t guessFourcc(const char* fileName) +{ + static const char* possibleFourcc[] = { + "I420", "NV12", "YV12", + "P010", + "YUY2", "UYVY", + "RGBX", "RGBA", "BGRX", "BGRA", + "XRGB", "ARGB", "XBGR", "ABGR", + //RGB 565 + "RG16", + //temprary format for RGB 10 bits + "R210", + //for jpeg + "444P", "422V", "422H", "IMC3" + }; + const char* extension = strrchr(fileName, '.'); + if (extension) { + extension++; + for (size_t i = 0; i < N_ELEMENTS(possibleFourcc); i++) { + const char* fourcc = possibleFourcc[i]; + if (!strcasecmp(fourcc, extension)) { + uint32_t ret = YAMI_FOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3]); + DEBUG_FOURCC("guessed input fourcc:", ret); + return ret; + } + } + } + WARNING("can't find fourcc for %s, return i420", extension); + + return YAMI_FOURCC_I420; +} + +//do not use sscanf to get int, the function will make guessResolutionOverflow failed +//see http://www.kumobius.com/2013/08/c-string-to-int/ for detials +static bool getInt(const char* tokStart, int& v) +{ + std::istringstream iss(tokStart); + iss >> v; + return !iss.fail(); +} + +bool guessResolution(const char* filename, int& w, int& h) +{ + enum { + STATE_START, + STATE_WIDTH, + STATE_X, + STATE_HEIGHT, + STATE_END, + }; + int state = STATE_START; + const char* p = filename; + const char* tokStart = NULL; + w = h = 0; + while (*p != '\0') { + switch (state) { + case STATE_START: + { + if (isdigit(*p)) { + tokStart = p; + state = STATE_WIDTH; + } + break; + } + case STATE_WIDTH: { + if (*p == 'x' || *p == 'X') { + state = STATE_X; + if (!getInt(tokStart, w)) { + state = STATE_START; + } + } else if (!isdigit(*p)){ + state = STATE_START; + } + break; + } + case STATE_X: + { + if (isdigit(*p)) { + tokStart = p; + state = STATE_HEIGHT; + } else { + state = STATE_START; + } + break; + } + case STATE_HEIGHT: + { + if (!isdigit(*p)) { + state = STATE_END; + if (!getInt(tokStart, h)) { + state = STATE_START; + } + } + break; + } + } + if (state == STATE_END) + break; + p++; + } + //conner case + if (*p == '\0' && state == STATE_HEIGHT) { + if (!getInt(tokStart, h)) + return false; + } + return w > 0 && h > 0; +} + +struct ResolutionEntry { + uint32_t fourcc; + uint32_t planes; + //multiple to half width + //if it equals 1, you need divide width with 2 + //if it equals 4, you need multiple width with 2 + uint32_t widthMultiple[3]; + uint32_t heightMultiple[3]; +}; + +const static ResolutionEntry resolutionEntrys[] = { + { YAMI_FOURCC_I420, 3, { 2, 1, 1 }, { 2, 1, 1 } }, + { YAMI_FOURCC_YV12, 3, { 2, 1, 1 }, { 2, 1, 1 } }, + { YAMI_FOURCC_IMC3, 3, { 2, 1, 1 }, { 2, 1, 1 } }, + { YAMI_FOURCC_422H, 3, { 2, 1, 1 }, { 2, 2, 2 } }, + { YAMI_FOURCC_422V, 3, { 2, 2, 2 }, { 2, 1, 1 } }, + { YAMI_FOURCC_444P, 3, { 2, 2, 2 }, { 2, 2, 2 } }, + { YAMI_FOURCC_Y800, 1, { 2 }, { 2 } }, + { YAMI_FOURCC_YUY2, 1, { 4 }, { 2 } }, + { YAMI_FOURCC_UYVY, 1, { 4 }, { 2 } }, + { YAMI_FOURCC_RGBX, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_RGBA, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_BGRX, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_BGRA, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_XRGB, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_ARGB, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_XBGR, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_ABGR, 1, { 8 }, { 2 } }, + { YAMI_FOURCC_RGB565, 1, { 4 }, { 2 } }, + { YAMI_FOURCC_R210, 1, { 8 }, { 2 } }, +}; + +/* l is length in pixel*/ +/* length[] are length in each plane*/ +static void getPlaneLength(uint32_t l, uint32_t plane, const uint32_t multiple[3], uint32_t length[3]) +{ + for (uint32_t i = 0; i < plane; i++) { + length[i] = (l * multiple[i] + 1) >> 1; + } +} + +bool getPlaneResolution(uint32_t fourcc, uint32_t pixelWidth, uint32_t pixelHeight, uint32_t byteWidth[3], uint32_t byteHeight[3], uint32_t& planes) +{ + int w = pixelWidth; + int h = pixelHeight; + uint32_t* width = byteWidth; + uint32_t* height = byteHeight; + //NV12 is special since it need add one for width[1] when w is odd + if (fourcc == YAMI_FOURCC_NV12) { + width[0] = w; + height[0] = h; + width[1] = w + (w & 1); + height[1] = (h + 1) >> 1; + planes = 2; + return true; + } + if (fourcc == YAMI_FOURCC_P010) { + width[0] = w * 2; + height[0] = h; + width[1] = (w + (w & 1)) * 2; + height[1] = (h + 1) >> 1; + planes = 2; + return true; + } + for (size_t i = 0; i < N_ELEMENTS(resolutionEntrys); i++) { + const ResolutionEntry& e = resolutionEntrys[i]; + if (e.fourcc == fourcc) { + planes = e.planes; + getPlaneLength(pixelWidth, planes, e.widthMultiple, width); + getPlaneLength(pixelHeight, planes, e.heightMultiple, height); + return true; + } + } + ERROR("do not support this format, fourcc %.4s", (char*)&fourcc); + planes = 0; + return false; +} + +/// return system clock in ms +uint64_t getSystemTime() +{ + struct timeval tv; + if (gettimeofday(&tv, NULL)) + return 0; + return tv.tv_usec/1000+tv.tv_sec*1000; +} + +double getFps(uint64_t current, uint64_t start, int frames) +{ + uint64_t sysTime = current - start; + double fps = frames*1000.0/sysTime; + return fps; +} + +FpsCalc::FpsCalc():m_frames(0) {} + +void FpsCalc::addFrame() +{ + if (m_frames == 0) { + m_start = getSystemTime(); + } else if (m_frames == NET_FPS_START){ + m_netStart = getSystemTime(); + } + m_frames++; +} +void FpsCalc::log() +{ + uint64_t current = getSystemTime(); + if (m_frames > 0) { + printf("%d frame decoded, fps = %.2f. ", m_frames, getFps(current, m_start,m_frames)); + } + if (m_frames > NET_FPS_START) { + printf("fps after %d frames = %.2f.", NET_FPS_START, getFps(current, m_netStart, m_frames-NET_FPS_START)); + } + printf("\n"); +} +void CalcFps::setAnchor() +{ + m_timeStart = getSystemTime(); +} + +float CalcFps::fps(uint32_t frameCount) +{ + if (!m_timeStart) { + fprintf(stderr, "anchor point isn't set, please call setAnchor first\n"); + return 0.0f; + } + + uint64_t sysTime = getSystemTime() - m_timeStart; + float fps = frameCount*1000.0/sysTime; + fprintf(stdout, "rendered frame count: %d in %" PRIu64 " ms; fps=%.2f\n", + frameCount, sysTime, fps); + + return fps; +} + +bool fillFrameRawData(VideoFrameRawData* frame, uint32_t fourcc, uint32_t width, uint32_t height, uint8_t* data) +{ + memset(frame, 0, sizeof(*frame)); + uint32_t planes; + uint32_t w[3], h[3]; + if (!getPlaneResolution(fourcc, width, height, w, h, planes)) + return false; + frame->fourcc = fourcc; + frame->width = width; + frame->height = height; + frame->handle = reinterpret_cast(data); + frame->memoryType = VIDEO_DATA_MEMORY_TYPE_RAW_POINTER; + + uint32_t offset = 0; + for (uint32_t i = 0; i < planes; i++) { + frame->pitch[i] = w[i]; + frame->offset[i] = offset; + offset += w[i] * h[i]; + } + return true; +} + +}; diff --git a/common/utils.h b/common/utils.h new file mode 100644 index 0000000..053065f --- /dev/null +++ b/common/utils.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef utils_h +#define utils_h + +#include +#include + +#include "VideoCommonDefs.h" + +#ifndef VA_FOURCC_I420 +#define VA_FOURCC_I420 VA_FOURCC('I','4','2','0') +#endif + +namespace YamiMediaCodec{ + +uint32_t guessFourcc(const char* fileName); + +bool guessResolution(const char* filename, int& w, int& h); + +bool getPlaneResolution(uint32_t fourcc, uint32_t pixelWidth, uint32_t pixelHeight, uint32_t byteWidth[3], uint32_t byteHeight[3], uint32_t& planes); + +bool fillFrameRawData(VideoFrameRawData* frame, uint32_t fourcc, uint32_t width, uint32_t height, uint8_t* data); + +class CalcFps +{ + public: + CalcFps() { m_timeStart = 0;}; + void setAnchor(); + float fps(uint32_t frameCount); + + private: + uint64_t m_timeStart; +}; + +//slim version of CalcFps, hide all fps all fps detials. +class FpsCalc +{ +public: + FpsCalc(); + void addFrame(); + void log(); +private: + int m_frames; + uint64_t m_start; + uint64_t m_netStart; + static const int NET_FPS_START = 5; +}; +}; + +#endif diff --git a/common/utils_unittest.cpp b/common/utils_unittest.cpp new file mode 100644 index 0000000..d1c5ea4 --- /dev/null +++ b/common/utils_unittest.cpp @@ -0,0 +1,212 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "utils.h" + +// library headers +#include "common/unittest.h" +#include "common/common_def.h" + +// system headers +#include +#include +#include + +#define UTILS_TEST(name) \ + TEST(UtilsTest, name) + +using namespace YamiMediaCodec; + +UTILS_TEST(guessFourcc) { + EXPECT_EQ(guessFourcc("test.i420"), (uint32_t)YAMI_FOURCC_I420); + EXPECT_EQ(guessFourcc("test.nv12"), (uint32_t)YAMI_FOURCC_NV12); + EXPECT_EQ(guessFourcc("test.yv12"), (uint32_t)YAMI_FOURCC_YV12); + EXPECT_EQ(guessFourcc("test.yuy2"), (uint32_t)YAMI_FOURCC_YUY2); + EXPECT_EQ(guessFourcc("test.uyvy"), (uint32_t)YAMI_FOURCC_UYVY); + EXPECT_EQ(guessFourcc("test.rgbx"), (uint32_t)YAMI_FOURCC_RGBX); + EXPECT_EQ(guessFourcc("test.bgrx"), (uint32_t)YAMI_FOURCC_BGRX); + EXPECT_EQ(guessFourcc("test.xrgb"), (uint32_t)YAMI_FOURCC_XRGB); + EXPECT_EQ(guessFourcc("test.xbgr"), (uint32_t)YAMI_FOURCC_XBGR); + + EXPECT_EQ(guessFourcc("test.txt"), (uint32_t)YAMI_FOURCC_I420); + EXPECT_EQ(guessFourcc("test"), (uint32_t)YAMI_FOURCC_I420); + + EXPECT_EQ(guessFourcc("test.I420"), (uint32_t)YAMI_FOURCC_I420); + EXPECT_EQ(guessFourcc("test.NV12"), (uint32_t)YAMI_FOURCC_NV12); + EXPECT_EQ(guessFourcc("test.YV12"), (uint32_t)YAMI_FOURCC_YV12); + EXPECT_EQ(guessFourcc("test.YUY2"), (uint32_t)YAMI_FOURCC_YUY2); + EXPECT_EQ(guessFourcc("test.UYVY"), (uint32_t)YAMI_FOURCC_UYVY); + + EXPECT_EQ(guessFourcc("test.RGBX"), (uint32_t)YAMI_FOURCC_RGBX); + EXPECT_EQ(guessFourcc("test.BGRX"), (uint32_t)YAMI_FOURCC_BGRX); + EXPECT_EQ(guessFourcc("test.XRGB"), (uint32_t)YAMI_FOURCC_XRGB); + EXPECT_EQ(guessFourcc("test.XBGR"), (uint32_t)YAMI_FOURCC_XBGR); + + EXPECT_EQ(guessFourcc("test.RGBA"), (uint32_t)YAMI_FOURCC_RGBA); + EXPECT_EQ(guessFourcc("test.BGRA"), (uint32_t)YAMI_FOURCC_BGRA); + EXPECT_EQ(guessFourcc("test.ARGB"), (uint32_t)YAMI_FOURCC_ARGB); + EXPECT_EQ(guessFourcc("test.ABGR"), (uint32_t)YAMI_FOURCC_ABGR); + + EXPECT_EQ(guessFourcc("test.RG16"), (uint32_t)YAMI_FOURCC_RGB565); + EXPECT_EQ(guessFourcc("test.R210"), (uint32_t)YAMI_FOURCC_R210); +} + +UTILS_TEST(guessResolutionBasic) { + int w(-1), h(-1); + EXPECT_TRUE(guessResolution("test1920x1080", w, h)); + EXPECT_EQ(w, 1920); + EXPECT_EQ(h, 1080); + + w = -1, h = -1; + EXPECT_TRUE(guessResolution("test1920X1080", w, h)); + EXPECT_EQ(w, 1920); + EXPECT_EQ(h, 1080); + + w = -1, h = -1; + EXPECT_TRUE(guessResolution("test123-1920x1080", w, h)); + EXPECT_EQ(w, 1920); + EXPECT_EQ(h, 1080); + + w = -1, h = -1; + EXPECT_TRUE(guessResolution("test-1920x1080-123", w, h)); + EXPECT_EQ(w, 1920); + EXPECT_EQ(h, 1080); + + w = -1, h = -1; + EXPECT_FALSE(guessResolution("test1920xx1080", w, h)); + EXPECT_EQ(w, 1920); + EXPECT_EQ(h, 0); + + w = -1, h = -1; + EXPECT_FALSE(guessResolution("test", w, h)); + EXPECT_EQ(w, 0); + EXPECT_EQ(h, 0); + + w = -1, h = -1; + EXPECT_FALSE(guessResolution("test1080p", w, h)); + EXPECT_EQ(w, 0); + EXPECT_EQ(h, 0); + + w = -1, h = -1; + EXPECT_FALSE(guessResolution("test720x", w, h)); + EXPECT_EQ(w, 720); + EXPECT_EQ(h, 0); + + w = -1, h = -1; + EXPECT_TRUE(guessResolution("1280x720", w, h)); + EXPECT_EQ(w, 1280); + EXPECT_EQ(h, 720); + + w = -1, h = -1; + EXPECT_FALSE(guessResolution("w3840h2160", w, h)); + EXPECT_EQ(w, 0); + EXPECT_EQ(h, 0); +} + +UTILS_TEST(guessResolutionOverflow) { + std::stringstream sstream; + int w, h; + + w = h = std::numeric_limits::max(); + + // sanity check + ASSERT_GT(std::numeric_limits::max(), w); + ASSERT_GT(std::numeric_limits::max(), h); + + sstream << std::numeric_limits::max() + << "x" + << std::numeric_limits::max(); + + EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h)); + + sstream.str(""); + sstream << long(std::numeric_limits::max()) * 2 + 3 << "x" + << long(std::numeric_limits::max()) * 3 + 2; + EXPECT_FALSE(guessResolution(sstream.str().c_str(), w, h)); +} + +struct BppEntry { + uint32_t fourcc; + uint32_t planes; + float bpp; +}; + +const static BppEntry bppEntrys[] = { + { YAMI_FOURCC_NV12, 2, 1.5 }, + { YAMI_FOURCC_I420, 3, 1.5 }, + { YAMI_FOURCC_YV12, 3, 1.5 }, + { YAMI_FOURCC_IMC3, 3, 1.5 }, + { YAMI_FOURCC_422H, 3, 2 }, + { YAMI_FOURCC_422V, 3, 2 }, + { YAMI_FOURCC_444P, 3, 3 }, + { YAMI_FOURCC_Y800, 1, 1 }, + { YAMI_FOURCC_P010, 2, 3 }, + { YAMI_FOURCC_YUY2, 1, 2 }, + { YAMI_FOURCC_UYVY, 1, 2 }, + + { YAMI_FOURCC_RGBX, 1, 4 }, + { YAMI_FOURCC_BGRX, 1, 4 }, + { YAMI_FOURCC_XRGB, 1, 4 }, + { YAMI_FOURCC_XBGR, 1, 4 }, + + { YAMI_FOURCC_RGBA, 1, 4 }, + { YAMI_FOURCC_BGRA, 1, 4 }, + { YAMI_FOURCC_ARGB, 1, 4 }, + { YAMI_FOURCC_ABGR, 1, 4 }, + + { YAMI_FOURCC_RGB565, 1, 2 }, + { YAMI_FOURCC_R210, 1, 4 }, +}; + +//check selected unsupported format. +//we do not want check all unsupported formats, it will introduce too many dependency on libva +const static uint32_t unsupported[] = { + 0, + YAMI_FOURCC_411P, +}; + +UTILS_TEST(getPlaneResolution) +{ + + uint32_t width = 1920; + uint32_t height = 1080; + uint32_t planes; + uint32_t w[3]; + uint32_t h[3]; + + for (size_t i = 0; i < N_ELEMENTS(unsupported); i++) { + EXPECT_FALSE(getPlaneResolution(unsupported[i], 1920, 1080, w, h, planes)); + EXPECT_EQ(0u, planes); + } + for (size_t i = 0; i < N_ELEMENTS(bppEntrys); i++) { + const BppEntry& e = bppEntrys[i]; + EXPECT_TRUE(getPlaneResolution(e.fourcc, width, height, w, h, planes)); + EXPECT_EQ(e.planes, planes); + + float bpp; + uint32_t bytes = 0; + for (uint32_t p = 0; p < planes; p++) { + bytes += w[p] * h[p]; + } + bpp = (float)bytes / (width * height); + EXPECT_FLOAT_EQ(e.bpp, bpp); + } +} diff --git a/common/videopool.h b/common/videopool.h new file mode 100644 index 0000000..73aaa31 --- /dev/null +++ b/common/videopool.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef videopool_h +#define videopool_h +#include "VideoCommonDefs.h" +#include "common/lock.h" +#include + +namespace YamiMediaCodec{ + +template +class VideoPool : public EnableSharedFromThis > +{ +public: + VideoPool(std::deque >& buffers) + { + m_holder.swap(buffers); + for (size_t i = 0; i < m_holder.size(); i++) { + m_freed.push_back(m_holder[i].get()); + } + } + + SharedPtr alloc() + { + SharedPtr ret; + AutoLock _l(m_lock); + if (!m_freed.empty()) { + T* p = m_freed.front(); + m_freed.pop_front(); + ret.reset(p, Recycler(this->shared_from_this())); + } + return ret; + } + +private: + + void recycle(T* ptr) + { + AutoLock _l(m_lock); + m_freed.push_back(ptr); + } + + class Recycler + { + public: + Recycler(const SharedPtr >& pool) + :m_pool(pool) + { + } + void operator()(T* ptr) const + { + m_pool->recycle(ptr); + } + private: + SharedPtr > m_pool; + }; + + Lock m_lock; + std::deque m_freed; + std::deque > m_holder; +}; + +}; +#endif //videopool_h diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..59a2eac --- /dev/null +++ b/configure.ac @@ -0,0 +1,547 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. +AC_PREREQ([2.68]) + +# YAMI-API version +# YAMI-API version for api headers, only change it when the api interface is changed. +m4_define([yami_api_major_version], 0) +# update this for every release when micro version large than zero +m4_define([yami_api_minor_version], 6) +# change this for any api change +m4_define([yami_api_micro_version], 0) +m4_define([yami_api_version], + [yami_api_major_version.yami_api_minor_version.yami_api_micro_version]) + +# package version (lib name suffix), usually sync with git tag +m4_define([libyami_major_version], 1) +m4_define([libyami_minor_version], 3) +# even number of micro_version means a release after full validation cycle +m4_define([libyami_micro_version], 1) +m4_define([libyami_version], + [libyami_major_version.libyami_minor_version.libyami_micro_version]) + +# libva minimun version requirement +m4_define([va_min_api_version], [0.36]) + +AC_INIT([libyami], + [libyami_version], + [https://github.com/01org/libyami/issues/new], + [libyami], + [https://github.com/01org/libyami]) + +AC_CONFIG_SRCDIR([common/common_def.h]) +AC_CONFIG_HEADERS([config.h]) +AC_CONFIG_MACRO_DIR([m4]) +AC_CONFIG_AUX_DIR([build-aux]) +AM_INIT_AUTOMAKE([foreign subdir-objects]) +AM_SILENT_RULES([yes]) + +LIBYAMI_LT_VERSION="libyami_major_version:libyami_minor_version:libyami_micro_version" +LIBYAMI_LT_LDFLAGS="-version-number $LIBYAMI_LT_VERSION" +# "-release" option should be avoid, that create lib name like libyami-1.s0.xxx +AC_SUBST(LIBYAMI_LT_VERSION) +AC_SUBST(LIBYAMI_LT_LDFLAGS) + +YAMI_API_MAJOR_VERSION=yami_api_major_version +YAMI_API_MINOR_VERSION=yami_api_minor_version +YAMI_API_MICRO_VERSION=yami_api_micro_version +YAMI_API_VERSION=yami_api_version +AC_SUBST(YAMI_API_MAJOR_VERSION) +AC_SUBST(YAMI_API_MINOR_VERSION) +AC_SUBST(YAMI_API_MICRO_VERSION) +AC_SUBST(YAMI_API_VERSION) + +AM_CONDITIONAL(BUILD_STATIC, + [test "x$enable_static" = "xyes"]) + +AC_ARG_ENABLE(debug, + [AC_HELP_STRING([--enable-debug], + [build with extra debug @<:@default=no@:>@])], + [], [enable_debug="no"]) + +if test "$enable_debug" = "yes"; then + AC_DEFINE([__ENABLE_DEBUG__], [1], + [Defined to 1 if --enable-debug="yes"]) +fi + +AC_ARG_ENABLE(dmabuf, + [AC_HELP_STRING([--enable-dmabuf], + [support dma_buf buffer sharing @<:@default=no@:>@])], + [], [enable_dmabuf="no"]) + +if test "$enable_dmabuf" = "yes"; then + AC_DEFINE([__ENABLE_DMABUF__], [1], + [Defined to 1 if --enable-dmabuf="yes"]) +fi +AM_CONDITIONAL(ENABLE_DMABUF, + [test "x$enable_dmabuf" = "xyes"]) + +AC_ARG_ENABLE(v4l2, + [AC_HELP_STRING([--enable-v4l2], + [wrapper of v4l2 interface @<:@default=no@:>@])], + [], [enable_v4l2="no"]) + +if test "$enable_v4l2" = "yes"; then + AC_DEFINE([__ENABLE_V4L2__], [1], + [Defined to 1 if --enable-v4l2="yes"]) +fi +AM_CONDITIONAL(ENABLE_V4L2, + [test "x$enable_v4l2" = "xyes"]) + +AC_ARG_ENABLE(x11, + [AC_HELP_STRING([--enable-x11], + [enable x11 @<:@default=yes@:>@])], + [], [enable_x11="yes"]) + +if test "$enable_x11" = "yes"; then + AC_DEFINE([__ENABLE_X11__], [1], + [Defined to 1 if --enable-x11="yes"]) +fi +AM_CONDITIONAL(ENABLE_X11, + [test "x$enable_x11" = "xyes"]) + +AC_ARG_ENABLE(egl, + [AC_HELP_STRING([--enable-egl], + [enable egl @<:@default=yes@:>@])], + [], [enable_egl="yes"]) + +if test "$enable_egl" = "yes"; then + AC_DEFINE([__ENABLE_EGL__], [1], + [Defined to 1 if --enable-egl="yes"]) +fi +AM_CONDITIONAL(ENABLE_EGL, + [test "x$enable_egl" = "xyes"]) + +AC_ARG_ENABLE(wayland, + [AC_HELP_STRING([--enable-wayland], + [enable wayland @<:@default=no@:>@])], + [], [enable_wayland="no"]) + +if test "$enable_wayland" = "yes"; then + AC_DEFINE([__ENABLE_WAYLAND__], [1], + [Defined to 1 if --enable-wayland="yes"]) +fi +AM_CONDITIONAL(ENABLE_WAYLAND, + [test "x$enable_wayland" = "xyes"]) + +AC_ARG_ENABLE(baytrail, + [AC_HELP_STRING([--enable-baytrail], + [build with baytrail/chromeos support @<:@default=no@:>@])], + [], [enable_baytrail="no"]) + +if test "$enable_baytrail" = "yes"; then + AC_DEFINE([__PLATFORM_BYT__], [1], + [Defined to 1 if --enable-baytrail="yes"]) +fi + +AC_ARG_ENABLE(v4l2-ops, + [AC_HELP_STRING([--enable-v4l2-ops], + [support v4l2codec_device_ops.h interface in v4l2 wrapper @<:@default=no@:>@])], + [], [enable_v4l2_ops="no"]) + +if test "$enable_v4l2_ops" = "yes"; then + AC_DEFINE([__ENABLE_V4L2_OPS__], [1], + [Defined to 1 if --enable-v4l2-ops="yes"]) +fi +AM_CONDITIONAL(ENABLE_V4L2_OPS, + [test "x$enable_v4l2_ops" = "xyes"]) + +AC_ARG_ENABLE(md5, + [AC_HELP_STRING([--enable-md5], [enable generate md5 by per frame@<:@default=yes@:>@])], + [], [enable_md5="yes"]) + +dnl mpeg2 decoder +AC_ARG_ENABLE(mpeg2dec, + [AC_HELP_STRING([--enable-mpeg2dec], + [build with mpeg2 decoder support @<:@default=no@:>@])], + [], [enable_mpeg2dec="no"]) + +if test "$enable_mpeg2dec" = "yes"; then + AC_DEFINE([__BUILD_MPEG2_DECODER__], [1], + [Defined to 1 if --enable-mpeg2dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_MPEG2_DECODER, + [test "x$enable_mpeg2dec" = "xyes"]) + +dnl vp8 decoder +AC_ARG_ENABLE(vp8dec, + [AC_HELP_STRING([--enable-vp8dec], + [build with vp8 decoder support @<:@default=yes@:>@])], + [], [enable_vp8dec="yes"]) + +if test "$enable_vp8dec" = "yes"; then + AC_DEFINE([__BUILD_VP8_DECODER__], [1], + [Defined to 1 if --enable-vp8dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_VP8_DECODER, + [test "x$enable_vp8dec" = "xyes"]) + +dnl vp9 decoder +AC_ARG_ENABLE(vp9dec, + [AC_HELP_STRING([--enable-vp9dec], + [build with vp9 decoder support @<:@default=no@:>@])], + [], [enable_vp9dec="no"]) + +if test "$enable_vp9dec" = "yes"; then + AC_DEFINE([__BUILD_VP9_DECODER__], [1], + [Defined to 1 if --enable-vp9dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_VP9_DECODER, + [test "x$enable_vp9dec" = "xyes"]) + +dnl jpeg decoder +AC_ARG_ENABLE(jpegdec, + [AC_HELP_STRING([--enable-jpegdec], + [build with jpeg decoder support @<:@default=yes@:>@])], + [], [enable_jpegdec="yes"]) + +if test "$enable_jpegdec" = "yes"; then + AC_DEFINE([__BUILD_JPEG_DECODER__], [1], + [Defined to 1 if --enable-jpegdec="yes"]) +fi + +AM_CONDITIONAL(BUILD_JPEG_DECODER, + [test "x$enable_jpegdec" = "xyes"]) + +dnl h264 decoder +AC_ARG_ENABLE(h264dec, + [AC_HELP_STRING([--enable-h264dec], + [build with h264 decoder support @<:@default=yes@:>@])], + [], [enable_h264dec="yes"]) + +if test "$enable_h264dec" = "yes"; then + AC_DEFINE([__BUILD_H264_DECODER__], [1], + [Defined to 1 if --enable-h264dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_H264_DECODER, + [test "x$enable_h264dec" = "xyes"]) + +dnl h265 decoder +AC_ARG_ENABLE(h265dec, + [AC_HELP_STRING([--enable-h265dec], + [build with h265 decoder support @<:@default=yes@:>@])], + [], [enable_h265dec="yes"]) + +if test "$enable_h265dec" = "yes"; then + AC_DEFINE([__BUILD_H265_DECODER__], [1], + [Defined to 1 if --enable-h265dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_H265_DECODER, + [test "x$enable_h265dec" = "xyes"]) + +dnl vc1 decoder +AC_ARG_ENABLE(vc1dec, + [AC_HELP_STRING([--enable-vc1dec], + [build with vc1 decoder support @<:@default=no@:>@])], + [], [enable_vc1dec="no"]) + +if test "$enable_vc1dec" = "yes"; then + AC_DEFINE([__BUILD_VC1_DECODER__], [1], + [Defined to 1 if --enable-vc1dec="yes"]) +fi + +AM_CONDITIONAL(BUILD_VC1_DECODER, + [test "x$enable_vc1dec" = "xyes"]) + +dnl fake decoder +AC_ARG_ENABLE(fakedec, + [AC_HELP_STRING([--enable-fakedec], + [build with fake decoder support @<:@default=no@:>@])], + [], [enable_fakedec="no"]) + +if test "$enable_fakedec" = "yes"; then + AC_DEFINE([__BUILD_FAKE_DECODER__], [1], + [Defined to 1 if --enable-fakedec="yes"]) +fi +AM_CONDITIONAL(BUILD_FAKE_DECODER, + [test "x$enable_fakedec" = "xyes"]) + +dnl h264 encoder +AC_ARG_ENABLE(h264enc, + [AC_HELP_STRING([--enable-h264enc], + [build with h264 encoder support @<:@default=yes@:>@])], + [], [enable_h264enc="yes"]) + +if test "$enable_h264enc" = "yes"; then + AC_DEFINE([__BUILD_H264_ENCODER__], [1], + [Defined to 1 if --enable-h264enc="yes"]) +fi + +AM_CONDITIONAL(BUILD_H264_ENCODER, + [test "x$enable_h264enc" = "xyes"]) + +dnl jpeg encoder +AC_ARG_ENABLE(jpegenc, + [AC_HELP_STRING([--enable-jpegenc], + [build with jpeg encoder support @<:@default=no@:>@])], + [], [enable_jpegenc="no"]) + +if test "$enable_jpegenc" = "yes"; then + AC_DEFINE([__BUILD_JPEG_ENCODER__], [1], + [Defined to 1 if --enable-jpegenc="yes"]) +fi + +AM_CONDITIONAL(BUILD_JPEG_ENCODER, + [test "x$enable_jpegenc" = "xyes"]) + +dnl vp8 encoder +AC_ARG_ENABLE(vp8enc, + [AC_HELP_STRING([--enable-vp8enc], + [build with vp8 encoder support @<:@default=no@:>@])], + [], [enable_vp8enc="no"]) + +if test "$enable_vp8enc" = "yes"; then + AC_DEFINE([__BUILD_VP8_ENCODER__], [1], + [Defined to 1 if --enable-vp8enc="yes"]) +fi + +AM_CONDITIONAL(BUILD_VP8_ENCODER, + [test "x$enable_vp8enc" = "xyes"]) + +AC_ARG_ENABLE(vp8svct, + [AC_HELP_STRING([--enable-vp8svct], + [enable vp8 SVC-T encoding @<:@default=no@:>@])], + [], [enable_vp8svct="no"]) + +if test "$enable_vp8enc" = "yes" -a "$enable_vp8svct" = "yes"; then + AC_DEFINE([__ENABLE_VP8_SVCT__], [1], + [Defined to 1 if --enable-vp8enc="yes" and --enable-vp8svct="yes"]) +fi + +dnl vp9 encoder +AC_ARG_ENABLE(vp9enc, + [AC_HELP_STRING([--enable-vp9enc], + [build with vp9 encoder support @<:@default=no@:>@])], + [], [enable_vp9enc="no"]) + +if test "$enable_vp9enc" = "yes"; then + AC_DEFINE([__BUILD_VP9_ENCODER__], [1], + [Defined to 1 if --enable-vp9enc="yes"]) +fi + +AM_CONDITIONAL(BUILD_VP9_ENCODER, + [test "x$enable_vp9enc" = "xyes"]) + +dnl h265 encoder +AC_ARG_ENABLE(h265enc, + [AC_HELP_STRING([--enable-h265enc], + [build with h265 encoder support @<:@default=no@:>@])], + [], [enable_h265enc="no"]) + +if test "$enable_h265enc" = "yes"; then + AC_DEFINE([__BUILD_H265_ENCODER__], [1], + [Defined to 1 if --enable-h265enc="yes"]) +fi + +AM_CONDITIONAL(BUILD_H265_ENCODER, + [test "x$enable_h265enc" = "xyes"]) + +dnl jpeg parser +AM_CONDITIONAL(BUILD_JPEG_PARSER, + [test "x$enable_jpegdec" = "xyes" -o "x$enable_jpegenc" = "xyes"]) + +dnl encoder getmv +AC_ARG_ENABLE(getmv, + [AC_HELP_STRING([--enable-getmv], + [build with get mv support @<:@default=no@:>@])], + [], [enable_getmv="no"]) + +if test "$enable_getmv" = "yes"; then + AC_DEFINE([__BUILD_GET_MV__], [1], + [Defined to 1 if --enable-getmv="yes"]) +fi +AM_CONDITIONAL(BUILD_GET_MV, + [test "x$enable_getmv" = "xyes"]) + +dnl ocl filters +AC_ARG_ENABLE(oclfilters, + [AC_HELP_STRING([--enable-oclfilters], + [build with opencl based alpha blend support @<:@default=no@:>@])], + [], [enable_oclfilters="no"]) + +if test "$enable_oclfilters" = "yes"; then + AC_DEFINE([__BUILD_OCL_FILTERS__], [1], + [Defined to 1 if --enable-oclfilters="yes"]) +fi + +AM_CONDITIONAL(BUILD_OCL_FILTERS, + [test "x$enable_oclfilters" = "xyes"]) + + +# dnl Doxygen +AC_ARG_ENABLE(docs, + [AC_HELP_STRING([--enable-docs], + [build Doxygen docs @<:@default=no@:>@])], + [], [enable_docs="no"]) + +if test "$enable_docs" = "yes"; then + AC_CHECK_TOOL([DOXYGEN], [doxygen], [no]) + if test "$DOXYGEN" = "no"; then + enable_docs="no" + fi +fi +AM_CONDITIONAL(ENABLE_DOCS, + [test "$enable_docs" = "yes"]) + +AC_ARG_ENABLE([tests], + [AC_HELP_STRING([--enable-tests], + [build unit tests @<:@default=no@:>@])], + [], [enable_tests="no"]) + +AM_CONDITIONAL(ENABLE_TESTS, test "$enable_tests" = "yes") + +AC_ARG_ENABLE(media-studio-va, + [AC_HELP_STRING([--enable-media-studio-va], + [enable being based on media studio libva @<:@default=no@:>@])], + [], [enable_media_studio_va="no"]) + +if test "$enable_media_studio_va" = "yes"; then + AC_DEFINE([__ENABLE_H265_ENC_ON_STUDIO_VA__], [1], + [Defined to 1 to enable H265 encoding when --enable-media-studio-va="yes"]) +fi + +AC_SUBST([AM_CFLAGS], ["-g -O2 -fPIE -fPIC -fstack-protector -Wall -Wno-unused-function -Wno-cpp -Werror"]) +AC_SUBST([AM_CXXFLAGS], ["-g -O2 -fPIE -fPIC -fstack-protector -Wall -Wno-unused-function -Wno-cpp -Wno-missing-braces -Werror"]) + +#Add flags for SDL signoff called SDL325 - Compile With Defenses Enabled +AC_SUBST([AM_CPPFLAGS], ["-D_FORTIFY_SOURCE=2"]) +AC_SUBST([AM_LDFLAGS], ["-z noexecstack -z relro -z now -pie"]) + +# Checks for programs. +AC_DISABLE_STATIC +AC_PROG_CXX +AC_PROG_AWK +AC_PROG_CC +AC_PROG_CPP +AC_PROG_INSTALL +AC_PROG_LN_S +AC_PROG_MAKE_SET +AC_PROG_LIBTOOL +#LT_INIT +# Checks for libraries. + +# Checks for header files. +AC_CHECK_HEADERS([stddef.h stdint.h stdlib.h string.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_HEADER_STDBOOL +AC_C_INLINE +AC_TYPE_INT32_T +AC_TYPE_INT64_T +AC_TYPE_SIZE_T +AC_TYPE_UINT16_T +AC_TYPE_UINT32_T +AC_TYPE_UINT64_T +AC_TYPE_UINT8_T + +pkgconfigdir=${libdir}/pkgconfig +AC_SUBST(pkgconfigdir) + +# Check for libva (vaapi version) +VA_API_VERSION=va_min_api_version +AS_IF([test x$enable_h265dec = xyes], [VA_API_VERSION="0.37"]) +AS_IF([test x$enable_vp9dec = xyes], [VA_API_VERSION="0.37"]) +AS_IF([test x$enable_jpegenc = xyes], [VA_API_VERSION="0.37"]) +AS_IF([test x$enable_h265enc = xyes], [VA_API_VERSION="0.38"]) +AS_IF([test x$enable_vp8enc = xyes], [VA_API_VERSION="0.38"]) +AS_IF([test x$enable_vp9enc = xyes], [VA_API_VERSION="0.39"]) +LIBVA_PKG_REQ="libva >= $VA_API_VERSION" +PKG_CHECK_MODULES([LIBVA], [$LIBVA_PKG_REQ]) +AC_SUBST(LIBVA_VERSION) +AC_SUBST(LIBVA_PKG_REQ) + +LIBVA_DRM_PKG_REQ="libva-drm" +PKG_CHECK_MODULES([LIBVA_DRM], [$LIBVA_DRM_PKG_REQ]) +AC_SUBST(LIBVA_DRM_PKG_REQ) + +LIBVA_X11_PKG_REQ="" +X11_PKG_REQ="" +if test "$enable_x11" = "yes"; then + LIBVA_X11_PKG_REQ="libva-x11" + PKG_CHECK_MODULES([LIBVA_X11], [$LIBVA_X11_PKG_REQ], + [AC_DEFINE([HAVE_VA_X11], [1], + [Defined to 1 if VA/X11 API is enabled])]) + X11_PKG_REQ="x11" + PKG_CHECK_MODULES([X11], [$X11_PKG_REQ]) +fi +AC_SUBST(LIBVA_X11_PKG_REQ) +AC_SUBST(X11_PKG_REQ) +if test "$enable_wayland" = "yes"; then + PKG_CHECK_MODULES([LIBVA_WAYLAND], [libva-wayland], + [AC_DEFINE([HAVE_VA_WAYLAND], [1], + [Defined to 1 if VA/WAYLAND API is enabled])], + []) +fi + +if test "$enable_v4l2" = "yes"; then + PKG_CHECK_MODULES([LIBV4L2], [libv4l2]) + PKG_CHECK_MODULES([LIBEGL], [egl]) + PKG_CHECK_MODULES([LIBGLES2], [glesv2]) +fi + +# drm_fourcc.h for dma_buf support +if test "$enable_dmabuf" = "yes"; then + PKG_CHECK_MODULES([LIBDRM], [libdrm]) +fi + +# Checks for library functions. +AC_FUNC_MALLOC +AC_FUNC_REALLOC +AC_CHECK_FUNCS([memset strcasecmp strdup]) + +AC_CONFIG_FILES([Makefile + codecparsers/Makefile + common/Makefile + vaapi/Makefile + decoder/Makefile + encoder/Makefile + vpp/Makefile + v4l2/Makefile + capi/Makefile + doc/Makefile + gtestsrc/Makefile + pkgconfig/Makefile]) + +AC_OUTPUT([ + pkgconfig/libyami.pc + pkgconfig/libyami_v4l2.pc + interface/YamiVersion.h +]) + +# Print a configuration summary +DECODERS="" +AS_IF([test x$enable_h265dec = xyes], [DECODERS="$DECODERS h265"]) +AS_IF([test x$enable_vc1dec = xyes], [DECODERS="$DECODERS vc1"]) +AS_IF([test x$enable_h264dec = xyes], [DECODERS="$DECODERS h264"]) +AS_IF([test x$enable_jpegdec = xyes], [DECODERS="$DECODERS jpeg"]) +AS_IF([test x$enable_mpeg2dec = xyes], [DECODERS="$DECODERS mpeg2"]) +AS_IF([test x$enable_vp8dec = xyes], [DECODERS="$DECODERS vp8"]) +AS_IF([test x$enable_vp9dec = xyes], [DECODERS="$DECODERS vp9"]) +AS_IF([test x$enable_fakedec = xyes], [DECODERS="$DECODERS fake"]) + +ENCODERS="" +AS_IF([test x$enable_h265enc = xyes], [ENCODERS="$ENCODERS h265"]) +AS_IF([test x$enable_h264enc = xyes], [ENCODERS="$ENCODERS h264"]) +AS_IF([test x$enable_jpegenc = xyes], [ENCODERS="$ENCODERS jpeg"]) +AS_IF([test x$enable_vp8enc = xyes], [ENCODERS="$ENCODERS vp8"]) +AS_IF([test x$enable_vp9enc = xyes], [ENCODERS="$ENCODERS vp9"]) + +VPPS=" scaler" +AS_IF([test x$enable_oclfilters = xyes], [VPPS="$VPPS oclfilters"]) + +AC_MSG_RESULT([ + libyami - libyami_version (API: yami_api_version) + + Build decoders ................... :$DECODERS + Build encoders ....................:$ENCODERS + Build vpps ........................:$VPPS + Build gtest unit tests ........... : $enable_tests + Build documentation .............. : $enable_docs + Enable debug ..................... : $enable_debug + Installation prefix .............. : $prefix +]) diff --git a/decoder/Android.mk b/decoder/Android.mk new file mode 100644 index 0000000..7604a16 --- /dev/null +++ b/decoder/Android.mk @@ -0,0 +1,60 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + vaapidecoder_base.cpp \ + vaapidecoder_host.cpp \ + vaapidecsurfacepool.cpp \ + vaapidecpicture.cpp \ + +LOCAL_SRC_FILES += \ + vaapidecoder_h264.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_h265.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_vp8.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_vp9.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_vc1.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_mpeg2.cpp + +LOCAL_SRC_FILES += \ + vaapiDecoderJPEG.cpp + +LOCAL_SRC_FILES += \ + vaapidecoder_fake.cpp + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../common \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva \ + +LOCAL_CFLAGS := \ + -D__BUILD_H264_DECODER__=1 \ + -D__BUILD_H265_DECODER__=1 \ + -D__BUILD_VP8_DECODER__=1 \ + -D__BUILD_VP9_DECODER__=1 \ + -D__BUILD_VC1_DECODER__=1 \ + -D__BUILD_MPEG2_DECODER__=1 \ + -D__BUILD_JPEG_DECODER__=1 \ + + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libc++ + +LOCAL_ALLOW_UNDEFINED_SYMBOLS := true + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_decoder +include $(BUILD_STATIC_LIBRARY) diff --git a/decoder/DecoderApi_unittest.cpp b/decoder/DecoderApi_unittest.cpp new file mode 100644 index 0000000..33f514b --- /dev/null +++ b/decoder/DecoderApi_unittest.cpp @@ -0,0 +1,521 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" +#include "common/common_def.h" +#include "common/log.h" +#include "decoder/FrameData.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/vaapisurfaceallocator.h" +// primary header +#include "VideoDecoderHost.h" + +// system headers +#include +#include +#include + +namespace YamiMediaCodec { + +static FrameData g_h264data[] = { + g_avc8x8I, + g_avc8x8P, + g_avc8x8B, + g_avc8x16, + g_avc16x16, + g_avc8x8I, + g_avc8x8P, + g_avc8x8B, + g_avc8x8I, + g_avc8x8P, + g_avc8x8B, + g_EOF, +}; + +static FrameData g_h265data[] = { + g_hevc8x8I, + g_hevc8x8P, + g_hevc8x8B, + g_hevc8x18, + g_hevc16x16, + g_hevc8x8I, + g_hevc8x8P, + g_hevc8x8B, + g_hevc8x8I, + g_hevc8x8P, + g_hevc8x8B, + g_EOF, +}; + +static FrameData g_vp8data[] = { + g_vp8_8x8I, + g_vp8_8x8P1, + g_vp8_8x8P2, + g_vp8_16x16, + g_vp8_8x8I, + g_vp8_8x8P1, + g_vp8_8x8P2, + g_EOF, +}; + +static FrameData g_vp9data[] = { + g_vp9_8x8I, + g_vp9_8x8P1, + g_vp9_8x8P2, + g_vp9_16x16, + g_vp9_8x8I, + g_vp9_8x8P1, + g_vp9_8x8P2, + g_EOF, +}; + +static FrameData g_jpegdata[] = { + g_jpeg1_8x8, + g_jpeg2_8x8, + g_jpeg_16x16, + g_jpeg1_8x8, + g_jpeg2_8x8, + g_EOF, +}; + +static FrameData g_h264data_lowlatency[] = { + g_avc8x8I, + g_avc8x8P, + g_avc8x16, + g_avc16x16, + g_avc8x8I, + g_avc8x8P, + g_avc8x8I, + g_avc8x8P, + g_EOF, +}; + +static FrameData g_vp8data_lowlatency[] = { + g_vp8_8x8I, + g_vp8_8x8P1, + g_vp8_8x8P2, + g_vp8_16x16, + g_vp8_8x8I, + g_vp8_8x8P1, + g_vp8_8x8P2, + g_EOF, +}; + +static FrameData g_vp9data_lowlatency[] = { + g_vp9_8x8I, + g_vp9_8x8P1, + g_vp9_8x8P2, + g_vp9_16x16, + g_vp9_8x8I, + g_vp9_8x8P1, + g_vp9_8x8P2, + g_EOF, +}; + +static FrameData g_jpegdata_lowlatency[] = { + g_jpeg1_8x8, + g_jpeg2_8x8, + g_jpeg_16x16, + g_jpeg1_8x8, + g_jpeg2_8x8, + g_EOF, +}; + +static const std::string getFullTestName() +{ + const ::testing::TestInfo* const info = ::testing::UnitTest::GetInstance()->current_test_info(); + return std::string(info->test_case_name()) + + std::string(".") + + std::string(info->name()); +} + +class TestDecodeFrames { +public: + typedef SharedPtr Shared; + + static Shared create( + const FrameData* data, + const char* mime) + { + Shared frames(new TestDecodeFrames(data, mime)); + return frames; + } + + const char* getMime() const + { + return m_mime; + } + + const uint32_t getFrameCount() const + { + uint32_t i = 0; + FrameData d = m_data[i]; + while (d.m_data != NULL) { + i++; + d = m_data[i]; + } + return i; + } + + bool getFrame(VideoDecodeBuffer& buffer, FrameInfo& info) + { + const FrameData& d = m_data[m_idx]; + if (d.m_data != NULL) { + buffer.data = (uint8_t*)d.m_data; + buffer.size = d.m_size; + info = d.m_info; + m_idx++; + return true; + } + return false; + } + + void seekToStart() + { + m_idx = 0; + } + + friend std::ostream& operator<<(std::ostream& os, const TestDecodeFrames& t) + { + os << t.m_mime; + return os; + } + +private: + TestDecodeFrames( + const FrameData* data, + const char* mime) + : m_data(data) + , m_mime(mime) + , m_idx(0) + { + } + + const FrameData* m_data; + + const char* m_mime; + int m_idx; +}; + +class DecodeSurfaceAllocator : public VaapiSurfaceAllocator { +public: + DecodeSurfaceAllocator(const DisplayPtr& display) + : VaapiSurfaceAllocator(display->getID()) + , m_width(0) + , m_height(0) + { + } + void onFormatChange(const VideoFormatInfo* format) + { + m_width = format->surfaceWidth; + m_height = format->surfaceHeight; + } + +protected: + YamiStatus doAlloc(SurfaceAllocParams* params) + { + EXPECT_EQ(m_width, params->width); + EXPECT_EQ(m_height, params->height); + return VaapiSurfaceAllocator::doAlloc(params); + } + void doUnref() + { + delete this; + } + +private: + uint32_t m_width; + uint32_t m_height; +}; + +class DecodeApiTest + : public ::testing::Test, + public ::testing::WithParamInterface { +}; + +class DecodeApiTestLowlatency + : public ::testing::Test, + public ::testing::WithParamInterface { +}; + +bool checkOutput(SharedPtr& decoder, std::deque& formats) +{ + SharedPtr output(decoder->getOutput()); + bool gotOutput = bool(output); + if (gotOutput) { + int size = (int)formats.size(); + EXPECT_GT(size, 0); + + const VideoFormatInfo& format = formats.front(); + + if (format.width != output->crop.width + || format.height != output->crop.height) { + formats.pop_front(); + EXPECT_GT(size, 1); + + const VideoFormatInfo& f = formats.front(); + EXPECT_EQ(f.width, output->crop.width); + EXPECT_EQ(f.height, output->crop.height); + } + + //Consider a corner case here, nalu based h264 decoder. + //We have three frames with different resolution. R1 R2 R3. + //When we decode R3, it will generate format change, and we send R3 again. + //The h264 decoder will cache R3 and wait for AUD or next frame to decide + //it's a complete frame. So R3 is not *really* decoded, It only has R1, R2 decoded. + //According to h264 decode logical, IDR frame R2 will make all previous frames bumped. + //But it does not include himself. So we only get R1 output. + //So the formats will include three resolution R1, R2, R3 + size = (int)formats.size(); + EXPECT_LE(size, 3); + + } + return gotOutput; +} + +bool isFormatChanged(const std::deque& formats, const FrameInfo& info) +{ + if (formats.size() == 0) { + //no format yet any frame will generate format change + return true; + } + const VideoFormatInfo& format = formats.back(); + return (format.width != info.m_width) || (format.height != info.m_height); +} + +TEST_P(DecodeApiTest, Format_Change) +{ + NativeDisplay nativeDisplay; + memset(&nativeDisplay, 0, sizeof(nativeDisplay)); + DisplayPtr display = VaapiDisplay::create(nativeDisplay); + + SharedPtr decoder; + TestDecodeFrames frames = *GetParam(); + decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder); + ASSERT_TRUE(bool(decoder)); + DecodeSurfaceAllocator* allocator = new DecodeSurfaceAllocator(display); + + decoder->setAllocator(allocator); + + VideoConfigBuffer config; + memset(&config, 0, sizeof(config)); + ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config)); + + VideoDecodeBuffer buffer; + memset(&buffer, 0, sizeof(buffer)); + FrameInfo info; + uint32_t inFrames = 0; + uint32_t outFrames = 0; + //keep previous resolution + std::deque formats; + + while (frames.getFrame(buffer, info)) { + + YamiStatus status = decoder->decode(&buffer); + if (isFormatChanged(formats, info)) { + EXPECT_EQ(YAMI_DECODE_FORMAT_CHANGE, status); + } + if (status == YAMI_DECODE_FORMAT_CHANGE) { + + //check format + const VideoFormatInfo* format = decoder->getFormatInfo(); + ASSERT_TRUE(format); + EXPECT_EQ(info.m_width, format->width); + EXPECT_EQ(info.m_height, format->height); + formats.push_back(*format); + allocator->onFormatChange(format); + + //send buffer again + status = decoder->decode(&buffer); + if (YAMI_UNSUPPORTED == status) { + RecordProperty("skipped", true); + std::cout << "[ SKIPPED ] " << getFullTestName() + << " Hw does not support this decoder." << std::endl; + return; + } + EXPECT_EQ(YAMI_SUCCESS, status); + } + else { + EXPECT_EQ(YAMI_SUCCESS, status); + } + inFrames++; + while (checkOutput(decoder, formats)) + outFrames++; + + + } + //drain the decoder + EXPECT_EQ(YAMI_SUCCESS, decoder->decode(NULL)); + while (checkOutput(decoder, formats)) + outFrames++; + EXPECT_TRUE(inFrames > 0); + EXPECT_EQ((int)formats.size(), 1); + EXPECT_EQ(inFrames, outFrames); +} + +TEST_P(DecodeApiTest, Flush) +{ + NativeDisplay nativeDisplay; + memset(&nativeDisplay, 0, sizeof(nativeDisplay)); + DisplayPtr display = VaapiDisplay::create(nativeDisplay); + + SharedPtr decoder; + TestDecodeFrames frames = *GetParam(); + decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder); + ASSERT_TRUE(bool(decoder)); + DecodeSurfaceAllocator* allocator = new DecodeSurfaceAllocator(display); + + decoder->setAllocator(allocator); + + VideoConfigBuffer config; + memset(&config, 0, sizeof(config)); + ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config)); + + VideoDecodeBuffer buffer; + memset(&buffer, 0, sizeof(buffer)); + FrameInfo info; + int64_t timeBeforeFlush = 0; + int64_t timeCurrent = 0; + SharedPtr output; + int32_t size = frames.getFrameCount(); + int32_t outFrames = 0; + + for (int i = 0; i < size; i++) { + outFrames = 0; + frames.seekToStart(); + for (int j = 0; j <= i; j++) { + if (!frames.getFrame(buffer, info)) + break; + + buffer.timeStamp = timeCurrent; + timeCurrent++; + YamiStatus status = decoder->decode(&buffer); + while ((output = decoder->getOutput())) { + EXPECT_TRUE(output->timeStamp > timeBeforeFlush); + outFrames++; + } + + if (status == YAMI_DECODE_FORMAT_CHANGE) { + //check format + const VideoFormatInfo* format = decoder->getFormatInfo(); + allocator->onFormatChange(format); + + //send buffer again + status = decoder->decode(&buffer); + if (YAMI_UNSUPPORTED == status) { + RecordProperty("skipped", true); + std::cout << "[ SKIPPED ] " << getFullTestName() + << " Hw does not support this decoder." << std::endl; + return; + } + EXPECT_EQ(YAMI_SUCCESS, status); + } + else { + EXPECT_EQ(YAMI_SUCCESS, status); + } + } + timeBeforeFlush = buffer.timeStamp; + + // No flush at last round, it has EOS at the end + if (i < (size - 1)) + decoder->flush(); + } + //drain the decoder + EXPECT_EQ(YAMI_SUCCESS, decoder->decode(NULL)); + while (decoder->getOutput()) { + outFrames++; + } + EXPECT_EQ(outFrames, size); +} + +TEST_P(DecodeApiTestLowlatency, Format_Change) +{ + SharedPtr decoder; + TestDecodeFrames frames = *GetParam(); + decoder.reset(createVideoDecoder(frames.getMime()), releaseVideoDecoder); + ASSERT_TRUE(bool(decoder)); + + VideoConfigBuffer config; + memset(&config, 0, sizeof(config)); + config.enableLowLatency = true; + ASSERT_EQ(YAMI_SUCCESS, decoder->start(&config)); + + VideoDecodeBuffer buffer; + memset(&buffer, 0, sizeof(buffer)); + FrameInfo info; + uint32_t inFrames = 0; + uint32_t outFrames = 0; + //keep previous resolution + + while (frames.getFrame(buffer, info)) { + buffer.flag = VIDEO_DECODE_BUFFER_FLAG_FRAME_END; + YamiStatus status = decoder->decode(&buffer); + if (status == YAMI_DECODE_FORMAT_CHANGE) { + + //send buffer again + status = decoder->decode(&buffer); + if (YAMI_UNSUPPORTED == status) { + RecordProperty("skipped", true); + std::cout << "[ SKIPPED ] " << getFullTestName() + << " Hw does not support this decoder." << std::endl; + return; + } + } + inFrames++; + while (bool(decoder->getOutput())) + outFrames++; + EXPECT_EQ(inFrames, outFrames); + } +} + +/** Teach Google Test how to print a TestDecodeFrames::Shared object */ +void PrintTo(const TestDecodeFrames::Shared& t, std::ostream* os) +{ + *os << *t; +} + +INSTANTIATE_TEST_CASE_P( + VaapiDecoder, DecodeApiTest, + ::testing::Values( + TestDecodeFrames::create(g_h264data, YAMI_MIME_H264), + TestDecodeFrames::create(g_h265data, YAMI_MIME_H265), + TestDecodeFrames::create(g_vp8data, YAMI_MIME_VP8), + TestDecodeFrames::create(g_vp9data, YAMI_MIME_VP9), + TestDecodeFrames::create(g_jpegdata, YAMI_MIME_JPEG))); + +INSTANTIATE_TEST_CASE_P( + VaapiDecoderLowlatency, DecodeApiTestLowlatency, + ::testing::Values( + TestDecodeFrames::create(g_h264data_lowlatency, YAMI_MIME_H264), + TestDecodeFrames::create(g_vp8data_lowlatency, YAMI_MIME_VP8), + TestDecodeFrames::create(g_vp9data_lowlatency, YAMI_MIME_VP9), + TestDecodeFrames::create(g_jpegdata_lowlatency, YAMI_MIME_JPEG))); +} diff --git a/decoder/FrameData.h b/decoder/FrameData.h new file mode 100644 index 0000000..2f18b90 --- /dev/null +++ b/decoder/FrameData.h @@ -0,0 +1,579 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// we put all data in header file.This is intended. +// it avoid static init order problem +// you should only include this in a cpp file +#ifndef FrameData_h +#define FrameData_h + +#include +#include + +namespace YamiMediaCodec { + +static const uint8_t s_avc8x8I[] = { + 0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, 0x28, 0xab, 0x6e, 0xcb, 0x2c, + 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, 0x07, 0x90, 0x80, 0x00, + 0x00, 0x00, 0x01, 0x68, 0xee, 0x3c, 0x30, 0x00, 0x00, 0x00, 0x01, 0x2e, + 0xc0, 0x80, 0x0f, 0x20, 0x00, 0x00, 0x00, 0x01, 0x65, 0xb8, 0x10, 0x06, + 0x42, 0x7f, 0xb8, 0x13, 0xf4, 0xff, 0xf8, 0x2c, 0x86, 0xea, 0xe6, 0x31, + 0x5e, 0x4a, 0x22, 0x19, 0xdd, 0xa9, 0x66, 0x33, 0xec, 0x13, 0x58, 0x39, + 0x65, 0xbb, 0xc6, 0x0d, 0x81, 0xda, 0x6d, 0x1c, 0xd5, 0xc0, 0x00, 0x00, + 0x00, 0x01 +}; + +static const uint8_t s_avc8x8P[] = { + 0x2e, 0x80, 0x80, 0x0f, 0x20, 0x00, 0x00, 0x00, 0x01, 0x41, 0xe1, 0x13, + 0x39, 0x09, 0xfe, 0x87, 0x67, 0x81, 0x0b, 0xcd, 0x6c, 0xff, 0xc7, 0x85, + 0x44, 0x90, 0xbe, 0x3b, 0xb2, 0x2d, 0x2b, 0x9b, 0xc1, 0x81, 0x47, 0xa1, + 0x10, 0xbb, 0x74, 0xb0, 0x96, 0xfe, 0x05, 0xe8, 0x6f, 0x44, 0x35, 0xb8, + 0x24, 0xe5, 0x7d, 0x97, 0x62, 0x6e, 0x36, 0x5d, 0x29, 0x51, 0x27, 0xa6, + 0x34, 0x41, 0xa0, 0x00, 0x00, 0x00, 0x01 +}; + +static const uint8_t s_avc8x8B[] = { + 0x0e, 0x80, 0x80, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x01, 0x01, 0xa8, 0x42, + 0x73, 0x90, 0x9f, 0xf8, 0xe3, 0xac, 0xc3, 0x6c, 0xf4, 0x31, 0xfb, 0xd3, + 0xd4, 0x0e, 0xbb, 0xb8, 0xf9, 0x6e, 0x6f, 0x2c, 0xdd, 0xe6, 0x1f, 0xf0, + 0x93, 0x37, 0x62, 0xc7, 0xbf, 0x17, 0xa8, 0x5a, 0xc4, 0xa4, 0x92, 0x7a, + 0x40, 0x0f, 0x2d, 0xfc, 0x11, 0xb8, 0x53, 0x4c, 0xb7, 0xac, 0xd0, 0x27, + 0x2f, 0xaf, 0x73, 0x6d, 0x49, 0xb8, 0x95, 0xd5, 0xd0, 0xbe, 0x51, 0xa5, + 0xfe, 0xaa, 0xb4 +}; + +static const uint8_t s_avc16x16[] = { + 0x00, 0x00, 0x00, 0x01, 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x5e, 0x84, + 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xc8, 0x3c, 0x48, + 0x96, 0x58, 0x00, 0x00, 0x00, 0x01, 0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0, + 0x00, 0x00, 0x01, 0x06, 0x05, 0xff, 0xff, 0xaa, 0xdc, 0x45, 0xe9, 0xbd, + 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef, + 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72, 0x65, 0x20, + 0x31, 0x34, 0x38, 0x20, 0x72, 0x32, 0x37, 0x32, 0x31, 0x20, 0x37, 0x32, + 0x64, 0x35, 0x33, 0x61, 0x62, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, + 0x34, 0x2f, 0x4d, 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, 0x41, 0x56, 0x43, + 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x20, 0x2d, 0x20, 0x43, 0x6f, 0x70, + 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x32, + 0x30, 0x31, 0x36, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, + 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6c, 0x61, + 0x6e, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, 0x68, + 0x74, 0x6d, 0x6c, 0x20, 0x2d, 0x20, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x3a, 0x20, 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d, 0x31, 0x20, 0x72, + 0x65, 0x66, 0x3d, 0x33, 0x20, 0x64, 0x65, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x3d, 0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, 0x61, 0x6c, 0x79, + 0x73, 0x65, 0x3d, 0x30, 0x78, 0x33, 0x3a, 0x30, 0x78, 0x31, 0x31, 0x33, + 0x20, 0x6d, 0x65, 0x3d, 0x68, 0x65, 0x78, 0x20, 0x73, 0x75, 0x62, 0x6d, + 0x65, 0x3d, 0x37, 0x20, 0x70, 0x73, 0x79, 0x3d, 0x31, 0x20, 0x70, 0x73, + 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e, 0x30, 0x30, 0x3a, 0x30, 0x2e, + 0x30, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x66, + 0x3d, 0x31, 0x20, 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x3d, + 0x31, 0x36, 0x20, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x61, 0x5f, 0x6d, 0x65, + 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69, 0x73, 0x3d, 0x31, + 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x31, 0x20, 0x63, 0x71, + 0x6d, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a, 0x6f, 0x6e, 0x65, + 0x3d, 0x32, 0x31, 0x2c, 0x31, 0x31, 0x20, 0x66, 0x61, 0x73, 0x74, 0x5f, + 0x70, 0x73, 0x6b, 0x69, 0x70, 0x3d, 0x31, 0x20, 0x63, 0x68, 0x72, 0x6f, + 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, + 0x3d, 0x2d, 0x32, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, + 0x31, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, 0x61, 0x64, 0x5f, + 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x31, 0x20, 0x73, 0x6c, + 0x69, 0x63, 0x65, 0x64, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, + 0x3d, 0x30, 0x20, 0x6e, 0x72, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x63, 0x69, + 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, + 0x6c, 0x61, 0x63, 0x65, 0x64, 0x3d, 0x30, 0x20, 0x62, 0x6c, 0x75, 0x72, + 0x61, 0x79, 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x3d, 0x30, 0x20, + 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x5f, + 0x69, 0x6e, 0x74, 0x72, 0x61, 0x3d, 0x30, 0x20, 0x62, 0x66, 0x72, 0x61, + 0x6d, 0x65, 0x73, 0x3d, 0x33, 0x20, 0x62, 0x5f, 0x70, 0x79, 0x72, 0x61, + 0x6d, 0x69, 0x64, 0x3d, 0x32, 0x20, 0x62, 0x5f, 0x61, 0x64, 0x61, 0x70, + 0x74, 0x3d, 0x31, 0x20, 0x62, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x3d, 0x30, + 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x3d, 0x31, 0x20, 0x77, 0x65, + 0x69, 0x67, 0x68, 0x74, 0x62, 0x3d, 0x31, 0x20, 0x6f, 0x70, 0x65, 0x6e, + 0x5f, 0x67, 0x6f, 0x70, 0x3d, 0x30, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x70, 0x3d, 0x32, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x3d, + 0x32, 0x35, 0x30, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x5f, 0x6d, + 0x69, 0x6e, 0x3d, 0x32, 0x35, 0x20, 0x73, 0x63, 0x65, 0x6e, 0x65, 0x63, + 0x75, 0x74, 0x3d, 0x34, 0x30, 0x20, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x5f, + 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x3d, 0x30, 0x20, 0x72, 0x63, + 0x5f, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, 0x61, 0x64, 0x3d, 0x34, + 0x30, 0x20, 0x72, 0x63, 0x3d, 0x63, 0x72, 0x66, 0x20, 0x6d, 0x62, 0x74, + 0x72, 0x65, 0x65, 0x3d, 0x31, 0x20, 0x63, 0x72, 0x66, 0x3d, 0x32, 0x33, + 0x2e, 0x30, 0x20, 0x71, 0x63, 0x6f, 0x6d, 0x70, 0x3d, 0x30, 0x2e, 0x36, + 0x30, 0x20, 0x71, 0x70, 0x6d, 0x69, 0x6e, 0x3d, 0x30, 0x20, 0x71, 0x70, + 0x6d, 0x61, 0x78, 0x3d, 0x36, 0x39, 0x20, 0x71, 0x70, 0x73, 0x74, 0x65, + 0x70, 0x3d, 0x34, 0x20, 0x69, 0x70, 0x5f, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x3d, 0x31, 0x2e, 0x34, 0x30, 0x20, 0x61, 0x71, 0x3d, 0x31, 0x3a, 0x31, + 0x2e, 0x30, 0x30, 0x00, 0x80, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, + 0x29, 0xff, 0xc5, 0xa1, 0x95, 0xea, 0xd5, 0xff, 0xf0, 0x34, 0x1d, 0x07, + 0x3a, 0xda, 0x37, 0x5f, 0x49, 0x5b, 0xe7, 0x40, 0x37, 0x78, 0x74, 0xd2, + 0xd8, 0xc0, 0xd5, 0xcb, 0xfb, 0xdc, 0x5a, 0xf7, 0xfb, 0xbe, 0x46, 0xfc, + 0x3f, 0x17, 0xd7, 0x94, 0x29, 0x85, 0x55, 0x0f, 0x2b, 0xbe, 0xfa, 0x14, + 0xe9, 0x6c, 0x80, 0xa1, 0xbd, 0x2a, 0x50, 0x2d +}; + +static const uint8_t s_avc8x18[] = { + 0x00, 0x00, 0x00, 0x01, 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x55, 0xe5, + 0x88, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, + 0xc8, 0x3c, 0x48, 0x96, 0x58, 0x00, 0x00, 0x00, 0x01, 0x68, 0xeb, 0xe3, + 0xcb, 0x22, 0xc0, 0x00, 0x00, 0x01, 0x06, 0x05, 0xff, 0xff, 0xab, 0xdc, + 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8, 0x20, 0xd9, + 0x23, 0xee, 0xef, 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, + 0x72, 0x65, 0x20, 0x31, 0x34, 0x32, 0x20, 0x72, 0x32, 0x33, 0x38, 0x39, + 0x20, 0x39, 0x35, 0x36, 0x63, 0x38, 0x64, 0x38, 0x20, 0x2d, 0x20, 0x48, + 0x2e, 0x32, 0x36, 0x34, 0x2f, 0x4d, 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, + 0x41, 0x56, 0x43, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x20, 0x2d, 0x20, + 0x43, 0x6f, 0x70, 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30, + 0x33, 0x2d, 0x32, 0x30, 0x31, 0x34, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, + 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, + 0x6f, 0x6c, 0x61, 0x6e, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, + 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x2d, 0x20, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x20, 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d, + 0x31, 0x20, 0x72, 0x65, 0x66, 0x3d, 0x33, 0x20, 0x64, 0x65, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x3d, 0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, + 0x61, 0x6c, 0x79, 0x73, 0x65, 0x3d, 0x30, 0x78, 0x33, 0x3a, 0x30, 0x78, + 0x31, 0x31, 0x33, 0x20, 0x6d, 0x65, 0x3d, 0x68, 0x65, 0x78, 0x20, 0x73, + 0x75, 0x62, 0x6d, 0x65, 0x3d, 0x37, 0x20, 0x70, 0x73, 0x79, 0x3d, 0x31, + 0x20, 0x70, 0x73, 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e, 0x30, 0x30, + 0x3a, 0x30, 0x2e, 0x30, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, + 0x72, 0x65, 0x66, 0x3d, 0x31, 0x20, 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e, + 0x67, 0x65, 0x3d, 0x31, 0x36, 0x20, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x61, + 0x5f, 0x6d, 0x65, 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69, + 0x73, 0x3d, 0x31, 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x31, + 0x20, 0x63, 0x71, 0x6d, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a, + 0x6f, 0x6e, 0x65, 0x3d, 0x32, 0x31, 0x2c, 0x31, 0x31, 0x20, 0x66, 0x61, + 0x73, 0x74, 0x5f, 0x70, 0x73, 0x6b, 0x69, 0x70, 0x3d, 0x31, 0x20, 0x63, + 0x68, 0x72, 0x6f, 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66, + 0x73, 0x65, 0x74, 0x3d, 0x2d, 0x32, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, + 0x64, 0x73, 0x3d, 0x31, 0x32, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, + 0x65, 0x61, 0x64, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, + 0x31, 0x20, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x64, 0x5f, 0x74, 0x68, 0x72, + 0x65, 0x61, 0x64, 0x73, 0x3d, 0x30, 0x20, 0x6e, 0x72, 0x3d, 0x30, 0x20, + 0x64, 0x65, 0x63, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, 0x69, + 0x6e, 0x74, 0x65, 0x72, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x3d, 0x30, 0x20, + 0x62, 0x6c, 0x75, 0x72, 0x61, 0x79, 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, + 0x74, 0x3d, 0x30, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x61, 0x69, + 0x6e, 0x65, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x3d, 0x30, 0x20, + 0x62, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x3d, 0x33, 0x20, 0x62, 0x5f, + 0x70, 0x79, 0x72, 0x61, 0x6d, 0x69, 0x64, 0x3d, 0x32, 0x20, 0x62, 0x5f, + 0x61, 0x64, 0x61, 0x70, 0x74, 0x3d, 0x31, 0x20, 0x62, 0x5f, 0x62, 0x69, + 0x61, 0x73, 0x3d, 0x30, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x3d, + 0x31, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x62, 0x3d, 0x31, 0x20, + 0x6f, 0x70, 0x65, 0x6e, 0x5f, 0x67, 0x6f, 0x70, 0x3d, 0x30, 0x20, 0x77, + 0x65, 0x69, 0x67, 0x68, 0x74, 0x70, 0x3d, 0x32, 0x20, 0x6b, 0x65, 0x79, + 0x69, 0x6e, 0x74, 0x3d, 0x32, 0x35, 0x30, 0x20, 0x6b, 0x65, 0x79, 0x69, + 0x6e, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x3d, 0x32, 0x35, 0x20, 0x73, 0x63, + 0x65, 0x6e, 0x65, 0x63, 0x75, 0x74, 0x3d, 0x34, 0x30, 0x20, 0x69, 0x6e, + 0x74, 0x72, 0x61, 0x5f, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x3d, + 0x30, 0x20, 0x72, 0x63, 0x5f, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, + 0x61, 0x64, 0x3d, 0x34, 0x30, 0x20, 0x72, 0x63, 0x3d, 0x63, 0x72, 0x66, + 0x20, 0x6d, 0x62, 0x74, 0x72, 0x65, 0x65, 0x3d, 0x31, 0x20, 0x63, 0x72, + 0x66, 0x3d, 0x32, 0x33, 0x2e, 0x30, 0x20, 0x71, 0x63, 0x6f, 0x6d, 0x70, + 0x3d, 0x30, 0x2e, 0x36, 0x30, 0x20, 0x71, 0x70, 0x6d, 0x69, 0x6e, 0x3d, + 0x30, 0x20, 0x71, 0x70, 0x6d, 0x61, 0x78, 0x3d, 0x36, 0x39, 0x20, 0x71, + 0x70, 0x73, 0x74, 0x65, 0x70, 0x3d, 0x34, 0x20, 0x69, 0x70, 0x5f, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x3d, 0x31, 0x2e, 0x34, 0x30, 0x20, 0x61, 0x71, + 0x3d, 0x31, 0x3a, 0x31, 0x2e, 0x30, 0x30, 0x00, 0x80, 0x00, 0x00, 0x01, + 0x65, 0x88, 0x84, 0x00, 0x2b, 0xff, 0xfe, 0xf6, 0x73, 0x7c, 0x0a, 0x6b, + 0x47, 0x32, 0xf5, 0x1f +}; + +static const uint8_t s_vp8_8x8I[] = { + 0x30, 0x02, 0x00, 0x9d, 0x01, 0x2a, 0x08, 0x00, 0x08, 0x00, 0x04, 0xc7, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x1a, 0x04, 0x00, 0x18, + 0x1b, 0xdc, 0x00, 0xfe, 0xf6, 0xf4, 0xff, 0xff, 0x3e, 0x1f, 0xff, 0xe7, + 0xac, 0x3f, 0xff, 0xcf, 0x1b, 0xfd, 0xff, 0xff, 0xcd, 0x76, 0xff, 0xfe, + 0x6b, 0xb7, 0xfc, 0xd7, 0x6e, 0x7f, 0xff, 0xcd, 0x76, 0xff, 0xfe, 0x6b, + 0xb7, 0xfc, 0xd0, 0x60, 0x00, 0x00, 0x00 +}; + +static const uint8_t s_vp8_8x8P1[] = { + 0x31, 0x04, 0x00, 0x13, 0x1c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x08, 0x68, 0x03, 0x18, 0x00, 0x30, 0x2d, 0xf4, 0x0c, 0x11, 0x44, 0x0e, + 0x91, 0xc5, 0xce, 0x62, 0xc8, 0x80, 0xea, 0xc6, 0x5f, 0x3b, 0xf1, 0x68, + 0xfe, 0xfa, 0x59, 0xc7, 0x5e, 0xf7, 0xc7, 0xf1, 0xd5, 0xae, 0x1d, 0xd6, + 0x53, 0xff, 0xe6, 0x91, 0x7f, 0xf9, 0xa4, 0x5e, 0xd8, 0xac, 0x43, 0x7f, + 0x65, 0xe4, 0x51, 0xd6, 0xee, 0xb2, 0x95, 0x83, 0x20, 0xe6, 0xe9, 0x4a, + 0x48, 0x28, 0xff, 0xde, 0xc8, 0x19, 0x88, 0xaf, 0xfd, 0xfd, 0x71, 0xbe, + 0x62, 0x83, 0x39, 0xef, 0x73, 0x7d, 0x42, 0x35, 0x3a, 0x45, 0x40, 0x05, + 0x71, 0xcc, 0x2b, 0xbf, 0xe9, 0x55, 0x58, 0xff, 0xfe, 0x6b, 0xb7, 0xff, + 0xf3, 0x5d, 0xbf, 0xe6, 0xbb, 0x7f, 0xfb, 0x56, 0xc6, 0xbf, 0xcf, 0xfe, + 0x31, 0xc8, 0xbb, 0x7f, 0xfe, 0x6b, 0xb7, 0xff, 0xf3, 0x5d, 0xbf, 0xe6, + 0x83, 0x00, 0x00, 0x00, 0x00 +}; + +static const uint8_t s_vp8_8x8P2[] = { + 0x91, 0x03, 0x00, 0x13, 0x1c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, + 0x08, 0x68, 0x03, 0x18, 0x00, 0x30, 0x2d, 0xf4, 0x0c, 0x11, 0x44, 0x0e, + 0x91, 0xc5, 0xce, 0x62, 0xc8, 0xbb, 0x00, 0xfe, 0xba, 0x5e, 0xa9, 0xec, + 0x5b, 0xff, 0xed, 0xe7, 0x79, 0x15, 0xa7, 0x12, 0xff, 0xff, 0xba, 0x3e, + 0x3f, 0xe9, 0x6f, 0xfd, 0x3d, 0x74, 0xfe, 0x27, 0x44, 0xb7, 0xff, 0x7d, + 0xd4, 0xff, 0xbe, 0x4f, 0xfd, 0x6a, 0x3f, 0xe2, 0x74, 0x25, 0xff, 0xe1, + 0xfd, 0xff, 0x89, 0xd6, 0x75, 0xdf, 0x58, 0x1f, 0xfe, 0x25, 0x7e, 0xf7, + 0xf9, 0x9c, 0x26, 0x3b, 0xf9, 0xa0, 0x00, 0x00, 0x00 +}; + +static const uint8_t s_vp8_16x16[] = { + 0xd0, 0x02, 0x00, 0x9d, 0x01, 0x2a, 0x10, 0x00, 0x10, 0x00, 0x04, 0xc7, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x1a, 0x04, 0x00, 0x18, + 0x17, 0x6f, 0x22, 0x12, 0xd0, 0xed, 0x83, 0x00, 0xfe, 0xff, 0x00, 0xaf, + 0xe4, 0xa3, 0xcb, 0xa7, 0x21, 0xff, 0xc1, 0xaf, 0xff, 0xc9, 0xe3, 0xfc, + 0xd3, 0xff, 0x71, 0x2d, 0x39, 0x3b, 0x63, 0xff, 0xc4, 0xfd, 0x6f, 0xeb, + 0x39, 0xd9, 0xc2, 0x34, 0xc3, 0x9c, 0xe9, 0x7f, 0x9c, 0xce, 0x75, 0x54, + 0x3b, 0x87, 0xfc, 0xf8, 0x64, 0xdf, 0xfe, 0x1c, 0xde, 0xbc, 0x23, 0x2c, + 0x99, 0xd0, 0x3f, 0xfe, 0x1a, 0x87, 0xde, 0x14, 0x8e, 0x05, 0xfd, 0x5f, + 0x7a, 0xaf, 0xf5, 0x5f, 0xf1, 0xfe, 0xdf, 0xd4, 0xb2, 0xf4, 0xf9, 0x57, + 0x7b, 0xec, 0xff, 0xff, 0x13, 0x58, 0x34, 0x0a, 0x71, 0xab, 0x04, 0xd0, + 0xb9, 0x25, 0xbf, 0xf9, 0xbc, 0x8f, 0xf3, 0xff, 0xee, 0x6e, 0x7d, 0x3b, + 0xff, 0x33, 0xbf, 0xd7, 0xfd, 0x7f, 0xef, 0xff, 0xef, 0xfe, 0xfe, 0x63, + 0xed, 0x40, 0x00, 0x00, 0x00 +}; + +static const uint8_t s_hevc8x8I[] = { + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x40, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, + 0x99, 0x19, 0x40, 0x90, 0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x01, 0x01, + 0x40, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x99, 0xa0, 0x88, 0x47, 0x2c, 0xbb, 0x19, 0x6e, 0xdb, 0x48, 0x80, + 0x40, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x07, 0x82, 0x00, 0x00, + 0x00, 0x01, 0x44, 0x01, 0xc0, 0x73, 0xe0, 0x09, 0x00, 0x00, 0x00, 0x01, + 0x26, 0x01, 0xaf, 0xc0, 0x35, 0x17, 0x7e, 0xc3, 0x4f, 0xc3, 0x4f, 0xfc, + 0xe1, 0x07, 0xfd, 0x25, 0xff, 0xe9, 0x7c, 0x4f, 0xf7, 0x93, 0x5f, 0xf2, + 0x0d, 0xef, 0x3a, 0x30, 0x86, 0x2a, 0xe1, 0xb4, 0xb9, 0xef, 0xed, 0xeb, + 0x86, 0x97, 0x7c, 0xf4, 0x45, 0xa4, 0x84, 0x9d, 0xaf, 0x80 +}; + +static const uint8_t s_hevc8x8P[] = { + 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0xd0, 0x45, 0x5f, 0xe0, 0xf2, 0x29, + 0xd8, 0x4f, 0xf8, 0x5a, 0x05, 0x28, 0x01, 0x0b, 0x54, 0x65, 0x34, 0x66, + 0xb5, 0x23, 0x83, 0x67, 0x4b, 0x68, 0x88, 0x17, 0x24, 0x5e, 0x75, 0x0c, + 0x62, 0xda, 0x42, 0xff, 0x4c, 0x4c, 0x7e, 0xb5, 0x83, 0x59, 0x9a, 0xcf, + 0x07, 0xb9, 0x29, 0x00, 0x6c, 0x76, 0xd6, 0x1e, 0x45, 0xfc, 0x36, 0x17, + 0xe8, 0xab, 0xcc, 0x65, 0x69, 0x3b, 0xc0, 0xb1, 0xfe, 0xb9, 0x7e, 0x70, + 0x5e, 0x4d, 0xa7, 0x62, 0x55, 0x9f, 0xf6, 0x46, 0xeb, 0x19, 0xe9, 0xa2, + 0x32, 0xc4, 0xed, 0x9f, 0x3f, 0xc1, 0xb3, 0x04, 0xbd, 0xd9, 0xbe, 0xd8, + 0x3f, 0xe0, 0xe9, 0xdd, 0xaa, 0x61 +}; + +static const uint8_t s_hevc8x8B[] = { + 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0xe0, 0x92, 0xfe, 0xf8, 0xf3, 0x1d, + 0x6f, 0xff, 0x9c, 0xdc, 0x78, 0x8c, 0x52, 0x0a, 0x58, 0x2d, 0xf6, 0x8d, + 0x70, 0x22, 0x80, 0x4a, 0xbc, 0x47, 0xad, 0x6c, 0x57, 0xae, 0xab, 0x60, + 0x01, 0x9b, 0xcb, 0xce, 0x38, 0x51, 0xff, 0x94, 0x19, 0xec, 0xfa, 0xff, + 0x0f, 0x3e, 0x33, 0xd8, 0x64, 0x94, 0xbb, 0xe6, 0x67, 0xfc, 0xd7, 0x67, + 0xe9, 0x0e, 0x2b, 0x47, 0x2e, 0xa7, 0xa4, 0x7f, 0xbc, 0xdf, 0xe5, 0x7d, + 0x13, 0xfa, 0x88, 0xfd, 0x81, 0xb0, 0xdf, 0xd8, 0x68, 0x1f, 0xfd, 0x9d, + 0xaa, 0xf5, 0x8a, 0x69, 0x00, 0xa5, 0x45, 0xb6, 0x7c, 0xe6, 0xeb, 0xb0, + 0x5f, 0x73, 0x86, 0x9a, 0x91, 0x20, 0x65, 0xd4, 0x1c, 0x10 +}; + +static const uint8_t s_hevc8x18[] = { + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x40, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, + 0x99, 0x19, 0x40, 0x90, 0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x01, 0x01, + 0x40, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x99, 0xa0, 0x88, 0x21, 0xcb, 0x11, 0xb1, 0x96, 0xed, 0xb4, 0x88, + 0x04, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x78, 0x20, + 0x00, 0x00, 0x00, 0x01, 0x44, 0x01, 0xc0, 0x73, 0xe0, 0x09, 0x00, 0x00, + 0x00, 0x01, 0x26, 0x01, 0xaf, 0xc0, 0x35, 0x0a, 0xbc, 0x5e, 0x1c, 0x9b, + 0xff, 0xb8, 0x4b, 0x1f, 0xc1, 0x8e, 0xfe, 0x5d, 0xd3, 0xff, 0xb9, 0x74, + 0x65, 0x8d, 0xc3, 0xd7, 0x57, 0x0e, 0x5f, 0xb4, 0x67, 0xf4, 0x8d, 0x59, + 0xfb, 0xbe, 0x56, 0x22, 0xd2, 0x8c, 0xae, 0x03, 0x73, 0x7f, 0x07, 0x48, + 0xbd, 0x1a, 0x79, 0xe0, 0x02, 0xeb, 0xce, 0xf6, 0xbc, 0x44, 0xaf, 0xff, + 0xd5, 0xcd, 0x7a, 0x96, 0xac, 0x0c, 0x95, 0xd3, 0x0f, 0x45, 0x82, 0x40, + 0xde, 0x18, 0x43, 0xd7, 0x8f, 0x05, 0x09, 0xa5, 0x1d, 0xd6, 0x59, 0x52, + 0xb6, 0x81, 0xdb, 0xca, 0xb5, 0x19, 0x32, 0xee, 0x0b, 0xc7, 0x41, 0x10, + 0x30, 0xdf, 0xff, 0xcc, 0x91, 0x77, 0x80 +}; + +static const uint8_t s_hevc16x16[] = { + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x40, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, + 0x99, 0x19, 0x40, 0x90, 0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x01, 0x01, + 0x40, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x99, 0xa0, 0x88, 0x45, 0xb1, 0x96, 0xed, 0xb4, 0x88, 0x04, 0x00, + 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x78, 0x20, 0x00, 0x00, + 0x00, 0x01, 0x44, 0x01, 0xc0, 0x73, 0xe0, 0x09, 0x00, 0x00, 0x00, 0x01, + 0x26, 0x01, 0xaf, 0xc0, 0xc6, 0x7c, 0x02, 0xea, 0x1a, 0x20, 0x17, 0x3b, + 0xa1, 0x75, 0xc5, 0xc3, 0xf0, 0x46, 0x94, 0xcc, 0x1f, 0x59, 0xd8, 0x3e, + 0xed, 0x5b, 0x37, 0x37, 0x55, 0x79, 0xbf, 0x32, 0x7f, 0x82, 0x0c, 0x58, + 0x31, 0xd5, 0xe8, 0x23, 0x75, 0xad, 0xb0, 0x75, 0xb4, 0x75, 0x94, 0x00, + 0x7c, 0xc7, 0x4f, 0x88, 0x60, 0xe6, 0x7f, 0x9b, 0x1d, 0xed, 0xea, 0xfd, + 0xcb, 0x4a, 0x37, 0x58, 0x9a, 0x16, 0x31, 0xeb, 0x7c, 0x18, 0x34, 0x21, + 0x9c, 0xf9, 0xd2, 0x7b, 0x64, 0x71, 0x20, 0x5f, 0xac, 0x25, 0xbb, 0x08, + 0x3e, 0xfe, 0xc3, 0x05, 0xd2, 0x1a, 0xc9, 0x78 +}; + +static const uint8_t s_vp9_8x8I[] = { + 0x82, 0x49, 0x83, 0x42, 0x00, 0x00, 0x70, 0x00, 0x76, 0x00, 0x38, 0x24, + 0x1c, 0x18, 0x54, 0x00, 0x00, 0x20, 0x20, 0x00, 0x15, 0x2f, 0xff, 0xff, + 0xee, 0x22, 0x80, 0x00 +}; + +static const uint8_t s_vp9_8x8P1[] = { + 0x86, 0x00, 0x40, 0x92, 0xf0, 0x01, 0x31, 0x00, 0x00, 0x0c, 0x20, 0x00, + 0x00, 0x00, 0xb9, 0xff, 0xfe, 0x5c, 0xd5, 0x2f, 0x09, 0xa7, 0x5c, 0x15, + 0xf1, 0x6e, 0xbf, 0xf6, 0xe1, 0x6f, 0xfe, 0xba, 0x3c, 0xff, 0x57, 0x29, + 0x2c, 0x00 +}; + +static const uint8_t s_vp9_8x8P2[] = { + 0x86, 0x00, 0x40, 0x92, 0x8c, 0x00, 0x4d, 0xc0, 0x00, 0x03, 0x20, 0x00, + 0x00, 0x22, 0xae, 0x2c, 0x2f, 0x86, 0xef, 0xff, 0xde, 0x91, 0xf2, 0x10, + 0xf0, 0x80 +}; + +static const uint8_t s_vp9_16x16[] = { + 0x82, 0x49, 0x83, 0x42, 0x00, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0x38, 0x24, + 0x1c, 0x18, 0x54, 0x00, 0x00, 0x20, 0x20, 0x00, 0x65, 0x7f, 0xff, 0xff, + 0xfe, 0x48, 0x21, 0xac, 0x8b, 0x51, 0x78, 0x41, 0x91, 0x6d, 0xfe, 0xa5, + 0x12, 0x0d, 0x82, 0x37, 0xb0, 0x47, 0xa6, 0x57, 0x3c, 0xdf, 0xe0, 0x97, + 0xe4, 0x11, 0xa1, 0x80, 0x1d, 0xee, 0xf9, 0x17, 0x26, 0xf9, 0xa2, 0x49, + 0x55, 0xf3, 0xb5, 0x86, 0x0e, 0x06, 0xa5, 0x58, 0x3f, 0x2d, 0x50, 0xbe, + 0x79, 0xf6, 0x85, 0x64, 0xe1, 0x0b, 0x23, 0x85, 0x65, 0x21, 0xe3, 0x7b, + 0xbf, 0x7b, 0x8f, 0x1d, 0x3c, 0xb6, 0x5f, 0xf6, 0xf6, 0x6a, 0x4c, 0xc7, + 0xc1, 0x79, 0x0b, 0xd3, 0x14, 0xfe, 0x13, 0x61, 0x1b, 0xbc, 0x00 +}; + +static const uint8_t s_jpeg1_8x8[] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x02, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, + 0x4c, 0x61, 0x76, 0x63, 0x35, 0x37, 0x2e, 0x32, 0x34, 0x2e, 0x31, 0x30, + 0x32, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, + 0x08, 0x08, 0x07, 0x07, 0x07, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, 0x08, + 0x08, 0x09, 0x09, 0x09, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x0a, 0x0a, + 0x0a, 0x0c, 0x0c, 0x0b, 0x0b, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x14, 0xff, + 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, + 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, + 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, + 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, + 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, + 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, + 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, + 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, + 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, + 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, + 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, + 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, + 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, + 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, + 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, + 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x08, 0x00, 0x08, 0x03, 0x01, 0x22, 0x00, + 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, + 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf5, 0xdd, 0x3f, 0xfe, + 0x4a, 0x36, 0xb1, 0xff, 0x00, 0x5e, 0x11, 0xff, 0x00, 0xe8, 0x36, 0x55, + 0xd0, 0xd7, 0x3d, 0xa7, 0xff, 0x00, 0xc9, 0x46, 0xd6, 0x3f, 0xeb, 0xc2, + 0x3f, 0xfd, 0x06, 0xca, 0xba, 0x1a, 0xc7, 0x0d, 0xaf, 0xb6, 0xe9, 0x6a, + 0xf5, 0x16, 0x9f, 0x23, 0xbb, 0x3d, 0x56, 0x79, 0x63, 0xbb, 0x77, 0xcb, + 0x30, 0x6f, 0x5e, 0x9a, 0x49, 0x59, 0x76, 0x5a, 0x5f, 0xd5, 0xb3, 0xff, + 0xd9 +}; + +static const uint8_t s_jpeg2_8x8[] = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x02, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x10, + 0x4c, 0x61, 0x76, 0x63, 0x35, 0x37, 0x2e, 0x32, 0x34, 0x2e, 0x31, 0x30, + 0x32, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, + 0x08, 0x08, 0x07, 0x07, 0x07, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, 0x08, + 0x08, 0x09, 0x09, 0x09, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x0a, 0x0a, + 0x0a, 0x0c, 0x0c, 0x0b, 0x0b, 0x0e, 0x0e, 0x0e, 0x11, 0x11, 0x14, 0xff, + 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, + 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, + 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, + 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, + 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, + 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, + 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, + 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, + 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, + 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, + 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, + 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, + 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, + 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, + 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, + 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, + 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, + 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, + 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, + 0xc0, 0x00, 0x11, 0x08, 0x00, 0x08, 0x00, 0x08, 0x03, 0x01, 0x22, 0x00, + 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, + 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf7, 0x9c, 0xdd, 0x8f, + 0xe1, 0x8d, 0xe9, 0x33, 0x75, 0xff, 0x00, 0x3c, 0x63, 0xfc, 0xea, 0x71, + 0x45, 0x71, 0xac, 0x96, 0xe9, 0x3f, 0xed, 0x1c, 0xcf, 0x55, 0x7f, 0xe3, + 0xc3, 0xf3, 0x74, 0xae, 0xfe, 0x6d, 0xb1, 0xba, 0x9a, 0xbf, 0x76, 0x1b, + 0xbe, 0x87, 0xff, 0xd9 +}; + +static const uint8_t s_jpeg16x16[] = { + 0xff, 0xd8, 0xff, 0xfe, 0x00, 0x10, 0x4c, 0x61, 0x76, 0x63, 0x35, 0x37, + 0x2e, 0x34, 0x38, 0x2e, 0x31, 0x30, 0x31, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x08, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x07, 0x07, 0x07, 0x08, 0x08, 0x08, 0x07, 0x07, 0x07, 0x06, + 0x06, 0x07, 0x07, 0x08, 0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x08, 0x08, + 0x08, 0x08, 0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0c, 0x0c, 0x0b, 0x0b, 0x0e, + 0x0e, 0x0e, 0x11, 0x11, 0x14, 0xff, 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x01, + 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, + 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, + 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, + 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, + 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, + 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, + 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, + 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, + 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, + 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, + 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, + 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, + 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, + 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, + 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, + 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, + 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, + 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, + 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, + 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x10, + 0x00, 0x10, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, + 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, + 0x3f, 0x00, 0xf7, 0xfa, 0xcb, 0xf0, 0xff, 0x00, 0xfc, 0x85, 0xbc, 0x5b, + 0xff, 0x00, 0x61, 0xb8, 0x3f, 0xf4, 0xc3, 0xa3, 0xd4, 0xb7, 0xbe, 0x1b, + 0xd3, 0xaf, 0xee, 0x64, 0xb9, 0x9a, 0x7d, 0x61, 0x1d, 0xf6, 0xee, 0x5b, + 0x6d, 0x73, 0x5b, 0xb3, 0x84, 0x6d, 0x50, 0xa3, 0x64, 0x16, 0x9a, 0x84, + 0x30, 0x27, 0x03, 0x9d, 0x91, 0x8d, 0xc7, 0x2c, 0x72, 0x49, 0x35, 0x91, + 0xa1, 0xf8, 0x43, 0xc3, 0x17, 0x1a, 0x9f, 0x8a, 0x05, 0xe6, 0x93, 0x67, + 0xa9, 0xb4, 0x3a, 0xc4, 0x31, 0x47, 0x3e, 0xa9, 0x1f, 0xf6, 0xad, 0xd8, + 0x8c, 0xe8, 0x9a, 0x54, 0x9b, 0x0d, 0xd6, 0xa4, 0x6e, 0x2e, 0x59, 0x43, + 0xbb, 0x15, 0x56, 0x94, 0x85, 0xce, 0x17, 0x02, 0xb3, 0xa8, 0xea, 0x73, + 0xc2, 0xd1, 0x8f, 0xc6, 0xec, 0xdc, 0x9e, 0xbe, 0xec, 0xbf, 0xba, 0x76, + 0x60, 0xe1, 0x82, 0xfa, 0xb6, 0x31, 0xca, 0xbd, 0x76, 0xde, 0x1a, 0x1c, + 0xd1, 0x8d, 0x08, 0xfb, 0xbf, 0xed, 0x14, 0x36, 0x94, 0xab, 0xa5, 0x2b, + 0x3d, 0x36, 0x57, 0xdc, 0xff, 0xd9 +}; + +struct FrameInfo { + uint32_t m_width; + uint32_t m_height; + FrameInfo() + : m_width(0) + , m_height(0) + { + } + + FrameInfo(uint32_t width, uint32_t height) + : m_width(width) + , m_height(height) + { + /* nothing */ + } +}; + +struct FrameData { + const uint8_t* m_data; + size_t m_size; + FrameInfo m_info; + FrameData(const uint8_t* data, size_t size, uint32_t width, uint32_t height) + : m_data(data) + , m_size(size) + , m_info(width, height) + { + /* nothing */ + } +}; + +const static FrameData g_avc8x8I(s_avc8x8I, N_ELEMENTS(s_avc8x8I), 8, 8); +const static FrameData g_avc8x8P(s_avc8x8P, N_ELEMENTS(s_avc8x8P), 8, 8); +const static FrameData g_avc8x8B(s_avc8x8B, N_ELEMENTS(s_avc8x8B), 8, 8); +const static FrameData g_avc8x16(s_avc8x18, N_ELEMENTS(s_avc8x18), 8, 18); +const static FrameData g_avc16x16(s_avc16x16, N_ELEMENTS(s_avc16x16), 16, 16); + +const static FrameData g_hevc8x8I(s_hevc8x8I, N_ELEMENTS(s_hevc8x8I), 8, 8); +const static FrameData g_hevc8x8P(s_hevc8x8P, N_ELEMENTS(s_hevc8x8P), 8, 8); +const static FrameData g_hevc8x8B(s_hevc8x8B, N_ELEMENTS(s_hevc8x8B), 8, 8); +const static FrameData g_hevc8x18(s_hevc8x18, N_ELEMENTS(s_hevc8x18), 8, 18); +const static FrameData g_hevc16x16(s_hevc16x16, N_ELEMENTS(s_hevc16x16), 16, 16); + +const static FrameData g_vp8_8x8I(s_vp8_8x8I, N_ELEMENTS(s_vp8_8x8I), 8, 8); +const static FrameData g_vp8_8x8P1(s_vp8_8x8P1, N_ELEMENTS(s_vp8_8x8P1), 8, 8); +const static FrameData g_vp8_8x8P2(s_vp8_8x8P2, N_ELEMENTS(s_vp8_8x8P2), 8, 8); +const static FrameData g_vp8_16x16(s_vp8_16x16, N_ELEMENTS(s_vp8_16x16), 16, 16); + +const static FrameData g_vp9_8x8I(s_vp9_8x8I, N_ELEMENTS(s_vp9_8x8I), 8, 8); +const static FrameData g_vp9_8x8P1(s_vp9_8x8P1, N_ELEMENTS(s_vp9_8x8P1), 8, 8); +const static FrameData g_vp9_8x8P2(s_vp9_8x8P2, N_ELEMENTS(s_vp9_8x8P2), 8, 8); +const static FrameData g_vp9_16x16(s_vp9_16x16, N_ELEMENTS(s_vp9_16x16), 16, 16); + +const static FrameData g_jpeg1_8x8(s_jpeg1_8x8, N_ELEMENTS(s_jpeg1_8x8), 8, 8); +const static FrameData g_jpeg2_8x8(s_jpeg2_8x8, N_ELEMENTS(s_jpeg2_8x8), 8, 8); +const static FrameData g_jpeg_16x16(s_jpeg16x16, N_ELEMENTS(s_jpeg16x16), 16, 16); + +const static FrameData g_EOF(NULL, 0, 0, 0); +}; +#endif diff --git a/decoder/Makefile.am b/decoder/Makefile.am new file mode 100644 index 0000000..392b34b --- /dev/null +++ b/decoder/Makefile.am @@ -0,0 +1,127 @@ +libyami_decoder_source_c = \ + vaapidecoder_base.cpp \ + vaapidecoder_host.cpp \ + vaapidecsurfacepool.cpp \ + vaapidecpicture.cpp \ + $(NULL) + +if BUILD_MPEG2_DECODER +libyami_decoder_source_c += vaapidecoder_mpeg2.cpp +endif + +if BUILD_H264_DECODER +libyami_decoder_source_c += vaapidecoder_h264.cpp +endif + +if BUILD_VP8_DECODER +libyami_decoder_source_c += vaapidecoder_vp8.cpp +endif + +if BUILD_H265_DECODER +libyami_decoder_source_c += vaapidecoder_h265.cpp +endif + +if BUILD_VP9_DECODER +libyami_decoder_source_c += vaapidecoder_vp9.cpp +endif + +if BUILD_VC1_DECODER +libyami_decoder_source_c += vaapidecoder_vc1.cpp +endif + +if BUILD_JPEG_DECODER +libyami_decoder_source_c += vaapiDecoderJPEG.cpp +endif + +if BUILD_FAKE_DECODER +libyami_decoder_source_c += vaapidecoder_fake.cpp +endif + +libyami_decoder_source_h = \ + ../interface/VideoCommonDefs.h \ + ../interface/VideoDecoderDefs.h \ + ../interface/VideoDecoderInterface.h \ + ../interface/VideoDecoderHost.h \ + $(NULL) + +libyami_decoder_source_h_priv = \ + vaapidecoder_base.h \ + vaapidecsurfacepool.h \ + vaapidecpicture.h \ + $(NULL) + +if BUILD_MPEG2_DECODER +libyami_decoder_source_h_priv += vaapidecoder_mpeg2.h +endif + +if BUILD_H264_DECODER +libyami_decoder_source_h_priv += vaapidecoder_h264.h +endif + +if BUILD_VP8_DECODER +libyami_decoder_source_h_priv += vaapidecoder_vp8.h +endif + +if BUILD_H265_DECODER +libyami_decoder_source_h_priv += vaapidecoder_h265.h +endif + +if BUILD_VP9_DECODER +libyami_decoder_source_h_priv += vaapidecoder_vp9.h +endif + +if BUILD_VC1_DECODER +libyami_decoder_source_h_priv += vaapidecoder_vc1.h +endif + +if BUILD_JPEG_DECODER +libyami_decoder_source_h_priv += vaapiDecoderJPEG.h +endif + +if BUILD_FAKE_DECODER +libyami_decoder_source_h_priv += vaapidecoder_fake.h +endif + +libyami_decoder_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + -ldl \ + $(NULL) + +if ENABLE_X11 +libyami_decoder_ldflags += $(LIBVA_X11_LIBS) $(X11_LIBS) +endif + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_decoder_cppflags = \ + $(LIBVA_CFLAGS) \ + $(LIBVA_DRM_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +if ENABLE_X11 +libyami_decoder_cppflags += $(LIBVA_X11_CFLAGS) +endif + +noinst_LTLIBRARIES = libyami_decoder.la +libyami_decoderincludedir = $(includedir)/libyami +libyami_decoderinclude_HEADERS = $(libyami_decoder_source_h) +noinst_HEADERS = $(libyami_decoder_source_h_priv) +libyami_decoder_la_SOURCES = $(libyami_decoder_source_c) +libyami_decoder_la_LDFLAGS = $(libyami_decoder_ldflags) $(AM_LDFLAGS) +libyami_decoder_la_CPPFLAGS = $(libyami_decoder_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in + + diff --git a/decoder/Makefile.unittest b/decoder/Makefile.unittest new file mode 100644 index 0000000..1967ee5 --- /dev/null +++ b/decoder/Makefile.unittest @@ -0,0 +1,97 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + $(NULL) + +if BUILD_VP8_DECODER +unittest_SOURCES += vaapidecoder_vp8_unittest.cpp +endif + +if BUILD_JPEG_DECODER +unittest_SOURCES += vaapiDecoderJPEG_unittest.cpp +endif + +if BUILD_H264_DECODER +unittest_SOURCES += vaapidecoder_h264_unittest.cpp +endif + +if BUILD_H265_DECODER +unittest_SOURCES += vaapidecoder_h265_unittest.cpp +endif + +if BUILD_MPEG2_DECODER +unittest_SOURCES += vaapidecoder_mpeg2_unittest.cpp +endif + +if BUILD_VC1_DECODER +unittest_SOURCES += vaapidecoder_vc1_unittest.cpp +endif + +if BUILD_VP9_DECODER +unittest_SOURCES += vaapidecoder_vp9_unittest.cpp +endif + +unittest_SOURCES += DecoderApi_unittest.cpp + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_decoder.la \ + $(top_builddir)/codecparsers/libyami_codecparser.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +# Separate the vaapidecoder_host_unittest so that we can detect static +# initialization bugs with the decoder factory. Separation is required +# since any derived decoder that is explicitly constructed in another test +# would hide such bugs. +noinst_PROGRAMS += unittest_host +unittest_host_SOURCES = \ + unittest_main.cpp \ + vaapidecoder_host_unittest.cpp \ + $(NULL) + +unittest_host_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_host_LDADD = \ + libyami_decoder.la \ + $(top_builddir)/codecparsers/libyami_codecparser.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_host_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_host_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest unittest_host + $(builddir)/unittest + $(builddir)/unittest_host diff --git a/decoder/unittest_main.cpp b/decoder/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/decoder/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/decoder/vaapiDecoderJPEG.cpp b/decoder/vaapiDecoderJPEG.cpp new file mode 100644 index 0000000..74a0597 --- /dev/null +++ b/decoder/vaapiDecoderJPEG.cpp @@ -0,0 +1,496 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// primary header +#include "vaapiDecoderJPEG.h" + +// library headers +#include "codecparsers/jpegParser.h" +#include "common/common_def.h" + +// system headers +#include + +using ::YamiParser::JPEG::Component; +using ::YamiParser::JPEG::FrameHeader; +using ::YamiParser::JPEG::HuffTable; +using ::YamiParser::JPEG::HuffTables; +using ::YamiParser::JPEG::Parser; +using ::YamiParser::JPEG::QuantTable; +using ::YamiParser::JPEG::QuantTables; +using ::YamiParser::JPEG::ScanHeader; +using ::YamiParser::JPEG::Defaults; +using ::std::function; +using ::std::bind; +using ::std::ref; + +namespace YamiMediaCodec { + +#define JPEG_SURFACE_NUM 2 + +struct Slice { + Slice() : data(NULL), start(0) , length(0) { } + + const uint8_t* data; + uint32_t start; + uint32_t length; +}; + +class VaapiDecoderJPEG::Impl +{ +public: + typedef function DecodeHandler; + + Impl(const DecodeHandler& start, const DecodeHandler& finish) + : m_startHandler(start) + , m_finishHandler(finish) + , m_parser() + , m_dcHuffmanTables(Defaults::instance().dcHuffTables()) + , m_acHuffmanTables(Defaults::instance().acHuffTables()) + , m_quantizationTables(Defaults::instance().quantTables()) + , m_slice() + , m_decodeStatus(YAMI_SUCCESS) + { + } + + YamiStatus decode(const uint8_t* data, const uint32_t size) + { + using namespace ::YamiParser::JPEG; + + //this mainly for codec flush, jpeg/mjpeg do not have to flush. + //just return success for this + if (!data || !size) + return YAMI_SUCCESS; + + Parser::Callback defaultCallback = + bind(&Impl::onMarker, ref(*this)); + Parser::Callback sofCallback = + bind(&Impl::onStartOfFrame, ref(*this)); + m_slice.data = data; + m_parser.reset(new Parser(data, size)); + m_parser->registerCallback(M_SOI, defaultCallback); + m_parser->registerCallback(M_EOI, defaultCallback); + m_parser->registerCallback(M_SOS, defaultCallback); + m_parser->registerCallback(M_DHT, defaultCallback); + m_parser->registerCallback(M_DQT, defaultCallback); + m_parser->registerStartOfFrameCallback(sofCallback); + + if (!m_parser->parse()) + m_decodeStatus = YAMI_FAIL; + + return m_decodeStatus; + } + + const FrameHeader::Shared& frameHeader() const + { + return m_parser->frameHeader(); + } + + const ScanHeader::Shared& scanHeader() const + { + return m_parser->scanHeader(); + } + + const unsigned restartInterval() const + { + return m_parser->restartInterval(); + } + + const HuffTables& dcHuffmanTables() const { return m_dcHuffmanTables; } + const HuffTables& acHuffmanTables() const { return m_acHuffmanTables; } + const QuantTables& quantTables() const { return m_quantizationTables; } + const Slice& slice() const { return m_slice; } + +private: + Parser::CallbackResult onMarker() + { + using namespace ::YamiParser::JPEG; + + m_decodeStatus = YAMI_SUCCESS; + + switch(m_parser->current().marker) { + case M_SOI: + m_slice.start = 0; + m_slice.length = 0; + break; + case M_SOS: + m_slice.start = m_parser->current().position + 1 + + m_parser->current().length; + break; + case M_EOI: + if (m_slice.start >= m_parser->current().position) { + // we can't have zero or negative length + m_decodeStatus = YAMI_FAIL; + } else { + m_slice.length = m_parser->current().position - m_slice.start; + m_decodeStatus = m_finishHandler(); + } + break; + case M_DQT: + m_quantizationTables = m_parser->quantTables(); + break; + case M_DHT: + m_dcHuffmanTables = m_parser->dcHuffTables(); + m_acHuffmanTables = m_parser->acHuffTables(); + break; + default: + m_decodeStatus = YAMI_FAIL; + } + + if (m_decodeStatus != YAMI_SUCCESS) + return Parser::ParseSuspend; + return Parser::ParseContinue; + } + + Parser::CallbackResult onStartOfFrame() + { + m_decodeStatus = m_startHandler(); + if (m_decodeStatus != YAMI_SUCCESS) + return Parser::ParseSuspend; + return Parser::ParseContinue; + } + + const DecodeHandler m_startHandler; // called after SOF + const DecodeHandler m_finishHandler; // called after EOI + + Parser::Shared m_parser; + HuffTables m_dcHuffmanTables; + HuffTables m_acHuffmanTables; + QuantTables m_quantizationTables; + + Slice m_slice; + + YamiStatus m_decodeStatus; +}; + +VaapiDecoderJPEG::VaapiDecoderJPEG() + : VaapiDecoderBase::VaapiDecoderBase() + , m_impl() + , m_picture() +{ + return; +} + +YamiStatus VaapiDecoderJPEG::fillPictureParam() +{ + const FrameHeader::Shared frame = m_impl->frameHeader(); + + const size_t numComponents = frame->components.size(); + + if (numComponents > 4) + return YAMI_FAIL; + + VAPictureParameterBufferJPEGBaseline* vaPicParam(NULL); + + if (!m_picture->editPicture(vaPicParam)) + return YAMI_FAIL; + + for (size_t i(0); i < numComponents; ++i) { + const Component::Shared& component = frame->components[i]; + vaPicParam->components[i].component_id = component->id; + vaPicParam->components[i].h_sampling_factor = component->hSampleFactor; + vaPicParam->components[i].v_sampling_factor = component->vSampleFactor; + vaPicParam->components[i].quantiser_table_selector = + component->quantTableNumber; + } + + vaPicParam->picture_width = frame->imageWidth; + vaPicParam->picture_height = frame->imageHeight; + vaPicParam->num_components = frame->components.size(); + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::fillSliceParam() +{ + const ScanHeader::Shared scan = m_impl->scanHeader(); + const FrameHeader::Shared frame = m_impl->frameHeader(); + const Slice& slice = m_impl->slice(); + VASliceParameterBufferJPEGBaseline *sliceParam(NULL); + + if (!m_picture->newSlice(sliceParam, slice.data + slice.start, slice.length)) + return YAMI_FAIL; + + for (size_t i(0); i < scan->numComponents; ++i) { + sliceParam->components[i].component_selector = + scan->components[i]->id; + sliceParam->components[i].dc_table_selector = + scan->components[i]->dcTableNumber; + sliceParam->components[i].ac_table_selector = + scan->components[i]->acTableNumber; + } + + sliceParam->restart_interval = m_impl->restartInterval(); + sliceParam->num_components = scan->numComponents; + sliceParam->slice_horizontal_position = 0; + sliceParam->slice_vertical_position = 0; + + int width = frame->imageWidth; + int height = frame->imageHeight; + int maxHSample = frame->maxHSampleFactor << 3; + int maxVSample = frame->maxVSampleFactor << 3; + int codedWidth; + int codedHeight; + + if (scan->numComponents == 1) { /* Noninterleaved Scan */ + if (frame->components.front() == scan->components.front()) { + /* Y mcu */ + codedWidth = width >> 3; + codedHeight = height >> 3; + } else { + /* Cr, Cb mcu */ + codedWidth = width >> 4; + codedHeight = height >> 4; + } + } else { /* Interleaved Scan */ + codedWidth = (width + maxHSample - 1) / maxHSample; + codedHeight = (height + maxVSample - 1) / maxVSample; + } + + sliceParam->num_mcus = codedWidth * codedHeight; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::loadQuantizationTables() +{ + using namespace ::YamiParser::JPEG; + + VAIQMatrixBufferJPEGBaseline* vaIqMatrix(NULL); + + if (!m_picture->editIqMatrix(vaIqMatrix)) + return YAMI_FAIL; + + size_t numTables = std::min( + N_ELEMENTS(vaIqMatrix->quantiser_table), size_t(NUM_QUANT_TBLS)); + + for (size_t i(0); i < numTables; ++i) { + const QuantTable::Shared& quantTable = m_impl->quantTables()[i]; + vaIqMatrix->load_quantiser_table[i] = bool(quantTable); + if (!quantTable) + continue; + assert(quantTable->precision == 0); + for (uint32_t j(0); j < DCTSIZE2; ++j) + vaIqMatrix->quantiser_table[i][j] = quantTable->values[j]; + } + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::loadHuffmanTables() +{ + using namespace ::YamiParser::JPEG; + + VAHuffmanTableBufferJPEGBaseline* vaHuffmanTable(NULL); + + if (!m_picture->editHufTable(vaHuffmanTable)) + return YAMI_FAIL; + + size_t numTables = std::min( + N_ELEMENTS(vaHuffmanTable->huffman_table), size_t(NUM_HUFF_TBLS)); + + for (size_t i(0); i < numTables; ++i) { + const HuffTable::Shared& dcTable = m_impl->dcHuffmanTables()[i]; + const HuffTable::Shared& acTable = m_impl->acHuffmanTables()[i]; + bool valid = bool(dcTable) && bool(acTable); + vaHuffmanTable->load_huffman_table[i] = valid; + if (!valid) + continue; + + // Load DC Table + memcpy(vaHuffmanTable->huffman_table[i].num_dc_codes, + &dcTable->codes[0], + sizeof(vaHuffmanTable->huffman_table[i].num_dc_codes)); + memcpy(vaHuffmanTable->huffman_table[i].dc_values, + &dcTable->values[0], + sizeof(vaHuffmanTable->huffman_table[i].dc_values)); + + // Load AC Table + memcpy(vaHuffmanTable->huffman_table[i].num_ac_codes, + &acTable->codes[0], + sizeof(vaHuffmanTable->huffman_table[i].num_ac_codes)); + memcpy(vaHuffmanTable->huffman_table[i].ac_values, + &acTable->values[0], + sizeof(vaHuffmanTable->huffman_table[i].ac_values)); + + memset(vaHuffmanTable->huffman_table[i].pad, + 0, sizeof(vaHuffmanTable->huffman_table[i].pad)); + } + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::decode(VideoDecodeBuffer* buffer) +{ + if (!buffer || !buffer->data) + return YAMI_SUCCESS; + + m_currentPTS = buffer->timeStamp; + + if (!m_impl.get()) + m_impl.reset(new VaapiDecoderJPEG::Impl( + bind(&VaapiDecoderJPEG::start, ref(*this), &m_configBuffer), + bind(&VaapiDecoderJPEG::finish, ref(*this)))); + + return m_impl->decode(buffer->data, buffer->size); +} + +#define RETURN_FORMAT(f) \ + do { \ + uint32_t fourcc = f; \ + DEBUG("jpeg format %.4s", (char*) & fourcc); \ + return fourcc; \ + } while (0) + +//get frame fourcc, return 0 for unsupport format +static uint32_t getFourcc(const FrameHeader::Shared& frame) +{ + if (frame->components.size() == 1) // monochrome image + RETURN_FORMAT(YAMI_FOURCC_Y800); + + if (frame->components.size() != 3) { + ERROR("unsupported component size %d", (int)frame->components.size()); + return 0; + } + int h1 = frame->components[0]->hSampleFactor; + int h2 = frame->components[1]->hSampleFactor; + int h3 = frame->components[2]->hSampleFactor; + int v1 = frame->components[0]->vSampleFactor; + int v2 = frame->components[1]->vSampleFactor; + int v3 = frame->components[2]->vSampleFactor; + if (h2 != h3 || v2 != v3) { + ERROR("unsupported format h1 = %d, h2 = %d, h3 = %d, v1 = %d, v2 = %d, v3 = %d", h1, h2, h3, v1, v2, v3); + return 0; + } + if (h1 == h2) { + if (v1 == v2) + RETURN_FORMAT(YAMI_FOURCC_444P); + if (v1 == 2 * v2) + RETURN_FORMAT(YAMI_FOURCC_422V); + } + else if (h1 == 2 * h2) { + if (v1 == v2) + RETURN_FORMAT(YAMI_FOURCC_422H); + if (v1 == 2 * v2) + RETURN_FORMAT(YAMI_FOURCC_IMC3); + } + ERROR("unsupported format h1 = %d, h2 = %d, h3 = %d, v1 = %d, v2 = %d, v3 = %d", h1, h2, h3, v1, v2, v3); + return 0; +} + +YamiStatus VaapiDecoderJPEG::start(VideoConfigBuffer* buffer) +{ + DEBUG("%s", __func__); + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::finish() +{ + if (!m_impl->frameHeader()) { + ERROR("Start of Frame (SOF) not found"); + return YAMI_FAIL; + } + + if (!m_impl->scanHeader()) { + ERROR("Start of Scan (SOS) not found"); + return YAMI_FAIL; + } + + YamiStatus status; + status = ensureContext(); + if (status != YAMI_SUCCESS) { + return status; + } + status = createPicture(m_picture, m_currentPTS); + if (status != YAMI_SUCCESS) { + ERROR("Could not create a VAAPI picture."); + return status; + } + + m_picture->m_timeStamp = m_currentPTS; + SurfacePtr surf; + surf = m_picture->getSurface(); + surf->setCrop(0, 0, m_videoFormatInfo.width, m_videoFormatInfo.height); + + status = fillSliceParam(); + if (status != YAMI_SUCCESS) { + ERROR("Failed to load VAAPI slice parameters."); + return status; + } + + status = fillPictureParam(); + if (status != YAMI_SUCCESS) { + ERROR("Failed to load VAAPI picture parameters"); + return status; + } + + status = loadQuantizationTables(); + if (status != YAMI_SUCCESS) { + ERROR("Failed to load VAAPI quantization tables"); + return status; + } + + status = loadHuffmanTables(); + + if (status != YAMI_SUCCESS) { + ERROR("Failed to load VAAPI huffman tables"); + return status; + } + + if (!m_picture->decode()) + return YAMI_FAIL; + + status = outputPicture(m_picture); + if (status != YAMI_SUCCESS) + return status; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderJPEG::reset(VideoConfigBuffer* buffer) +{ + DEBUG("%s", __func__); + + m_picture.reset(); + + m_impl.reset(); + + return VaapiDecoderBase::reset(buffer); +} + +YamiStatus VaapiDecoderJPEG::ensureContext() +{ + const FrameHeader::Shared frame = m_impl->frameHeader(); + if (!frame->isBaseline) { + ERROR("Unsupported JPEG profile. Only JPEG Baseline is supported."); + return YAMI_FAIL; + } + + if (!getFourcc(frame)) { + return YAMI_UNSUPPORTED; + } + if (setFormat(frame->imageWidth, frame->imageHeight, frame->imageWidth, + frame->imageHeight, JPEG_SURFACE_NUM, getFourcc(frame))) { + return YAMI_DECODE_FORMAT_CHANGE; + } + return ensureProfile(VAProfileJPEGBaseline); +} +} diff --git a/decoder/vaapiDecoderJPEG.h b/decoder/vaapiDecoderJPEG.h new file mode 100644 index 0000000..8a20045 --- /dev/null +++ b/decoder/vaapiDecoderJPEG.h @@ -0,0 +1,66 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiDecoderJPEG_h +#define vaapiDecoderJPEG_h + +// library headers +#include "vaapidecpicture.h" +#include "vaapidecoder_base.h" + +namespace YamiMediaCodec { + +class VaapiDecoderJPEG + : public VaapiDecoderBase { +public: + VaapiDecoderJPEG(); + + virtual ~VaapiDecoderJPEG() { } + + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus reset(VideoConfigBuffer*); + virtual YamiStatus decode(VideoDecodeBuffer*); + +private: + friend class FactoryTest; + friend class VaapiDecoderJPEGTest; + class Impl; + + YamiStatus fillPictureParam(); + YamiStatus fillSliceParam(); + + YamiStatus loadQuantizationTables(); + YamiStatus loadHuffmanTables(); + + YamiStatus finish(); + + YamiStatus ensureContext(); + + SharedPtr m_impl; + PicturePtr m_picture; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; + + DISALLOW_COPY_AND_ASSIGN(VaapiDecoderJPEG); +}; + +} // namespace YamiMediaCodec + +#endif // vaapiDecoderJPEG_h diff --git a/decoder/vaapiDecoderJPEG_unittest.cpp b/decoder/vaapiDecoderJPEG_unittest.cpp new file mode 100644 index 0000000..15efa0f --- /dev/null +++ b/decoder/vaapiDecoderJPEG_unittest.cpp @@ -0,0 +1,432 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiDecoderJPEG.h" + +// library headers +#include "common/Array.h" + +// system headers +#include + +namespace YamiMediaCodec { + +const static std::array g_Simple444P = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x0a, 0x03, + 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, + 0x1f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, + 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, + 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, + 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, + 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, + 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, + 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, + 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc4, 0x00, + 0x1f, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, + 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, + 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, + 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, + 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, + 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, + 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, + 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, + 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, + 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xda, 0x00, + 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xfe, + 0x7b, 0xb4, 0xcd, 0x33, 0xee, 0xfc, 0xa7, 0x9c, 0x76, 0xfc, 0x7b, 0x8f, + 0xc3, 0x1f, 0xd7, 0x9a, 0xff, 0x00, 0x72, 0x7e, 0x90, 0xbf, 0x48, 0x3b, + 0xbc, 0x77, 0xfb, 0x6a, 0xff, 0x00, 0x97, 0x9b, 0x55, 0xd9, 0x59, 0xeb, + 0xf1, 0x34, 0x7f, 0x56, 0x7d, 0x1c, 0xbe, 0x8e, 0x97, 0xfa, 0x82, 0xfa, + 0x87, 0x4a, 0x7f, 0xf2, 0xeb, 0xc9, 0x2e, 0xdf, 0x77, 0xcb, 0xa6, 0xaf, + 0xad, 0x5d, 0x30, 0xe0, 0x7c, 0xa3, 0xa0, 0xee, 0x3d, 0x3e, 0xb5, 0xfe, + 0x62, 0x62, 0xbe, 0x90, 0xd1, 0xfa, 0xd6, 0x27, 0xfd, 0xb7, 0xfe, 0x62, + 0x2b, 0x7f, 0xcb, 0xc7, 0xff, 0x00, 0x3f, 0x24, 0x7f, 0xa9, 0x98, 0x5f, + 0xa3, 0xa4, 0x7e, 0xab, 0x86, 0xff, 0x00, 0x62, 0x5f, 0xee, 0xf4, 0x7f, + 0xe5, 0xd2, 0xff, 0x00, 0x9f, 0x71, 0xfe, 0xe8, 0x69, 0x8a, 0xbc, 0x70, + 0x3a, 0x0e, 0xc3, 0xd4, 0x55, 0xfd, 0x21, 0x31, 0x58, 0xaf, 0xf6, 0xef, + 0xf6, 0x9a, 0xff, 0x00, 0x15, 0x5f, 0xf9, 0x7d, 0x53, 0xfb, 0xdf, 0xde, + 0x23, 0xe8, 0xe3, 0x84, 0xc2, 0xdb, 0x2f, 0xff, 0x00, 0x66, 0xc3, 0xef, + 0x4b, 0xfe, 0x5c, 0xd3, 0xf2, 0xfe, 0xe9, 0xd5, 0xed, 0x5f, 0x41, 0xf9, + 0x0a, 0xff, 0x00, 0x31, 0x31, 0x58, 0xac, 0x4f, 0xd6, 0x71, 0x1f, 0xed, + 0x15, 0xff, 0x00, 0x8f, 0x5b, 0xfe, 0x5f, 0x54, 0xff, 0x00, 0x9f, 0x92, + 0xfe, 0xf1, 0xfe, 0xa5, 0xe1, 0x30, 0x98, 0x5f, 0xaa, 0xe1, 0xbf, 0xd9, + 0xb0, 0xff, 0x00, 0xee, 0xf4, 0x7f, 0xe5, 0xcd, 0x3f, 0xf9, 0xf7, 0x1f, + 0xee, 0x9f, 0xff, 0xd9 +}; + +const static std::array g_Simple422V = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x0a, 0x03, + 0x01, 0x22, 0x00, 0x02, 0x21, 0x01, 0x03, 0x21, 0x01, 0xff, 0xc4, 0x00, + 0x16, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0a, 0xff, 0xc4, 0x00, + 0x23, 0x10, 0x00, 0x01, 0x03, 0x03, 0x02, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x11, 0x21, 0x41, + 0x51, 0x02, 0x31, 0x22, 0x32, 0x61, 0x71, 0x81, 0x91, 0xa1, 0xff, 0xc4, + 0x00, 0x14, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xff, 0xc4, 0x00, 0x2a, + 0x11, 0x00, 0x00, 0x03, 0x04, 0x08, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x04, 0x00, 0x07, 0x08, 0x21, + 0x02, 0x11, 0x13, 0x14, 0x44, 0x51, 0x53, 0x63, 0x23, 0x24, 0x31, 0x34, + 0x62, 0x71, 0x73, 0xd1, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, + 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xcf, 0x73, 0x63, 0x67, 0x2c, 0x69, + 0x35, 0x8b, 0x79, 0xb8, 0x9e, 0x91, 0xf2, 0x6a, 0x96, 0x86, 0xc3, 0x03, + 0x84, 0x6c, 0x2e, 0x31, 0xdd, 0x4d, 0x80, 0x40, 0xa0, 0xd8, 0x58, 0x64, + 0x25, 0x70, 0x30, 0x3d, 0x04, 0x9d, 0x44, 0x24, 0x4f, 0x3c, 0x1e, 0x7a, + 0xb3, 0x6b, 0x99, 0x81, 0xdd, 0x1b, 0xe5, 0xb7, 0xf9, 0xed, 0x8c, 0x55, + 0x51, 0x3e, 0xf0, 0x85, 0x52, 0x91, 0xb5, 0x09, 0xa8, 0x3b, 0x12, 0x66, + 0xa5, 0x2d, 0xb6, 0x51, 0x61, 0xc6, 0x16, 0x5d, 0xd8, 0xdc, 0x06, 0xca, + 0x5c, 0x20, 0xaa, 0xe8, 0x56, 0x5f, 0x4c, 0xa5, 0xd1, 0x94, 0xb4, 0x90, + 0xb2, 0xee, 0x85, 0x2a, 0x61, 0xb1, 0xc3, 0x93, 0x85, 0x2f, 0x4e, 0x8e, + 0xeb, 0x7f, 0xff, 0xd9 +}; + +const static std::array g_Simple422H = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x0a, 0x03, + 0x01, 0x22, 0x00, 0x02, 0x12, 0x01, 0x03, 0x12, 0x01, 0xff, 0xc4, 0x00, + 0x16, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0a, 0xff, 0xc4, 0x00, + 0x23, 0x10, 0x00, 0x01, 0x03, 0x03, 0x02, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x11, 0x21, 0x41, + 0x51, 0x02, 0x31, 0x22, 0x32, 0x61, 0x71, 0x81, 0x91, 0xa1, 0xff, 0xc4, + 0x00, 0x14, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xff, 0xc4, 0x00, 0x2d, + 0x11, 0x00, 0x00, 0x03, 0x04, 0x04, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x08, 0x00, 0x02, 0x03, 0x43, + 0x11, 0x17, 0x24, 0x62, 0x06, 0x16, 0x23, 0x31, 0x32, 0x33, 0x51, 0x52, + 0x53, 0x61, 0x63, 0x71, 0x91, 0xb1, 0xd1, 0xff, 0xda, 0x00, 0x0c, 0x03, + 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xcf, 0x73, 0x63, + 0x67, 0x2c, 0x69, 0x35, 0x8b, 0x79, 0xb8, 0x9e, 0x91, 0xf2, 0x6a, 0x96, + 0x86, 0xc3, 0x03, 0x84, 0x6c, 0x2e, 0x31, 0xdd, 0x4d, 0x80, 0x40, 0xa0, + 0xd8, 0x58, 0x64, 0x25, 0x70, 0x30, 0x3d, 0x04, 0x95, 0xaa, 0xc5, 0x0a, + 0x01, 0x87, 0x6f, 0xd2, 0x77, 0x3c, 0x43, 0x33, 0x47, 0x6b, 0x9c, 0xc7, + 0xdd, 0x1e, 0x18, 0xc8, 0x55, 0xa6, 0x8c, 0xe3, 0xe0, 0xda, 0x23, 0xe9, + 0x9a, 0x9b, 0x13, 0x7a, 0x1d, 0xe6, 0x54, 0x92, 0x4a, 0x74, 0x0a, 0xbf, + 0x72, 0xc2, 0x01, 0x93, 0x2d, 0x2b, 0xa7, 0xd8, 0x7e, 0xb2, 0x90, 0x92, + 0x4a, 0x15, 0xab, 0xf7, 0x2c, 0xc5, 0xf5, 0x65, 0x64, 0xc3, 0xe1, 0x8d, + 0xd6, 0xff, 0xd9 +}; + +const static std::array g_SimpleIMC3 = { + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, + 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x0a, 0x03, + 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, + 0x16, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0a, 0xff, 0xc4, 0x00, + 0x23, 0x10, 0x00, 0x01, 0x03, 0x03, 0x02, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x11, 0x21, 0x41, + 0x51, 0x02, 0x31, 0x22, 0x32, 0x61, 0x71, 0x81, 0x91, 0xa1, 0xff, 0xc4, + 0x00, 0x15, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x09, 0xff, 0xc4, 0x00, + 0x24, 0x11, 0x00, 0x00, 0x03, 0x06, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x08, 0x00, 0x02, 0x04, + 0x07, 0x23, 0x43, 0x16, 0x17, 0x31, 0x42, 0x44, 0x52, 0x61, 0x63, 0xff, + 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, + 0x00, 0xcf, 0x73, 0x63, 0x67, 0x2c, 0x69, 0x35, 0x8b, 0x79, 0xb8, 0x9e, + 0x91, 0xf2, 0x6a, 0x96, 0x86, 0xc3, 0x03, 0x84, 0x6c, 0x2e, 0x31, 0xdd, + 0x4d, 0x80, 0x40, 0xa0, 0xd8, 0x58, 0x64, 0x25, 0x70, 0x30, 0x3d, 0x04, + 0x9a, 0x55, 0x6a, 0x7e, 0x60, 0xe3, 0xc7, 0xaa, 0xdc, 0x88, 0xd6, 0x28, + 0xc1, 0xde, 0x5f, 0xc8, 0x1a, 0xf5, 0x24, 0x94, 0xb1, 0x2e, 0xf2, 0xfd, + 0xca, 0x56, 0xe1, 0x78, 0x85, 0xf4, 0xf0, 0xd0, 0x6f, 0xff, 0xd9 +}; + +class VaapiDecoderJPEGTest + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIDECODER_JPEG_TEST(name) \ + TEST_F(VaapiDecoderJPEGTest, name) + +VAAPIDECODER_JPEG_TEST(Factory) +{ + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_JPEG); + doFactoryTest(mimeTypes); +} + +class TestDecodeBuffer + : public VideoDecodeBuffer +{ +public: + typedef SharedPtr Shared; + + template + static Shared create( + const std::array& data, + const std::string& fourcc, + const uint32_t sliceStart) + { + Shared buffer(new TestDecodeBuffer(fourcc, sliceStart)); + buffer->data = const_cast(data.data()); + buffer->size = data.size(); + buffer->timeStamp = 0; + return buffer; + } + + uint32_t getFourcc() const + { + return VA_FOURCC(m_fourcc[0], m_fourcc[1], m_fourcc[2], m_fourcc[3]); + } + + friend std::ostream& operator <<(std::ostream& os, const TestDecodeBuffer& t) + { + os << t.m_fourcc; + return os; + } + +private: + TestDecodeBuffer(const std::string& fourcc, const uint32_t sliceStart) + : m_fourcc(fourcc) + , m_sliceStart(sliceStart) + { } + + std::string m_fourcc; + +public: + const uint32_t m_sliceStart; +}; + +class JPEGTest + : public ::testing::Test + , public ::testing::WithParamInterface +{ }; + +TEST_P(JPEGTest, Decode_Simple) +{ + VaapiDecoderJPEG decoder; + VideoConfigBuffer config; + VideoDecodeBuffer buffer = *GetParam(); + + config.flag = 0; + + ASSERT_EQ(YAMI_SUCCESS, decoder.start(&config)); + ASSERT_EQ(YAMI_DECODE_FORMAT_CHANGE, decoder.decode(&buffer)); + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + + SharedPtr output(decoder.getOutput()); + ASSERT_TRUE(bool(output)); + EXPECT_EQ(GetParam()->getFourcc(), output->fourcc); +} + +TEST_P(JPEGTest, Decode_SimpleMulti) +{ + /* + * Test MJPEG decoding. VaapiDecoderJPEG::decode will only accept + * one JPEG buffer at a time (i.e. the buffer must start at one SOI marker + * and end at one EOI marker. Otherwise it will indicate YAMI_FAIL. It + * is up to the caller to ensure the MJPEG is divided on single JPEG images + * for each call to decode. + */ + VaapiDecoderJPEG decoder; + VideoConfigBuffer config; + VideoDecodeBuffer buffer; + SharedPtr output; + const uint8_t *paramData = GetParam()->data; + const size_t paramSize = GetParam()->size; + std::vector mjpeg(paramSize * 2); // 2 images + + // First image + std::copy(paramData, paramData + paramSize, mjpeg.begin()); + // Second image + std::copy(paramData, paramData + paramSize, mjpeg.begin() + paramSize); + + config.flag = 0; + + // Set buffer at first jpeg image + buffer.data = const_cast(mjpeg.data()); + buffer.size = paramSize; // Length of first jpeg image data + buffer.timeStamp = 0; + + ASSERT_EQ(YAMI_SUCCESS, decoder.start(&config)); + + // Decode returns format change for the first frame decoding at first time. + ASSERT_EQ(YAMI_DECODE_FORMAT_CHANGE, decoder.decode(&buffer)); + + // Decode has been initiated by the last "decoder.decode(&buffer)" call. + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + + output = decoder.getOutput(); + ASSERT_TRUE(bool(output)); + EXPECT_EQ(GetParam()->getFourcc(), output->fourcc); + + // Set buffer at second jpeg image + buffer.data = const_cast(mjpeg.data() + paramSize); + buffer.size = paramSize; // Length of second jpeg image data + buffer.timeStamp = 1; + + //Decode the seconde jpeg image. + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + + output = decoder.getOutput(); + ASSERT_TRUE(bool(output)); + EXPECT_EQ(GetParam()->getFourcc(), output->fourcc); + + /* decoder should fail if more than one image in buffer */ + buffer.data = const_cast(mjpeg.data()); + buffer.size = mjpeg.size(); // Length of entire mjpeg + buffer.timeStamp = 3; + + // In this case, the decode should fail since it encounters a second image in the + // buffer. + ASSERT_EQ(YAMI_FAIL, decoder.decode(&buffer)); +} + +TEST_P(JPEGTest, Decode_SimpleTruncated) +{ + const size_t size(GetParam()->size); + + for (size_t i(1); i < size; ++i) { + VaapiDecoderJPEG decoder; + VideoConfigBuffer config; + VideoDecodeBuffer buffer; + + config.flag = 0; + + buffer.data = GetParam()->data; + buffer.size = i; + buffer.timeStamp = 0; + + ASSERT_EQ(YAMI_SUCCESS, decoder.start(&config)); + + if (i <= GetParam()->m_sliceStart + 1) { + // decode always return YAMI_FAIL since it doesn't have enough data. + EXPECT_EQ(YAMI_FAIL, decoder.decode(&buffer)) << i; + EXPECT_EQ(YAMI_FAIL, decoder.decode(&buffer)) << i; + } else { + // The decoder has enough data to produce a slice for encoding + // but does not encounter an EOI marker, so a fake EOI is inserted. + // This means the decoder will still attempt to decode the slice + // but cannot guarantee the final decoded output is correct since + // the slice may not actually be complete. + EXPECT_EQ(YAMI_DECODE_FORMAT_CHANGE, decoder.decode(&buffer)) << i; + EXPECT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)) << i; + } + } +} + +/** Teach Google Test how to print a TestDecodeBuffer::Shared object */ +void PrintTo(const TestDecodeBuffer::Shared& t, std::ostream* os) +{ + *os << *t; +} + +INSTANTIATE_TEST_CASE_P( + VaapiDecoder, JPEGTest, + ::testing::Values( + TestDecodeBuffer::create(g_Simple444P, "444P", 623), + TestDecodeBuffer::create(g_SimpleIMC3, "IMC3", 313), + TestDecodeBuffer::create(g_Simple422H, "422H", 321), + TestDecodeBuffer::create(g_Simple422V, "422V", 318))); + +} diff --git a/decoder/vaapidecoder_base.cpp b/decoder/vaapidecoder_base.cpp new file mode 100644 index 0000000..de6f7d5 --- /dev/null +++ b/decoder/vaapidecoder_base.cpp @@ -0,0 +1,449 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapidecoder_base.h" +#include "common/log.h" +#include "vaapi/vaapisurfaceallocator.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/VaapiUtils.h" +#include "vaapidecsurfacepool.h" +#include +#include // for setenv +#include +#include + +namespace YamiMediaCodec{ +typedef VaapiDecoderBase::PicturePtr PicturePtr; + +inline void unrefAllocator(SurfaceAllocator* allocator) +{ + allocator->unref(allocator); +} + +VaapiDecoderBase::VaapiDecoderBase() + : m_VAStarted(false) + , m_currentPTS(INVALID_PTS) +{ + INFO("base: construct()"); + m_externalDisplay.handle = 0, + m_externalDisplay.type = NATIVE_DISPLAY_AUTO, + memset(&m_videoFormatInfo, 0, sizeof(VideoFormatInfo)); + memset(&m_configBuffer, 0, sizeof(m_configBuffer)); + m_configBuffer.fourcc = YAMI_FOURCC_NV12; +} + +VaapiDecoderBase::~VaapiDecoderBase() +{ + INFO("base: deconstruct()"); + stop(); +} + +YamiStatus VaapiDecoderBase::createPicture(PicturePtr& picture, int64_t timeStamp /* , VaapiPictureStructure structure = VAAPI_PICTURE_STRUCTURE_FRAME */) +{ + /*accquire one surface from m_surfacePool in base decoder */ + SurfacePtr surface = createSurface(); + if (!surface) { + DEBUG("create surface failed"); + return YAMI_DECODE_NO_SURFACE; + } + + picture.reset(new VaapiDecPicture(m_context, surface, timeStamp)); + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderBase::start(VideoConfigBuffer* buffer) +{ + YamiStatus status; + + INFO("base: start()"); + + if (buffer == NULL) { + return YAMI_DECODE_INVALID_DATA; + } + + m_configBuffer = *buffer; + m_configBuffer.data = NULL; + m_configBuffer.size = 0; + + m_videoFormatInfo.width = buffer->width; + m_videoFormatInfo.height = buffer->height; + m_videoFormatInfo.surfaceWidth = buffer->surfaceWidth; + m_videoFormatInfo.surfaceHeight = buffer->surfaceHeight; + m_videoFormatInfo.surfaceNumber = buffer->surfaceNumber; + if (!m_configBuffer.fourcc) { + /* This just a workaround, user usually memset the VideoConfigBuffer to zero, and we will copy it to m_configBuffer. + We need remove fields only for internal user from VideoConfigBuffer + i.e., following thing should removed: + int32_t surfaceWidth; + int32_t surfaceHeight; + int32_t frameRate; + int32_t surfaceNumber; + VAProfile profile; + uint32_t flag; + uint32_t fourcc; + */ + m_videoFormatInfo.fourcc = m_configBuffer.fourcc = YAMI_FOURCC_NV12; + } + else { + m_videoFormatInfo.fourcc = m_configBuffer.fourcc; + } + + status = setupVA(buffer->surfaceNumber, buffer->profile); + if (status != YAMI_SUCCESS) + return status; + + DEBUG + ("m_videoFormatInfo video size: %d x %d, m_videoFormatInfo surface size: %d x %d", + m_videoFormatInfo.width, m_videoFormatInfo.height, + m_videoFormatInfo.surfaceWidth, m_videoFormatInfo.surfaceHeight); + +#ifdef __ENABLE_DEBUG__ + renderPictureCount = 0; + if (access("/tmp/yami", F_OK) == 0) { + m_dumpSurface = true; + } + else { + m_dumpSurface = false; + } + DEBUG("m_dumpSurface: %d", m_dumpSurface); +#endif + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderBase::reset(VideoConfigBuffer* buffer) +{ + YamiStatus status; + + INFO("base: reset()"); + if (buffer == NULL) { + return YAMI_DECODE_INVALID_DATA; + } + + flush(); + + status = terminateVA(); + if (status != YAMI_SUCCESS) + return status; + + status = start(buffer); + if (status != YAMI_SUCCESS) + return status; + + return YAMI_SUCCESS; +} + +void VaapiDecoderBase::stop(void) +{ + INFO("base: stop()"); + terminateVA(); + + m_currentPTS = INVALID_PTS; + + m_videoFormatInfo.valid = false; +} + +void VaapiDecoderBase::flush(void) +{ + + INFO("base: flush()"); + m_output.clear(); + + m_currentPTS = INVALID_PTS; +} + +SharedPtr VaapiDecoderBase::getOutput() +{ + SharedPtr frame; + if (m_output.empty()) + return frame; + frame = m_output.front(); + m_output.pop_front(); + return frame; +} + +const VideoFormatInfo *VaapiDecoderBase::getFormatInfo(void) +{ + INFO("base: getFormatInfo()"); + + if (!m_VAStarted) + return NULL; + + return &m_videoFormatInfo; +} + +YamiStatus +VaapiDecoderBase::setupVA(uint32_t numSurface, VAProfile profile) +{ + INFO("base: setup VA"); + + if (m_VAStarted) { + return YAMI_SUCCESS; + } + + if (m_display) { + WARNING("VA is partially started."); + return YAMI_FAIL; + } + + m_display = VaapiDisplay::create(m_externalDisplay); + + if (!m_display) { + ERROR("failed to create display"); + return YAMI_FAIL; + } + + VAConfigAttrib attrib; + attrib.type = VAConfigAttribRTFormat; + attrib.value = VA_RT_FORMAT_YUV420; + ConfigPtr config; + + YamiStatus status = VaapiConfig::create(m_display, profile, VAEntrypointVLD, &attrib, 1, config); + if (YAMI_SUCCESS != status) { + ERROR("failed to create config"); + return status; + } + + if (!m_externalAllocator) { + //use internal allocator + m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); + } else { + m_allocator = m_externalAllocator; + } + + m_configBuffer.surfaceNumber = numSurface; + m_surfacePool = VaapiDecSurfacePool::create(&m_configBuffer, m_allocator); + DEBUG("surface pool is created"); + if (!m_surfacePool) + return YAMI_FAIL; + std::vector surfaces; + m_surfacePool->getSurfaceIDs(surfaces); + if (surfaces.empty()) + return YAMI_FAIL; + int size = surfaces.size(); + m_context = VaapiContext::create(config, + m_videoFormatInfo.width, + m_videoFormatInfo.height, + 0, &surfaces[0], size); + + if (!m_context) { + ERROR("create context failed"); + return YAMI_FAIL; + } + + m_videoFormatInfo.surfaceWidth = m_videoFormatInfo.width; + m_videoFormatInfo.surfaceHeight = m_videoFormatInfo.height; + + m_VAStarted = true; + return YAMI_SUCCESS; +} + +bool VaapiDecoderBase::createAllocator() +{ + if (m_allocator) + return true; + m_display = VaapiDisplay::create(m_externalDisplay); + if (!m_display) { + ERROR("failed to create display"); + return false; + } + + if (!m_externalAllocator) { + //use internal allocator + m_allocator.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); + } + else { + m_allocator = m_externalAllocator; + } + if (!m_allocator) { + m_display.reset(); + ERROR("failed to create allocator"); + return false; + } + return true; +} + +bool VaapiDecoderBase::isSurfaceGeometryChanged() const +{ + return m_config.width < m_videoFormatInfo.surfaceWidth + || m_config.height < m_videoFormatInfo.surfaceHeight + || m_config.surfaceNumber != m_videoFormatInfo.surfaceNumber + || m_config.fourcc != m_videoFormatInfo.fourcc; +} + +YamiStatus VaapiDecoderBase::ensureSurfacePool() +{ + + if (!isSurfaceGeometryChanged()) + return YAMI_SUCCESS; + VideoFormatInfo& info = m_videoFormatInfo; + m_config.width = info.surfaceWidth; + m_config.height = info.surfaceHeight; + m_config.surfaceNumber = info.surfaceNumber; + m_config.fourcc = info.fourcc; + + if (!createAllocator()) + return YAMI_FAIL; + + m_surfacePool = VaapiDecSurfacePool::create(&m_config, m_allocator); + if (!m_surfacePool) + return YAMI_FAIL; + DEBUG("surface pool is created"); + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderBase::ensureProfile(VAProfile profile) +{ + YamiStatus status; + status = ensureSurfacePool(); + if (status != YAMI_SUCCESS) + return status; + + if (!m_display || !m_surfacePool) { + ERROR("bug: no display or surface pool"); + return YAMI_FAIL; + } + if (m_config.profile == profile) + return YAMI_SUCCESS; + + m_config.profile = profile; + VAConfigAttrib attrib; + attrib.type = VAConfigAttribRTFormat; + attrib.value = VA_RT_FORMAT_YUV420; + ConfigPtr config; + + status = VaapiConfig::create(m_display, profile, VAEntrypointVLD, &attrib, 1, config); + if (YAMI_SUCCESS != status) { + ERROR("failed to create config"); + return status; + } + + std::vector surfaces; + m_surfacePool->getSurfaceIDs(surfaces); + if (surfaces.empty()) + return YAMI_FAIL; + int size = surfaces.size(); + m_context = VaapiContext::create(config, + m_videoFormatInfo.width, + m_videoFormatInfo.height, + 0, &surfaces[0], size); + + if (!m_context) { + ERROR("create context failed"); + return YAMI_FAIL; + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderBase::terminateVA(void) +{ + INFO("base: terminate VA"); + m_output.clear(); + m_config.resetConfig(); + m_surfacePool.reset(); + m_allocator.reset(); + DEBUG("surface pool is reset"); + m_context.reset(); + m_display.reset(); + + m_VAStarted = false; + return YAMI_SUCCESS; +} + +void VaapiDecoderBase::setNativeDisplay(NativeDisplay * nativeDisplay) +{ + if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO) + return; + + m_externalDisplay = *nativeDisplay; +} + +void VaapiDecoderBase::releaseLock(bool lockable) +{ + if (!m_surfacePool) + return; + +} + +void VaapiDecoderBase::setAllocator(SurfaceAllocator* allocator) +{ + m_externalAllocator.reset(allocator,unrefAllocator); +} + +SurfacePtr VaapiDecoderBase::createSurface() +{ + SurfacePtr surface; + if (m_surfacePool) { + surface = m_surfacePool->acquire(); + } + return surface; +} + +struct VaapiDecoderBase::VideoFrameRecycler { + VideoFrameRecycler(const SurfacePtr& surface) + : m_surface(surface) + { + } + void operator()(VideoFrame* frame) {} +private: + SurfacePtr m_surface; +}; + +YamiStatus VaapiDecoderBase::outputPicture(const PicturePtr& picture) +{ + SurfacePtr surface = picture->getSurface(); + SharedPtr frame(surface->m_frame.get(), VideoFrameRecycler(surface)); + frame->timeStamp = picture->m_timeStamp; + m_output.push_back(frame); + return YAMI_SUCCESS; +} + +VADisplay VaapiDecoderBase::getDisplayID() +{ + if (!m_display) + return NULL; + return m_display->getID(); +} + +#define CHECK(f) \ + do { \ + if (m_videoFormatInfo.f != f) { \ + m_videoFormatInfo.f = f; \ + changed = true; \ + } \ + } while (0) + +bool VaapiDecoderBase::setFormat(uint32_t width, uint32_t height, uint32_t surfaceWidth, uint32_t surfaceHeight, + uint32_t surfaceNumber, uint32_t fourcc) +{ + bool changed = false; + CHECK(width); + CHECK(height); + CHECK(surfaceWidth); + CHECK(surfaceHeight); + CHECK(surfaceNumber); + CHECK(fourcc); + //this not true, but it's only way to let user get format info + m_VAStarted = true; + return changed; +} + +} //namespace YamiMediaCodec diff --git a/decoder/vaapidecoder_base.h b/decoder/vaapidecoder_base.h new file mode 100644 index 0000000..a676807 --- /dev/null +++ b/decoder/vaapidecoder_base.h @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef vaapidecoder_base_h +#define vaapidecoder_base_h + +#include "common/log.h" +#include "common/common_def.h" +#include "VideoDecoderInterface.h" +#include "vaapi/vaapiptrs.h" +#include "vaapidecpicture.h" +#include +#include +#include +#include +#ifdef HAVE_VA_X11 +#include +#else +typedef unsigned int Display; +#endif + +template class FactoryTest; + +namespace YamiMediaCodec{ + +#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) +#define ALIGN_MB(a) (((a) + 15 ) & (~15)) + +#define INVALID_PTS ((uint64_t)-1) + +struct VideoDecoderConfig { + /// it is the frame size, height is 1088 for h264 1080p stream + uint32_t width; + uint32_t height; + uint32_t fourcc; + uint32_t surfaceNumber; + VAProfile profile; + + VideoDecoderConfig() + { + resetConfig(); + } + void resetConfig() + { + width = 0; + height = 0; + fourcc = 0; + surfaceNumber = 0; + profile = VAProfileNone; + } +}; + +class VaapiDecoderBase:public IVideoDecoder { + public: + typedef SharedPtr PicturePtr; + + VaapiDecoderBase(); + virtual ~ VaapiDecoderBase(); + + virtual YamiStatus createPicture(PicturePtr& picture, int64_t timeStamp /* , VaapiPictureStructure structure = VAAPI_PICTURE_STRUCTURE_FRAME */); + virtual YamiStatus start(VideoConfigBuffer* buffer); + virtual YamiStatus reset(VideoConfigBuffer* buffer); + virtual void stop(void); + //virtual YamiStatus decode(VideoDecodeBuffer *buffer); + virtual void flush(void); + virtual const VideoFormatInfo *getFormatInfo(void); + virtual SharedPtr getOutput(); + + /* native window related functions */ + void setNativeDisplay(NativeDisplay * nativeDisplay); + void releaseLock(bool lockable=false); + + void setAllocator(SurfaceAllocator* allocator); + + //do not use this, we will remove this in near future + virtual VADisplay getDisplayID(); + protected: + YamiStatus setupVA(uint32_t numSurface, VAProfile profile); + YamiStatus terminateVA(void); + YamiStatus updateReference(void); + YamiStatus outputPicture(const PicturePtr& picture); + SurfacePtr createSurface(); + YamiStatus ensureProfile(VAProfile profile); + + //set format to m_videoFormatInfo, return true if something changed. + bool setFormat(uint32_t width, uint32_t height, uint32_t surfaceWidth, uint32_t surfaceHeight, + uint32_t surfaceNumber, uint32_t fourcc = YAMI_FOURCC_NV12); + bool isSurfaceGeometryChanged() const; + + NativeDisplay m_externalDisplay; + DisplayPtr m_display; + ContextPtr m_context; + + VideoConfigBuffer m_configBuffer; + VideoFormatInfo m_videoFormatInfo; + + + /* allocate all surfaces need for decoding & display + * in one pool, the pool will responsable for allocating + * empty surface, recycle used surface. + */ + DecSurfacePoolPtr m_surfacePool; + SharedPtr m_allocator; + SharedPtr m_externalAllocator; + + /* output queue*/ + typedef std::deque > OutputQueue; + OutputQueue m_output; + + + bool m_VAStarted; + + uint64_t m_currentPTS; + + private: + bool createAllocator(); + YamiStatus ensureSurfacePool(); + VideoDecoderConfig m_config; + + struct VideoFrameRecycler; + +#ifdef __ENABLE_DEBUG__ + int renderPictureCount; + bool m_dumpSurface; +#endif + +}; +} +#endif // vaapidecoder_base_h diff --git a/decoder/vaapidecoder_factory.h b/decoder/vaapidecoder_factory.h new file mode 100644 index 0000000..98f63e7 --- /dev/null +++ b/decoder/vaapidecoder_factory.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_factory_h +#define vaapidecoder_factory_h + +#include "common/factory.h" +#include "VideoDecoderInterface.h" + +namespace YamiMediaCodec { + +typedef Factory VaapiDecoderFactory; + +} // namespace YamiMediaCodec +#endif // vaapidecoder_factory_h diff --git a/decoder/vaapidecoder_fake.cpp b/decoder/vaapidecoder_fake.cpp new file mode 100644 index 0000000..729cbbb --- /dev/null +++ b/decoder/vaapidecoder_fake.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "vaapidecoder_fake.h" + +namespace YamiMediaCodec{ +typedef VaapiDecoderFake::PicturePtr PicturePtr; + +VaapiDecoderFake::VaapiDecoderFake(int32_t width, int32_t height) + :m_width(width), m_height(height), m_first(true) +{ +} + +VaapiDecoderFake::~VaapiDecoderFake() +{ + stop(); +} + +YamiStatus VaapiDecoderFake::start(VideoConfigBuffer* buffer) +{ + DEBUG("VP9: start() buffer size: %d x %d", buffer->width, + buffer->height); + + VideoConfigBuffer config; + config = *buffer; + config.profile = VAProfileH264Main; + config.surfaceNumber = FAKE_EXTRA_SURFACE_NUMBER; + config.width = m_width; + config.height = m_height; + config.surfaceWidth = m_width; + config.surfaceHeight = m_height; + return VaapiDecoderBase::start(&config); +} + +YamiStatus VaapiDecoderFake::decode(VideoDecodeBuffer* buffer) +{ + if (m_first) { + m_first = false; + return YAMI_DECODE_FORMAT_CHANGE; + } + PicturePtr picture; + YamiStatus status = createPicture(picture, buffer->timeStamp); + if (status != YAMI_SUCCESS) + return status; + return outputPicture(picture); +} + +} + diff --git a/decoder/vaapidecoder_fake.h b/decoder/vaapidecoder_fake.h new file mode 100644 index 0000000..c3da621 --- /dev/null +++ b/decoder/vaapidecoder_fake.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_fake_h +#define vaapidecoder_fake_h + +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" + + +namespace YamiMediaCodec{ +enum { + FAKE_EXTRA_SURFACE_NUMBER = 8, +}; + +class VaapiDecoderFake:public VaapiDecoderBase { + public: + typedef SharedPtr PicturePtr; + VaapiDecoderFake(int32_t width, int32_t height); + virtual ~ VaapiDecoderFake(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus decode(VideoDecodeBuffer*); + + private: + int32_t m_width; + int32_t m_height; + bool m_first; +}; + +}; + +#endif + diff --git a/decoder/vaapidecoder_h264.cpp b/decoder/vaapidecoder_h264.cpp new file mode 100644 index 0000000..50529e0 --- /dev/null +++ b/decoder/vaapidecoder_h264.cpp @@ -0,0 +1,1841 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapidecoder_h264.h" + +#include "common/log.h" +#include "common/nalreader.h" + +#include "vaapi/vaapiptrs.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapidecpicture.h" + +#include + +namespace YamiMediaCodec { +typedef VaapiDecoderH264::PicturePtr PicturePtr; +using std::bind; +using std::placeholders::_1; +using std::ref; +using std::vector; +using namespace YamiParser::H264; + +class VaapiDecPictureH264 : public VaapiDecPicture { +public: + VaapiDecPictureH264(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiDecPicture(context, surface, timeStamp) + , m_idrFlag(false) + , m_picStructure(VAAPI_PICTURE_FRAME) + , m_longTermRefFlag(false) + , m_shortTermRefFlag(false) + , m_topFieldOrderCnt(0) + , m_bottomFieldOrderCnt(0) + , m_pocMsb(0) + , m_pocLsb(0) + , m_poc(0) + , m_frameNumOffset(0) + , m_frameNum(0) + , m_frameNumWrap(0) + , m_picNum(0) + , m_longTermFrameIdx(0) + , m_longTermPicNum(0) + , m_picOutputFlag(true) + , m_isReference(false) + , m_hasMmco5(false) + , m_isSecondField(false) + { + } + VaapiDecPictureH264() {} + + PicturePtr allocPicture() + { + PicturePtr picture( + new VaapiDecPictureH264(m_context, m_surface, m_timeStamp)); + assert(picture); + return picture; + } + + PicturePtr allocField(bool isBottomField) + { + PicturePtr field = allocPicture(); + *field = *this; + + field->m_picStructure = VAAPI_PICTURE_TOP_FIELD; + field->m_poc = this->m_topFieldOrderCnt; + + if (isBottomField) { + field->m_picStructure = VAAPI_PICTURE_BOTTOM_FIELD; + field->m_poc = this->m_bottomFieldOrderCnt; + } + + return field; + } + + PicturePtr allocDummyPicture(int32_t frameNum) + { + PicturePtr picture = allocPicture(); + *picture = *this; + + picture->m_picStructure = VAAPI_PICTURE_FRAME; + picture->m_frameNum = frameNum; + picture->m_picOutputFlag = false; + picture->m_idrFlag = false; + picture->m_poc = 0x7fffffff; + + picture->m_isReference = true; + picture->m_longTermRefFlag = false; + picture->m_shortTermRefFlag = true; + + return picture; + } + + bool m_idrFlag; + VaapiPictureType m_picStructure; + bool m_longTermRefFlag; + bool m_shortTermRefFlag; + int32_t m_topFieldOrderCnt; + int32_t m_bottomFieldOrderCnt; + int32_t m_pocMsb; + uint16_t m_pocLsb; + int32_t m_poc; + int32_t m_frameNumOffset; + int32_t m_frameNum; + int32_t m_frameNumWrap; + int32_t m_picNum; + int32_t m_longTermFrameIdx; + int32_t m_longTermPicNum; + bool m_picOutputFlag; + bool m_isReference; + bool m_hasMmco5; + bool m_isSecondField; + PicturePtr m_complementField; +}; + +static bool isISlice(uint32_t sliceType) +{ + return (IS_I_SLICE(sliceType) || IS_SI_SLICE(sliceType)); +} + +static bool isPSlice(uint32_t sliceType) +{ + return (IS_P_SLICE(sliceType) || IS_SP_SLICE(sliceType)); +} + +static bool isBSlice(uint32_t sliceType) { return (IS_B_SLICE(sliceType)); } + +static bool isIdr(const PicturePtr& picture) { return picture->m_idrFlag; } + +static bool isFrame(const PicturePtr& picture) +{ + return picture->m_picStructure == VAAPI_PICTURE_FRAME; +} + +static bool isField(const PicturePtr& picture) +{ + return picture->m_picStructure != VAAPI_PICTURE_FRAME; +} + +static bool isTopField(const PicturePtr& picture) +{ + return picture->m_picStructure == VAAPI_PICTURE_TOP_FIELD; +} + +static bool isBottomField(const PicturePtr& picture) +{ + return picture->m_picStructure == VAAPI_PICTURE_BOTTOM_FIELD; +} + +static bool isSecondField(const PicturePtr& picture) +{ + return picture->m_isSecondField; +} + +inline bool isOutputNeeded(const PicturePtr& picture) +{ + return picture->m_picOutputFlag; +} + +inline bool isReference(const PicturePtr& picture) +{ + return picture->m_isReference; +} + +inline bool isUnusedPicture(const PicturePtr& picture) +{ + return !isReference(picture) && !isOutputNeeded(picture); +} + +inline bool isShortTermReference(const PicturePtr& picture) +{ + return picture->m_shortTermRefFlag && picture->m_isReference; +} + +inline bool isLongTermReference(const PicturePtr& picture) +{ + return picture->m_longTermRefFlag && picture->m_isReference; +} + +void markUnusedReference(const PicturePtr& picture) +{ + picture->m_isReference = false; + DEBUG("mark pic(poc: %d frameNumWrap: %d) as unused ref", picture->m_poc, + picture->m_frameNumWrap); +} + +void markLongTermReference(const PicturePtr& picture) +{ + picture->m_isReference = true; + picture->m_longTermRefFlag = true; + picture->m_shortTermRefFlag = false; + + DEBUG("mark pic(poc: %d frameNumWrap: %d) as LongTerm ref", picture->m_poc, + picture->m_frameNumWrap); +} + +void markUnusedLongTermRefWithMaxIndex(const PicturePtr& picture, + int32_t maxLongTermFrameIdx) +{ + if (isLongTermReference(picture) + && (picture->m_longTermFrameIdx > maxLongTermFrameIdx)) + markUnusedReference(picture); +} + +inline bool findComplementaryField(const PicturePtr& picture, int32_t frameNum, + VaapiPictureType picStructure) +{ + return ((picture->m_frameNum == frameNum) + && (picture->m_picStructure + picStructure + == VAAPI_PICTURE_FRAME)); +} + +inline bool matchPocLsb(const PicturePtr& picture, int32_t poc) +{ + return picture->m_pocLsb == poc; +} + +inline bool matchPicNum(const PicturePtr& picture, int32_t picNum) +{ + return picture->m_picNum == picNum; +} + +inline bool matchFrameNumInShortTermList(const PicturePtr& picture, + int32_t frameNum) +{ + return (picture->m_frameNum == frameNum && picture->m_shortTermRefFlag + && picture->m_isReference); +} + +inline bool matchShortTermFrameNumWrap(const PicturePtr& picture, + int32_t frameNumWrap) +{ + return (isShortTermReference(picture) + && picture->m_frameNumWrap == frameNumWrap); +} + +inline bool matchShortTermPicNum(const PicturePtr& picture, int32_t picNum) +{ + return (isShortTermReference(picture) && picture->m_picNum == picNum); +} + +inline bool matchLongTermPicNum(const PicturePtr& picture, + int32_t longTermPicNum) +{ + return (isLongTermReference(picture) + && picture->m_longTermPicNum == longTermPicNum); +} + +inline bool matchPicStructure(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_picStructure == picture2->m_picStructure; +} + +inline bool ascCompareFrameNumWrap(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_frameNumWrap < picture2->m_frameNumWrap; +} + +inline bool decCompareFrameNumWrap(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_frameNumWrap > picture2->m_frameNumWrap; +} + +inline bool decCompareStPicNum(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_picNum > picture2->m_picNum; +} + +inline bool ascCompareLtPicNum(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_longTermPicNum < picture2->m_longTermPicNum; +} + +inline bool ascCompareLtFrameIndex(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_longTermFrameIdx < picture2->m_longTermFrameIdx; +} + +inline bool decComparePoc(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_poc > picture2->m_poc; +} + +inline bool ascComparePoc(const PicturePtr& picture1, + const PicturePtr& picture2) +{ + return picture1->m_poc < picture2->m_poc; +} + +inline bool VaapiDecoderH264::DPB::PocLess:: +operator()(const PicturePtr& left, const PicturePtr& right) const +{ + return left->m_poc <= right->m_poc; +} + +bool checkMMCO5(DecRefPicMarking decRefPicMarking) +{ + for (uint32_t i = 0; i < decRefPicMarking.n_ref_pic_marking; i++) { + if (5 + == decRefPicMarking.ref_pic_marking[i] + .memory_management_control_operation) + return true; + } + + return false; +} + +VaapiDecoderH264::DPB::DPB(OutputCallback output) + : m_output(output) + , m_dummy(new VaapiDecPictureH264) + , m_noOutputOfPriorPicsFlag(false) + , m_maxFrameNum(0) + , m_maxNumRefFrames(0) + , m_maxDecFrameBuffering(H264_MAX_REFRENCE_SURFACE_NUMBER) +{ +} + +void VaapiDecoderH264::DPB::removeUnused() +{ + /* Remove unused pictures from DPB */ + PictureList::iterator it; + for (it = m_pictures.begin(); it != m_pictures.end();) { + if (isUnusedPicture(*it)) + m_pictures.erase(it++); + else + ++it; + } +} + +void VaapiDecoderH264::DPB::clearRefSet() +{ + m_shortTermList.clear(); + m_shortTermList1.clear(); + m_longTermList.clear(); + m_refList0.clear(); + m_refList1.clear(); +} + +void VaapiDecoderH264::DPB::printRefList() +{ + uint32_t i; + + for (i = 0; i < m_shortTermList.size(); i++) { + DEBUG("m_shortTermList(Index %d: Poc %d, frameNumWrap: %d)", i, + m_shortTermList[i]->m_poc, m_shortTermList[i]->m_frameNumWrap); + } + + for (i = 0; i < m_shortTermList1.size(); i++) { + DEBUG("m_shortTermList1(Index %d: Poc %d, frameNumWrap: %d)", i, + m_shortTermList1[i]->m_poc, m_shortTermList1[i]->m_frameNumWrap); + } + + for (i = 0; i < m_longTermList.size(); i++) { + DEBUG("m_longTermList(Index %d: Poc %d, longTermFrameIdx %d)", i, + m_longTermList[i]->m_poc, m_longTermList[i]->m_longTermFrameIdx); + } + + for (i = 0; i < m_refList0.size(); i++) { + DEBUG("m_refList0(Index %d: Poc %d)", i, m_refList0[i]->m_poc); + } + + for (i = 0; i < m_refList1.size(); i++) { + DEBUG("m_refList1(Index %d: Poc %d)", i, m_refList1[i]->m_poc); + } + + PictureList::iterator it; + + for (i = 0, it = m_pictures.begin(); it != m_pictures.end(); it++, i++) { + DEBUG("m_pictures(Index %d: Poc %d, frameNumWrap: %d, " + "shortTermRefFlag:%d, longTermRefFlag:%d, isRefer: %d, " + "outPutFlag:%d)", + i, (*it)->m_poc, (*it)->m_frameNumWrap, (*it)->m_shortTermRefFlag, + (*it)->m_longTermRefFlag, (*it)->m_isReference, + (*it)->m_picOutputFlag); + } +} + +static void calcShortTermPicNum(vector& shortRefSet, + const PicturePtr& picture, + PicturePtr& refPicture, uint32_t maxFrameNum) +{ + if (refPicture->m_frameNum > picture->m_frameNum) + refPicture->m_frameNumWrap = refPicture->m_frameNum - maxFrameNum; + else + refPicture->m_frameNumWrap = refPicture->m_frameNum; + + if (isFrame(refPicture)) + refPicture->m_picNum = refPicture->m_frameNumWrap; + else if (matchPicStructure(picture, refPicture)) + refPicture->m_picNum = 2 * refPicture->m_frameNumWrap + 1; + else + refPicture->m_picNum = 2 * refPicture->m_frameNumWrap; + + if (isField(picture) && isFrame(refPicture)) { + shortRefSet.push_back(refPicture->allocField(false)); + shortRefSet.push_back(refPicture->allocField(true)); + } else + shortRefSet.push_back(refPicture); +} + +static void calcLongTermPicNum(vector& longRefSet, + const PicturePtr& picture, + PicturePtr& refPicture) +{ + if (isFrame(refPicture)) + refPicture->m_longTermPicNum = refPicture->m_longTermFrameIdx; + else if (matchPicStructure(picture, refPicture)) + refPicture->m_longTermPicNum = 2 * refPicture->m_longTermFrameIdx + 1; + else + refPicture->m_longTermPicNum = 2 * refPicture->m_longTermFrameIdx; + + if (isField(picture) && isFrame(refPicture)) { + longRefSet.push_back(refPicture->allocField(false)); + longRefSet.push_back(refPicture->allocField(true)); + } else + longRefSet.push_back(refPicture); +} + +void VaapiDecoderH264::DPB::calcPicNum(const PicturePtr& picture, + const SliceHeader* const slice) +{ + PictureList::iterator it; + PicturePtr refPicture; + + m_shortTermList.clear(); + m_longTermList.clear(); + + picture->m_picNum = isFrame(picture) ? picture->m_frameNum + : 2 * picture->m_frameNum + 1; + + for (it = m_pictures.begin(); it != m_pictures.end(); it++) { + refPicture = *it; + if (isShortTermReference(refPicture)) { + calcShortTermPicNum(m_shortTermList, picture, refPicture, + m_maxFrameNum); + } else if (isLongTermReference(refPicture)) + calcLongTermPicNum(m_longTermList, picture, refPicture); + } +} + +void partitionAndInterleave(const PicturePtr& picture, + vector& refSet) +{ + vector refSet1, refSet2; + vector::iterator it; + uint32_t i, n; + + // refset has been sorted, use stable_partition to keep the sequence. + it = std::stable_partition(refSet.begin(), refSet.end(), + bind(matchPicStructure, _1, picture)); + refSet1.insert(refSet1.end(), refSet.begin(), it); + refSet2.insert(refSet2.end(), it, refSet.end()); + refSet.clear(); + + for (i = 0; i < refSet1.size(); i++) { + DEBUG("refSet1(Index %d: Poc %d, frameNumWrap: %d)", i, + refSet1[i]->m_poc, refSet1[i]->m_frameNumWrap); + } + + for (i = 0; i < refSet2.size(); i++) { + DEBUG("refSet2(Index %d: Poc %d, frameNumWrap: %d)", i, + refSet2[i]->m_poc, refSet2[i]->m_frameNumWrap); + } + + n = MIN(refSet1.size(), refSet2.size()); + + for (i = 0; i < n; i++) { + refSet.push_back(refSet1[i]); + refSet.push_back(refSet2[i]); + } + + if (n < refSet1.size()) + refSet.insert(refSet.end(), refSet1.begin() + n, refSet1.end()); + else if (n < refSet2.size()) + refSet.insert(refSet.end(), refSet2.begin() + n, refSet2.end()); +} + +void VaapiDecoderH264::DPB::initReferenceList(const PicturePtr& picture, + const SliceHeader* const slice) +{ + + if (isISlice(slice->slice_type)) + return; + + if (isField(picture)) { + partitionAndInterleave(picture, m_shortTermList); + partitionAndInterleave(picture, m_longTermList); + } + m_refList0.insert(m_refList0.end(), m_shortTermList.begin(), + m_shortTermList.end()); + m_refList0.insert(m_refList0.end(), m_longTermList.begin(), + m_longTermList.end()); + + if (isBSlice(slice->slice_type)) { + if (isField(picture)) + partitionAndInterleave(picture, m_shortTermList1); + + m_refList1.insert(m_refList1.end(), m_shortTermList1.begin(), + m_shortTermList1.end()); + m_refList1.insert(m_refList1.end(), m_longTermList.begin(), + m_longTermList.end()); + } +} + +void VaapiDecoderH264::DPB::initPSliceRef(const PicturePtr& picture, + const SliceHeader* const slice) +{ + std::sort(m_shortTermList.begin(), m_shortTermList.end(), + isFrame(picture) ? decCompareStPicNum : decCompareFrameNumWrap); + std::sort(m_longTermList.begin(), m_longTermList.end(), + isFrame(picture) ? ascCompareLtPicNum : ascCompareLtFrameIndex); + + initReferenceList(picture, slice); +} + +void VaapiDecoderH264::DPB::initBSliceRef(const PicturePtr& picture, + const SliceHeader* const slice) +{ + RefSet::iterator it; + + // Reflist0 init + // For short term reflist: descending sort for all m_poc less than curPic, + // ascending sort for the rest. + // For long term reflist: ascending sort as m_longTermPicNum or + // m_longTermFrameIdx; + std::sort(m_shortTermList.begin(), m_shortTermList.end(), ascComparePoc); + it = std::partition(m_shortTermList.begin(), m_shortTermList.end(), + bind(ascComparePoc, _1, picture)); + std::sort(m_shortTermList.begin(), it, decComparePoc); + std::sort(m_longTermList.begin(), m_longTermList.end(), + isFrame(picture) ? ascCompareLtPicNum : ascCompareLtFrameIndex); + + // Reflist1 init + // For short term reflist: swap to reflist0. For long term reflist: some as + // reflist0 + m_shortTermList1.insert(m_shortTermList1.end(), it, m_shortTermList.end()); + m_shortTermList1.insert(m_shortTermList1.end(), m_shortTermList.begin(), + it); + + initReferenceList(picture, slice); + + if ((m_refList1.size() > 1) && (m_refList0 == m_refList1)) + std::swap(m_refList1[0], m_refList1[1]); +} + +void VaapiDecoderH264::DPB::initReference(const PicturePtr& picture, + const SliceHeader* const slice) +{ + clearRefSet(); + if (isIdr(picture)) + return; + + m_decRefPicMarking = slice->dec_ref_pic_marking; + + calcPicNum(picture, slice); + + if (isPSlice(slice->slice_type)) + initPSliceRef(picture, slice); + else if (isBSlice(slice->slice_type)) + initBSliceRef(picture, slice); + + if (!isISlice(slice->slice_type)) + modifyReferenceList(picture, slice, m_refList0, 0); + + if (isBSlice(slice->slice_type)) + modifyReferenceList(picture, slice, m_refList1, 1); + + if (m_refList0.size() > (uint32_t)(slice->num_ref_idx_l0_active_minus1 + 1)) + m_refList0.resize(slice->num_ref_idx_l0_active_minus1 + 1); + if (m_refList1.size() > (uint32_t)(slice->num_ref_idx_l1_active_minus1 + 1)) + m_refList1.resize(slice->num_ref_idx_l1_active_minus1 + 1); +} + +bool VaapiDecoderH264::DPB::modifyReferenceList(const PicturePtr& picture, + const SliceHeader* const slice, + RefSet& refList, uint8_t refIdx) +{ + uint32_t refPicListModifyFlag, refPicListModifyNum; + const RefPicListModification* refPicListModify; + + if (refIdx == 0) { + refPicListModifyFlag = slice->ref_pic_list_modification_flag_l0; + refPicListModifyNum = slice->n_ref_pic_list_modification_l0; + refPicListModify = slice->ref_pic_list_modification_l0; + } else if (refIdx == 1) { + refPicListModifyFlag = slice->ref_pic_list_modification_flag_l1; + refPicListModifyNum = slice->n_ref_pic_list_modification_l1; + refPicListModify = slice->ref_pic_list_modification_l1; + } else { + assert(0); + } + + if (!refPicListModifyFlag) + return true; + + DEBUG("modifyReferenceList, refIdx(%d), refPicListModifyNum(%d)", refIdx, + refPicListModifyNum); + + int32_t maxPicNum = isFrame(picture) ? m_maxFrameNum : 2 * m_maxFrameNum; + int32_t picNumLxPred, picNumLxNoWrap, picNumLx, picNumF, absDiffPicNum; + uint32_t refIdxLx = 0, nIdx, cIdx; + RefSet::iterator it; + + picNumLxPred = picture->m_picNum; + + for (uint32_t i = 0; i < refPicListModifyNum; i++) { + switch (refPicListModify[i].modification_of_pic_nums_idc) { + case 0: + case 1: + // reorder short term reflist + absDiffPicNum = refPicListModify[i].abs_diff_pic_num_minus1 + 1; + //(8-34) and (8-35) + if (refPicListModify[i].modification_of_pic_nums_idc == 0) { + if (picNumLxPred - absDiffPicNum < 0) + picNumLxNoWrap = picNumLxPred - absDiffPicNum + maxPicNum; + else + picNumLxNoWrap = picNumLxPred - absDiffPicNum; + } else { + if (picNumLxPred + absDiffPicNum >= maxPicNum) + picNumLxNoWrap = picNumLxPred + absDiffPicNum - maxPicNum; + else + picNumLxNoWrap = picNumLxPred + absDiffPicNum; + } + picNumLxPred = picNumLxNoWrap; + //(8-36) + if (picNumLxNoWrap > picture->m_picNum) + picNumLx = picNumLxNoWrap - maxPicNum; + else + picNumLx = picNumLxNoWrap; + + it = find_if(m_shortTermList.begin(), m_shortTermList.end(), + bind(matchPicNum, _1, picNumLx)); + + if (it != m_shortTermList.end()) { + refList.insert(refList.begin() + refIdxLx, *it); + DEBUG(" Insert refList( Poc %d, PicNum %d)", (*it)->m_poc, + (*it)->m_picNum); + } else + WARNING("can't find this picture"); + + nIdx = ++refIdxLx; + for (cIdx = refIdxLx; cIdx < refList.size(); cIdx++) { + picNumF = isShortTermReference(refList[cIdx]) + ? refList[cIdx]->m_picNum + : maxPicNum; + if (picNumF != picNumLx) + refList[nIdx++] = refList[cIdx]; + } + break; + + case 2: + // reoder long term reflist + picNumLx = refPicListModify[i].long_term_pic_num; + it = find_if(m_longTermList.begin(), m_longTermList.end(), + bind(matchLongTermPicNum, _1, picNumLx)); + + if (it != m_longTermList.end()) + refList.insert(refList.begin() + refIdxLx, *it); + else + WARNING("can't find this picture"); + + nIdx = ++refIdxLx; + for (cIdx = refIdxLx; cIdx < refList.size(); cIdx++) { + if (!isLongTermReference(refList[cIdx]) + || (refList[cIdx]->m_longTermPicNum) != picNumLx) + refList[nIdx++] = refList[cIdx]; + } + break; + default: + break; + } + } + + return true; +} + +void VaapiDecoderH264::DPB::adaptiveMarkReference(const PicturePtr& picture) +{ + uint32_t i, mmco, picNumX; + int32_t maxLongTermFrameIdx; + PictureList::iterator it; + for (i = 0; i < m_decRefPicMarking.n_ref_pic_marking; i++) { + RefPicMarking refPicMarking = m_decRefPicMarking.ref_pic_marking[i]; + mmco = refPicMarking.memory_management_control_operation; + picNumX = picture->m_picNum + - (refPicMarking.difference_of_pic_nums_minus1 + 1); // (8-39) + DEBUG("mmco type: %d", mmco); + switch (mmco) { + case 1: + findAndMarkUnusedReference(bind(matchShortTermPicNum, _1, picNumX)); + break; + case 2: + findAndMarkUnusedReference( + bind(matchLongTermPicNum, _1, refPicMarking.long_term_pic_num)); + break; + case 3: + findAndMarkUnusedReference(bind(matchLongTermPicNum, _1, + refPicMarking.long_term_frame_idx)); + it = find_if(m_pictures.begin(), m_pictures.end(), + bind(matchShortTermPicNum, _1, picNumX)); + if (it != m_pictures.end()) { + markLongTermReference(*it); + (*it)->m_longTermFrameIdx = refPicMarking.long_term_frame_idx; + } + break; + case 4: + maxLongTermFrameIdx = refPicMarking.max_long_term_frame_idx_plus1 + - 1; + forEach(bind(markUnusedLongTermRefWithMaxIndex, _1, + maxLongTermFrameIdx)); + break; + case 5: + forEach(markUnusedReference); + break; + case 6: + findAndMarkUnusedReference(bind(matchLongTermPicNum, _1, + refPicMarking.long_term_frame_idx)); + markLongTermReference(picture); + picture->m_longTermFrameIdx = refPicMarking.long_term_frame_idx; + break; + default: + DEBUG("mmco type undefined!"); + break; + } + } +} + +bool +VaapiDecoderH264::DPB::slidingWindowMarkReference(const PicturePtr& picture) +{ + uint32_t numShortTerm, numLongTerm; + + if (isSecondField(picture)) + return true; + + numShortTerm = m_shortTermList.size(); + numLongTerm = m_longTermList.size(); + + if (numShortTerm && (numShortTerm + numLongTerm >= m_maxNumRefFrames)) { + RefSet::iterator it1 + = std::min_element(m_shortTermList.begin(), m_shortTermList.end(), + ascCompareFrameNumWrap); + PicturePtr unUsedRefPic = *it1; + DEBUG("Find unUsedRefPic (poc %d, FrameNumWrap: %d, isReference: %d)", + unUsedRefPic->m_poc, unUsedRefPic->m_frameNumWrap, + unUsedRefPic->m_isReference); + /*for field case, m_shortTermList comes from m_fields, set unUsedRefPic + won't effect m_pictures. + So we need one more step to mark unUsedRefPic in m_pictures */ + if (isField(picture)) { + PictureList::iterator it2 = find_if( + m_pictures.begin(), m_pictures.end(), + bind(matchShortTermFrameNumWrap, _1, (*it1)->m_frameNumWrap)); + if (it2 == m_pictures.end()) { + ERROR("can't find picture"); + return false; + } + unUsedRefPic = *it2; + } + markUnusedReference(unUsedRefPic); + } + + return true; +} + +bool VaapiDecoderH264::DPB::markReference(const PicturePtr& picture) +{ + if (!picture->m_isReference) + return false; + + if (m_decRefPicMarking.adaptive_ref_pic_marking_mode_flag) { + DEBUG("Adaptive ref pic marking right now"); + adaptiveMarkReference(picture); + } else { + slidingWindowMarkReference(picture); + } + + return true; +} + +void VaapiDecoderH264::DPB::forEach(ForEachFunction fn) +{ + std::for_each(m_pictures.begin(), m_pictures.end(), fn); +} + +template +void VaapiDecoderH264::DPB::findAndMarkUnusedReference(P pred) +{ + PictureList::iterator it + = find_if(m_pictures.begin(), m_pictures.end(), pred); + + if (it != m_pictures.end()) + markUnusedReference(*it); +} + +bool VaapiDecoderH264::DPB::isFull() +{ + DEBUG("m_pictures size: %zu", m_pictures.size()); + return m_pictures.size() >= m_maxDecFrameBuffering; +} + +/* 8.3.1 */ +bool VaapiDecoderH264::DPB::calcPoc(const PicturePtr& picture, + const SliceHeader* const slice) +{ + const SharedPtr pps = slice->m_pps; + const SharedPtr sps = pps->m_sps; + + const int32_t maxPicOrderCntLsb + = 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + + picture->m_frameNumOffset + = m_prevPicture->m_frameNumOffset + + (picture->m_frameNum < m_prevPicture->m_frameNum ? m_maxFrameNum + : 0); + + if (sps->pic_order_cnt_type == 0) { + if (picture->m_pocLsb < m_prevPicture->m_pocLsb + && m_prevPicture->m_pocLsb - picture->m_pocLsb + >= (maxPicOrderCntLsb / 2)) + picture->m_pocMsb = m_prevPicture->m_pocMsb + maxPicOrderCntLsb; + else if (picture->m_pocLsb > m_prevPicture->m_pocLsb + && picture->m_pocLsb - m_prevPicture->m_pocLsb + > (maxPicOrderCntLsb / 2)) + picture->m_pocMsb = m_prevPicture->m_pocMsb - maxPicOrderCntLsb; + else + picture->m_pocMsb = m_prevPicture->m_pocMsb; + + picture->m_topFieldOrderCnt = picture->m_pocMsb + picture->m_pocLsb; + picture->m_bottomFieldOrderCnt + = picture->m_topFieldOrderCnt + + (isFrame(picture) ? slice->delta_pic_order_cnt_bottom : 0); + } else if (sps->pic_order_cnt_type == 1) { + uint32_t absFrameNum = 0, expectedPicOrderCnt = 0, + expectedDeltaPerPicOrderCntCycle = 0; + uint32_t i, picOrderCntCycleCnt, frameNumInPicOrderCntCycle; + + /*(8-6) ~ (8-10) */ + if (sps->num_ref_frames_in_pic_order_cnt_cycle) + absFrameNum = picture->m_frameNumOffset + picture->m_frameNum; + if (!picture->m_isReference && absFrameNum) + absFrameNum--; + + if (absFrameNum) { + picOrderCntCycleCnt = (absFrameNum - 1) + / sps->num_ref_frames_in_pic_order_cnt_cycle; + frameNumInPicOrderCntCycle + = (absFrameNum - 1) + % sps->num_ref_frames_in_pic_order_cnt_cycle; + + for (i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++) + expectedDeltaPerPicOrderCntCycle + += sps->offset_for_ref_frame[i]; //(7-11) + + expectedPicOrderCnt = picOrderCntCycleCnt + * expectedDeltaPerPicOrderCntCycle; + + for (i = 0; i <= frameNumInPicOrderCntCycle; i++) + expectedPicOrderCnt += sps->offset_for_ref_frame[i]; + } else + expectedPicOrderCnt = 0; + + if (!picture->m_isReference) + expectedPicOrderCnt += sps->offset_for_non_ref_pic; + + picture->m_topFieldOrderCnt = expectedPicOrderCnt + + slice->delta_pic_order_cnt[0]; + picture->m_bottomFieldOrderCnt + = picture->m_topFieldOrderCnt + sps->offset_for_top_to_bottom_field + + (isFrame(picture) ? slice->delta_pic_order_cnt[1] : 0); + } else if (sps->pic_order_cnt_type == 2) { + uint32_t tempPicOrderCnt; + //(8-12) + if (isIdr(picture)) + tempPicOrderCnt = 0; + else if (!isReference(picture)) + tempPicOrderCnt + = 2 * (picture->m_frameNumOffset + picture->m_frameNum) - 1; + else + tempPicOrderCnt + = 2 * (picture->m_frameNumOffset + picture->m_frameNum); + + picture->m_topFieldOrderCnt = picture->m_bottomFieldOrderCnt + = tempPicOrderCnt; + } else { + ERROR("incorrect poc type!"); + return false; + } + + if (isBottomField(picture)) + picture->m_poc = picture->m_bottomFieldOrderCnt; + else + picture->m_poc = picture->m_topFieldOrderCnt; + + DEBUG("slice_type: %d, poc_type: %d, m_poc:%d, pocLsb:%d, pocMsb:%d, " + "isbottomfield: %d ", + slice->slice_type % 5, sps->pic_order_cnt_type, picture->m_poc, + picture->m_pocLsb, picture->m_pocMsb, slice->bottom_field_flag); + + return true; +} + +void +VaapiDecoderH264::DPB::processFrameNumWithGaps(const PicturePtr& picture, + const SliceHeader* const slice) +{ + const SharedPtr sps = slice->m_pps->m_sps; + + /*Inserted dummy picture won't be referred when pic_order_cnt_type is 0 ?*/ + if (!sps->pic_order_cnt_type) { + WARNING("Process Gaps In FrameNum: pic_order_cnt_type is zero"); + } + + uint32_t unusedShortTermFrameNum, prevFrameNum, frameNum; + + SliceHeader tmpSlice = *slice; + tmpSlice.delta_pic_order_cnt[0] = tmpSlice.delta_pic_order_cnt[1] = 0; + /* alway use sliding window mark for dummy picture*/ + tmpSlice.dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag = 0; + m_decRefPicMarking = tmpSlice.dec_ref_pic_marking; + + prevFrameNum = m_prevPicture->m_frameNum; + frameNum = picture->m_frameNum; + unusedShortTermFrameNum = (prevFrameNum + 1) % m_maxFrameNum; /*(7-23) */ + while (unusedShortTermFrameNum != frameNum) { + printRefList(); + DEBUG("Alloc dummy picture, unusedShortTermFrameNum: %d", + unusedShortTermFrameNum); + PicturePtr dummyPic + = m_prevPicture->allocDummyPicture(unusedShortTermFrameNum); + calcPoc(dummyPic, &tmpSlice); + calcPicNum(dummyPic, &tmpSlice); + PictureList::iterator it = find_if( + m_pictures.begin(), m_pictures.end(), + bind(matchFrameNumInShortTermList, _1, unusedShortTermFrameNum)); + if (it == m_pictures.end()) { + DEBUG("Add dummy picture"); + add(dummyPic); + } + + unusedShortTermFrameNum = (unusedShortTermFrameNum + 1) % m_maxFrameNum; + m_prevPicture = dummyPic; + } +} + +// C.5.2.2 +bool VaapiDecoderH264::DPB::init(const PicturePtr& picture, + const PicturePtr& prevPicture, + const SliceHeader* const slice, + const NalUnit* const nalu, bool newStream, + bool contextChanged, + uint32_t maxDecFrameBuffering) +{ + const SharedPtr pps = slice->m_pps; + const SharedPtr sps = pps->m_sps; + + m_prevPicture = prevPicture; + m_maxFrameNum = 1 << (sps->log2_max_frame_num_minus4 + 4); + m_decRefPicMarking = slice->dec_ref_pic_marking; + m_maxNumRefFrames = MAX(sps->num_ref_frames, 1); + m_maxDecFrameBuffering = maxDecFrameBuffering; + if (isField(picture)) + m_maxNumRefFrames *= 2; + + // must double check mmco5 cases + if (picture->m_hasMmco5) + WARNING("MMCO5"); + + if (isIdr(picture)) { + if (!newStream && contextChanged) + m_noOutputOfPriorPicsFlag = true; + else + m_noOutputOfPriorPicsFlag + = m_decRefPicMarking.no_output_of_prior_pics_flag; + } + + /*8.2.5.2 Decoding process for gaps in frame_num */ + if (sps->gaps_in_frame_num_value_allowed_flag + && picture->m_frameNum != m_prevPicture->m_frameNum + && picture->m_frameNum + != (int32_t)((m_prevPicture->m_frameNum + 1) % m_maxFrameNum)) { + DEBUG("processForGapsInFrameNum, m_frameNum %d, prevFrameNum: %d", + picture->m_frameNum, m_prevPicture->m_frameNum); + processFrameNumWithGaps(picture, slice); + } + + if (!calcPoc(picture, slice)) + return false; + + return true; +} + +bool VaapiDecoderH264::DPB::output(const PicturePtr& picture) +{ + picture->m_picOutputFlag = false; + + DEBUG("DPB: output picture(Poc:%d)", picture->m_poc); + return m_output(picture) == YAMI_SUCCESS; +} + +bool VaapiDecoderH264::DPB::bump() +{ + PictureList::iterator it + = find_if(m_pictures.begin(), m_pictures.end(), isOutputNeeded); + if (it == m_pictures.end()) + return false; + bool success = output(*it); + if (!isReference(*it)) + m_pictures.erase(it); + return success; +} + +void VaapiDecoderH264::DPB::bumpAll() +{ + while (bump()) { + /* nothing */; + } +} + +void resetPictureHasMmco5(const PicturePtr& picture) +{ + picture->m_topFieldOrderCnt -= picture->m_poc; + picture->m_bottomFieldOrderCnt -= picture->m_poc; + picture->m_poc = 0; + picture->m_frameNum = 0; + picture->m_frameNumOffset = 0; + picture->m_pocMsb = 0; + picture->m_pocLsb = isBottomField(picture) ? 0 : picture->m_pocLsb; +} + +bool VaapiDecoderH264::DPB::add(const PicturePtr& picture) +{ + PictureList::iterator it = m_pictures.begin(); // picture with minimum poc + + /*(8.2.1)*/ + if (picture->m_hasMmco5) + resetPictureHasMmco5(picture); + + // C4.4: removal of pictures from the DPB before possible insertion of the + // current picture + if (isIdr(picture)) { + forEach(markUnusedReference); + + if (m_noOutputOfPriorPicsFlag) + m_pictures.clear(); + } else + markReference(picture); + + removeUnused(); + printRefList(); + + if (picture->m_hasMmco5 || (isIdr(picture) && !m_noOutputOfPriorPicsFlag)) { + DEBUG("noOutputOfPriorPicsFlag: %d", m_noOutputOfPriorPicsFlag); + bumpAll(); + m_pictures.clear(); + } + + if (!picture->m_isReference && isFull() && picture->m_poc < (*it)->m_poc) { + DEBUG("Derectly output picture(Poc:%d)", picture->m_poc); + return output(picture); + } + + while (isFull()) { + if (!bump()) + return false; + } + + if (!isSecondField(picture)) + m_pictures.insert(picture); + else { + // since the second field use same surface as the first field, no need + // to add second filed into DPB buffer. + PicturePtr compPicture = picture->m_complementField; + if (isTopField(compPicture)) + compPicture->m_bottomFieldOrderCnt = picture->m_bottomFieldOrderCnt; + else + compPicture->m_topFieldOrderCnt = picture->m_topFieldOrderCnt; + compPicture->m_picStructure = VAAPI_PICTURE_FRAME; + } + + if (m_isLowLatencymode) + forEach(bind(&VaapiDecoderH264::DPB::outputReadyFrame, this, _1)); + + return true; +} + +void VaapiDecoderH264::DPB::outputReadyFrame(const PicturePtr& picture) +{ + if (isOutputNeeded(picture)) { + output(picture); + } +} + +void VaapiDecoderH264::DPB::flush() +{ + bumpAll(); + clearRefSet(); + m_pictures.clear(); + m_prevPicture.reset(); +} + +VaapiDecoderH264::VaapiDecoderH264() + : m_newStream(true) + , m_endOfSequence(false) + , m_endOfStream(false) + , m_dpb(bind(&VaapiDecoderH264::outputPicture, this, _1)) + , m_nalLengthSize(0) + , m_contextChanged(false) +{ +} + +VaapiDecoderH264::~VaapiDecoderH264() { stop(); } + +bool VaapiDecoderH264::decodeAvcRecordData(uint8_t* buf, int32_t bufSize) +{ + if (buf == NULL || bufSize == 0) { + ERROR("invalid record data"); + return false; + } + + if (buf[0] != 1) { + VideoDecodeBuffer buffer; + memset(&buffer, 0, sizeof(buffer)); + buffer.data = buf; + buffer.size = bufSize; + //we ignore no faltal error + return (decode(&buffer) >= YAMI_SUCCESS); + } + + if (bufSize < 7) { + ERROR("invalid avcc record data"); + return false; + } + + const uint8_t spsNalLengthSize = 2; + const uint8_t ppsNalLengthSize = 2; + NalUnit nalu; + const uint8_t* nalBuf = NULL; + int32_t i = 0, numOfSps, numOfPps, nalBufSize = 0; + + numOfSps = buf[5] & 0x1f; + for (NalReader nr(&buf[6], bufSize - 6, spsNalLengthSize); i < numOfSps; + i++) { + if (!nr.read(nalBuf, nalBufSize)) + return false; + + if (!nalu.parseNalUnit(nalBuf, nalBufSize)) + return false; + + if (decodeSps(&nalu) != YAMI_SUCCESS) + return false; + } + nalBuf += nalBufSize; + numOfPps = nalBuf[0] & 0x1f; + i = 0; + for (NalReader nr(&nalBuf[1], bufSize - (nalBuf - buf + 1), + ppsNalLengthSize); + i < numOfPps; i++) { + if (!nr.read(nalBuf, nalBufSize)) + return false; + + if (!nalu.parseNalUnit(nalBuf, nalBufSize)) + return false; + + if (decodePps(&nalu) != YAMI_SUCCESS) + return false; + } + + m_nalLengthSize = 1 + (buf[4] & 0x3); + + return true; +} + +YamiStatus VaapiDecoderH264::start(VideoConfigBuffer* buffer) +{ + if (buffer->data && buffer->size > 0) { + if (!decodeAvcRecordData(buffer->data, buffer->size)) { + ERROR("decode record data failed"); + return DECODE_FAIL; + } + } + + m_dpb.m_isLowLatencymode = buffer->enableLowLatency; + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderH264::decodeSps(NalUnit* nalu) +{ + SharedPtr sps(new SPS()); + + memset(sps.get(), 0, sizeof(SPS)); + if (!m_parser.parseSps(sps, nalu)) { + return YAMI_DECODE_INVALID_DATA; + } + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderH264::decodePps(NalUnit* nalu) +{ + SharedPtr pps(new PPS()); + + if (!m_parser.parsePps(pps, nalu)) { + return YAMI_DECODE_INVALID_DATA; + } + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderH264::outputPicture(const PicturePtr& picture) +{ + VaapiDecoderBase::PicturePtr base + = std::static_pointer_cast(picture); + return VaapiDecoderBase::outputPicture(base); +} + +#define FILL_SCALING_LIST(mxm, n) \ + void fillScalingList##mxm(VAIQMatrixBufferH264* iqMatrix, \ + const SharedPtr pps) \ + { \ + for (uint32_t i = 0; i < N_ELEMENTS(iqMatrix->ScalingList##mxm); i++) { \ + transform_coefficients_for_frame_macroblocks( \ + iqMatrix->ScalingList##mxm[i], pps->scaling_lists_##mxm[i], n, \ + mxm); \ + } \ + } + +FILL_SCALING_LIST(4x4, 16) +FILL_SCALING_LIST(8x8, 64) + +bool VaapiDecoderH264::fillIqMatrix(const PicturePtr& picture, + const SliceHeader* const slice) +{ + const SharedPtr pps = slice->m_pps; + + VAIQMatrixBufferH264* iqMatrix; + if (!picture->editIqMatrix(iqMatrix)) + return false; + + fillScalingList4x4(iqMatrix, pps); + fillScalingList8x8(iqMatrix, pps); + + return true; +} + +void fillVAPictureH264(VAPictureH264* vaPicH264, const PicturePtr& picture) +{ + + vaPicH264->picture_id = picture->getSurfaceID(); + vaPicH264->TopFieldOrderCnt = picture->m_topFieldOrderCnt; + vaPicH264->BottomFieldOrderCnt = picture->m_bottomFieldOrderCnt; + vaPicH264->frame_idx = picture->m_frameNum; + + if (picture->m_picStructure == VAAPI_PICTURE_TOP_FIELD) { + vaPicH264->flags |= VA_PICTURE_H264_TOP_FIELD; + vaPicH264->BottomFieldOrderCnt = 0; + } + + if (picture->m_picStructure == VAAPI_PICTURE_BOTTOM_FIELD) { + vaPicH264->flags |= VA_PICTURE_H264_BOTTOM_FIELD; + vaPicH264->TopFieldOrderCnt = 0; + } + + if (picture->m_shortTermRefFlag) + vaPicH264->flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE; + + if (picture->m_longTermRefFlag) { + vaPicH264->flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE; + vaPicH264->frame_idx = picture->m_longTermFrameIdx; + } +} + +void VaapiDecoderH264::fillReference(VAPictureH264* refs, size_t size) +{ + size_t i = 0; + DPB::PictureList::iterator it = m_dpb.m_pictures.begin(); + + for (; it != m_dpb.m_pictures.end(); it++) { + if (!isReference(*it)) + continue; + fillVAPictureH264(&refs[i++], *it); + DEBUG("id %d, poc %d, isShortRef %d, isRef %d", (*it)->getSurfaceID(), + (*it)->m_poc, (*it)->m_shortTermRefFlag, (*it)->m_isReference); + } + + for (; i < size; i++) { + refs[i].picture_id = VA_INVALID_SURFACE; + refs[i].TopFieldOrderCnt = 0; + refs[i].BottomFieldOrderCnt = 0; + refs[i].flags = VA_PICTURE_H264_INVALID; + refs[i].frame_idx = 0; + } +} + +bool VaapiDecoderH264::fillPicture(const PicturePtr& picture, + const SliceHeader* const slice) +{ + VAPictureParameterBufferH264* picParam; + const SharedPtr pps = slice->m_pps; + const SharedPtr sps = pps->m_sps; + if (!picture->editPicture(picParam)) + return false; + + fillVAPictureH264(&picParam->CurrPic, picture); + fillReference(picParam->ReferenceFrames, + N_ELEMENTS(picParam->ReferenceFrames)); + + picParam->picture_width_in_mbs_minus1 = (sps->m_width + 15) / 16 - 1; + picParam->picture_height_in_mbs_minus1 = (sps->m_height + 15) / 16 - 1; + picParam->bit_depth_luma_minus8 = sps->bit_depth_luma_minus8; + picParam->bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8; + picParam->num_ref_frames = sps->num_ref_frames; + + picParam->seq_fields.bits.chroma_format_idc = sps->chroma_format_idc; + picParam->seq_fields.bits.residual_colour_transform_flag = 0; + picParam->seq_fields.bits.gaps_in_frame_num_value_allowed_flag + = sps->gaps_in_frame_num_value_allowed_flag; + picParam->seq_fields.bits.frame_mbs_only_flag = sps->frame_mbs_only_flag; + picParam->seq_fields.bits.mb_adaptive_frame_field_flag + = sps->mb_adaptive_frame_field_flag; + picParam->seq_fields.bits.direct_8x8_inference_flag + = sps->direct_8x8_inference_flag; + picParam->seq_fields.bits.MinLumaBiPredSize8x8 + = (sps->profile_idc == PROFILE_MAIN || sps->profile_idc == PROFILE_HIGH) + && (sps->level_idc >= 31); + picParam->seq_fields.bits.log2_max_frame_num_minus4 + = sps->log2_max_frame_num_minus4; + picParam->seq_fields.bits.pic_order_cnt_type = sps->pic_order_cnt_type; + picParam->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 + = sps->log2_max_pic_order_cnt_lsb_minus4; + picParam->seq_fields.bits.delta_pic_order_always_zero_flag + = sps->delta_pic_order_always_zero_flag; + + picParam->pic_init_qp_minus26 = pps->pic_init_qp_minus26; + picParam->pic_init_qs_minus26 = pps->pic_init_qs_minus26; + picParam->chroma_qp_index_offset = pps->chroma_qp_index_offset; + picParam->second_chroma_qp_index_offset + = pps->second_chroma_qp_index_offset; + + picParam->pic_fields.bits.entropy_coding_mode_flag + = pps->entropy_coding_mode_flag; + picParam->pic_fields.bits.weighted_pred_flag = pps->weighted_pred_flag; + picParam->pic_fields.bits.weighted_bipred_idc = pps->weighted_bipred_idc; + picParam->pic_fields.bits.transform_8x8_mode_flag + = pps->transform_8x8_mode_flag; + picParam->pic_fields.bits.field_pic_flag = slice->field_pic_flag; + picParam->pic_fields.bits.constrained_intra_pred_flag + = pps->constrained_intra_pred_flag; + picParam->pic_fields.bits.pic_order_present_flag + = pps->pic_order_present_flag; + picParam->pic_fields.bits.deblocking_filter_control_present_flag + = pps->deblocking_filter_control_present_flag; + picParam->pic_fields.bits.redundant_pic_cnt_present_flag + = pps->redundant_pic_cnt_present_flag; + picParam->pic_fields.bits.reference_pic_flag = picture->m_isReference; + + picParam->frame_num = slice->frame_num; + + return true; +} + +void VaapiDecoderH264::fillReferenceIndexForList( + VASliceParameterBufferH264* sliceParam, const SliceHeader* const slice, + RefSet& refSet, bool isList0) +{ + uint32_t i = 0; + VAPictureH264* refPicture + = (isList0 ? sliceParam->RefPicList0 : sliceParam->RefPicList1); + RefSet::iterator it = refSet.begin(); + + if (isList0) + sliceParam->num_ref_idx_l0_active_minus1 + = slice->num_ref_idx_l0_active_minus1; + else + sliceParam->num_ref_idx_l1_active_minus1 + = slice->num_ref_idx_l1_active_minus1; + + for (; it != refSet.end(); i++, it++) { + fillVAPictureH264(&refPicture[i], *it); + } + for (; i < N_ELEMENTS(sliceParam->RefPicList0); i++) { + refPicture[i].picture_id = VA_INVALID_SURFACE; + refPicture[i].TopFieldOrderCnt = 0; + refPicture[i].BottomFieldOrderCnt = 0; + refPicture[i].flags = VA_PICTURE_H264_INVALID; + refPicture[i].frame_idx = 0; + } +} + +bool +VaapiDecoderH264::fillReferenceIndex(VASliceParameterBufferH264* sliceParam, + const SliceHeader* const slice) +{ + + if (!isISlice(slice->slice_type)) + fillReferenceIndexForList(sliceParam, slice, m_dpb.m_refList0, true); + + if (isBSlice(slice->slice_type)) + fillReferenceIndexForList(sliceParam, slice, m_dpb.m_refList1, false); + + return true; +} + +#define FILL_WEIGHT_TABLE(n) \ + void fillPredWedightTableL##n(VASliceParameterBufferH264* sliceParam, \ + const SliceHeader* slice, \ + uint8_t chromaArrayType) \ + { \ + const PredWeightTable& w = slice->pred_weight_table; \ + sliceParam->luma_weight_l##n##_flag = 1; \ + sliceParam->chroma_weight_l##n##_flag = !!chromaArrayType; \ + for (int i = 0; i <= sliceParam->num_ref_idx_l##n##_active_minus1; \ + i++) { \ + sliceParam->luma_weight_l##n[i] = w.luma_weight_l##n[i]; \ + sliceParam->luma_offset_l##n[i] = w.luma_offset_l##n[i]; \ + if (sliceParam->chroma_weight_l##n##_flag) { \ + for (int j = 0; j < 2; j++) { \ + sliceParam->chroma_weight_l##n[i][j] \ + = w.chroma_weight_l##n[i][j]; \ + sliceParam->chroma_offset_l##n[i][j] \ + = w.chroma_offset_l##n[i][j]; \ + } \ + } \ + } \ + } + +FILL_WEIGHT_TABLE(0) +FILL_WEIGHT_TABLE(1) + +bool +VaapiDecoderH264::fillPredWeightTable(VASliceParameterBufferH264* sliceParam, + const SliceHeader* const slice) +{ + const SharedPtr pps = slice->m_pps; + const SharedPtr sps = pps->m_sps; + const PredWeightTable& w = slice->pred_weight_table; + + sliceParam->luma_log2_weight_denom = w.luma_log2_weight_denom; + sliceParam->chroma_log2_weight_denom = w.chroma_log2_weight_denom; + + if (pps->weighted_pred_flag && isPSlice(slice->slice_type)) + fillPredWedightTableL0(sliceParam, slice, sps->m_chromaArrayType); + + if (pps->weighted_bipred_idc && isBSlice(slice->slice_type)) { + fillPredWedightTableL0(sliceParam, slice, sps->m_chromaArrayType); + fillPredWedightTableL1(sliceParam, slice, sps->m_chromaArrayType); + } + + return true; +} + +bool VaapiDecoderH264::fillSlice(const PicturePtr& picture, + const SliceHeader* const slice, + const NalUnit* const nalu) +{ + VASliceParameterBufferH264* sliceParam; + if (!picture->newSlice(sliceParam, nalu->m_data, nalu->m_size)) + return false; + + sliceParam->slice_data_bit_offset + = slice->m_headerSize + + ((nalu->m_nalUnitHeaderBytes - slice->m_emulationPreventionBytes) + << 3); + sliceParam->first_mb_in_slice = slice->first_mb_in_slice; + sliceParam->slice_type = slice->slice_type % 5; + sliceParam->direct_spatial_mv_pred_flag + = slice->direct_spatial_mv_pred_flag; + sliceParam->cabac_init_idc = slice->cabac_init_idc; + sliceParam->slice_qp_delta = slice->slice_qp_delta; + sliceParam->disable_deblocking_filter_idc + = slice->disable_deblocking_filter_idc; + sliceParam->slice_alpha_c0_offset_div2 = slice->slice_alpha_c0_offset_div2; + sliceParam->slice_beta_offset_div2 = slice->slice_beta_offset_div2; + + if (!fillReferenceIndex(sliceParam, slice)) + return false; + + if (!fillPredWeightTable(sliceParam, slice)) + return false; + + return true; +} + +YamiStatus VaapiDecoderH264::decodeCurrent() +{ + YamiStatus status = YAMI_SUCCESS; + if (!m_currPic) + return status; + + if (!m_currPic->decode()) { + ERROR("decode %d failed", m_currPic->m_poc); + // ignore it to let application continue to decode the next frame + return YAMI_DECODE_INVALID_DATA; + } else + DEBUG("decode %d done", m_currPic->m_poc); + + if (!m_dpb.add(m_currPic)) + return YAMI_DECODE_INVALID_DATA; + + m_prevPic = m_currPic; + m_currPic.reset(); + m_newStream = false; + return status; +} + +uint32_t calcMaxDecFrameBufferingNum(const SharedPtr& sps) +{ + + if (sps->vui_parameters_present_flag + && sps->m_vui.bitstream_restriction_flag) { + return sps->m_vui.max_dec_frame_buffering; + } + + uint32_t maxDpbMbs; + + /*get MaxDpbMbs as Table A-1*/ + switch (sps->level_idc) { + case 9: + case 10: + maxDpbMbs = 396; + break; + case 11: + maxDpbMbs = 900; + break; + case 12: + case 13: + case 20: + maxDpbMbs = 2376; + break; + case 21: + maxDpbMbs = 4752; + break; + case 22: + case 30: + maxDpbMbs = 8100; + break; + case 31: + maxDpbMbs = 18000; + break; + case 32: + maxDpbMbs = 20480; + break; + case 40: + case 41: + maxDpbMbs = 32768; + break; + case 42: + maxDpbMbs = 34816; + break; + case 50: + maxDpbMbs = 110400; + break; + case 51: + case 52: + maxDpbMbs = 184320; + break; + default: + ERROR("undefined level_idc"); + maxDpbMbs = 184320; + break; + } + + uint32_t picWidthInMbs, frameHeightInMbs, maxDpbFrames; + + picWidthInMbs = sps->pic_width_in_mbs_minus1 + 1; //(7-12) + frameHeightInMbs = (2 - sps->frame_mbs_only_flag) + * (sps->pic_height_in_map_units_minus1 + 1); //(7-17) + + maxDpbFrames = maxDpbMbs / (picWidthInMbs * frameHeightInMbs); + + return maxDpbFrames; +} + +bool VaapiDecoderH264::isDecodeContextChanged(const SharedPtr& sps) +{ + uint32_t maxDecFrameBuffering; + + maxDecFrameBuffering = calcMaxDecFrameBufferingNum(sps); + + if (maxDecFrameBuffering > H264_MAX_REFRENCE_SURFACE_NUMBER) + maxDecFrameBuffering = H264_MAX_REFRENCE_SURFACE_NUMBER; + else if (maxDecFrameBuffering < sps->num_ref_frames) + maxDecFrameBuffering = sps->num_ref_frames; + + uint32_t width = sps->frame_cropping_flag ? sps->m_cropRectWidth + : sps->m_width; + uint32_t height = sps->frame_cropping_flag ? sps->m_cropRectHeight + : sps->m_height; + if (setFormat(width, height, sps->m_width, sps->m_height, maxDecFrameBuffering + 1)) { + if (isSurfaceGeometryChanged()) { + decodeCurrent(); + m_dpb.flush(); + m_contextChanged = true; + } + return true; + } + return false; +} + +YamiStatus VaapiDecoderH264::ensureContext(const SharedPtr& sps) +{ + if (isDecodeContextChanged(sps)) + return YAMI_DECODE_FORMAT_CHANGE; + return ensureProfile(VAProfileH264High); // FIXME: set different profile later +} + +SurfacePtr VaapiDecoderH264::createSurface(const SliceHeader* const slice) +{ + SurfacePtr s = VaapiDecoderBase::createSurface(); + if (!s) + return s; + SharedPtr& sps = slice->m_pps->m_sps; + + if (sps->frame_cropping_flag) + s->setCrop(sps->m_cropX, sps->m_cropY, sps->m_cropRectWidth, sps->m_cropRectHeight); + else + s->setCrop(0, 0, sps->m_width, sps->m_height); + return s; +} + +YamiStatus VaapiDecoderH264::createPicture(const SliceHeader* const slice, + const NalUnit* const nalu) +{ + YamiStatus status = YAMI_SUCCESS; + VaapiPictureType picStructure; + bool isSecondField = false; + + /* skip all non-idr slices if m_prevPic is a NULL */ + if(!m_prevPic && !nalu->m_idrPicFlag) + return YAMI_DECODE_INVALID_DATA; + + if (slice->field_pic_flag) { + if (slice->bottom_field_flag) + picStructure = VAAPI_PICTURE_BOTTOM_FIELD; + else + picStructure = VAAPI_PICTURE_TOP_FIELD; + } else + picStructure = VAAPI_PICTURE_FRAME; + + /*The sencond field should use the same surface of the first filed*/ + if (slice->field_pic_flag) { + DPB::PictureList::iterator it = find_if( + m_dpb.m_pictures.begin(), m_dpb.m_pictures.end(), + bind(findComplementaryField, _1, slice->frame_num, picStructure)); + if (it != m_dpb.m_pictures.end()) { + m_currPic = (*it)->allocPicture(); + m_currPic->m_isSecondField = isSecondField = true; + m_currPic->m_complementField = *it; + } + } + + if (!slice->field_pic_flag || !isSecondField) { + m_currSurface = createSurface(slice); + if (!m_currSurface) + return YAMI_DECODE_NO_SURFACE; + m_currPic.reset( + new VaapiDecPictureH264(m_context, m_currSurface, m_currentPTS)); + } + + m_currPic->m_picOutputFlag = true; + m_currPic->m_idrFlag = nalu->m_idrPicFlag; + m_currPic->m_frameNum = slice->frame_num; + m_currPic->m_pocLsb = slice->pic_order_cnt_lsb; + m_currPic->m_hasMmco5 = checkMMCO5(slice->dec_ref_pic_marking); + m_currPic->m_picStructure = picStructure; + + if (isIdr(m_currPic)) { + m_prevPic.reset( + new VaapiDecPictureH264(m_context, m_currSurface, m_currentPTS)); + } + + if (nalu->nal_ref_idc) { + m_currPic->m_isReference = true; + m_currPic->m_longTermRefFlag + = (isIdr(m_currPic) + && slice->dec_ref_pic_marking.long_term_reference_flag); + m_currPic->m_shortTermRefFlag = !m_currPic->m_longTermRefFlag; + } else + m_currPic->m_isReference = m_currPic->m_longTermRefFlag + = m_currPic->m_shortTermRefFlag = false; + + return status; +} + +YamiStatus VaapiDecoderH264::decodeSlice(NalUnit* nalu) +{ + SharedPtr currSlice(new SliceHeader); + SliceHeader* slice = currSlice.get(); + YamiStatus status; + + *slice = SliceHeader(); + + if (!slice->parseHeader(&m_parser, nalu)) + return YAMI_DECODE_INVALID_DATA; + + status = ensureContext(slice->m_pps->m_sps); + if (status != YAMI_SUCCESS) { + return status; + } + + /* first slice when first_mb_in_slice is zero */ + if (!slice->first_mb_in_slice) { + status = decodeCurrent(); + if (status != YAMI_SUCCESS) + return status; + status = createPicture(slice, nalu); + if (status != YAMI_SUCCESS) + return status; + if (!m_currPic + || !m_dpb.init(m_currPic, m_prevPic, slice, nalu, m_newStream, + m_contextChanged, m_videoFormatInfo.surfaceNumber)) + return YAMI_DECODE_INVALID_DATA; + m_contextChanged = false; + if (!fillPicture(m_currPic, slice) || !fillIqMatrix(m_currPic, slice)) + return YAMI_FAIL; + } + + if (!m_currPic) + return YAMI_DECODE_INVALID_DATA; + + /* should init reference for every slice */ + m_dpb.initReference(m_currPic, slice); + + if (!fillSlice(m_currPic, slice, nalu)) + return YAMI_FAIL; + + return status; +} + +YamiStatus VaapiDecoderH264::decodeNalu(NalUnit* nalu) +{ + uint8_t type = nalu->nal_unit_type; + YamiStatus status = YAMI_SUCCESS; + + if (NAL_SLICE_NONIDR <= type && type <= NAL_SLICE_IDR) { + status = decodeSlice(nalu); + } else { + status = decodeCurrent(); + if (status != YAMI_SUCCESS) + return status; + switch (type) { + case NAL_SPS: + status = decodeSps(nalu); + break; + case NAL_PPS: + status = decodePps(nalu); + break; + case NAL_STREAM_END: + m_endOfStream = true; + break; + case NAL_SEQ_END: + m_endOfSequence = true; + break; + default: + break; + } + } + + return status; +} + +void VaapiDecoderH264::flush(void) +{ + decodeCurrent(); + m_dpb.flush(); + m_newStream = true; + m_endOfStream = false; + m_endOfSequence = false; + m_currPic.reset(); + m_prevPic.reset(); + m_currSurface.reset(); + m_contextChanged = false; + VaapiDecoderBase::flush(); +} + +YamiStatus VaapiDecoderH264::decode(VideoDecodeBuffer* buffer) +{ + if (!buffer || !buffer->data) { + decodeCurrent(); + m_dpb.flush(); + m_newStream = true; + m_endOfStream = false; + m_endOfSequence = false; + m_currPic.reset(); + m_prevPic.reset(); + m_currSurface.reset(); + m_contextChanged = false; + return YAMI_SUCCESS; + } + m_currentPTS = buffer->timeStamp; + + int32_t size; + NalUnit nalu; + YamiStatus lastError = YAMI_SUCCESS; + YamiStatus status = YAMI_SUCCESS; + const uint8_t* nal; + NalReader nr(buffer->data, buffer->size, m_nalLengthSize); + + while (nr.read(nal, size)) { + if (nalu.parseNalUnit(nal, size)) + status = decodeNalu(&nalu); + if (status != YAMI_SUCCESS) { + //we will continue decode if decodeNalu return YAMI_DECODE_INVALID_DATA + //but we will return the error at end of fucntion + lastError = status; + if (status != YAMI_DECODE_INVALID_DATA) + return status; + } + } + if (buffer->flag & VIDEO_DECODE_BUFFER_FLAG_FRAME_END) { + //send current buffer to libva + decodeCurrent(); + } + return lastError; +} + +} diff --git a/decoder/vaapidecoder_h264.h b/decoder/vaapidecoder_h264.h new file mode 100644 index 0000000..4a8b23a --- /dev/null +++ b/decoder/vaapidecoder_h264.h @@ -0,0 +1,179 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_h264_h +#define vaapidecoder_h264_h + +#include "codecparsers/h264Parser.h" +#include "common/Functional.h" +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" + +#include + +namespace YamiMediaCodec { + +#define H264_MAX_REFRENCE_SURFACE_NUMBER 16 + +class VaapiDecPictureH264; +class VaapiDecoderH264 : public VaapiDecoderBase { +public: + typedef SharedPtr PicturePtr; + typedef std::vector RefSet; + typedef YamiParser::H264::SliceHeader SliceHeader; + typedef YamiParser::H264::NalUnit NalUnit; + typedef YamiParser::H264::SPS SPS; + + VaapiDecoderH264(); + virtual ~VaapiDecoderH264(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus decode(VideoDecodeBuffer*); + virtual void flush(void); + +private: + friend class FactoryTest; + friend class VaapiDecoderH264Test; + + class DPB { + typedef VaapiDecoderH264::RefSet RefSet; + typedef std::function + OutputCallback; + typedef std::function ForEachFunction; + + public: + typedef VaapiDecoderH264::PicturePtr PicturePtr; + struct PocLess { + inline bool operator()(const PicturePtr& left, + const PicturePtr& right) const; + }; + typedef std::set PictureList; + + DPB(OutputCallback output); + bool init(const PicturePtr&, const PicturePtr&, + const SliceHeader* const, const NalUnit* const, + bool newStream, bool contextChanged, + uint32_t maxDecFrameBuffering); + bool add(const PicturePtr&); + void outputReadyFrame(const PicturePtr&); + void initReference(const PicturePtr&, const SliceHeader* const); + void flush(); + + RefSet m_refList0; + RefSet m_refList1; + + PictureList m_pictures; + bool m_isLowLatencymode; + + private: + void forEach(ForEachFunction); + + template void findAndMarkUnusedReference(P); + + void initPSliceRef(const PicturePtr& picture, const SliceHeader* const); + + void initBSliceRef(const PicturePtr& picture, const SliceHeader* const); + + void initReferenceList(const PicturePtr& picture, + const SliceHeader* const); + + bool modifyReferenceList(const PicturePtr& picture, + const SliceHeader* const slice, + RefSet& refList, uint8_t refIdx); + + void processFrameNumWithGaps(const PicturePtr& picture, + const SliceHeader* const slice); + + void adaptiveMarkReference(const PicturePtr& picture); + + bool slidingWindowMarkReference(const PicturePtr& picture); + bool markReference(const PicturePtr& picture); + + bool isFull(); + void removeUnused(); + void clearRefSet(); + + bool calcPoc(const PicturePtr&, const SliceHeader* const); + void calcPicNum(const PicturePtr& picture, + const SliceHeader* const slice); + + void bumpAll(); + bool bump(); + bool output(const PicturePtr& picture); + void printRefList(); + + RefSet m_shortTermList; + RefSet m_shortTermList1; // used to reoder m_shortTermList, then + // generate m_refList1 + RefSet m_longTermList; + + PicturePtr m_prevPicture; + OutputCallback m_output; + PicturePtr m_dummy; + bool m_noOutputOfPriorPicsFlag; + uint32_t m_maxFrameNum; + uint32_t m_maxNumRefFrames; + uint32_t m_maxDecFrameBuffering; + YamiParser::H264::DecRefPicMarking m_decRefPicMarking; + }; + + YamiStatus decodeNalu(NalUnit*); + YamiStatus decodeSps(NalUnit*); + YamiStatus decodePps(NalUnit*); + YamiStatus decodeSlice(NalUnit*); + + YamiStatus ensureContext(const SharedPtr& sps); + bool fillPicture(const PicturePtr&, const SliceHeader* const); + bool fillSlice(const PicturePtr&, const SliceHeader* const, + const NalUnit* const); + bool fillIqMatrix(const PicturePtr&, const SliceHeader* const); + bool fillPredWeightTable(VASliceParameterBufferH264*, + const SliceHeader* const); + void fillReference(VAPictureH264* refs, size_t size); + + bool fillReferenceIndex(VASliceParameterBufferH264*, + const SliceHeader* const); + void fillReferenceIndexForList(VASliceParameterBufferH264* sliceParam, + const SliceHeader* const slice, + RefSet& refSet, bool isList0); + bool isDecodeContextChanged(const SharedPtr& sps); + bool decodeAvcRecordData(uint8_t* buf, int32_t bufSize); + + YamiStatus createPicture(const SliceHeader* const, + const NalUnit* const nalu); + YamiStatus decodeCurrent(); + YamiStatus outputPicture(const PicturePtr&); + SurfacePtr createSurface(const SliceHeader* const); + + YamiParser::H264::Parser m_parser; + PicturePtr m_currPic; + PicturePtr m_prevPic; + bool m_newStream; + bool m_endOfSequence; + bool m_endOfStream; + DPB m_dpb; + uint32_t m_nalLengthSize; + SurfacePtr m_currSurface; + bool m_contextChanged; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; +} // namespace YamiMediaCodec + +#endif diff --git a/decoder/vaapidecoder_h264_unittest.cpp b/decoder/vaapidecoder_h264_unittest.cpp new file mode 100644 index 0000000..1af46bc --- /dev/null +++ b/decoder/vaapidecoder_h264_unittest.cpp @@ -0,0 +1,177 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapidecoder_h264.h" + +// library headers +#include "common/Array.h" + +namespace YamiMediaCodec { + +const static std::array g_SimpleH264 = { + 0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, 0x28, 0xab, 0x40, 0xb0, 0x4a, + 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x79, 0x08, + 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x03, 0x9c, 0x30, 0x00, 0x00, 0x00, + 0x01, 0x65, 0xb8, 0x20, 0x19, 0x09, 0xf4, 0xa0, 0x97, 0x12, 0x5b, 0xaa, + 0x1d, 0x1d, 0x71, 0x2f, 0x30, 0xfe, 0xa0, 0x80, 0x7d, 0x32, 0xf6, 0xae, + 0x7f, 0x6d, 0xd2, 0x1c, 0x59, 0xfe, 0xc7, 0x15, 0x7c, 0x08, 0xa4, 0xa2, + 0x80, 0xed, 0x28, 0xfc, 0xcf, 0x73, 0x1c, 0x36, 0x1f, 0x33, 0x7e, 0x3a, + 0xd2, 0xcf, 0x46, 0xa8, 0x29, 0x79, 0x10, 0x7e, 0x14, 0x49, 0x63, 0xc5, + 0x93, 0x30, 0x16, 0x4b, 0x55, 0xef, 0x8f, 0x2b, 0x77, 0xb6, 0x62, 0x20, + 0x54, 0x1c, 0x49, 0x22, 0xda, 0xe8, 0xfd, 0x9c, 0xad, 0x5b, 0x3b, 0xaa, + 0x1f, 0x2f, 0xff, 0x30, 0xe0, 0x76, 0x49, 0xa7, 0x3f, 0x45, 0xd8, 0x9d, + 0x43, 0x41, 0xda, 0xd8, 0x8b, 0x7a, 0xa4, 0x77, 0x74, 0x83, 0xe5, 0x51, + 0x2c, 0x2e, 0x60, 0xfa, 0xcc, 0x35, 0x8f, 0x65, 0x7b, 0xa0, 0xd8, 0xfc, + 0xcd, 0x11, 0xa8, 0x6e, 0xae, 0xc8, 0x89, 0xe3, 0xdc, 0x2f, 0xa3, 0x4d, + 0x0d, 0x7a, 0xdd, 0xdd, 0x02, 0x59, 0xc4, 0xc3, 0xde, 0xda, 0x74, 0x2a, + 0xea, 0xbc, 0x85, 0x40, 0x97, 0x9f, 0x2f, 0x4d, 0x12, 0x74, 0x5d, 0x0f, + 0x29, 0xed, 0x23, 0xf6, 0x65, 0x3e, 0xd6, 0x35, 0x40, 0xea, 0xce, 0x2a, + 0xf6, 0x74, 0xbb, 0x88, 0x13, 0xb7, 0xa7, 0x04, 0xdd, 0x0f, 0x47, 0x52, + 0xbd, 0xef, 0xe0, 0xd2, 0x26, 0x8c, 0x56, 0xf3, 0x3f, 0xe7, 0x53, 0xba, + 0x4e, 0xc0, 0x62, 0xec, 0xbc, 0x56, 0x1c, 0x1c, 0xce, 0xf1, 0x01, 0x62, + 0x53, 0xdd, 0x1f, 0x55, 0x18, 0x32, 0xfb, 0x22, 0x40, 0xc9, 0xdf, 0x1e, + 0x77, 0x82, 0x80, 0x62, 0xec, 0x08, 0xc8, 0xc6, 0x64, 0x85, 0xb1, 0x38, + 0x48, 0x59, 0x76, 0xc3, 0x1e, 0x6a, 0x19, 0x11, 0xfd, 0x83, 0x4e, 0x0b, + 0xd1, 0xb0, 0x17, 0x2d, 0xde, 0x76, 0x9c, 0x90, 0x59, 0xa3, 0xe4, 0xe8, + 0x30, 0x88, 0x5c, 0x8c, 0x85, 0x47, 0xfe, 0x07, 0x88, 0x68, 0x1b, 0xbd, + 0x8a, 0x99, 0xc1, 0x5f, 0x6b, 0x0c, 0xfd, 0xbd, 0x33, 0x1a, 0x3f, 0xc1, + 0x7b, 0x97, 0xbb, 0x8a, 0xf2, 0x49, 0xda, 0x3e, 0xb8, 0x5e, 0xae, 0xbc, + 0xe2, 0x64, 0xc5, 0xfa, 0xa2, 0xeb, 0xc9, 0xcb, 0x7f, 0xf6, 0x78, 0xa3, + 0xa0, 0x8f, 0xae, 0xb0, 0x63, 0x09, 0x1b, 0x25, 0x49, 0x13, 0xdf, 0x65, + 0x4e, 0x73, 0xfc, 0xf0, 0xed, 0xd0, 0x42, 0x84, 0xc7, 0x78, 0xc0, 0xe7, + 0xe5, 0x15, 0x97, 0xc3, 0x13, 0xe9, 0x6f, 0xd2, 0xe3, 0x46, 0xa3, 0x84, + 0x9a, 0x51, 0xe5, 0x27, 0x5e, 0x00, 0x37, 0x5e, 0x8e, 0x1b, 0xd0, 0xdf, + 0xe0, 0xa2, 0x90, 0x1b, 0x96, 0x74, 0xca, 0xae, 0x7e, 0x61, 0x79, 0xe7, + 0x9f, 0x7a, 0x5a, 0x52, 0xe9, 0x60, 0x24, 0x07, 0x56, 0x07, 0x06, 0xb7, + 0xaa, 0x55, 0x48, 0xf3, 0x5b, 0x3c, 0x18, 0xce, 0x78, 0xf4, 0x36, 0x69, + 0xf3, 0xb0, 0x89, 0x6e, 0x96, 0x42, 0x47, 0x12, 0xef, 0x30, 0x1e, 0xff, + 0xb8, 0xfc, 0x94, 0x02, 0x8d, 0xa6, 0x5d, 0x01, 0xc4, 0xa0, 0xbe, 0xe7, + 0x6d, 0x21, 0xc5, 0xe1, 0x4d, 0xf7, 0x8b, 0x23, 0xd5, 0xac, 0x1a, 0xe4, + 0xba, 0xb1, 0x1e, 0x0c, 0x60, 0xe0, 0xcd, 0x60, 0xe1, 0x13, 0xa7, 0x35, + 0x12, 0x50, 0x40, 0x33, 0x81, 0x80, 0x05, 0x6e, 0xc4, 0xc6, 0xd6, 0xb5, + 0x38, 0xa2, 0x96, 0xee, 0x94, 0x37, 0xcf, 0x70, 0xdb, 0xec, 0x27, 0x6e, + 0x8e, 0x9b, 0xaa, 0x38, 0x85, 0x15, 0x09, 0x10, 0x01, 0xba, 0x7e, 0x18, + 0xb8, 0x05, 0xba, 0x4b, 0x76, 0x7e, 0x78, 0x8f, 0xaa, 0xaa, 0xaf, 0x5f, + 0xad, 0x42, 0x62, 0x76, 0x1f, 0x0f, 0xfe, 0x8d, 0x74, 0x24, 0xc8, 0x48, + 0x55, 0x54, 0xcf, 0x5b, 0x97, 0xf7, 0x10, 0x6f, 0x9a, 0xe2, 0xb4, 0xfa, + 0x53, 0x2d, 0x37, 0x2b, 0xd0, 0x50, 0x5a, 0x29, 0x99, 0xd6, 0x37, 0xdb, + 0xa7, 0x45, 0x33, 0x42, 0x34, 0x91, 0xad, 0xa2, 0x87, 0xf8, 0xa3, 0x6a, + 0xb2, 0x52, 0xe4, 0x37, 0x37, 0x92, 0x8b, 0xd2, 0xad, 0x91, 0xa5, 0xbd, + 0xcb, 0x0e, 0x32, 0x3b, 0xf9, 0x47, 0x2f, 0xd8, 0xc0, 0x50, 0x7e, 0x24, + 0xb7, 0xe6, 0x0b, 0xc2, 0x55, 0xb7, 0x11, 0x11, 0x04, 0x6a, 0x39, 0x54, + 0x66, 0xb1, 0x97, 0x94, 0x40, 0x98, 0xac, 0xf1, 0x07, 0x90, 0x74, 0xf7, + 0xab, 0x58, 0x05, 0x3d, 0x1a, 0xa5, 0x50, 0x48, 0x3f, 0x6f, 0xb1, 0x87, + 0x78, 0xf9, 0x7e, 0xbc, 0x0e, 0xdf, 0x05, 0x70, 0xa1, 0xd1, 0x55, 0xe9, + 0x76, 0x2f, 0xd5, 0x58, 0x31, 0x5d, 0x57, 0x17, 0x5e, 0xf0, 0xaa, 0xa7, + 0x3a, 0xe1, 0x72, 0xaf, 0x6f, 0x9c, 0x8f, 0xff, 0x34, 0x24, 0x2e, 0xed, + 0x46, 0x6e, 0xad, 0xd0, 0xfb, 0xcf, 0x28, 0xdd, 0xc9, 0x2e, 0x53, 0x3e, + 0xa5, 0xc0, 0xda, 0xcb, 0x32, 0x95, 0x13, 0xd6, 0x89, 0x6d, 0x3f, 0xa6, + 0x81, 0xc7, 0xa5, 0x47, 0x43, 0x7f, 0xe5, 0xd4, 0x82, 0xfa, 0x0d, 0xd1, + 0x93, 0x27, 0x06, 0xb5, 0x55, 0x37, 0x60, 0x20, 0xe1, 0x12, 0xf5, 0xf1, + 0xa6, 0x5e, 0x51, 0x79, 0x5e, 0x3d, 0xee, 0xab, 0xf1, 0xf7, 0x7d, 0x72, + 0x95, 0x59, 0xbb, 0x29, 0xba, 0x24, 0x85, 0xa9, 0xba, 0x52, 0x59, 0x64, + 0xee, 0x90, 0x19, 0x7c, 0x91, 0x4e, 0x1a, 0x4f, 0xd4, 0xed, 0x54, 0x01, + 0x86, 0x33, 0x78, 0xfe, 0x71, 0xdb, 0xd6, 0x36, 0x3b, 0xba, 0x5e, 0xd4, + 0x2c, 0x28, 0xa4, 0x97, 0x19, 0xb8, 0xf5, 0x6b, 0x30, 0x60, 0x4a, 0xf8, + 0xb7, 0x6d, 0x54, 0x2a, 0x52, 0x36, 0xae, 0xb1, 0x65, 0x26, 0xe6, 0xf5, + 0x2b, 0x12, 0x1c, 0x3b, 0x80, 0x0a, 0x4e, 0xf4, 0x9c, 0xd4, 0x28, 0x32, + 0x8e, 0x7c, 0x3f, 0x4d, 0xee, 0x54, 0xd8, 0x5e, 0xe9, 0x2d, 0xf3, 0x1d, + 0x20, 0xb3, 0x7b, 0x31, 0xcf, 0x4b, 0x76, 0x81, 0x39, 0xe8, 0xb2, 0x94, + 0x07, 0x3c, 0x7f, 0x38, 0xfa, 0x13, 0x25, 0x9f, 0xe7, 0x8d, 0xfb, 0xea, + 0x76, 0xe4, 0x2c, 0x14, 0x9e, 0x37, 0x32, 0x54, 0x62, 0xd2, 0x1e, 0xca, + 0x4d, 0xb7, 0x7c, 0x92, 0x52, 0x04, 0x67, 0xfa, 0x87, 0x86, 0x3f, 0xf2, + 0xdf, 0xaf, 0xac, 0x86, 0x10, 0x20, 0x68, 0x8f, 0xbe, 0xc4, 0x01, 0x6d, + 0x22, 0xe5, 0x0d, 0x37, 0x19, 0xb2, 0x83, 0x08, 0x75, 0xc3, 0x5a, 0xc1, + 0xc4, 0x9c, 0x44, 0xba, 0x18, 0x0f, 0x76, 0xdc, 0xc9, 0x3c, 0xd6, 0x59, + 0x67, 0x5d, 0xa0, 0x3b, 0x0b, 0x7d, 0xb0, 0x18, 0xff, 0xf6, 0x84, 0x43, + 0x81, 0xee, 0x5f, 0x4d, 0x58, 0x22, 0x29, 0x00, 0x78, 0x53, 0xb4, 0x61, + 0x0a, 0x38, 0x8d, 0x1a, 0xf5, 0xa1, 0x1b, 0x6c, 0x65, 0x75, 0x2a, 0xa2, + 0xe6, 0x30, 0xc3, 0x8d, 0x00, 0xd4, 0xe5, 0x7c, 0x14, 0x5c, 0x94, 0xb2, + 0xe8, 0x90, 0x4e, 0x38, 0xf1, 0x5a, 0x80, 0x5e, 0xa7, 0xae, 0xce, 0x3a, + 0x8c, 0x14, 0x44, 0x4b, 0x8e, 0x00, 0x8a, 0x37, 0x1d, 0x55, 0xe3, 0xa1, + 0x8f, 0x38, 0x33, 0x96, 0xcd, 0xf5, 0x9a, 0x00, 0x0a, 0xe5, 0x3d, 0xa0, + 0x59, 0x56, 0xfe, 0xf4, 0x74, 0x85, 0x58, 0x76, 0x38, 0x7c, 0xaf, 0x93, + 0x97, 0x4a, 0x41, 0x15, 0x7e, 0xfe, 0x8a, 0x5e, 0x34, 0x95, 0x06, 0xd6, + 0x64, 0xa0 +}; + +class VaapiDecoderH264Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIDECODER_H264_TEST(name) \ + TEST_F(VaapiDecoderH264Test, name) + +VAAPIDECODER_H264_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_AVC); + mimeTypes.push_back(YAMI_MIME_H264); + doFactoryTest(mimeTypes); +} + +VAAPIDECODER_H264_TEST(Decode_Simple) +{ + + VaapiDecoderH264 decoder; + VideoConfigBuffer configBuffer; + VideoDecodeBuffer buffer; + + memset(&configBuffer,0,sizeof(VideoConfigBuffer)); + configBuffer.profile = VAProfileNone; + + buffer.data = const_cast(g_SimpleH264.data()); + buffer.size = g_SimpleH264.size(); + buffer.timeStamp = 0; + + ASSERT_EQ(YAMI_SUCCESS, decoder.start(&configBuffer)); + ASSERT_EQ(YAMI_DECODE_FORMAT_CHANGE, decoder.decode(&buffer)); + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + /* pass a NULL buffer to flush output */ + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(NULL)); + + EXPECT_TRUE(bool(decoder.getOutput())); +} + +} diff --git a/decoder/vaapidecoder_h265.cpp b/decoder/vaapidecoder_h265.cpp new file mode 100644 index 0000000..d5dda5a --- /dev/null +++ b/decoder/vaapidecoder_h265.cpp @@ -0,0 +1,1252 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "codecparsers/h265Parser.h" +#include "common/log.h" +#include "common/nalreader.h" + +#include "vaapi/vaapiptrs.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapidecpicture.h" + +#include + +#include "vaapidecoder_h265.h" + +namespace YamiMediaCodec{ +typedef VaapiDecoderH265::PicturePtr PicturePtr; +using std::bind; +using std::placeholders::_1; +using std::ref; + +using namespace YamiParser::H265; + +bool isIdr(const NalUnit* const nalu) +{ + return nalu->nal_unit_type == NalUnit::IDR_W_RADL + || nalu->nal_unit_type == NalUnit::IDR_N_LP; +} + +bool isBla(const NalUnit* const nalu) +{ + return nalu->nal_unit_type == NalUnit::BLA_W_LP + || nalu->nal_unit_type == NalUnit::BLA_W_RADL + || nalu->nal_unit_type == NalUnit::BLA_N_LP; +} + +bool isIrap(const NalUnit* const nalu) +{ + return nalu->nal_unit_type >= NalUnit::BLA_W_LP + && nalu->nal_unit_type <= NalUnit::RSV_IRAP_VCL23; +} + +bool isRasl(const NalUnit* const nalu) +{ + return nalu->nal_unit_type == NalUnit::RASL_R + || nalu->nal_unit_type == NalUnit::RASL_N; +} + +bool isRadl(const NalUnit* const nalu) +{ + return nalu->nal_unit_type == NalUnit::RADL_R + || nalu->nal_unit_type == NalUnit::RADL_N; +} + +bool isCra(const NalUnit* const nalu) +{ + return nalu->nal_unit_type == NalUnit::CRA_NUT; +} + +bool isSublayerNoRef(const NalUnit* const nalu) +{ + static const uint8_t noRef[] = { + NalUnit::TRAIL_N, + NalUnit::TSA_N, + NalUnit::STSA_N, + NalUnit::RADL_N, + NalUnit::RASL_N, + NalUnit::RSV_VCL_N10, + NalUnit::RSV_VCL_N12, + NalUnit::RSV_VCL_N14 + }; + static const uint8_t* end = noRef + N_ELEMENTS(noRef); + return std::binary_search(noRef, end, nalu->nal_unit_type); +} + +class VaapiDecPictureH265 : public VaapiDecPicture +{ +public: + VaapiDecPictureH265(const ContextPtr& context, const SurfacePtr& surface, int64_t timeStamp): + VaapiDecPicture(context, surface, timeStamp) + { + } + VaapiDecPictureH265() + { + } + int32_t m_poc; + uint16_t m_pocLsb; + bool m_noRaslOutputFlag; + bool m_picOutputFlag; + uint32_t m_picLatencyCount; + + //is unused reference picture + bool m_isUnusedReference; + //is this picture ref able? + bool m_isReference; + +}; + +inline bool VaapiDecoderH265::DPB::PocLess::operator()(const PicturePtr& left, const PicturePtr& right) const +{ + return left->m_poc < right->m_poc; +} + +VaapiDecoderH265::DPB::DPB(OutputCallback output): + m_output(output), + m_dummy(new VaapiDecPictureH265) +{ +} + +bool VaapiDecoderH265::DPB::initShortTermRef(RefSet& ref, int32_t currPoc, + const int32_t* delta, const uint8_t* used, uint8_t num) +{ + if (num > 16) + return false; + ref.clear(); + for (uint8_t i = 0; i < num; i++) { + int32_t poc = currPoc + delta[i]; + VaapiDecPictureH265* pic = getPic(poc); + if (!pic) { + ERROR("can't find short ref %d for %d", poc, currPoc); + } else { + if (used[i]) + ref.push_back(pic); + else + m_stFoll.push_back(pic); + } + } + return true; +} + +bool VaapiDecoderH265::DPB::initShortTermRef(const PicturePtr& picture, + const SliceHeader* const slice) +{ + const PPS *const pps = slice->pps.get(); + const SPS *const sps = pps->sps.get(); + + const ShortTermRefPicSet* stRef; + if (!slice->short_term_ref_pic_set_sps_flag) + stRef = &slice->short_term_ref_pic_sets; + else + stRef = &sps->short_term_ref_pic_set[slice->short_term_ref_pic_set_idx]; + + //clear it here + m_stFoll.clear(); + + if (!initShortTermRef(m_stCurrBefore, picture->m_poc, + stRef->DeltaPocS0, stRef->UsedByCurrPicS0, stRef->NumNegativePics)) + return false; + if (!initShortTermRef(m_stCurrAfter, picture->m_poc, + stRef->DeltaPocS1, stRef->UsedByCurrPicS1, stRef->NumPositivePics)) + return false; + return true; +} + +bool VaapiDecoderH265::DPB::initLongTermRef(const PicturePtr& picture, const SliceHeader *const slice) +{ + const PPS *const pps = slice->pps.get(); + const SPS *const sps = pps->sps.get(); + + int32_t deltaPocMsbCycleLt[16]; + + const int32_t maxPicOrderCntLsb =1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + uint16_t num = slice->num_long_term_sps + slice->num_long_term_pics; + //(7-38) + for (int i = 0; i < num; i++) { + if( i == 0 || i == slice->num_long_term_sps) + deltaPocMsbCycleLt[ i ] = slice->delta_poc_msb_cycle_lt[i]; + else + deltaPocMsbCycleLt[ i ] = slice->delta_poc_msb_cycle_lt[ i ] + deltaPocMsbCycleLt[i-1]; + } + //(8-5) + for (int i = 0; i < num; i++) { + int32_t poc; + bool used; + if (i < slice->num_long_term_sps) { + poc = sps->lt_ref_pic_poc_lsb_sps[slice->lt_idx_sps[i]]; + used = sps->used_by_curr_pic_lt_sps_flag[slice->lt_idx_sps[i]]; + } else { + poc = slice->poc_lsb_lt[i]; + used = slice->used_by_curr_pic_lt_flag[i]; + } + if (slice->delta_poc_msb_present_flag[i]) { + poc += picture->m_poc - deltaPocMsbCycleLt[i] * maxPicOrderCntLsb + - slice->slice_pic_order_cnt_lsb; + } + VaapiDecPictureH265* pic = getPic(poc, slice->delta_poc_msb_present_flag[i]); + if (!pic) { + ERROR("can't find long ref %d for %d", poc, picture->m_poc); + } else { + if (used) + m_ltCurr.push_back(pic); + else + m_ltFoll.push_back(pic); + } + } + return true; + +} + +void markUnusedReference(const PicturePtr& picture) +{ + picture->m_isUnusedReference = true; +} + +void clearReference(const PicturePtr& picture) +{ + if (picture->m_isUnusedReference) + picture->m_isReference = false; +} + +inline bool isOutputNeeded(const PicturePtr& picture) +{ + return picture->m_picOutputFlag; +} + +inline bool isReference(const PicturePtr& picture) +{ + return picture->m_isReference; +} + +inline bool isUnusedPicture(const PicturePtr& picture) +{ + return !isReference(picture) && !isOutputNeeded(picture); +} + +void VaapiDecoderH265::DPB::removeUnused() +{ + forEach(clearReference); + + /* Remove unused pictures from DPB */ + PictureList::iterator it; + for (it = m_pictures.begin(); it != m_pictures.end();) { + if (isUnusedPicture(*it)) + m_pictures.erase(it++); + else + ++it; + } +} + +void VaapiDecoderH265::DPB::clearRefSet() +{ + m_stCurrBefore.clear(); + m_stCurrAfter.clear(); + m_stFoll.clear(); + m_ltCurr.clear(); + m_ltFoll.clear(); +} +/*8.3.2*/ +bool VaapiDecoderH265::DPB::initReference(const PicturePtr& picture, + const SliceHeader *const slice, const NalUnit *const nalu, bool newStream) +{ + clearRefSet(); + if (isIdr(nalu)) + return true; + if (!initShortTermRef(picture, slice)) + return false; + if (!initLongTermRef(picture, slice)) + return false; + return true; +} + +bool matchPocLsb(const PicturePtr& picture, int32_t poc) +{ + return picture->m_pocLsb == poc; +} + +VaapiDecPictureH265* VaapiDecoderH265::DPB::getPic(int32_t poc, bool hasMsb) +{ + PictureList::iterator it; + if (hasMsb) { + m_dummy->m_poc = poc; + it = m_pictures.find(m_dummy); + } else { + it = find_if(m_pictures.begin(), m_pictures.end(), bind(matchPocLsb, _1, poc)); + } + if (it != m_pictures.end()) { + const PicturePtr& picture = *it; + if (picture->m_isReference) { + //use by current decode picture + picture->m_isUnusedReference = false; + return picture.get(); + } + } + return NULL; +} + +void VaapiDecoderH265::DPB::forEach(ForEachFunction fn) +{ + std::for_each(m_pictures.begin(), m_pictures.end(), fn); +} + +bool VaapiDecoderH265::DPB::checkReorderPics(const SPS* const sps) +{ + uint32_t num = count_if(m_pictures.begin(), m_pictures.end(), isOutputNeeded); + return num > sps->sps_max_num_reorder_pics[sps->sps_max_sub_layers_minus1]; +} + +bool checkPicLatencyCount(const PicturePtr& picture, uint32_t spsMaxLatencyPictures) +{ + return isOutputNeeded(picture) && (picture->m_picLatencyCount >= spsMaxLatencyPictures); +} + +bool VaapiDecoderH265::DPB::checkLatency(const SPS* const sps) +{ + uint8_t highestTid = sps->sps_max_sub_layers_minus1; + if (!sps->sps_max_latency_increase_plus1[highestTid]) + return false; + uint16_t spsMaxLatencyPictures = sps->sps_max_num_reorder_pics[highestTid] + + sps->sps_max_latency_increase_plus1[highestTid] - 1; + return find_if(m_pictures.begin(), + m_pictures.end(), + bind(checkPicLatencyCount, _1, spsMaxLatencyPictures) + ) != m_pictures.end(); + +} + +bool VaapiDecoderH265::DPB::checkDpbSize(const SPS* const sps) +{ + uint8_t highestTid = sps->sps_max_sub_layers_minus1; + return m_pictures.size() >= (size_t)(sps->sps_max_dec_pic_buffering_minus1[highestTid] + 1); +} + +//C.5.2.2 +bool VaapiDecoderH265::DPB::init(const PicturePtr& picture, + const SliceHeader *const slice, const NalUnit *const nalu, bool newStream) +{ + forEach(markUnusedReference); + if (!initReference(picture, slice, nalu, newStream)) + return false; + if (isIrap(nalu) && picture->m_noRaslOutputFlag && !newStream) { + bool noOutputOfPriorPicsFlag; + //TODO how to check C.5.2.2 item 1's second otherwise + if (isCra(nalu)) + noOutputOfPriorPicsFlag = true; + else + noOutputOfPriorPicsFlag = slice->no_output_of_prior_pics_flag; + clearRefSet(); + if (!noOutputOfPriorPicsFlag) { + removeUnused(); + bumpAll(); + } + m_pictures.clear(); + return true; + } + removeUnused(); + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); + while (checkReorderPics(sps) || checkLatency(sps) || checkDpbSize(sps)) { + if (!bump()) + return false; + } + + return true; +} + +bool VaapiDecoderH265::DPB::output(const PicturePtr& picture) +{ + picture->m_picOutputFlag = false; + + return m_output(picture) == YAMI_SUCCESS; +} + +bool VaapiDecoderH265::DPB::bump() +{ + PictureList::iterator it = + find_if(m_pictures.begin(),m_pictures.end(), isOutputNeeded); + if (it == m_pictures.end()) + return false; + bool success = output(*it); + if (!isReference(*it)) + m_pictures.erase(it); + return success; +} + +void VaapiDecoderH265::DPB::bumpAll() +{ + while (bump()) + /* nothing */; +} + +void addLatency(const PicturePtr& picture) +{ + if (picture->m_picOutputFlag) + picture->m_picLatencyCount++; +} + +bool VaapiDecoderH265::DPB::add(const PicturePtr& picture, const SliceHeader* const lastSlice) +{ + const PPS* const pps = lastSlice->pps.get(); + const SPS* const sps = pps->sps.get(); + + forEach(addLatency); + picture->m_picLatencyCount = 0; + picture->m_isReference = true; + m_pictures.insert(picture); + while (checkReorderPics(sps) || checkLatency(sps)) + bump(); + return true; +} + + +void VaapiDecoderH265::DPB::flush() +{ + bumpAll(); + clearRefSet(); + m_pictures.clear(); +} + +VaapiDecoderH265::VaapiDecoderH265(): + m_prevPicOrderCntMsb(0), + m_prevPicOrderCntLsb(0), + m_nalLengthSize(0), + m_newStream(true), + m_endOfSequence(false), + m_dpb(bind(&VaapiDecoderH265::outputPicture, this, _1)) +{ + m_parser.reset(new Parser()); + m_prevSlice.reset(new SliceHeader()); +} + +VaapiDecoderH265::~VaapiDecoderH265() +{ + stop(); +} + +YamiStatus VaapiDecoderH265::start(VideoConfigBuffer* buffer) +{ + if (buffer->data && buffer->size > 0) { + if (!decodeHevcRecordData(buffer->data, buffer->size)) { + ERROR("decode record data failed"); + return DECODE_FAIL; + } + } + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderH265::decodeParamSet(NalUnit* nalu) +{ + bool res = true; + + switch (nalu->nal_unit_type) { + case NalUnit::VPS_NUT: + res = m_parser->parseVps(nalu); + break; + case NalUnit::SPS_NUT: + res = m_parser->parseSps(nalu); + break; + case NalUnit::PPS_NUT: + res = m_parser->parsePps(nalu); + } + + return res ? YAMI_SUCCESS : YAMI_DECODE_INVALID_DATA; +} + +YamiStatus VaapiDecoderH265::outputPicture(const PicturePtr& picture) +{ + VaapiDecoderBase::PicturePtr base = std::static_pointer_cast(picture); + return VaapiDecoderBase::outputPicture(base); +} + +YamiStatus VaapiDecoderH265::decodeCurrent() +{ + YamiStatus status = YAMI_SUCCESS; + if (!m_current) + return status; + if (!m_current->decode()) { + ERROR("decode %d failed", m_current->m_poc); + //ignore it + return status; + } + if (!m_dpb.add(m_current, m_prevSlice.get())) + return YAMI_DECODE_INVALID_DATA; + m_current.reset(); + m_newStream = false; + return status; +} + +#define FILL_SCALING_LIST(mxm) \ +void fillScalingList##mxm(VAIQMatrixBufferHEVC* iqMatrix, const ScalingList* const scalingList) \ +{ \ + for (size_t i = 0; i < N_ELEMENTS(iqMatrix->ScalingList##mxm); i++) { \ + for (size_t j = 0; j < N_ELEMENTS(UpperRightDiagonal##mxm); j++) { \ + iqMatrix->ScalingList##mxm[i][UpperRightDiagonal##mxm[j]] = scalingList->scalingList##mxm[i][j]; \ + } \ + } \ +} + +FILL_SCALING_LIST(4x4) +FILL_SCALING_LIST(8x8) +FILL_SCALING_LIST(16x16) +void fillScalingList32x32(VAIQMatrixBufferHEVC* iqMatrix, const ScalingList* const scalingList) +{ + for (size_t i = 0; i < N_ELEMENTS(iqMatrix->ScalingList32x32); i++) { + for (size_t j = 0; j < N_ELEMENTS(UpperRightDiagonal32x32); j++) { + // According to spec "7.3.4 Scaling list data syntax", + // just use scalingList32x32[0] and scalingList32x32[3]. + iqMatrix->ScalingList32x32[i][UpperRightDiagonal32x32[j]] = scalingList->scalingList32x32[i * 3][j]; + } + } +} + +#define FILL_SCALING_LIST_DC(mxm) \ + void fillScalingListDc##mxm(VAIQMatrixBufferHEVC* iqMatrix, const ScalingList* const scalingList) \ + { \ + for (size_t i = 0; i < N_ELEMENTS(iqMatrix->ScalingListDC##mxm); i++) { \ + iqMatrix->ScalingListDC##mxm[i] = scalingList->scalingListDC##mxm[i]; \ + } \ + } + +FILL_SCALING_LIST_DC(16x16) +void fillScalingListDc32x32(VAIQMatrixBufferHEVC* iqMatrix, const ScalingList* const scalingList) +{ + for (size_t i = 0; i < N_ELEMENTS(iqMatrix->ScalingListDC32x32); i++) { + // similar to scalingList32x32. + iqMatrix->ScalingListDC32x32[i] = scalingList->scalingListDC32x32[i * 3]; + } +} + +bool VaapiDecoderH265::fillIqMatrix(const PicturePtr& picture, const SliceHeader* const slice) +{ + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); + const ScalingList* scalingList; + if (pps->pps_scaling_list_data_present_flag) { + scalingList = &pps->scaling_list; + } else if(sps->scaling_list_enabled_flag) { + if(sps->sps_scaling_list_data_present_flag) { + scalingList = &sps->scaling_list; + } else { + scalingList = &pps->scaling_list; + } + } else { + //default scaling list + return true; + } + VAIQMatrixBufferHEVC* iqMatrix; + if (!picture->editIqMatrix(iqMatrix)) + return false; + fillScalingList4x4(iqMatrix, scalingList); + fillScalingList8x8(iqMatrix, scalingList); + fillScalingList16x16(iqMatrix, scalingList); + fillScalingList32x32(iqMatrix, scalingList); + fillScalingListDc16x16(iqMatrix, scalingList); + fillScalingListDc32x32(iqMatrix, scalingList); + return true; +} + +void VaapiDecoderH265::fillReference(VAPictureHEVC* refs, int32_t& n, + const RefSet& refset, uint32_t flags) +{ + for (size_t i = 0; i < refset.size(); i++) { + VAPictureHEVC* r = refs + n; + const VaapiDecPictureH265* pic = refset[i]; + + r->picture_id = refset[i]->getSurfaceID(); + r->pic_order_cnt = pic->m_poc; + r->flags = flags; + + //record for late use + m_pocToIndex[pic->m_poc] = n; + + n++; + + } +} + +void VaapiDecoderH265::fillReference(VAPictureHEVC* refs, int32_t size) +{ + int32_t n = 0; + //clear index map + m_pocToIndex.clear(); + + fillReference(refs, n, m_dpb.m_stCurrBefore, VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE); + fillReference(refs, n, m_dpb.m_stCurrAfter, VA_PICTURE_HEVC_RPS_ST_CURR_AFTER); + fillReference(refs, n, m_dpb.m_stFoll, 0); + fillReference(refs, n, m_dpb.m_ltCurr, VA_PICTURE_HEVC_LONG_TERM_REFERENCE | VA_PICTURE_HEVC_RPS_LT_CURR); + fillReference(refs, n, m_dpb.m_ltFoll, VA_PICTURE_HEVC_LONG_TERM_REFERENCE); + for (int i = n; i < size; i++) { + VAPictureHEVC* ref = refs + i; + ref->picture_id = VA_INVALID_SURFACE; + ref->pic_order_cnt = 0; + ref->flags = VA_PICTURE_HEVC_INVALID; + } + + +} +bool VaapiDecoderH265::fillPicture(const PicturePtr& picture, const SliceHeader* const slice) +{ + VAPictureParameterBufferHEVC* param; + if (!picture->editPicture(param)) + return false; + param->CurrPic.picture_id = picture->getSurfaceID(); + param->CurrPic.pic_order_cnt = picture->m_poc; + fillReference(param->ReferenceFrames, N_ELEMENTS(param->ReferenceFrames)); + + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); +#define FILL(h, f) param->f = h->f + FILL(sps, pic_width_in_luma_samples); + FILL(sps, pic_height_in_luma_samples); +#define FILL_PIC(h, f) param->pic_fields.bits.f = h->f + FILL_PIC(sps, chroma_format_idc); + FILL_PIC(sps, separate_colour_plane_flag); + FILL_PIC(sps, pcm_enabled_flag); + FILL_PIC(sps, scaling_list_enabled_flag); + FILL_PIC(pps, transform_skip_enabled_flag); + FILL_PIC(sps, amp_enabled_flag); + FILL_PIC(sps, strong_intra_smoothing_enabled_flag); + FILL_PIC(pps, sign_data_hiding_enabled_flag); + FILL_PIC(pps, constrained_intra_pred_flag); + FILL_PIC(pps, cu_qp_delta_enabled_flag); + FILL_PIC(pps, weighted_pred_flag); + FILL_PIC(pps, weighted_bipred_flag); + FILL_PIC(pps, transquant_bypass_enabled_flag); + FILL_PIC(pps, tiles_enabled_flag); + FILL_PIC(pps, entropy_coding_sync_enabled_flag); + param->pic_fields.bits.pps_loop_filter_across_slices_enabled_flag + = pps->pps_loop_filter_across_slices_enabled_flag; + FILL_PIC(pps, loop_filter_across_tiles_enabled_flag); + FILL_PIC(sps, pcm_loop_filter_disabled_flag); + //how to fill this? + //NoPicReorderingFlag + //NoBiPredFlag + + param->sps_max_dec_pic_buffering_minus1 = + sps->sps_max_dec_pic_buffering_minus1[0]; + FILL(sps, bit_depth_luma_minus8); + FILL(sps, bit_depth_chroma_minus8); + FILL(sps, pcm_sample_bit_depth_luma_minus1); + FILL(sps, pcm_sample_bit_depth_chroma_minus1); + FILL(sps, log2_min_luma_coding_block_size_minus3); + FILL(sps, log2_diff_max_min_luma_coding_block_size); + FILL(sps, log2_min_transform_block_size_minus2); + FILL(sps, log2_diff_max_min_transform_block_size); + FILL(sps, log2_min_pcm_luma_coding_block_size_minus3); + FILL(sps, log2_diff_max_min_pcm_luma_coding_block_size); + FILL(sps, max_transform_hierarchy_depth_intra); + FILL(sps, max_transform_hierarchy_depth_inter); + FILL(pps, init_qp_minus26); + FILL(pps, diff_cu_qp_delta_depth); + param->pps_cb_qp_offset = pps->pps_cb_qp_offset; + param->pps_cr_qp_offset = pps->pps_cr_qp_offset; + FILL(pps, log2_parallel_merge_level_minus2); + FILL(pps, num_tile_columns_minus1); + FILL(pps, num_tile_rows_minus1); + for (int i = 0; i <= pps->num_tile_columns_minus1; i++) { + param->column_width_minus1[i] = pps->column_width_minus1[i]; + } + for (int i = 0; i <= pps->num_tile_rows_minus1; i++) { + param->row_height_minus1[i] = pps->row_height_minus1[i]; + } + + +#define FILL_SLICE(h, f) param->slice_parsing_fields.bits.f = h->f +#define FILL_SLICE_1(h, f) param->slice_parsing_fields.bits.h##_##f = h->f + + FILL_SLICE(pps, lists_modification_present_flag); + FILL_SLICE(sps, long_term_ref_pics_present_flag); + FILL_SLICE_1(sps, temporal_mvp_enabled_flag); + + FILL_SLICE(pps, cabac_init_present_flag); + FILL_SLICE(pps, output_flag_present_flag); + FILL_SLICE(pps, dependent_slice_segments_enabled_flag); + FILL_SLICE_1(pps, slice_chroma_qp_offsets_present_flag); + FILL_SLICE(sps, sample_adaptive_offset_enabled_flag); + FILL_SLICE(pps, deblocking_filter_override_enabled_flag); + param->slice_parsing_fields.bits.pps_disable_deblocking_filter_flag = + pps->pps_deblocking_filter_disabled_flag; + FILL_SLICE(pps, slice_segment_header_extension_present_flag); + + /* how to fill following fields + RapPicFlag + IdrPicFlag + IntraPicFlag */ + + FILL(sps, log2_max_pic_order_cnt_lsb_minus4); + FILL(sps, num_short_term_ref_pic_sets); + param->num_long_term_ref_pic_sps = sps->num_long_term_ref_pics_sps; + FILL(pps, num_ref_idx_l0_default_active_minus1); + FILL(pps, num_ref_idx_l1_default_active_minus1); + param->pps_beta_offset_div2 = pps->pps_beta_offset_div2; + param->pps_tc_offset_div2 = pps->pps_tc_offset_div2; + FILL(pps, num_extra_slice_header_bits); + + /* how to fill this + st_rps_bits*/ + +#undef FILL +#undef FILL_PIC +#undef FILL_SLICE +#undef FILL_SLICE_1 + + return true; +} + +bool VaapiDecoderH265::getRefPicList(RefSet& refset, const RefSet& stCurr0, const RefSet& stCurr1, + uint8_t numActive, bool modify, const uint32_t* modiList) +{ + if (numActive > 15) { + ERROR("bug: reference picutre can't large than 15"); + return false; + } + const RefSet& ltCurr = m_dpb.m_ltCurr; + uint8_t numPocTotalCurr = stCurr0.size() + stCurr1.size() + ltCurr.size(); + if (numActive && !numPocTotalCurr) { + ERROR("active refs is %d, but num numPocTotalCurr is %d", numActive, numPocTotalCurr); + return false; + } + uint8_t numRpsCurrTempList = std::max(numPocTotalCurr, numActive); + RefSet temp; + temp.reserve(numRpsCurrTempList); + uint32_t rIdx = 0; + //(8-8) and (8-10) + while (rIdx < numRpsCurrTempList) { + for(uint32_t i = 0; i < stCurr0.size() && rIdx < numRpsCurrTempList; rIdx++, i++ ) + temp.push_back(stCurr0[i]); + for(uint32_t i = 0; i < stCurr1.size() && rIdx < numRpsCurrTempList; rIdx++, i++ ) + temp.push_back(stCurr1[i]); + for(uint32_t i = 0; i < ltCurr.size() && rIdx < numRpsCurrTempList; rIdx++, i++ ) + temp.push_back(ltCurr[i]); + } + refset.clear(); + refset.reserve(numActive); + //(8-9) and (8-11) + for( rIdx = 0; rIdx < numActive; rIdx++) { + uint8_t idx = modify ? modiList[rIdx] : rIdx; + if (idx < temp.size()) { + refset.push_back(temp[idx]); + } else { + ERROR("can't get idx from temp ref, modify = %d, idx = %d, iIdx = %d", modify, idx, rIdx); + } + } + return true; +} + +uint8_t VaapiDecoderH265::getIndex(int32_t poc) +{ + return m_pocToIndex[poc]; +} + +void VaapiDecoderH265::fillReferenceIndexForList(VASliceParameterBufferHEVC* sliceParam, + const RefSet& refset, bool isList0) +{ + int n = isList0?0:1; + uint32_t i; + for (i = 0; i < refset.size(); i++) { + sliceParam->RefPicList[n][i] = getIndex(refset[i]->m_poc); + } + for ( ; i < N_ELEMENTS(sliceParam->RefPicList[n]); i++) { + sliceParam->RefPicList[n][i] = 0xFF; + } + +} + +// 8.3.4 +bool VaapiDecoderH265::fillReferenceIndex(VASliceParameterBufferHEVC* sliceParam, const SliceHeader* const slice) +{ + RefSet& before = m_dpb.m_stCurrBefore; + RefSet& after = m_dpb.m_stCurrAfter; + + RefSet refset; + if (!slice->isISlice()) { + if (!getRefPicList(refset, before, after, + slice->num_ref_idx_l0_active_minus1 + 1, + slice->ref_pic_list_modification.ref_pic_list_modification_flag_l0, + slice->ref_pic_list_modification.list_entry_l0)) { + return false; + } + } + fillReferenceIndexForList(sliceParam, refset, true); + + refset.clear(); + if (slice->isBSlice()) { + if (!getRefPicList(refset, after, before, + slice->num_ref_idx_l1_active_minus1 + 1, + slice->ref_pic_list_modification.ref_pic_list_modification_flag_l1, + slice->ref_pic_list_modification.list_entry_l1)) { + return false; + } + } + fillReferenceIndexForList(sliceParam, refset, false); + + sliceParam->num_ref_idx_l0_active_minus1 = slice->num_ref_idx_l0_active_minus1; + sliceParam->num_ref_idx_l1_active_minus1 = slice->num_ref_idx_l1_active_minus1; + + return true; + +} + +inline int32_t clip3(int32_t x, int32_t y, int32_t z) +{ + if (z < x) + return x; + if (z > y) + return y; + return z; +} + +#define FILL_WEIGHT_TABLE(n) \ +void fillPredWedightTableL##n(VASliceParameterBufferHEVC* sliceParam, \ + const SliceHeader* slice, uint8_t chromaLog2WeightDenom) \ +{ \ + const PredWeightTable& w = slice->pred_weight_table; \ + for (int i = 0; i <= sliceParam->num_ref_idx_l##n##_active_minus1; i++) { \ + if (w.luma_weight_l##n##_flag[i]) { \ + sliceParam->delta_luma_weight_l##n[i] = w.delta_luma_weight_l##n[i]; \ + sliceParam->luma_offset_l##n[i] = w.luma_offset_l##n[i];\ + } \ + if (w.chroma_weight_l##n##_flag[i]) { \ + for (int j = 0; j < 2; j++) { \ + int8_t deltaWeight = w.delta_chroma_weight_l##n[i][j]; \ + int32_t chromaWeight = (1 << chromaLog2WeightDenom) + deltaWeight; \ + int16_t deltaOffset = w.delta_chroma_offset_l##n[i][j]; \ + int32_t chromaOffset = \ + 128 + deltaOffset - ((128*chromaWeight)>>chromaLog2WeightDenom);\ +\ + sliceParam->delta_chroma_weight_l##n[i][j] = deltaWeight; \ + sliceParam->ChromaOffsetL##n[i][j]= (int8_t)clip3(-128, 127, chromaOffset); \ + } \ + } \ + } \ +} + +FILL_WEIGHT_TABLE(0) +FILL_WEIGHT_TABLE(1) + +bool VaapiDecoderH265::fillPredWeightTable(VASliceParameterBufferHEVC* sliceParam, const SliceHeader* const slice) +{ + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); + const PredWeightTable& w = slice->pred_weight_table; + if ((pps->weighted_pred_flag && slice->isPSlice()) || + (pps->weighted_bipred_flag && slice->isBSlice())) { + uint8_t chromaLog2WeightDenom = w.luma_log2_weight_denom; + sliceParam->luma_log2_weight_denom = w.luma_log2_weight_denom; + if (sps->chroma_format_idc != 0) { + sliceParam->delta_chroma_log2_weight_denom + = w.delta_chroma_log2_weight_denom; + chromaLog2WeightDenom + += w.delta_chroma_log2_weight_denom; + } + fillPredWedightTableL0(sliceParam, slice, chromaLog2WeightDenom); + if (pps->weighted_bipred_flag && slice->isBSlice()) + fillPredWedightTableL1(sliceParam, slice, chromaLog2WeightDenom); + } + return true; +} + +bool VaapiDecoderH265::fillSlice(const PicturePtr& picture, + const SliceHeader* const theSlice, const NalUnit* const nalu) +{ + const SliceHeader* slice = theSlice; + VASliceParameterBufferHEVC* sliceParam; + if (!picture->newSlice(sliceParam, nalu->m_data, nalu->m_size)) + return false; + sliceParam->slice_data_byte_offset = + slice->getSliceDataByteOffset(); + sliceParam->slice_segment_address = slice->slice_segment_address; + +#define FILL_LONG(f) sliceParam->LongSliceFlags.fields.f = slice->f +#define FILL_LONG_SLICE(f) sliceParam->LongSliceFlags.fields.slice_##f = slice->f + //how to fill this + //LastSliceOfPic + FILL_LONG(dependent_slice_segment_flag); + + //follow spec + if (slice->dependent_slice_segment_flag) { + slice = m_prevSlice.get(); + } + + if (!fillReferenceIndex(sliceParam, slice)) + return false; + + sliceParam->LongSliceFlags.fields.slice_type = slice->slice_type; + sliceParam->LongSliceFlags.fields.color_plane_id = slice->colour_plane_id; + FILL_LONG_SLICE(sao_luma_flag); + FILL_LONG_SLICE(sao_chroma_flag); + FILL_LONG(mvd_l1_zero_flag); + FILL_LONG(cabac_init_flag); + FILL_LONG_SLICE(temporal_mvp_enabled_flag); + + if (slice->deblocking_filter_override_flag) + FILL_LONG_SLICE(deblocking_filter_disabled_flag); + else + sliceParam->LongSliceFlags.fields.slice_deblocking_filter_disabled_flag= + slice->pps->pps_deblocking_filter_disabled_flag; + FILL_LONG(collocated_from_l0_flag); + FILL_LONG_SLICE(loop_filter_across_slices_enabled_flag); + +#define FILL(f) sliceParam->f = slice->f +#define FILL_SLICE(f) sliceParam->slice_##f = slice->f + FILL(collocated_ref_idx); + /* following fields fill in fillReference + num_ref_idx_l0_active_minus1 + num_ref_idx_l1_active_minus1*/ + + FILL_SLICE(qp_delta); + FILL_SLICE(cb_qp_offset); + FILL_SLICE(cr_qp_offset); + FILL_SLICE(beta_offset_div2); + FILL_SLICE(tc_offset_div2); + if (!fillPredWeightTable(sliceParam, slice)) + return false; + FILL(five_minus_max_num_merge_cand); + return true; +} + +#define CHECK(v, expect) \ + do { \ + if (v != expect) { \ + ERROR("the value of %s is %d, not equals to %d", #v, v, expect); \ + return VAProfileNone; \ + } \ + } while (0) + +#define CHECK_RANGE(v, min, max) \ + do { \ + if (v < min || v > max) { \ + ERROR("%s is %d, not in [%d,%d]", #v, v, min, max); \ + return VAProfileNone; \ + } \ + } while (0) + +VAProfile VaapiDecoderH265::getVaProfile(const SPS* const sps) +{ + if (sps->profile_tier_level.general_profile_idc == 0 + || sps->profile_tier_level.general_profile_compatibility_flag[0] == 1) { + //general_profile_idc = 0 is not defined in spec, but some stream have this + //we treat it as Main profile + CHECK(sps->chroma_format_idc, 1); + CHECK(sps->bit_depth_luma_minus8, 0); + CHECK(sps->bit_depth_chroma_minus8, 0); + return VAProfileHEVCMain; + } + + if (sps->profile_tier_level.general_profile_idc == 1 + || sps->profile_tier_level.general_profile_compatibility_flag[1] == 1) { + //A.3.2, but we only check some important values + CHECK(sps->chroma_format_idc, 1); + CHECK(sps->bit_depth_luma_minus8, 0); + CHECK(sps->bit_depth_chroma_minus8, 0); + return VAProfileHEVCMain; + } + if (sps->profile_tier_level.general_profile_idc == 2 + || sps->profile_tier_level.general_profile_compatibility_flag[2] == 1) { + //A.3.3, but we only check some important values + CHECK(sps->chroma_format_idc, 1); + CHECK_RANGE(sps->bit_depth_luma_minus8, 0, 2); + CHECK_RANGE(sps->bit_depth_chroma_minus8, 0, 2); + return VAProfileHEVCMain10; + } + ERROR("unsupported profile %d", sps->profile_tier_level.general_profile_idc); + return VAProfileNone; +} +#undef CHECK +#undef CHECK_RANGE + +YamiStatus VaapiDecoderH265::ensureContext(const SPS* const sps) +{ + uint32_t surfaceNumber = sps->sps_max_dec_pic_buffering_minus1[0] + 1; + uint32_t width = sps->conformance_window_flag ? sps->croppedWidth : sps->width; + uint32_t height = sps->conformance_window_flag ? sps->croppedHeight : sps->height; + uint32_t surfaceWidth = sps->width; + uint32_t surfaceHeight =sps->height; + VAProfile profile = getVaProfile(sps); + uint32_t fourcc = (profile == VAProfileHEVCMain10) ? YAMI_FOURCC_P010 : YAMI_FOURCC_NV12; + + if (setFormat(width, height, surfaceWidth, surfaceHeight, surfaceNumber, fourcc)) { + decodeCurrent(); + return YAMI_DECODE_FORMAT_CHANGE; + } + + if (profile == VAProfileNone) + return YAMI_UNSUPPORTED; + return ensureProfile(profile); +} + +/* 8.3.1 */ +void VaapiDecoderH265::getPoc(const PicturePtr& picture, + const SliceHeader* const slice, + const NalUnit* const nalu) +{ + const PPS* const pps = slice->pps.get(); + const SPS* const sps = pps->sps.get(); + + const uint16_t pocLsb = slice->slice_pic_order_cnt_lsb; + const int32_t MaxPicOrderCntLsb = 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + int32_t picOrderCntMsb; + if (isIrap(nalu) && picture->m_noRaslOutputFlag) { + picOrderCntMsb = 0; + } else { + if((pocLsb < m_prevPicOrderCntLsb) + && ((m_prevPicOrderCntLsb - pocLsb) >= (MaxPicOrderCntLsb / 2))) { + picOrderCntMsb = m_prevPicOrderCntMsb + MaxPicOrderCntLsb; + } else if((pocLsb > m_prevPicOrderCntLsb) + && ((pocLsb - m_prevPicOrderCntLsb) > (MaxPicOrderCntLsb / 2))) { + picOrderCntMsb = m_prevPicOrderCntMsb - MaxPicOrderCntLsb; + } else { + picOrderCntMsb = m_prevPicOrderCntMsb; + } + } + picture->m_poc = picOrderCntMsb + pocLsb; + picture->m_pocLsb = pocLsb; + + uint8_t temporalID = nalu->nuh_temporal_id_plus1 - 1; + //fixme:sub-layer non-reference picture. + if (!temporalID && !isRasl(nalu) && !isRadl(nalu) && !isSublayerNoRef(nalu)) { + m_prevPicOrderCntMsb = picOrderCntMsb; + m_prevPicOrderCntLsb = pocLsb; + } +} + +SurfacePtr VaapiDecoderH265::createSurface(const SliceHeader* const slice) +{ + SurfacePtr s = VaapiDecoderBase::createSurface(); + if (!s) + return s; + SharedPtr& sps = slice->pps->sps; + + if (sps->conformance_window_flag) + s->setCrop(sps->croppedLeft, sps->croppedTop, sps->croppedWidth, sps->croppedHeight); + else + s->setCrop(0, 0, sps->width, sps->height); + return s; +} + +YamiStatus VaapiDecoderH265::createPicture(PicturePtr& picture, const SliceHeader* const slice, + const NalUnit* const nalu) +{ + + SurfacePtr surface = createSurface(slice); + if (!surface) + return YAMI_DECODE_NO_SURFACE; + picture.reset(new VaapiDecPictureH265(m_context, surface, m_currentPTS)); + + picture->m_noRaslOutputFlag = isIdr(nalu) || isBla(nalu) || + m_newStream || m_endOfSequence; + m_noRaslOutputFlag = picture->m_noRaslOutputFlag; + if (isIrap(nalu)) + m_associatedIrapNoRaslOutputFlag = picture->m_noRaslOutputFlag; + picture->m_picOutputFlag + = (isRasl(nalu) && m_associatedIrapNoRaslOutputFlag) ? false : slice->pic_output_flag; + + getPoc(picture, slice, nalu); + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderH265::decodeSlice(NalUnit* nalu) +{ + SharedPtr currSlice(new SliceHeader()); + SliceHeader* slice = currSlice.get(); + YamiStatus status; + + if (!m_parser->parseSlice(nalu, slice)) + return YAMI_DECODE_INVALID_DATA; + + status = ensureContext(slice->pps->sps.get()); + if (status != YAMI_SUCCESS) { + return status; + } + if (slice->first_slice_segment_in_pic_flag) { + status = decodeCurrent(); + if (status != YAMI_SUCCESS) + return status; + status = createPicture(m_current, slice, nalu); + if (status != YAMI_SUCCESS) + return status; + if (m_noRaslOutputFlag && isRasl(nalu)) + return YAMI_SUCCESS; + if (!m_current || !m_dpb.init(m_current, slice, nalu, m_newStream)) + return YAMI_DECODE_INVALID_DATA; + if (!fillPicture(m_current, slice) || !fillIqMatrix(m_current, slice)) + return YAMI_FAIL; + } + if (!m_current) + return YAMI_FAIL; + if (!fillSlice(m_current, slice, nalu)) + return YAMI_FAIL; + if (!slice->dependent_slice_segment_flag) + std::swap(currSlice, m_prevSlice); + return status; + +} + +YamiStatus VaapiDecoderH265::decodeNalu(NalUnit* nalu) +{ + uint8_t type = nalu->nal_unit_type; + YamiStatus status = YAMI_SUCCESS; + + if (NalUnit::TRAIL_N <= type && type <= NalUnit::CRA_NUT) { + status = decodeSlice(nalu); + } + else if (NalUnit::PREFIX_SEI_NUT == type + || NalUnit::SUFFIX_SEI_NUT == type) { + //In some bitsstreams, SEI NAL units are inserted between picture NAL + //units which belong to the same picture. If decode the current + //picture when meeting a SEI NAL unit, the picture units after the SEI + //will not be decoded. + } + else { + status = decodeCurrent(); + if (status != YAMI_SUCCESS) + return status; + switch (type) { + case NalUnit::VPS_NUT: + case NalUnit::SPS_NUT: + case NalUnit::PPS_NUT: + status = decodeParamSet(nalu); + break; + case NalUnit::EOB_NUT: + m_newStream = true; + break; + case NalUnit::EOS_NUT: + m_endOfSequence = true; + break; + case NalUnit::AUD_NUT: + case NalUnit::FD_NUT: + default: + break; + } + } + + return status; +} + +void VaapiDecoderH265::flush(bool discardOutput) +{ + decodeCurrent(); + m_dpb.flush(); + m_prevPicOrderCntMsb = 0; + m_prevPicOrderCntLsb = 0; + m_newStream = true; + m_endOfSequence = false; + m_prevSlice.reset(new SliceHeader()); + if (discardOutput) + VaapiDecoderBase::flush(); +} + +void VaapiDecoderH265::flush(void) +{ + flush(true); +} + +YamiStatus VaapiDecoderH265::decode(VideoDecodeBuffer* buffer) +{ + if (!buffer || !buffer->data) { + flush(false); + return YAMI_SUCCESS; + } + m_currentPTS = buffer->timeStamp; + + NalReader nr(buffer->data, buffer->size, m_nalLengthSize); + const uint8_t* nal; + int32_t size; + YamiStatus lastError = YAMI_SUCCESS; + YamiStatus status; + while (nr.read(nal, size)) { + NalUnit nalu; + if (nalu.parseNaluHeader(nal, size)) { + status = decodeNalu(&nalu); + if (status != YAMI_SUCCESS) { + //we will continue decode if decodeNalu return YAMI_DECODE_INVALID_DATA + //but we will return the error at end of fucntion + lastError = status; + if (status != YAMI_DECODE_INVALID_DATA) + return status; + } + } + } + + if (buffer->flag & VIDEO_DECODE_BUFFER_FLAG_FRAME_END) { + //send current buffer to libva + decodeCurrent(); + } + return lastError; +} + +bool VaapiDecoderH265::decodeHevcRecordData(uint8_t* buf, int32_t bufSize) +{ + if (buf == NULL || bufSize == 0) { + ERROR("invalid record data"); + return false; + } + /* + * Some hvcC format don't used buf[0]==1 as flag, so now used the + * (buf[0] || buf[1] || buf[2] > 1) as hvcC condition. + */ + if (!(buf[0] || buf[1] || buf[2] > 1)) { //annexb format + VideoDecodeBuffer buffer; + memset(&buffer, 0, sizeof(buffer)); + buffer.data = buf; + buffer.size = bufSize; + //we ignore no fatal error + return (decode(&buffer) >= YAMI_SUCCESS); + } + if (bufSize < 24) { + ERROR("invalid avcc record data"); + return false; + } + NalUnit nalu; + const uint8_t* nalBuf; + int32_t i = 0, j, numNalu, nalBufSize; + nalBuf = &buf[21]; + int32_t nalLengthSize = (*nalBuf & 0x03) + 1; + nalBuf++; + numNalu = *nalBuf & 0x1f; + nalBuf++; + for (i = 0; i < numNalu; i++) { + nalBuf++; + int cnt = *(nalBuf + 1) & 0xf; + nalBuf += 2; + for (j = 0; j < cnt; j++) { + int nalsize = *(nalBuf + 1) + 2; + if (buf + bufSize - nalBuf < nalsize) + return false; + NalReader nr(nalBuf, nalsize, 2); + /*sps/pps/vps nal_length_size alway is 2 in hvcC format*/ + if (!nr.read(nalBuf, nalBufSize)) + return false; + if (!nalu.parseNaluHeader(nalBuf, nalBufSize)) + return false; + if (decodeNalu(&nalu) != YAMI_SUCCESS) + return false; + nalBuf += nalBufSize; + } + } + m_nalLengthSize = nalLengthSize; + return true; +} + +} + diff --git a/decoder/vaapidecoder_h265.h b/decoder/vaapidecoder_h265.h new file mode 100644 index 0000000..f7e2303 --- /dev/null +++ b/decoder/vaapidecoder_h265.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_h265_h +#define vaapidecoder_h265_h + +#include "common/Functional.h" +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" + +#include +#include +#include + +namespace YamiParser { +namespace H265 { + struct SPS; + struct SliceHeader; + struct NalUnit; + class Parser; +}; +}; + +namespace YamiMediaCodec { + +class VaapiDecPictureH265; +class VaapiDecoderH265:public VaapiDecoderBase { + typedef YamiParser::H265::SPS SPS; + typedef YamiParser::H265::SliceHeader SliceHeader; + typedef YamiParser::H265::NalUnit NalUnit; + typedef YamiParser::H265::Parser Parser; + +public: + typedef SharedPtr PicturePtr; + typedef std::vector RefSet; + VaapiDecoderH265(); + virtual ~VaapiDecoderH265(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus decode(VideoDecodeBuffer*); + virtual void flush(void); + +private: + friend class FactoryTest; + friend class VaapiDecoderH265Test; + + class DPB { + typedef VaapiDecoderH265::RefSet RefSet; + typedef std::function OutputCallback; + typedef std::function ForEachFunction; + public: + typedef VaapiDecoderH265::PicturePtr PicturePtr; + DPB(OutputCallback output); + bool init(const PicturePtr&, + const SliceHeader *const, + const NalUnit *const, + bool newStream); + bool add(const PicturePtr&, const SliceHeader* const lastSlice); + void flush(); + + RefSet m_stCurrBefore; + RefSet m_stCurrAfter; + RefSet m_stFoll; + RefSet m_ltCurr; + RefSet m_ltFoll; + private: + void forEach(ForEachFunction); + bool initReference(const PicturePtr&, + const SliceHeader *const, + const NalUnit *const, + bool newStream); + bool initShortTermRef(const PicturePtr& picture, + const SliceHeader* const); + bool initShortTermRef(RefSet& ref,int32_t currPoc, + const int32_t* const delta, + const uint8_t* const used, + uint8_t num); + bool initLongTermRef(const PicturePtr&, + const SliceHeader *const); + VaapiDecPictureH265* getPic(int32_t poc, bool hasMsb = true); + + //for C.5.2.2 + bool checkReorderPics(const SPS* const sps); + bool checkDpbSize(const SPS* const); + bool checkLatency(const SPS* const); + void removeUnused(); + void clearRefSet(); + + void bumpAll(); + bool bump(); + bool output(const PicturePtr& picture); + + + struct PocLess + { + inline bool operator()(const PicturePtr& left, const PicturePtr& right) const; + }; + typedef std::set PictureList; + PictureList m_pictures; + OutputCallback m_output; + PicturePtr m_dummy; + }; + YamiStatus decodeNalu(NalUnit*); + YamiStatus decodeParamSet(NalUnit*); + YamiStatus decodeSlice(NalUnit*); + + static VAProfile getVaProfile(const SPS* const sps); + YamiStatus ensureContext(const SPS* const); + bool fillPicture(const PicturePtr& , const SliceHeader* const ); + bool fillSlice(const PicturePtr&, const SliceHeader* const, const NalUnit* const ); + bool fillIqMatrix(const PicturePtr&, const SliceHeader* const); + bool fillPredWeightTable(VASliceParameterBufferHEVC*, const SliceHeader* const); + bool fillReference(const PicturePtr&, + VASliceParameterBufferHEVC*, const SliceHeader* const); + void fillReference(VAPictureHEVC* refs, int32_t size); + void fillReference(VAPictureHEVC* refs, int32_t& n, const RefSet& refset, uint32_t flags); + + + bool fillReferenceIndex(VASliceParameterBufferHEVC*, const SliceHeader* const); + void fillReferenceIndexForList(VASliceParameterBufferHEVC*, const RefSet&, bool isList0); + bool getRefPicList(RefSet& refset, const RefSet& stCurr0, const RefSet& stCurr1, + uint8_t numActive, bool modify, const uint32_t* modiList); + uint8_t getIndex(int32_t poc); + + bool decodeHevcRecordData(uint8_t* buf, int32_t bufSize); + + SurfacePtr createSurface(const SliceHeader* const); + YamiStatus createPicture(PicturePtr& picture, const SliceHeader* const, const NalUnit* const nalu); + void getPoc(const PicturePtr&, const SliceHeader* const, + const NalUnit* const); + YamiStatus decodeCurrent(); + YamiStatus outputPicture(const PicturePtr&); + void flush(bool discardOutput); + + SharedPtr m_parser; + PicturePtr m_current; + int32_t m_prevPicOrderCntMsb; + int32_t m_prevPicOrderCntLsb; + int32_t m_nalLengthSize; + bool m_associatedIrapNoRaslOutputFlag; + bool m_noRaslOutputFlag; + bool m_newStream; + bool m_endOfSequence; + DPB m_dpb; + std::map m_pocToIndex; + SharedPtr m_prevSlice; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; + +} // namespace YamiMediaCodec + +#endif + diff --git a/decoder/vaapidecoder_h265_unittest.cpp b/decoder/vaapidecoder_h265_unittest.cpp new file mode 100644 index 0000000..b16be1e --- /dev/null +++ b/decoder/vaapidecoder_h265_unittest.cpp @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapidecoder_h265.h" + +namespace YamiMediaCodec { + +class VaapiDecoderH265Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIDECODER_H265_TEST(name) \ + TEST_F(VaapiDecoderH265Test, name) + +VAAPIDECODER_H265_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_H265); + doFactoryTest(mimeTypes); +} + +} diff --git a/decoder/vaapidecoder_host.cpp b/decoder/vaapidecoder_host.cpp new file mode 100644 index 0000000..96c1dc8 --- /dev/null +++ b/decoder/vaapidecoder_host.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "VideoDecoderHost.h" +#include "vaapidecoder_factory.h" + +#if __BUILD_FAKE_DECODER__ +#include "vaapidecoder_fake.h" +#endif + +using namespace YamiMediaCodec; + +#if __BUILD_H264_DECODER__ +#include "vaapidecoder_h264.h" +const bool VaapiDecoderH264::s_registered + = VaapiDecoderFactory::register_(YAMI_MIME_AVC) + && VaapiDecoderFactory::register_(YAMI_MIME_H264); +#endif + +#if __BUILD_H265_DECODER__ +#include "vaapidecoder_h265.h" +const bool VaapiDecoderH265::s_registered = + VaapiDecoderFactory::register_(YAMI_MIME_H265) + && VaapiDecoderFactory::register_(YAMI_MIME_HEVC); +#endif + +#if __BUILD_MPEG2_DECODER__ +#include "vaapidecoder_mpeg2.h" +const bool VaapiDecoderMPEG2::s_registered + = VaapiDecoderFactory::register_(YAMI_MIME_MPEG2); +#endif + +#if __BUILD_VC1_DECODER__ +#include "vaapidecoder_vc1.h" +const bool VaapiDecoderVC1::s_registered + = VaapiDecoderFactory::register_(YAMI_MIME_VC1); +#endif + +#if __BUILD_VP8_DECODER__ +#include "vaapidecoder_vp8.h" +const bool VaapiDecoderVP8::s_registered = + VaapiDecoderFactory::register_(YAMI_MIME_VP8); +#endif + +#if __BUILD_VP9_DECODER__ +#include "vaapidecoder_vp9.h" +const bool VaapiDecoderVP9::s_registered = + VaapiDecoderFactory::register_(YAMI_MIME_VP9); +#endif + +#if __BUILD_JPEG_DECODER__ +#include "vaapiDecoderJPEG.h" +const bool VaapiDecoderJPEG::s_registered = + VaapiDecoderFactory::register_(YAMI_MIME_JPEG); +#endif + +IVideoDecoder *createVideoDecoder(const char *mimeType) +{ + if (!mimeType) { + ERROR("NULL mime type."); + return NULL; + } + +#if __BUILD_FAKE_DECODER__ + INFO("Created fake decoder"); + return new VaapiDecoderFake(1920, 1080); +#endif + + VaapiDecoderFactory::Type dec = VaapiDecoderFactory::create(mimeType); + + if (!dec) + ERROR("Failed to create decoder for mimeType: '%s'", mimeType); + else + INFO("Created decoder for mimeType: '%s'", mimeType); + + return dec; +} + +void releaseVideoDecoder(IVideoDecoder * p) +{ + delete p; +} + +std::vector getVideoDecoderMimeTypes() +{ + return VaapiDecoderFactory::keys(); +} diff --git a/decoder/vaapidecoder_host_unittest.cpp b/decoder/vaapidecoder_host_unittest.cpp new file mode 100644 index 0000000..bcb8ce7 --- /dev/null +++ b/decoder/vaapidecoder_host_unittest.cpp @@ -0,0 +1,116 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/unittest.h" + +// primary header +#include "VideoDecoderHost.h" + +// system headers +#include +#include +#include + +namespace YamiMediaCodec { + +std::set& expectations() +{ + static std::set e; + +#if __BUILD_H264_DECODER__ + e.insert(YAMI_MIME_H264); + e.insert(YAMI_MIME_AVC); +#endif + +#if __BUILD_H265_DECODER__ + e.insert(YAMI_MIME_H265); + e.insert(YAMI_MIME_HEVC); +#endif + +#if __BUILD_MPEG2_DECODER__ + e.insert(YAMI_MIME_MPEG2); +#endif + +#if __BUILD_VC1_DECODER__ + e.insert(YAMI_MIME_VC1); +#endif + +#if __BUILD_VP8_DECODER__ + e.insert(YAMI_MIME_VP8); +#endif + +#if __BUILD_VP9_DECODER__ + e.insert(YAMI_MIME_VP9); +#endif + +#if __BUILD_JPEG_DECODER__ + e.insert(YAMI_MIME_JPEG); +#endif + + return e; +} + +class VaapiDecoderHostTest + : public ::testing::TestWithParam +{ }; + +TEST_P(VaapiDecoderHostTest, createVideoDecoder) +{ + std::string mime = GetParam(); + IVideoDecoder *decoder = createVideoDecoder(mime.c_str()); + bool expect = expectations().count(mime) != 0; + + EXPECT_EQ(expect, (decoder != NULL)) + << "createVideoDecoder(" << mime << "): " + << "did not " << (expect ? "SUCCEED" : "FAIL") + << " as it should have."; + + releaseVideoDecoder(decoder); +} + +TEST_P(VaapiDecoderHostTest, getVideoDecoderMimeTypesContains) +{ + std::string mime = GetParam(); + std::vector avail = getVideoDecoderMimeTypes(); + + bool expect = expectations().count(mime) != 0; + bool actual = std::find(avail.begin(), avail.end(), mime) != avail.end(); + + EXPECT_EQ( expect, actual ); +} + +INSTANTIATE_TEST_CASE_P( + MimeType, VaapiDecoderHostTest, + ::testing::Values( + YAMI_MIME_H264, YAMI_MIME_AVC, YAMI_MIME_H265, YAMI_MIME_HEVC, + YAMI_MIME_MPEG2, YAMI_MIME_VC1, YAMI_MIME_VP8, YAMI_MIME_VP9, + YAMI_MIME_JPEG)); +} diff --git a/decoder/vaapidecoder_mpeg2.cpp b/decoder/vaapidecoder_mpeg2.cpp new file mode 100644 index 0000000..46ee796 --- /dev/null +++ b/decoder/vaapidecoder_mpeg2.cpp @@ -0,0 +1,1074 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "common/nalreader.h" +#include "vaapidecpicture.h" +#include "vaapidecoder_mpeg2.h" + +#include +#include + +using YamiParser::MPEG2::Slice; +using YamiParser::MPEG2::PictureCodingExtension; +using YamiParser::MPEG2::PictureHeader; +using YamiParser::MPEG2::GOPHeader; +using YamiParser::MPEG2::SeqExtension; +using YamiParser::MPEG2::SeqHeader; +using YamiParser::MPEG2::StreamHeader; +using YamiParser::MPEG2::Parser; +using YamiParser::MPEG2::QuantMatrices; + +namespace YamiMediaCodec { +typedef VaapiDecoderMPEG2::PicturePtr PicturePtr; + +IQMatricesRefs::IQMatricesRefs() { memset(this, 0, sizeof(*this)); } +// mpeg2picture class + +class VaapiDecPictureMpeg2 : public VaapiDecPicture { +public: + VaapiDecPictureMpeg2(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiDecPicture(context, surface, timeStamp) + , m_VAPictureStructure_(VAAPI_PICTURE_FRAME) + , m_sentToOutput_(false) + , m_isFirstField_(false) + { + } + VaapiDecPictureMpeg2() {} + + // move to private and create get/set methods + VaapiPictureType m_VAPictureStructure_; + bool m_sentToOutput_; + uint32_t m_temporalReference_; + uint32_t m_pictureCodingType_; + uint32_t m_topFieldFirst_; + uint32_t m_progressiveFrame_; + bool m_isFirstField_; + +private: +}; +// mpeg2picture class + +void VaapiDecoderMPEG2::DPB::flush() +{ + DEBUG("MPEG2-DPB flush"); + m_referencePictures.clear(); +} + +YamiStatus +VaapiDecoderMPEG2::DPB::outputPreviousPictures(const PicturePtr& picture, bool empty) +{ + YamiStatus status = YAMI_SUCCESS; + std::list::iterator it = m_referencePictures.begin(); + + if (picture->m_pictureCodingType_ == YamiParser::MPEG2::kIFrame) + empty = true; + + // send to the output all possible pictures + for (; it != m_referencePictures.end(); it++) { + DEBUG("candidate picture temporalReference %d", + picture->m_temporalReference_); + + if ((picture->m_temporalReference_ >= (*it)->m_temporalReference_ + || empty) + && (*it)->m_sentToOutput_ == false) { + + status = callOutputPicture((*it)); + if (status != YAMI_SUCCESS) + return status; + + (*it)->m_sentToOutput_ = true; + DEBUG("output temporalReference %d", (*it)->m_temporalReference_); + } + } + + return status; +} + +YamiStatus +VaapiDecoderMPEG2::DPB::insertPictureToReferences(const PicturePtr& picture) +{ + PicturePtr outputPicture; + YamiStatus status = YAMI_SUCCESS; + + if (picture->m_pictureCodingType_ != YamiParser::MPEG2::kBFrame) + { + DEBUG("Put picture %d on the reference queue", + picture->m_temporalReference_); + + if (m_referencePictures.size() == 2) { + outputPicture = m_referencePictures.front(); + DEBUG("Drop picture %d from reference queue", + outputPicture->m_temporalReference_); + m_referencePictures.pop_front(); + } + m_referencePictures.push_back(picture); + } else { + // this is a kBFrame + // send it to output right away + DEBUG("Send B frame picture to the output %d", + picture->m_temporalReference_); + status = callOutputPicture(picture); + if (status != YAMI_SUCCESS) + return status; + } + return status; +} + +YamiStatus VaapiDecoderMPEG2::DPB::insertPicture(const PicturePtr& picture) +{ + INFO("insertPicture to DPB size %zu", m_referencePictures.size()); + + YamiStatus status = YAMI_SUCCESS; + + DEBUG("temporalReference %d", picture->m_temporalReference_); + DEBUG("pictureCodingType %d", picture->m_pictureCodingType_); + DEBUG("topFieldFirst %d", picture->m_topFieldFirst_); + DEBUG("progressiveFrame %d", picture->m_progressiveFrame_); + + status = outputPreviousPictures(picture); + if (status != YAMI_SUCCESS) + return status; + + if (picture->m_progressiveFrame_ + || picture->m_VAPictureStructure_ == VAAPI_PICTURE_FRAME) { + + INFO("Insert one frame picture"); + // frame picture can be inserted straight to DPB as it was decoded + // completely before trying to insert, it can also be + // output if temporalReference matches PTS + + status = insertPictureToReferences(picture); + if (status != YAMI_SUCCESS) + return status; + + } else if (!picture->m_progressiveFrame_ + && picture->m_VAPictureStructure_ + != VAAPI_PICTURE_FRAME) { + // field pictures received, top field and bottom field have their lists + // based on those a decision will be made if frame can be displayed + INFO("This is a field picture"); + if (!picture->m_isFirstField_) { + status = insertPictureToReferences(picture); + if (status != YAMI_SUCCESS) + return status; + } + } + + DEBUG("insertPicture returns dpb size %zu", m_referencePictures.size()); + return status; +} + +YamiStatus +VaapiDecoderMPEG2::DPB::getReferencePictures(const PicturePtr& current_picture, + PicturePtr& previousPicture, + PicturePtr& nextPicture) +{ + // m_referencePictures can have 0,1 or 2 reference pictures to comply with + // the amount of reference frames needed by picture coding type + // picture coding type kIFrame - 0 ref frames + // picture coding type kPFrame - 1 ref frames + // picture coding type kBFrame - 2 ref frames + + if (m_referencePictures.size() == 1) { + previousPicture = m_referencePictures.front(); + } else if (m_referencePictures.size() == 2 + && current_picture->m_pictureCodingType_ + == YamiParser::MPEG2::kBFrame) { + previousPicture = m_referencePictures.front(); + nextPicture = m_referencePictures.back(); + } else if (m_referencePictures.size() == 2 + && current_picture->m_pictureCodingType_ + == YamiParser::MPEG2::kPFrame) { + previousPicture = m_referencePictures.back(); + } + + return YAMI_SUCCESS; +} + +VaapiDecoderMPEG2::VaapiDecoderMPEG2() + : m_DPB(std::bind(&VaapiDecoderMPEG2::outputPicture, this, + std::placeholders::_1)) + , m_VAStart(false) + , m_isParsingSlices(false) + , m_loadNewIQMatrix(false) +{ + m_parser.reset(new Parser()); + m_stream.reset(new StreamHeader()); + m_previousStartCode = YamiParser::MPEG2::MPEG2_INVALID_START_CODE; + m_nextStartCode = YamiParser::MPEG2::MPEG2_SEQUENCE_HEADER_CODE; + INFO("VaapiDecoderMPEG2 constructor"); +} + +VaapiDecoderMPEG2::~VaapiDecoderMPEG2() { stop(); } + +YamiStatus VaapiDecoderMPEG2::convertToVAProfile( + const YamiParser::MPEG2::ProfileType& profile) +{ + YamiStatus status = YAMI_SUCCESS; + + switch (profile) { + case YamiParser::MPEG2::MPEG2_PROFILE_MAIN: + m_VAProfile = VAProfileMPEG2Main; + break; + case YamiParser::MPEG2::MPEG2_PROFILE_SIMPLE: + m_VAProfile = VAProfileMPEG2Simple; + break; + default: + m_VAProfile = VAProfileNone; + status = YAMI_DECODE_PARSER_FAIL; + break; + } + return status; +} + +YamiStatus +VaapiDecoderMPEG2::checkLevel(const YamiParser::MPEG2::LevelType& level) +{ + switch (level) { + case YamiParser::MPEG2::MPEG2_LEVEL_HIGH: + case YamiParser::MPEG2::MPEG2_LEVEL_HIGH_1440: + case YamiParser::MPEG2::MPEG2_LEVEL_MAIN: + case YamiParser::MPEG2::MPEG2_LEVEL_LOW: + return YAMI_SUCCESS; + break; + default: + return YAMI_DECODE_PARSER_FAIL; + break; + } +} + +YamiStatus VaapiDecoderMPEG2::start(VideoConfigBuffer* buffer) +{ + + if (!buffer) { + ERROR("Cannot start codec without config buffer"); + return YAMI_FAIL; + } + + m_configBuffer = *buffer; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderMPEG2::processConfigBuffer() +{ + // buffer can contain one startcode of the mpeg2 sequence + // or several, but they will be processed one by one + + YamiStatus status = YAMI_SUCCESS; + YamiParser::MPEG2::StartCodeType next_code; + YamiParser::MPEG2::ExtensionIdentifierType extID; + + m_parser->nextStartCode(m_stream.get(), next_code); + INFO("processConfigBuffer Next start_code %x", next_code); + + switch (next_code) { + case YamiParser::MPEG2::MPEG2_SEQUENCE_HEADER_CODE: + INFO("parseSeqHdr"); + if (!m_parser->parseSequenceHeader(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_sequenceHeader = m_parser->getSequenceHeader(); + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE; + m_loadNewIQMatrix + = updateIQMatrix(&m_sequenceHeader->quantizationMatrices, true); + if (!m_DPB.isEmpty()) + m_DPB.flush(); + break; + case YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE: + INFO("parseSeqExt"); + extID = static_cast( + m_stream->nalData[1] >> 4); + if (!m_VAStart) { + + switch (extID) { + case YamiParser::MPEG2::kSequence: + if (!m_parser->parseSequenceExtension(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_sequenceExtension = m_parser->getSequenceExtension(); + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_GROUP_START_CODE; + // ready to fillConfigBuffer + // this should be returning YAMI_SUCCESS if + // application + // has not allocated output port earlier + + status = fillConfigBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + break; + + case YamiParser::MPEG2::kQuantizationMatrix: + if (!m_parser->parseQuantMatrixExtension(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_quantMatrixExtension = m_parser->getQuantMatrixExtension(); + m_loadNewIQMatrix = updateIQMatrix( + &m_quantMatrixExtension->quantizationMatrices); + break; + default: + break; + } + } + break; + default: + status = processDecodeBuffer(); + INFO("Calling processDecodeBuffer from " + "processConfigBuffer"); + if (status != YAMI_SUCCESS) { + return status; + } + break; + } + return status; +} + +YamiStatus VaapiDecoderMPEG2::processDecodeBuffer() +{ + // buffer can contain only one nal of the mpeg2 sequence + + YamiStatus status = YAMI_SUCCESS; + YamiParser::MPEG2::StartCodeType next_code; + YamiParser::MPEG2::ExtensionIdentifierType extID; + + m_parser->nextStartCode(m_stream.get(), next_code); + DEBUG("processDecodeBuffer Next start_code %x", next_code); + + switch (next_code) { + case YamiParser::MPEG2::MPEG2_SEQUENCE_HEADER_CODE: + INFO("parseSeqHdr"); + if (!m_parser->parseSequenceHeader(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_sequenceHeader = m_parser->getSequenceHeader(); + // reset the matrices + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE; + m_loadNewIQMatrix + = updateIQMatrix(&m_sequenceHeader->quantizationMatrices, true); + + break; + case YamiParser::MPEG2::MPEG2_GROUP_START_CODE: + INFO("Group start code"); + + if (m_isParsingSlices) { + status = decodePicture(); + if (status != YAMI_SUCCESS) { + return status; + } + m_isParsingSlices = false; + m_nextStartCode = YamiParser::MPEG2::MPEG2_GROUP_START_CODE; + } + + if (!m_parser->parseGOPHeader(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_GOPHeader = m_parser->getGOPHeader(); + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_PICTURE_START_CODE; + break; + case YamiParser::MPEG2::MPEG2_PICTURE_START_CODE: + INFO("picture start code"); + if (m_isParsingSlices) { + status = decodePicture(); + if (status != YAMI_SUCCESS) { + return status; + } + m_isParsingSlices = false; + } + + if (m_previousStartCode + == YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE + || m_previousStartCode + == YamiParser::MPEG2::MPEG2_GROUP_START_CODE) { + m_nextStartCode = YamiParser::MPEG2::MPEG2_PICTURE_START_CODE; + INFO("parsePictureHeader size %ld", m_stream->streamSize); + if (!m_parser->parsePictureHeader(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_pictureHeader = m_parser->getPictureHeader(); + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE; + } + break; + case YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE: + extID = static_cast( + m_stream->nalData[1] >> 4); + if (extID == YamiParser::MPEG2::kPictureCoding) { + if (m_nextStartCode == next_code) { + if (!m_parser->parsePictureCodingExtension(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_pictureCodingExtension + = m_parser->getPictureCodingExtension(); + + // picture can be created as soon as the first slice is + // parsed, but from here to there Extension Start Code can be + // parsed to update information like the Quant Matrix + + m_canCreatePicture = true; + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_SLICE_START_CODE_MIN; + m_isParsingSlices = true; + } + } + else if (extID == YamiParser::MPEG2::kQuantizationMatrix) { + INFO("this is a new quant matrix"); + if (!m_parser->parseQuantMatrixExtension(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_quantMatrixExtension = m_parser->getQuantMatrixExtension(); + m_loadNewIQMatrix + = updateIQMatrix(&m_quantMatrixExtension->quantizationMatrices); + } + else if (extID == YamiParser::MPEG2::kSequence) { + if (!m_parser->parseSequenceExtension(m_stream.get())) { + return YAMI_DECODE_PARSER_FAIL; + } + m_sequenceExtension = m_parser->getSequenceExtension(); + m_previousStartCode = m_nextStartCode; + m_nextStartCode = YamiParser::MPEG2::MPEG2_GROUP_START_CODE; + status = fillConfigBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + } + break; + case YamiParser::MPEG2::MPEG2_SEQUENCE_END_CODE: + INFO("End of sequence received"); + if (m_isParsingSlices) { + status = decodePicture(); + if (status != YAMI_SUCCESS) { + return status; + } + status = m_DPB.outputPreviousPictures(m_currentPicture, true); + if (status != YAMI_SUCCESS) { + return status; + } + m_isParsingSlices = false; + } + break; + default: + // process a SliceCode + if (isSliceCode(next_code)) { + + if (m_canCreatePicture) + { + // create a new picture with updated information a field + // picture doesn't need to create Picture twice as both top + // and bottom fields share the same slice number. + status = createPicture(); + if (status != YAMI_SUCCESS) { + return status; + } + m_canCreatePicture = false; + } + INFO("processSlice on next_code %x", next_code); + status = processSlice(); + if (status != YAMI_SUCCESS) { + return status; + } + } + break; + } + return status; +} + +YamiStatus VaapiDecoderMPEG2::fillConfigBuffer() +{ + + YamiStatus status = YAMI_SUCCESS; + YamiParser::MPEG2::ProfileType profile; + YamiParser::MPEG2::LevelType level; + + profile = static_cast( + (m_sequenceExtension->profile_and_level_indication & 0x70) >> 4); + level = static_cast( + m_sequenceExtension->profile_and_level_indication & 0xF); + + status = checkLevel(level); + if (status != YAMI_SUCCESS) { + return status; + } + + status = convertToVAProfile(profile); + if (status != YAMI_SUCCESS) { + return status; + } + + m_configBuffer.width + = (m_sequenceExtension->horizontal_size_extension & 0x3) + | (m_sequenceHeader->horizontal_size_value & 0xFFF); + m_configBuffer.height = (m_sequenceExtension->vertical_size_extension & 0x3) + | (m_sequenceHeader->vertical_size_value & 0xFFF); + + if (m_VAStart) { + // sequence start extension code with VA started has to conduct a + // port reconfiguration when stream size changes + if (m_configBuffer.width > m_videoFormatInfo.width + || m_configBuffer.height > m_videoFormatInfo.height) { + // need to re-start VA to generate new surfaces + status = VaapiDecoderBase::terminateVA(); + if (status != YAMI_SUCCESS) { + return status; + } + m_VAStart = false; + } + else if (m_configBuffer.width != m_videoFormatInfo.width + || m_configBuffer.height != m_videoFormatInfo.height) { + // VA surfaces can be re-used and client is notified + // public member from base class + m_videoFormatInfo.width = m_configBuffer.width; + m_videoFormatInfo.height = m_configBuffer.height; + m_videoFormatInfo.surfaceWidth = m_configBuffer.width; + m_videoFormatInfo.surfaceHeight = m_configBuffer.height; + m_configBuffer.surfaceWidth = m_configBuffer.width; + m_configBuffer.surfaceHeight = m_configBuffer.height; + status = YAMI_DECODE_FORMAT_CHANGE; + } + } + + if (!m_VAStart) { + + m_configBuffer.profile = m_VAProfile; + + DEBUG("MPEG2: start() buffer size: %d x %d m_VAProfile %x level %x", + m_configBuffer.width, m_configBuffer.height, + m_configBuffer.profile, level); + + m_configBuffer.surfaceWidth = m_configBuffer.width; + m_configBuffer.surfaceHeight = m_configBuffer.height; + if (!m_configBuffer.surfaceNumber) { + m_configBuffer.surfaceNumber = kMinSurfaces; + } + // no information is sent to start libva at this point + m_configBuffer.data = NULL; + m_configBuffer.size = 0; + + // ready to start libva + status = VaapiDecoderBase::start(&m_configBuffer); + if (status != YAMI_SUCCESS) { + return status; + } + m_VAStart = true; + status = YAMI_DECODE_FORMAT_CHANGE; + } + + return status; +} + +bool VaapiDecoderMPEG2::isSliceCode(YamiParser::MPEG2::StartCodeType next_code) +{ + if (next_code >= YamiParser::MPEG2::MPEG2_SLICE_START_CODE_MIN + && next_code <= YamiParser::MPEG2::MPEG2_SLICE_START_CODE_MAX) { + DEBUG("Slice code slice number %x", next_code); + return true; + } + + return false; +} + +YamiStatus VaapiDecoderMPEG2::processSlice() +{ + const Slice* slice; + YamiStatus status = YAMI_DECODE_PARSER_FAIL; + + if (m_parser->parseSlice(m_stream.get())) { + slice = m_parser->getMPEG2Slice(); + if (!m_currentPicture->newSlice(mpeg2SliceParams, + slice->sliceData, slice->sliceDataSize)) { + DEBUG("picture->newSlice failed"); + return YAMI_FAIL; + } + fillSliceParams(mpeg2SliceParams, slice); + status = YAMI_SUCCESS; + } + + return status; +} + +inline bool findTempReference(const PicturePtr& picture, + uint32_t temporalReference) +{ + return picture->m_temporalReference_ == temporalReference; +} + +YamiStatus VaapiDecoderMPEG2::assignSurface() +{ + SurfacePtr surface; + YamiStatus status = YAMI_SUCCESS; + + surface = VaapiDecoderBase::createSurface(); + + if (!surface) { + status = YAMI_DECODE_NO_SURFACE; + } else { + surface->setCrop(0, 0, m_configBuffer.width, m_configBuffer.height); + m_currentPicture.reset( + new VaapiDecPictureMpeg2(m_context, surface, m_currentPTS)); + m_currentPicture->m_isFirstField_ = true; + } + + return status; +} + +YamiStatus VaapiDecoderMPEG2::findReusePicture(std::list& list, + bool& reuse) +{ + std::list::iterator it; + it = std::find_if(list.begin(), list.end(), + std::bind(findTempReference, + std::placeholders::_1, + m_pictureHeader->temporal_reference)); + if (it != list.end()) { + m_currentPicture = (*it); + m_currentPicture->m_isFirstField_ = false; + list.erase(it); + reuse = true; + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderMPEG2::assignPicture() +{ + YamiStatus status = YAMI_SUCCESS; + bool reuseSurface = false; + + // reuse surface/picture when decoding a field picture, only complete + // pictures can be pushed to the dpb, so it is up to the topfield and + // bottomfield lists to hold partial pictures before pushing + + // determine if the current Picture is a field picture and if it is + // topfield or bottomfield + + if (!m_pictureCodingExtension->progressive_frame + && m_pictureCodingExtension->picture_structure != kFramePicture) { + DEBUG("Create a Field Picture"); + // this is a field picture + // + if (m_pictureCodingExtension->top_field_first) { + // top field picture first + DEBUG("Create Top Field Picture"); + + status = assignSurface(); + if (status != YAMI_SUCCESS) { + return status; + } + + m_topFieldPictures.push_back(m_currentPicture); + + } else { + // bottom field picture + if (!m_bottomFieldPictures.empty()) { + findReusePicture(m_bottomFieldPictures, reuseSurface); + if (status != YAMI_SUCCESS) { + return status; + } + } else if (!m_topFieldPictures.empty()) { + findReusePicture(m_topFieldPictures, reuseSurface); + if (status != YAMI_SUCCESS) { + return status; + } + } + } + if (!reuseSurface) { + status = assignSurface(); + if (status != YAMI_SUCCESS) { + return status; + } + m_bottomFieldPictures.push_back(m_currentPicture); + } + } else { + + DEBUG("Create a Frame Picture"); + status = assignSurface(); + if (status != YAMI_SUCCESS) { + return status; + } + } + return status; +} + +bool VaapiDecoderMPEG2::updateIQMatrix(const QuantMatrices* refIQMatrix, + bool reset) +{ + + // when a new update to the IQMatrix is received, one or more can be + // updated, leaving those previously updated untouched if this is an + // update triggered by a Quant Matrix Extension. A Sequence Header + // Extension must reset the matrices. + + if (reset) + m_IQMatrices = IQMatricesRefs(); + + if (refIQMatrix->load_intra_quantiser_matrix) { + m_IQMatrices.intra_quantiser_matrix + = refIQMatrix->intra_quantiser_matrix; + } + + if (refIQMatrix->load_non_intra_quantiser_matrix) { + m_IQMatrices.non_intra_quantiser_matrix + = refIQMatrix->non_intra_quantiser_matrix; + } + + if (refIQMatrix->load_chroma_intra_quantiser_matrix) { + m_IQMatrices.chroma_intra_quantiser_matrix + = refIQMatrix->chroma_intra_quantiser_matrix; + } + + if (refIQMatrix->load_chroma_non_intra_quantiser_matrix) { + m_IQMatrices.chroma_non_intra_quantiser_matrix + = refIQMatrix->chroma_non_intra_quantiser_matrix; + } + + return refIQMatrix->load_intra_quantiser_matrix + || refIQMatrix->load_non_intra_quantiser_matrix + || refIQMatrix->load_chroma_intra_quantiser_matrix + || refIQMatrix->load_chroma_non_intra_quantiser_matrix; +} + +YamiStatus VaapiDecoderMPEG2::loadIQMatrix() +{ + YamiStatus status = YAMI_SUCCESS; + VAIQMatrixBufferMPEG2* IQMatrix = NULL; + + if (!m_currentPicture->editIqMatrix(IQMatrix)) { + ERROR("picture->editIqMatrix failed"); + return YAMI_FAIL; + } + + if (m_IQMatrices.intra_quantiser_matrix) { + IQMatrix->load_intra_quantiser_matrix = 1; + memcpy(IQMatrix->intra_quantiser_matrix, + m_IQMatrices.intra_quantiser_matrix, 64); + } + + if (m_IQMatrices.non_intra_quantiser_matrix) { + IQMatrix->load_non_intra_quantiser_matrix = 1; + memcpy(IQMatrix->non_intra_quantiser_matrix, + m_IQMatrices.non_intra_quantiser_matrix, 64); + } + + if (m_IQMatrices.chroma_intra_quantiser_matrix) { + IQMatrix->load_chroma_intra_quantiser_matrix = 1; + memcpy(IQMatrix->chroma_intra_quantiser_matrix, + m_IQMatrices.chroma_intra_quantiser_matrix, 64); + } + + if (m_IQMatrices.chroma_non_intra_quantiser_matrix) { + IQMatrix->load_chroma_non_intra_quantiser_matrix = 1; + memcpy(IQMatrix->chroma_non_intra_quantiser_matrix, + m_IQMatrices.chroma_non_intra_quantiser_matrix, 64); + } + + return status; +} + +YamiStatus VaapiDecoderMPEG2::createPicture() +{ + YamiStatus status = YAMI_SUCCESS; + VAPictureParameterBufferMPEG2* mpeg2PictureParams; + + status = assignPicture(); + if (status != YAMI_SUCCESS) { + return status; + } + + m_currentPicture->m_temporalReference_ + = m_pictureHeader->temporal_reference; + m_currentPicture->m_pictureCodingType_ + = m_pictureHeader->picture_coding_type; + + switch (m_pictureCodingExtension->picture_structure) { + case kTopField: + m_currentPicture->m_VAPictureStructure_ + = VAAPI_PICTURE_TOP_FIELD; + break; + case kBottomField: + m_currentPicture->m_VAPictureStructure_ + = VAAPI_PICTURE_BOTTOM_FIELD; + break; + case kFramePicture: + m_currentPicture->m_VAPictureStructure_ + = VAAPI_PICTURE_FRAME; + break; + default: + break; + } + + m_currentPicture->m_topFieldFirst_ + = m_pictureCodingExtension->top_field_first; + m_currentPicture->m_progressiveFrame_ + = m_pictureCodingExtension->progressive_frame; + + if (!m_currentPicture->editPicture(mpeg2PictureParams)) { + ERROR("picture->editPicture failed"); + return YAMI_FAIL; + } + + fillPictureParams(mpeg2PictureParams, m_currentPicture); + + if (m_loadNewIQMatrix) { + status = loadIQMatrix(); + if (status != YAMI_SUCCESS) { + ERROR("loadIQMatrix failed"); + return status; + } + m_loadNewIQMatrix = false; + } + + return status; +} + +YamiStatus VaapiDecoderMPEG2::decodePicture() +{ + YamiStatus status; + + if (!m_currentPicture->decode()) { + DEBUG("picture->decode failed"); + return YAMI_FAIL; + } + // put full picture into the dpb + status = m_DPB.insertPicture(m_currentPicture); + if (status != YAMI_SUCCESS) { + ERROR("insertPicture to DPB failed"); + } + + return status; +} + +YamiStatus VaapiDecoderMPEG2::outputPicture(const PicturePtr& picture) +{ + VaapiDecoderBase::PicturePtr basePicture + = std::static_pointer_cast(picture); + + return VaapiDecoderBase::outputPicture(basePicture); +} + +YamiStatus VaapiDecoderMPEG2::decode(VideoDecodeBuffer* buffer) +{ + YamiParser::MPEG2::StartCodeType next_code; + YamiStatus status = YAMI_SUCCESS; + YamiParser::MPEG2::ExtensionIdentifierType extID; + + // safe check, client can retry if this happens + if (!buffer) { + return YAMI_SUCCESS; + } + + if (buffer->data == NULL || buffer->size == 0) { + // no information provided in the buffer + return YAMI_SUCCESS; + } + + m_stream->data = buffer->data; + m_stream->streamSize = buffer->size; + m_stream->time_stamp = buffer->timeStamp; + m_currentPTS = buffer->timeStamp; + + DEBUG("decode size %ld timeStamp %" PRIu64 "", m_stream->streamSize, + m_stream->time_stamp); + + if (m_stream->streamSize < YamiParser::MPEG2::kStartCodeSize) { + // not enough buffer, client to provide more input + return YAMI_SUCCESS; + } + + NalReader nalReader(m_stream->data, m_stream->streamSize); + + while (nalReader.read(m_stream->nalData, m_stream->nalSize)) { + m_parser->nextStartCode(m_stream.get(), next_code); + DEBUG("Next start_code %x", next_code); + + switch (next_code) { + case YamiParser::MPEG2::MPEG2_SEQUENCE_HEADER_CODE: + // the stream hasn't provided enough information to + // properly configure it + DEBUG("decode tries for a sequence_header"); + if (!m_VAStart) { + status = processConfigBuffer(); + if (status != YAMI_SUCCESS + && status != YAMI_DECODE_FORMAT_CHANGE) { + return status; + } + } else { + INFO("processDecodeBuffer is called"); + status = processDecodeBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + } + break; + case YamiParser::MPEG2::MPEG2_GROUP_START_CODE: + case YamiParser::MPEG2::MPEG2_PICTURE_START_CODE: + case YamiParser::MPEG2::MPEG2_SEQUENCE_END_CODE: + status = processDecodeBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + break; + case YamiParser::MPEG2::MPEG2_EXTENSION_START_CODE: + extID = static_cast( + m_stream->nalData[1] >> 4); + if (m_previousStartCode + == YamiParser::MPEG2::MPEG2_SEQUENCE_HEADER_CODE) { + status = processConfigBuffer(); + if (status != YAMI_SUCCESS + && status != YAMI_DECODE_FORMAT_CHANGE) { + return status; + } + } + else if (m_previousStartCode + == YamiParser::MPEG2::MPEG2_PICTURE_START_CODE + || extID == YamiParser::MPEG2::kQuantizationMatrix + || extID == YamiParser::MPEG2::kPictureCoding + || extID == YamiParser::MPEG2::kSequence) { + status = processDecodeBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + } + break; + default: + if (isSliceCode(next_code) && m_isParsingSlices) { + status = processDecodeBuffer(); + if (status != YAMI_SUCCESS) { + return status; + } + } + break; + } + } + + return YAMI_SUCCESS; +} + +void VaapiDecoderMPEG2::fillPictureParams(VAPictureParameterBufferMPEG2* param, + const PicturePtr& currentPicture) +{ + PicturePtr previousPicture, nextPicture; + param->horizontal_size = m_configBuffer.width; + param->vertical_size = m_configBuffer.height; + param->picture_coding_type = m_pictureHeader->picture_coding_type; + + DEBUG("fillPictureParams picture coding type %d", + param->picture_coding_type); + + m_DPB.getReferencePictures(currentPicture, previousPicture, + nextPicture); + + // I-Frame does not use references + param->forward_reference_picture = VA_INVALID_ID; + param->backward_reference_picture = VA_INVALID_ID; + if (param->picture_coding_type == YamiParser::MPEG2::kPFrame) { + if (previousPicture) { + DEBUG("Surface id on previous picture %d", + previousPicture->getSurfaceID()); + param->forward_reference_picture = previousPicture->getSurfaceID(); + } + } else if (param->picture_coding_type == YamiParser::MPEG2::kBFrame) { + if (previousPicture) { + DEBUG("Surface id on previous picture %d", + previousPicture->getSurfaceID()); + param->forward_reference_picture = previousPicture->getSurfaceID(); + } + if (nextPicture) { + DEBUG("Surface id on next picture %d", nextPicture->getSurfaceID()); + param->backward_reference_picture = nextPicture->getSurfaceID(); + } + } + + // libva packs all in one int. + param->f_code = ((m_pictureCodingExtension->f_code[0][0] << 12) + | (m_pictureCodingExtension->f_code[0][1] << 8) + | (m_pictureCodingExtension->f_code[1][0] << 4) + | m_pictureCodingExtension->f_code[1][1]); + + param->picture_coding_extension.bits.intra_dc_precision + = m_pictureCodingExtension->intra_dc_precision; + param->picture_coding_extension.bits.picture_structure + = m_pictureCodingExtension->picture_structure; + param->picture_coding_extension.bits.top_field_first + = m_pictureCodingExtension->top_field_first; + param->picture_coding_extension.bits.frame_pred_frame_dct + = m_pictureCodingExtension->frame_pred_frame_dct; + param->picture_coding_extension.bits.concealment_motion_vectors + = m_pictureCodingExtension->concealment_motion_vectors; + param->picture_coding_extension.bits.q_scale_type + = m_pictureCodingExtension->q_scale_type; + param->picture_coding_extension.bits.intra_vlc_format + = m_pictureCodingExtension->intra_vlc_format; + param->picture_coding_extension.bits.alternate_scan + = m_pictureCodingExtension->alternate_scan; + param->picture_coding_extension.bits.repeat_first_field + = m_pictureCodingExtension->repeat_first_field; + param->picture_coding_extension.bits.progressive_frame + = m_pictureCodingExtension->progressive_frame; + + DEBUG("currentPic temporalRef %d Progressive %d isFirstField %d", + currentPicture->m_temporalReference_, + currentPicture->m_progressiveFrame_, currentPicture->m_isFirstField_); + if (currentPicture->m_progressiveFrame_ == 1 + || currentPicture->m_isFirstField_ == 1) { + param->picture_coding_extension.bits.is_first_field = 1; + } else { + param->picture_coding_extension.bits.is_first_field = 0; + } +} + +void +VaapiDecoderMPEG2::fillSliceParams(VASliceParameterBufferMPEG2* slice_param, + const Slice* slice) +{ + slice_param->macroblock_offset = slice->sliceHeaderSize; + slice_param->slice_data_flag = VA_SLICE_DATA_FLAG_ALL; + slice_param->slice_horizontal_position = slice->macroblockColumn; + slice_param->slice_vertical_position = slice->macroblockRow; + slice_param->quantiser_scale_code = slice->quantiser_scale_code; + slice_param->intra_slice_flag = slice->intra_slice_flag; +} + +YamiStatus VaapiDecoderMPEG2::reset(VideoConfigBuffer* buffer) +{ + DEBUG("MPEG2: reset()"); + return VaapiDecoderBase::reset(buffer); +} + +void VaapiDecoderMPEG2::stop() +{ + DEBUG("MPEG2: stop()"); + flush(); + VaapiDecoderBase::stop(); +} + +void VaapiDecoderMPEG2::flush() +{ + DEBUG("MPEG2: flush()"); + m_DPB.flush(); + m_parser.reset(new Parser()); + VaapiDecoderBase::flush(); +} + +} diff --git a/decoder/vaapidecoder_mpeg2.h b/decoder/vaapidecoder_mpeg2.h new file mode 100644 index 0000000..0abcc49 --- /dev/null +++ b/decoder/vaapidecoder_mpeg2.h @@ -0,0 +1,169 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_mpeg2_h +#define vaapidecoder_mpeg2_h + +#include "codecparsers/mpeg2_parser.h" +#include "common/Functional.h" +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" + +#include +#include +#include + +namespace YamiMediaCodec { + +enum Mpeg2PictureStructureType { + kTopField = 1, + kBottomField, + kFramePicture, +}; + +enum { + kMaxRefPictures = 2, + kMinSurfaces = 8, +}; + +struct IQMatricesRefs { + IQMatricesRefs(); + + const uint8_t* intra_quantiser_matrix; + const uint8_t* non_intra_quantiser_matrix; + const uint8_t* chroma_intra_quantiser_matrix; + const uint8_t* chroma_non_intra_quantiser_matrix; +}; + +class VaapiDecPictureMpeg2; + +class VaapiDecoderMPEG2 : public VaapiDecoderBase { +public: + typedef SharedPtr PicturePtr; + VaapiDecoderMPEG2(); + virtual ~VaapiDecoderMPEG2(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus reset(VideoConfigBuffer*); + virtual void stop(void); + virtual void flush(void); + virtual YamiStatus decode(VideoDecodeBuffer*); + +private: + // mpeg2 DPB class + class DPB { + typedef std::function + OutputCallback; + + public: + DPB(OutputCallback callback) + : m_numberSurfaces(kMaxRefPictures) + , m_outputPicture(callback) + { + } + + void flush(); + bool isEmpty() { return m_referencePictures.empty(); } + YamiStatus insertPicture(const PicturePtr& picture); + YamiStatus insertPictureToReferences(const PicturePtr& picture); + + YamiStatus getReferencePictures(const PicturePtr& current_picture, + PicturePtr& previous_picture, + PicturePtr& next_picture); + YamiStatus callOutputPicture(const PicturePtr& picture) + { + return m_outputPicture(picture); + } + + YamiStatus outputPreviousPictures(const PicturePtr& picture, + bool empty = false); + + private: + // set to minimum number of surfaces required to operate + uint32_t m_numberSurfaces; + std::list m_referencePictures; + OutputCallback m_outputPicture; + }; + + // mpeg2 DPB class + + typedef SharedPtr ParserPtr; + typedef SharedPtr StreamHdrPtr; + + friend class FactoryTest; + friend class VaapiDecoderMPEG2Test; + + void fillSliceParams(VASliceParameterBufferMPEG2* slice_param, + const YamiParser::MPEG2::Slice* slice); + void fillPictureParams(VAPictureParameterBufferMPEG2* param, + const PicturePtr& picture); + + YamiStatus fillConfigBuffer(); + YamiStatus + convertToVAProfile(const YamiParser::MPEG2::ProfileType& profile); + YamiStatus checkLevel(const YamiParser::MPEG2::LevelType& level); + bool isSliceCode(YamiParser::MPEG2::StartCodeType next_code); + + YamiStatus processConfigBuffer(); + YamiStatus processDecodeBuffer(); + + YamiStatus preDecode(StreamHdrPtr shdr); + YamiStatus processSlice(); + YamiStatus decodeGOP(); + YamiStatus assignSurface(); + YamiStatus assignPicture(); + YamiStatus createPicture(); + YamiStatus loadIQMatrix(); + bool updateIQMatrix(const YamiParser::MPEG2::QuantMatrices* refIQMatrix, + bool reset = false); + YamiStatus decodePicture(); + YamiStatus outputPicture(const PicturePtr& picture); + YamiStatus findReusePicture(std::list& list, bool& reuse); + + ParserPtr m_parser; + StreamHdrPtr m_stream; + + const YamiParser::MPEG2::SeqHeader* m_sequenceHeader; + const YamiParser::MPEG2::SeqExtension* m_sequenceExtension; + const YamiParser::MPEG2::GOPHeader* m_GOPHeader; //check what's the use here + const YamiParser::MPEG2::PictureHeader* m_pictureHeader; + const YamiParser::MPEG2::PictureCodingExtension* m_pictureCodingExtension; + const YamiParser::MPEG2::QuantMatrixExtension* m_quantMatrixExtension; + DPB m_DPB; + VASliceParameterBufferMPEG2* mpeg2SliceParams; + + bool m_VAStart; + bool m_isParsingSlices; + bool m_loadNewIQMatrix; + bool m_canCreatePicture; + PicturePtr m_currentPicture; + YamiParser::MPEG2::StartCodeType m_previousStartCode; + YamiParser::MPEG2::StartCodeType m_nextStartCode; + IQMatricesRefs m_IQMatrices; + VAProfile m_VAProfile; + uint64_t m_currentPTS; + + std::list m_topFieldPictures; + std::list m_bottomFieldPictures; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; +} // namespace YamiMediaCodec + +#endif diff --git a/decoder/vaapidecoder_mpeg2_unittest.cpp b/decoder/vaapidecoder_mpeg2_unittest.cpp new file mode 100644 index 0000000..2caea80 --- /dev/null +++ b/decoder/vaapidecoder_mpeg2_unittest.cpp @@ -0,0 +1,1095 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapidecoder_mpeg2.h" + +namespace YamiMediaCodec { +namespace MPEG2 { + + const static uint8_t SimpleMpeg2[] = { + 0x00, 0x00, 0x01, 0xba, 0x21, 0x00, 0x01, 0x00, 0x01, 0x88, 0x66, 0x99, + 0x00, 0x00, 0x01, 0xbb, 0x00, 0x09, 0x88, 0x66, 0x99, 0x00, 0x21, 0xff, + 0xe0, 0xe0, 0x0c, 0x00, 0x00, 0x01, 0xe0, 0x07, 0xdf, 0x31, 0x00, 0x03, + 0x77, 0x07, 0x11, 0x00, 0x03, 0x5f, 0x91, 0x00, 0x00, 0x01, 0xb3, 0x20, + 0x01, 0x20, 0x34, 0xff, 0xff, 0xe0, 0x18, 0x00, 0x00, 0x01, 0xb5, 0x14, + 0x8a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0xb8, 0x00, 0x08, 0x06, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0x00, 0x00, 0x01, + 0xb5, 0x8f, 0xff, 0xf3, 0x41, 0x80, 0x00, 0x00, 0x01, 0x01, 0x13, 0xf8, + 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, + 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, + 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, + 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, + 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, + 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, + 0x00, 0x00, 0x01, 0x02, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, + 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x9b, 0xc5, + 0xca, 0x52, 0x90, 0xf1, 0x72, 0x94, 0xa4, 0xa2, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, + 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x91, + 0xfd, 0xa2, 0x2c, 0x52, 0x67, 0x86, 0xd1, 0x17, 0x1d, 0xe1, 0x4a, 0x44, + 0x5c, 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, 0x45, 0xca, 0x52, 0x91, 0x17, + 0x29, 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, 0x44, 0x00, + 0x00, 0x01, 0x03, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x11, + 0xbe, 0x14, 0x9f, 0xd1, 0x72, 0x91, 0x66, 0xa6, 0xef, 0x3d, 0xda, 0x2c, + 0x52, 0x94, 0xa6, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, + 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x91, + 0xfe, 0x22, 0xe7, 0xfb, 0x4c, 0x7d, 0x0f, 0x95, 0x1a, 0x25, 0x73, 0x67, + 0x85, 0x1e, 0xb4, 0xb2, 0x6f, 0x47, 0xfc, 0xe1, 0x31, 0x0f, 0x75, 0xfe, + 0xd3, 0x01, 0x94, 0x63, 0xdd, 0x87, 0xd6, 0xa0, 0x01, 0xf9, 0x31, 0xc6, + 0x25, 0x2b, 0xad, 0x01, 0xd9, 0x0c, 0x60, 0xc2, 0xc9, 0x9c, 0xf0, 0x08, + 0x92, 0x28, 0x57, 0x93, 0x54, 0x37, 0x5e, 0x34, 0x16, 0x82, 0xc9, 0x1f, + 0x71, 0x10, 0xba, 0x00, 0x64, 0x06, 0xf8, 0x0c, 0x95, 0x96, 0x80, 0x1c, + 0xa0, 0xe4, 0xe1, 0x78, 0x7e, 0xb3, 0x00, 0xc0, 0x06, 0x20, 0x37, 0xcb, + 0x1c, 0x7c, 0x34, 0x6e, 0xf7, 0x45, 0x29, 0x49, 0xca, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, + 0x00, 0x00, 0x01, 0x04, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x8f, 0x17, 0x29, 0x49, 0x93, + 0xfe, 0xf3, 0x8b, 0x5a, 0x4c, 0x4b, 0xf0, 0x1b, 0xbc, 0x64, 0xc5, 0x8a, + 0x52, 0x92, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4f, + 0x4a, 0x4d, 0xa2, 0xe6, 0xcd, 0x4a, 0x52, 0x3a, 0xa2, 0xe5, 0x29, 0x48, + 0xde, 0x2e, 0x52, 0x94, 0x94, 0x5c, 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, + 0x45, 0xca, 0x52, 0x91, 0x17, 0x29, 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, + 0x72, 0x94, 0x8f, 0xec, 0xa8, 0x8b, 0x9f, 0xcc, 0x7d, 0x25, 0x46, 0x89, + 0x5c, 0x42, 0x21, 0x4a, 0x44, 0xed, 0xc8, 0x61, 0xa0, 0x61, 0x17, 0x50, + 0x01, 0xc8, 0x03, 0xf2, 0xf2, 0x3e, 0x2a, 0xc2, 0x01, 0x8a, 0x58, 0x31, + 0x37, 0x68, 0x0a, 0x86, 0xbf, 0x4b, 0xd0, 0x56, 0x7a, 0x83, 0x52, 0x4f, + 0xbd, 0xa4, 0xd0, 0x13, 0x86, 0x8d, 0x7f, 0xfb, 0xd4, 0x00, 0x60, 0x00, + 0x95, 0x80, 0x28, 0x01, 0xd9, 0xdc, 0xe0, 0xd3, 0x37, 0x1c, 0x58, 0xa1, + 0x66, 0x5a, 0x80, 0x63, 0xb3, 0xda, 0x53, 0x47, 0xb4, 0x41, 0xf7, 0xe5, + 0x49, 0x98, 0x6e, 0x41, 0x34, 0x30, 0xc0, 0x0e, 0xf1, 0x1e, 0xa0, 0x99, + 0x89, 0x5f, 0xfc, 0x48, 0xeb, 0x61, 0xce, 0x40, 0xbb, 0x80, 0x05, 0xc0, + 0x0d, 0x40, 0x2a, 0x4e, 0x01, 0xd0, 0x6f, 0x72, 0xba, 0x83, 0x3f, 0x03, + 0xc0, 0x3c, 0x11, 0xcc, 0x17, 0x70, 0xb6, 0x6f, 0x98, 0xef, 0x5a, 0x75, + 0x08, 0xe7, 0xde, 0x70, 0xce, 0xf9, 0xa5, 0xac, 0x0c, 0xec, 0x9c, 0x15, + 0x57, 0x5f, 0xa7, 0x5c, 0xa5, 0x29, 0x12, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x20, 0x00, 0x00, 0x01, 0x05, 0x13, + 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, + 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x43, 0xe9, 0x49, 0xf8, 0xb6, 0x4e, 0xe8, 0x8c, + 0x91, 0xe8, 0x9f, 0xd1, 0x6c, 0xfe, 0x5c, 0x99, 0xa9, 0x33, 0xa4, 0xd6, + 0xaf, 0x09, 0xe1, 0x8b, 0xf2, 0xc9, 0x9d, 0xad, 0x22, 0xf0, 0xa4, 0xf8, + 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x26, 0xd1, + 0x72, 0x94, 0xa4, 0x45, 0xca, 0x52, 0x92, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x1f, 0xe2, 0x35, + 0xcf, 0xe6, 0xd0, 0x86, 0xd0, 0x7c, 0xae, 0x68, 0x52, 0x91, 0x3b, 0x94, + 0xa5, 0x22, 0x2f, 0x40, 0x08, 0x50, 0xe5, 0x7f, 0xee, 0xc0, 0x15, 0x00, + 0xd0, 0x0a, 0x86, 0xa7, 0x81, 0x80, 0xcf, 0xf0, 0xfb, 0x96, 0x01, 0x98, + 0x15, 0x18, 0x1a, 0x56, 0x4f, 0x64, 0x39, 0xb4, 0xe4, 0x30, 0x0d, 0x36, + 0x1b, 0xcb, 0x47, 0xd8, 0x72, 0xc9, 0xd4, 0x20, 0x45, 0x45, 0x84, 0xdf, + 0x70, 0x9a, 0x00, 0xc8, 0x04, 0xf8, 0x07, 0x24, 0xce, 0x1d, 0x6a, 0x2c, + 0x03, 0x2f, 0x8b, 0x18, 0xdd, 0xef, 0x3a, 0x58, 0x03, 0x30, 0x0d, 0x0a, + 0x2c, 0x0c, 0x12, 0xff, 0xc6, 0x71, 0x9d, 0x7f, 0x99, 0x80, 0xed, 0xd8, + 0x00, 0xcc, 0x03, 0x1f, 0x80, 0x33, 0x6d, 0x90, 0x4a, 0x71, 0xc7, 0xed, + 0x4a, 0x3b, 0x99, 0x68, 0x94, 0x0c, 0x3b, 0xdb, 0x94, 0x00, 0x98, 0x04, + 0xe5, 0xe1, 0xa8, 0x29, 0x43, 0xfb, 0x6b, 0x90, 0x00, 0xc0, 0x86, 0x05, + 0x4b, 0x26, 0x01, 0x82, 0x1e, 0x01, 0x48, 0x62, 0x9c, 0xf1, 0xbb, 0x1d, + 0xc4, 0x8f, 0x80, 0x60, 0x03, 0x50, 0x10, 0x24, 0xac, 0x01, 0x3f, 0xca, + 0x38, 0x31, 0xf0, 0x8e, 0x3a, 0xb3, 0x00, 0x6a, 0x01, 0xa1, 0x30, 0x0a, + 0x94, 0x1a, 0x4c, 0x0d, 0x25, 0x0d, 0xf8, 0x96, 0x52, 0x45, 0x8e, 0x9f, + 0xe2, 0xbc, 0xb6, 0x65, 0xbd, 0xf3, 0x79, 0x12, 0xab, 0x2e, 0xb7, 0x04, + 0xb7, 0xdd, 0x5f, 0x2a, 0x42, 0x8e, 0xaf, 0xd9, 0xa1, 0x76, 0xb4, 0xa5, + 0x27, 0x2b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, + 0x22, 0x00, 0x00, 0x01, 0x06, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, + 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x27, 0xe2, 0xd8, 0x6c, 0x32, 0x69, 0xf4, 0xd5, + 0x75, 0x45, 0xa5, 0x27, 0x83, 0xf9, 0x0d, 0x86, 0xb5, 0xa3, 0xcd, 0x93, + 0x4f, 0xde, 0x3f, 0x8b, 0x89, 0xef, 0x1a, 0x52, 0x72, 0xb9, 0x4a, 0x52, + 0x71, 0x72, 0x19, 0x31, 0xa4, 0xb4, 0x5a, 0xbc, 0x27, 0x80, 0xd9, 0x0d, + 0x9d, 0xad, 0x23, 0x93, 0x09, 0x45, 0xca, 0x52, 0x90, 0xf1, 0x72, 0x94, + 0xa4, 0x45, 0xca, 0x52, 0x92, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, + 0x88, 0xb9, 0x4a, 0x47, 0xf8, 0x8b, 0x9f, 0x8e, 0x9a, 0x87, 0xca, 0x8d, + 0xb4, 0x4a, 0xe6, 0xd0, 0xa5, 0x22, 0x77, 0x29, 0x4a, 0x44, 0x5c, 0xa7, + 0x3b, 0xd2, 0xb1, 0x24, 0xd1, 0x9c, 0x4a, 0xa1, 0xa2, 0xf5, 0x80, 0x31, + 0x02, 0x9c, 0xb0, 0xcd, 0x77, 0x80, 0xae, 0x26, 0x93, 0x13, 0xd9, 0x3f, + 0x08, 0xbc, 0xb9, 0x0c, 0xac, 0x1a, 0x57, 0xd7, 0x50, 0x04, 0x20, 0x0e, + 0x97, 0xfd, 0x98, 0x62, 0x6d, 0x09, 0xbb, 0x9f, 0x7d, 0x60, 0x29, 0x8b, + 0x2c, 0xb7, 0x4a, 0x7b, 0x65, 0xfe, 0x97, 0x6d, 0x38, 0x06, 0x2f, 0x80, + 0xae, 0x57, 0x51, 0xdd, 0xba, 0xf0, 0xfb, 0x8e, 0x01, 0x72, 0x00, 0x4c, + 0x18, 0x94, 0x86, 0x13, 0x72, 0x19, 0x97, 0xfe, 0x57, 0xf6, 0x30, 0x13, + 0xf0, 0x0b, 0x86, 0x60, 0xd2, 0x6f, 0x21, 0x0c, 0x42, 0x8c, 0xfc, 0x83, + 0x2e, 0x96, 0xad, 0x08, 0xfd, 0x6f, 0xaf, 0xd3, 0x16, 0x01, 0x68, 0x66, + 0xc9, 0x42, 0x53, 0x90, 0x93, 0x51, 0xf9, 0xe3, 0x84, 0xc4, 0x84, 0x4b, + 0x4f, 0x74, 0xf7, 0x17, 0x72, 0x92, 0x58, 0x06, 0x80, 0x27, 0x02, 0xa4, + 0xd2, 0x11, 0x30, 0xac, 0x82, 0x92, 0xc9, 0x47, 0x00, 0x14, 0xe3, 0xd5, + 0x32, 0x00, 0x1b, 0x74, 0x75, 0x69, 0x3b, 0xcf, 0xdf, 0x1c, 0x01, 0xa7, + 0xe9, 0x00, 0xc0, 0x0a, 0x7e, 0xbe, 0x31, 0xaa, 0x03, 0x2b, 0x80, 0x32, + 0xc3, 0x00, 0x40, 0x19, 0xb1, 0x8f, 0xaa, 0x43, 0x2d, 0x53, 0xd7, 0xec, + 0x43, 0x0e, 0xc2, 0x2d, 0x29, 0x4a, 0x4e, 0x9b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0x00, 0x00, 0x01, 0x07, 0x13, + 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, + 0xb9, 0x4a, 0x45, 0x3d, 0xa7, 0x16, 0x29, 0x30, 0xdf, 0x41, 0xbe, 0x63, + 0x61, 0xad, 0x69, 0x12, 0x5d, 0x06, 0xe8, 0x78, 0xb1, 0x1f, 0x42, 0x5e, + 0xa0, 0xdd, 0x27, 0x8b, 0x66, 0xa4, 0x3f, 0x8d, 0x5f, 0x4a, 0xe5, 0x29, + 0x1f, 0xea, 0x1b, 0x16, 0x29, 0x4a, 0x48, 0x6b, 0xc5, 0xca, 0x52, 0x90, + 0x74, 0x5c, 0xa5, 0x1c, 0x55, 0x23, 0x26, 0x2e, 0x50, 0x65, 0x1e, 0x19, + 0x2d, 0x4e, 0x5c, 0xee, 0x0c, 0xf1, 0x3a, 0x4a, 0x43, 0x45, 0xb0, 0xdf, + 0x01, 0xb4, 0xfa, 0x63, 0xa2, 0x2d, 0x5f, 0x50, 0x6c, 0xd4, 0x9b, 0xc5, + 0xa5, 0x26, 0xde, 0x5a, 0x62, 0xe5, 0x29, 0x49, 0x45, 0xca, 0x52, 0x64, + 0xa5, 0xa2, 0x2c, 0x25, 0x2c, 0xad, 0x3a, 0xfd, 0x36, 0xfe, 0xad, 0x1b, + 0x63, 0x26, 0x7c, 0x1d, 0x67, 0x66, 0xd0, 0xa5, 0x25, 0x17, 0x29, 0x4a, + 0x44, 0x5c, 0xa5, 0x29, 0x11, 0x67, 0x9d, 0x39, 0x48, 0x1b, 0xb3, 0xc9, + 0xfa, 0xbc, 0xc5, 0x77, 0x96, 0x8b, 0x09, 0xc3, 0x2e, 0x80, 0x03, 0x72, + 0x19, 0x64, 0xc2, 0x9c, 0xc1, 0xe3, 0xae, 0x72, 0x70, 0xdd, 0x69, 0x01, + 0xd9, 0x0b, 0x01, 0x52, 0x92, 0x57, 0x34, 0x7c, 0x91, 0x59, 0x37, 0x5e, + 0xb0, 0x18, 0x16, 0x02, 0x60, 0x31, 0x92, 0x4c, 0x46, 0x21, 0xa4, 0xd4, + 0xa5, 0x4b, 0x10, 0x7d, 0x68, 0x15, 0x21, 0x80, 0xef, 0x86, 0xbf, 0x00, + 0xc0, 0x0a, 0x27, 0x60, 0x12, 0xf4, 0xf3, 0x80, 0x22, 0x22, 0xd7, 0x00, + 0x9c, 0x03, 0x42, 0x18, 0x09, 0xbf, 0x19, 0xd8, 0x45, 0xa5, 0x20, 0x54, + 0x03, 0x33, 0xb9, 0x69, 0x6a, 0x19, 0xed, 0x3f, 0x7b, 0xca, 0x1a, 0x58, + 0x06, 0x99, 0x23, 0x52, 0x57, 0x02, 0x81, 0xa6, 0x70, 0xc5, 0xa1, 0x3c, + 0x5e, 0x32, 0xce, 0x01, 0x90, 0x69, 0x34, 0x9b, 0xb6, 0xe0, 0x7f, 0xb6, + 0xb7, 0x80, 0xc0, 0x07, 0x41, 0xa0, 0x3b, 0x2d, 0x0e, 0xbf, 0x70, 0xc0, + 0x30, 0x01, 0x36, 0x47, 0xc9, 0xf9, 0x99, 0x5a, 0x13, 0xda, 0x0a, 0x40, + 0xd6, 0xd6, 0x88, 0x0c, 0x41, 0x0b, 0x72, 0x90, 0x76, 0x23, 0xf9, 0x03, + 0x3c, 0x43, 0x49, 0x29, 0xa1, 0x47, 0xeb, 0x47, 0x7b, 0x13, 0xbd, 0xd5, + 0x4a, 0x52, 0x72, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, + 0xa5, 0x22, 0x20, 0x00, 0x00, 0x01, 0x08, 0x13, 0xf8, 0x7d, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x1f, 0xa1, 0x48, + 0x8b, 0x7a, 0x49, 0xe6, 0xf9, 0xab, 0xe8, 0x68, 0x7b, 0x34, 0xa5, 0x27, + 0xd5, 0x2b, 0x94, 0xa5, 0x21, 0xe6, 0xd7, 0x29, 0x4a, 0x43, 0xbc, 0xae, + 0x47, 0xe8, 0x53, 0xcd, 0x3a, 0x2d, 0xa0, 0xf1, 0xe8, 0x8d, 0xaf, 0x2d, + 0x28, 0x95, 0xa3, 0xd2, 0x77, 0xa6, 0x4d, 0x25, 0x01, 0x53, 0x3c, 0x7d, + 0x69, 0x48, 0xef, 0x0a, 0x33, 0x24, 0xef, 0x3b, 0x94, 0xa5, 0x23, 0x73, + 0x22, 0xd1, 0xde, 0x93, 0x6e, 0xd0, 0x1b, 0xa8, 0x77, 0x99, 0xd6, 0x28, + 0x7d, 0x29, 0x28, 0xb6, 0x25, 0x6a, 0x74, 0x34, 0xb4, 0x9b, 0x45, 0xb6, + 0xd2, 0xae, 0x94, 0x94, 0x5c, 0xa5, 0x26, 0x2c, 0xb6, 0x56, 0x94, 0x58, + 0x2c, 0xb6, 0x3a, 0x7c, 0xff, 0xd3, 0x6e, 0x9f, 0x26, 0x40, 0xc9, 0xe0, + 0x9f, 0x26, 0x6b, 0x1b, 0x35, 0x29, 0x49, 0x4d, 0xee, 0x52, 0x94, 0x88, + 0xb9, 0x4a, 0x52, 0x22, 0xe4, 0xc5, 0xa5, 0xa2, 0x1a, 0x05, 0x43, 0x09, + 0x99, 0xff, 0x0e, 0xc7, 0xda, 0x03, 0x40, 0x4e, 0x52, 0x52, 0x7f, 0x8d, + 0xbd, 0x49, 0x0d, 0x28, 0xa3, 0xd3, 0xb5, 0xd2, 0x4d, 0x0d, 0x25, 0x14, + 0xee, 0x7c, 0xe0, 0x3a, 0x0d, 0x25, 0xf4, 0x88, 0xd5, 0x80, 0x27, 0x4a, + 0x12, 0x18, 0x50, 0xcf, 0xba, 0xcc, 0x80, 0x09, 0xbe, 0x28, 0x96, 0xe3, + 0xb5, 0x2c, 0xa8, 0x25, 0xee, 0x6e, 0xba, 0x3a, 0x79, 0x5e, 0x8e, 0x82, + 0xcf, 0x54, 0xdd, 0x28, 0x2c, 0xef, 0x44, 0x0e, 0xf3, 0xab, 0xa5, 0xc5, + 0xeb, 0x60, 0xd0, 0x28, 0x4b, 0xcd, 0xf6, 0xf6, 0x92, 0xc0, 0x1f, 0x13, + 0x0d, 0x42, 0xec, 0x6b, 0xd1, 0xe4, 0xde, 0x3a, 0x5b, 0xfd, 0x3e, 0x8c, + 0x22, 0xed, 0x01, 0x80, 0x09, 0x8a, 0x0c, 0x3b, 0x35, 0x48, 0x19, 0xdd, + 0x58, 0xc5, 0x56, 0x16, 0x1a, 0x9e, 0x77, 0xda, 0x00, 0x00, 0x01, 0xe0, + 0x07, 0xfa, 0x0f, 0x50, 0xc0, 0xcd, 0x83, 0x0f, 0x7f, 0xfb, 0x87, 0xc2, + 0x5e, 0x03, 0x38, 0x4e, 0xc8, 0x16, 0xfc, 0x81, 0x61, 0x3d, 0xfa, 0x44, + 0x68, 0x14, 0x7c, 0xe6, 0xac, 0xdd, 0x9e, 0x42, 0x62, 0xe1, 0xa8, 0x75, + 0xdd, 0x54, 0xa5, 0x2a, 0xa6, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x52, 0x94, 0x88, 0x80, 0x00, 0x00, 0x01, 0x09, 0x13, 0xf8, 0x7d, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x23, 0xc5, 0xca, 0x52, 0x93, 0x8b, 0x94, + 0x88, 0xdd, 0x42, 0x5c, 0x0d, 0x8b, 0x14, 0xa5, 0x24, 0x7c, 0x59, 0xe8, + 0x99, 0x9a, 0x4a, 0x7c, 0xf5, 0x74, 0x3c, 0x6b, 0x7f, 0x37, 0xd2, 0x74, + 0x7d, 0x16, 0xb4, 0x49, 0x4c, 0x74, 0xb7, 0xb6, 0x83, 0xc6, 0x29, 0xb4, + 0xff, 0xef, 0x2b, 0x5d, 0xe1, 0x3b, 0xc3, 0x25, 0xa4, 0x80, 0x2a, 0x3e, + 0x1a, 0xd6, 0x3f, 0x3c, 0x37, 0x7a, 0x50, 0xe8, 0x2f, 0x4e, 0xdf, 0xe8, + 0xc9, 0xf3, 0xc7, 0xeb, 0x42, 0xc8, 0x4c, 0x74, 0x3d, 0xb4, 0xb8, 0xb8, + 0xb4, 0x6a, 0xc9, 0x49, 0x52, 0xb5, 0x7a, 0x3c, 0xce, 0xd2, 0xef, 0x4a, + 0x03, 0x46, 0xcf, 0xeb, 0x0f, 0x4d, 0xe3, 0x0d, 0xe8, 0x47, 0x8b, 0x0f, + 0x01, 0xbe, 0x34, 0xa1, 0x09, 0xf1, 0x60, 0x6c, 0x06, 0xcd, 0x49, 0x01, + 0x99, 0xda, 0x6f, 0x49, 0xf5, 0x0b, 0x26, 0x99, 0xa4, 0x36, 0x1a, 0xc2, + 0x4b, 0x65, 0x69, 0xf6, 0xe5, 0xfa, 0x14, 0x8e, 0x9a, 0xad, 0x9b, 0x46, + 0x5c, 0x8e, 0xb9, 0xb3, 0x52, 0x94, 0x93, 0x4e, 0xe5, 0x29, 0x49, 0x45, + 0xca, 0x75, 0x52, 0xd2, 0x02, 0x10, 0x0d, 0x71, 0x41, 0x05, 0x2f, 0x9b, + 0xcc, 0xd1, 0xb3, 0xcc, 0xb2, 0xd0, 0x18, 0x8f, 0xfd, 0xd6, 0x1a, 0x02, + 0x10, 0xc0, 0xcc, 0xb1, 0xbc, 0x38, 0x8b, 0x6b, 0x02, 0xa0, 0x19, 0x86, + 0x93, 0x55, 0x80, 0xb6, 0x1d, 0x88, 0xb3, 0xa4, 0x86, 0x1b, 0xcf, 0x4f, + 0xf3, 0xfb, 0x34, 0x15, 0xb1, 0xf7, 0x60, 0x15, 0x00, 0xd4, 0xb2, 0xd4, + 0x8f, 0xd1, 0x89, 0xf7, 0x0f, 0xa5, 0x0e, 0x8f, 0xa2, 0xde, 0xc3, 0xb4, + 0x98, 0x07, 0x69, 0xdd, 0x67, 0xb3, 0x38, 0xa1, 0xd5, 0x9c, 0xfa, 0x34, + 0x75, 0xc2, 0x03, 0x4b, 0x0c, 0xe1, 0x1f, 0xeb, 0xce, 0x4b, 0x42, 0x40, + 0x05, 0x1c, 0x02, 0x0e, 0x40, 0xaa, 0x29, 0x25, 0xa1, 0x9d, 0x62, 0xed, + 0x8e, 0xc7, 0x55, 0x86, 0x01, 0x54, 0x86, 0x1d, 0xd4, 0x38, 0xca, 0x86, + 0x59, 0x06, 0x00, 0xed, 0x6b, 0x50, 0xbd, 0x78, 0x90, 0x5c, 0xc1, 0xa5, + 0xb1, 0xd5, 0x88, 0x01, 0x8e, 0x49, 0x98, 0x39, 0x51, 0x48, 0x15, 0x28, + 0x02, 0x4e, 0x17, 0x58, 0xcf, 0x73, 0x80, 0x57, 0xba, 0x09, 0x3a, 0xca, + 0x49, 0x65, 0xd9, 0xc8, 0x45, 0x72, 0x8a, 0xdb, 0xf5, 0xfb, 0x4f, 0x01, + 0x0f, 0xc4, 0x84, 0x6d, 0x29, 0x40, 0x1a, 0xbe, 0xc3, 0x65, 0xf7, 0x1d, + 0x58, 0x61, 0x34, 0x98, 0x82, 0xdf, 0xa7, 0xfe, 0x4e, 0xba, 0x89, 0xbb, + 0xba, 0x8f, 0x6a, 0xe2, 0x83, 0x49, 0xa4, 0x2e, 0xe4, 0xef, 0x54, 0x1a, + 0x5a, 0x9e, 0xb8, 0x9a, 0x94, 0xa5, 0x0e, 0x11, 0xa1, 0x16, 0x64, 0x3e, + 0x07, 0xf7, 0xf9, 0x96, 0xab, 0xab, 0x00, 0x3f, 0x02, 0x61, 0x81, 0x5e, + 0xa8, 0x98, 0x03, 0xb2, 0x88, 0x64, 0x85, 0x71, 0xde, 0xe8, 0x6e, 0x67, + 0x97, 0x27, 0xa3, 0xbe, 0x3e, 0x5c, 0x33, 0x5a, 0xa0, 0x03, 0x10, 0xdd, + 0xd6, 0xc9, 0xc4, 0xf0, 0xbb, 0xe6, 0xd2, 0xd8, 0x50, 0x06, 0x64, 0xdc, + 0x7f, 0xdc, 0x4e, 0xa8, 0x21, 0x00, 0xc5, 0x01, 0xa7, 0x84, 0x72, 0x75, + 0x7c, 0xaf, 0xac, 0x03, 0x00, 0x62, 0x4c, 0x0d, 0x56, 0xec, 0x26, 0xea, + 0xa5, 0x0c, 0xa4, 0xec, 0xee, 0x52, 0x94, 0x88, 0x80, 0x00, 0x00, 0x01, + 0x0a, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x27, 0xe2, 0xe4, + 0x7f, 0x68, 0x53, 0xe7, 0x9f, 0x8b, 0x7a, 0x52, 0x95, 0x4a, 0xe3, 0xf9, + 0x72, 0x66, 0xa4, 0xb7, 0x86, 0xb4, 0x7a, 0x4f, 0x01, 0xb2, 0xc5, 0xbc, + 0xed, 0x47, 0xcf, 0x07, 0x8c, 0x7e, 0xf1, 0x67, 0xe8, 0xf9, 0x69, 0x68, + 0x5a, 0x1e, 0x4f, 0x6f, 0xf4, 0x65, 0xf4, 0xb5, 0x49, 0x52, 0xb6, 0x83, + 0xd3, 0xe8, 0xd5, 0xff, 0x2a, 0x2d, 0x37, 0xa3, 0xe9, 0xf2, 0x5a, 0x03, + 0x5e, 0x92, 0x80, 0x77, 0x8d, 0x8f, 0xad, 0x7c, 0x69, 0x17, 0xa7, 0xf1, + 0xb1, 0xac, 0x34, 0x5a, 0x0f, 0x4a, 0xba, 0x34, 0x59, 0xd0, 0x8f, 0x45, + 0x0e, 0x87, 0xfa, 0x1a, 0xd7, 0x78, 0x79, 0xde, 0x19, 0x34, 0x14, 0x1b, + 0x36, 0xb5, 0xa5, 0x22, 0x94, 0xb5, 0x9b, 0xe6, 0x8b, 0x9d, 0x2c, 0x74, + 0x50, 0x57, 0x4d, 0x36, 0x1b, 0xea, 0xb6, 0x56, 0x84, 0x01, 0x7f, 0x25, + 0x6d, 0x73, 0x66, 0x55, 0x29, 0x4a, 0x1a, 0xab, 0x94, 0xa5, 0x22, 0x2e, + 0x53, 0xaa, 0x95, 0xc0, 0x21, 0x01, 0x88, 0x0d, 0xb0, 0xc4, 0x12, 0x79, + 0x3a, 0x59, 0x0f, 0x34, 0xa7, 0x15, 0xba, 0x79, 0xda, 0xd8, 0x04, 0xe4, + 0xd2, 0xd9, 0x8a, 0x42, 0x58, 0x03, 0xbb, 0x67, 0xf2, 0xa4, 0xb2, 0xff, + 0x71, 0xbe, 0x9f, 0x80, 0xdf, 0x0e, 0x49, 0x1e, 0xcc, 0xac, 0x32, 0xec, + 0x21, 0x90, 0xc0, 0x2d, 0xe6, 0xe1, 0x5c, 0xeb, 0x7a, 0x43, 0x21, 0xc4, + 0xd0, 0x62, 0x75, 0x36, 0xad, 0xc7, 0x5c, 0x19, 0xbc, 0x7d, 0x28, 0xe2, + 0xa2, 0x7e, 0xda, 0x90, 0xa4, 0xa7, 0x66, 0x8f, 0x46, 0xa4, 0x4e, 0xc6, + 0xec, 0x6c, 0x09, 0x69, 0x1f, 0x36, 0xda, 0x9e, 0x23, 0x7f, 0xac, 0x3b, + 0x9b, 0x1f, 0xdb, 0xd1, 0x74, 0x68, 0x8b, 0x4c, 0x05, 0x53, 0x90, 0xce, + 0x74, 0xdd, 0x3f, 0xae, 0x34, 0x86, 0xda, 0x44, 0xb4, 0xfc, 0xcf, 0xec, + 0x3b, 0xc8, 0x8f, 0x59, 0xa5, 0x41, 0xf1, 0xe4, 0x8b, 0xac, 0x64, 0x6a, + 0xc6, 0x45, 0x96, 0x23, 0x4d, 0xec, 0xc6, 0x5c, 0x28, 0x86, 0x1a, 0x51, + 0x21, 0x3f, 0x4a, 0x00, 0x6a, 0x43, 0x77, 0xff, 0x7c, 0x39, 0xab, 0x1a, + 0x83, 0x26, 0xdb, 0xcb, 0x06, 0x86, 0xa0, 0xe4, 0xf0, 0xbb, 0xcc, 0x80, + 0x0b, 0xd1, 0xc9, 0x28, 0x6a, 0xbc, 0x03, 0x12, 0x67, 0xce, 0x35, 0x84, + 0xdb, 0x9f, 0x23, 0x7f, 0xce, 0xda, 0xd8, 0x02, 0x10, 0x13, 0xf0, 0x0b, + 0x0b, 0x4f, 0x56, 0x4b, 0x62, 0x91, 0xbf, 0x75, 0x0f, 0x63, 0x38, 0xf3, + 0x2a, 0xe1, 0x9a, 0xc8, 0x84, 0x02, 0x72, 0x69, 0x7d, 0x95, 0xc5, 0xf3, + 0x20, 0x00, 0x00, 0x01, 0x0b, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, + 0xa5, 0x26, 0xd1, 0x72, 0x94, 0xa4, 0x45, 0xc8, 0xfc, 0xf0, 0xa4, 0x7d, + 0x16, 0xff, 0x35, 0x24, 0x8f, 0x2a, 0x7d, 0x11, 0x6d, 0x47, 0xa7, 0xdf, + 0x52, 0xbf, 0xbe, 0x95, 0xca, 0x45, 0xbd, 0x1e, 0x79, 0x3f, 0x45, 0x8a, + 0x52, 0x92, 0x3e, 0x2c, 0xfd, 0x16, 0x96, 0x3f, 0x4f, 0xe8, 0xb3, 0x4f, + 0x9e, 0x91, 0xfe, 0xd1, 0x2a, 0x95, 0x96, 0x8c, 0x29, 0x68, 0x94, 0x6f, + 0x2b, 0x8f, 0xf4, 0x1d, 0xe2, 0xd1, 0x9e, 0x2f, 0x95, 0x16, 0xbe, 0x8f, + 0x17, 0xa3, 0xd2, 0x4b, 0xdd, 0x7a, 0x6d, 0x60, 0x6c, 0x3f, 0xde, 0x68, + 0xbc, 0xf1, 0x70, 0xd6, 0x29, 0x48, 0xa5, 0x2d, 0x1c, 0xbd, 0x0d, 0x61, + 0x24, 0xd6, 0xa1, 0x58, 0x6a, 0xe7, 0x42, 0x1d, 0x7e, 0x4d, 0x24, 0x16, + 0x9e, 0x7c, 0xbd, 0xd7, 0x97, 0x2e, 0xf5, 0x9b, 0xcb, 0x73, 0x86, 0x16, + 0xf5, 0xfd, 0x69, 0x4a, 0x64, 0xbd, 0x2c, 0xf7, 0x8b, 0x94, 0xa4, 0xc4, + 0xd2, 0x1e, 0x26, 0x21, 0xf9, 0xe6, 0x68, 0x3e, 0x38, 0xfb, 0x24, 0xd4, + 0xf4, 0x1c, 0x94, 0x61, 0x7e, 0xd8, 0x43, 0x0c, 0x0d, 0x71, 0xaa, 0x2f, + 0x0f, 0xd1, 0x26, 0x86, 0xa4, 0x9a, 0x91, 0xa9, 0x99, 0x09, 0xe8, 0x24, + 0x7b, 0x34, 0x21, 0xae, 0xa0, 0x2a, 0x03, 0xb4, 0x13, 0x54, 0xdd, 0xb0, + 0xb2, 0x25, 0xb3, 0xbc, 0x1a, 0x46, 0xc4, 0x33, 0x99, 0x09, 0x27, 0x79, + 0xc5, 0x25, 0x5e, 0x9b, 0x71, 0x8c, 0x2c, 0x5d, 0x8f, 0xba, 0x73, 0xe3, + 0xf5, 0x32, 0x79, 0xba, 0x08, 0x7c, 0xb9, 0x46, 0x3c, 0x52, 0x84, 0x3d, + 0xb3, 0x6e, 0x64, 0x46, 0x0a, 0xa9, 0x25, 0x50, 0x0c, 0x43, 0xcb, 0x93, + 0x3f, 0xbb, 0xfa, 0x22, 0xba, 0xbf, 0xa3, 0xca, 0xe3, 0xda, 0x4f, 0x5a, + 0x4a, 0x6b, 0xb3, 0xb8, 0xe8, 0xcb, 0xd0, 0x2d, 0xe6, 0xf2, 0xab, 0xa2, + 0xe3, 0xc5, 0xe1, 0x18, 0xa8, 0xeb, 0x94, 0x7a, 0x53, 0x44, 0x6b, 0x8f, + 0xe9, 0xa9, 0x48, 0x8b, 0x9d, 0xa9, 0xbb, 0x52, 0x91, 0x0f, 0x79, 0xc9, + 0x84, 0xdc, 0x94, 0x30, 0x1f, 0xc6, 0x0f, 0x93, 0x06, 0x7d, 0x96, 0x7f, + 0xb5, 0x6f, 0xd1, 0xdf, 0x1f, 0x61, 0x02, 0x81, 0xa5, 0x10, 0xca, 0xdf, + 0x9e, 0x77, 0xad, 0x2a, 0xcf, 0x73, 0x80, 0xc3, 0x80, 0x5b, 0xc6, 0x73, + 0xf6, 0x50, 0xbb, 0xb3, 0x95, 0x32, 0x4a, 0x6d, 0x66, 0xe0, 0x60, 0x79, + 0x3a, 0x6e, 0x51, 0x5f, 0xe9, 0x92, 0xec, 0x52, 0x03, 0x0f, 0x7a, 0xc0, + 0xa9, 0x09, 0x25, 0xec, 0x8c, 0x3d, 0x77, 0x48, 0x01, 0x9a, 0x49, 0x49, + 0xc1, 0x8e, 0xa0, 0xc2, 0x3f, 0x3e, 0xe1, 0x7e, 0x80, 0xc4, 0x25, 0x3c, + 0x0f, 0x6f, 0xc2, 0xaf, 0x4c, 0x00, 0xf5, 0x29, 0xe4, 0xd4, 0xff, 0xcf, + 0x7e, 0x1f, 0xe4, 0x8e, 0xf0, 0x03, 0x60, 0x1b, 0x61, 0x30, 0x00, 0x00, + 0x01, 0x0c, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x6d, 0x17, 0x29, 0x4a, 0x44, 0x5c, + 0x69, 0x89, 0x52, 0xd2, 0x6e, 0x2a, 0x2d, 0xe9, 0x2b, 0x4d, 0xf3, 0x4f, + 0xa2, 0x32, 0xae, 0x52, 0x94, 0xa8, 0x64, 0xae, 0x52, 0x94, 0x86, 0x8b, + 0x91, 0xf8, 0x74, 0x29, 0x3f, 0xb4, 0x5b, 0x34, 0x7c, 0x8d, 0x16, 0xaf, + 0x93, 0x31, 0x91, 0x6f, 0x49, 0x7e, 0x8b, 0x5a, 0x24, 0x99, 0xf0, 0xef, + 0x4b, 0xdb, 0x7a, 0x4a, 0xd1, 0x6a, 0xc9, 0x49, 0x44, 0x59, 0xa4, 0x18, + 0x54, 0xc1, 0xa9, 0x6d, 0x09, 0x47, 0x8b, 0x29, 0x2d, 0xa2, 0x84, 0x7e, + 0xbf, 0x44, 0x06, 0x73, 0xfc, 0xac, 0xd6, 0x9c, 0x69, 0xba, 0x47, 0x58, + 0x78, 0x4d, 0x41, 0xb4, 0x94, 0x4d, 0xfa, 0x6d, 0x75, 0xe9, 0x6b, 0x11, + 0xe4, 0xde, 0xe6, 0x02, 0x85, 0xef, 0x3f, 0xac, 0x6d, 0x00, 0x9a, 0x22, + 0x62, 0x18, 0x15, 0x41, 0x31, 0x59, 0x69, 0x1d, 0xb3, 0xb0, 0x9b, 0x0d, + 0xaa, 0xff, 0x63, 0xd5, 0x60, 0xb0, 0x2b, 0x83, 0x37, 0x3f, 0xf1, 0xdb, + 0x11, 0x6d, 0xa4, 0xd2, 0x1a, 0x48, 0x69, 0x7f, 0xc3, 0xa5, 0x49, 0x65, + 0xfe, 0xe3, 0x42, 0xd5, 0x37, 0x4a, 0x03, 0x54, 0x5e, 0x25, 0x24, 0x09, + 0x90, 0x6c, 0xca, 0x43, 0x5d, 0x20, 0x54, 0x86, 0x06, 0x42, 0x37, 0xe8, + 0xc2, 0xce, 0xe1, 0xe6, 0x5b, 0x52, 0x89, 0x42, 0x4a, 0xec, 0x90, 0xee, + 0x67, 0xa3, 0x50, 0xf6, 0xff, 0x77, 0x1d, 0x71, 0xda, 0x45, 0x13, 0x73, + 0x75, 0x24, 0xcf, 0x3e, 0x95, 0x08, 0x9b, 0xc9, 0x07, 0x8a, 0xe7, 0xeb, + 0x08, 0x7a, 0xa2, 0x8a, 0x88, 0x61, 0x4f, 0x54, 0x84, 0x34, 0xff, 0xb0, + 0x26, 0x13, 0x2c, 0xfc, 0x33, 0x3f, 0xad, 0x2c, 0x37, 0x1b, 0xea, 0x8b, + 0x4a, 0x1d, 0x97, 0xbf, 0x3b, 0xf3, 0xa6, 0x66, 0x3d, 0x05, 0x24, 0x42, + 0xa7, 0xa9, 0x2f, 0x3a, 0xb1, 0x16, 0xee, 0x48, 0x6e, 0xe7, 0x6e, 0x15, + 0x30, 0x17, 0xe7, 0x15, 0xfd, 0x98, 0x02, 0xd2, 0x62, 0x00, 0xf0, 0xc0, + 0xe8, 0x00, 0x1e, 0x86, 0x52, 0x34, 0x55, 0xa0, 0x0d, 0x91, 0xcf, 0x26, + 0xec, 0x1d, 0x7a, 0x80, 0xc1, 0x37, 0x00, 0x93, 0xc5, 0x25, 0x17, 0x8f, + 0x45, 0x9d, 0x20, 0x55, 0x3c, 0x90, 0xd3, 0x96, 0x59, 0x69, 0x3f, 0xc6, + 0x4f, 0x1d, 0x52, 0x48, 0x45, 0x63, 0x92, 0x9e, 0x1d, 0xae, 0xf1, 0x91, + 0x19, 0x52, 0x32, 0x3c, 0xa9, 0x0d, 0xb4, 0xe1, 0x97, 0x71, 0x2a, 0x84, + 0xaa, 0xa2, 0x54, 0x5a, 0x43, 0x67, 0xc3, 0x1a, 0xdc, 0x60, 0xb8, 0x0c, + 0xa7, 0x78, 0xb2, 0x62, 0x76, 0x1b, 0x51, 0xb5, 0x00, 0x6c, 0x1b, 0xcc, + 0x94, 0x00, 0xf0, 0x36, 0x1c, 0x5c, 0x62, 0x93, 0xce, 0x47, 0xf6, 0xec, + 0xf2, 0x86, 0x24, 0x0c, 0x77, 0x1a, 0x4a, 0xc6, 0xf3, 0x25, 0x00, 0xb1, + 0x28, 0x3e, 0x62, 0xd0, 0x02, 0x82, 0xc0, 0x55, 0x1d, 0xbd, 0x25, 0x21, + 0x21, 0x85, 0xee, 0x77, 0xcb, 0xb5, 0xe1, 0xa8, 0xe0, 0x89, 0xfe, 0xe8, + 0x0a, 0xe4, 0x08, 0x01, 0x94, 0x02, 0x2f, 0xfb, 0x86, 0x13, 0xed, 0xc4, + 0xbf, 0xa8, 0x37, 0xd6, 0x4a, 0xd7, 0x20, 0x01, 0xfa, 0x47, 0x6b, 0xa4, + 0x01, 0xf8, 0x0c, 0x40, 0x6c, 0x05, 0x38, 0x05, 0x28, 0x2c, 0x6f, 0xc8, + 0x6c, 0x47, 0xb7, 0x80, 0x3d, 0x0c, 0xc5, 0x90, 0xc4, 0xed, 0xc9, 0xd2, + 0x00, 0xec, 0xae, 0x03, 0xb0, 0xd0, 0xc0, 0xcc, 0x27, 0x87, 0xd0, 0x01, + 0xb8, 0x60, 0xc0, 0x2b, 0x91, 0x80, 0xf2, 0x11, 0x82, 0xb5, 0x3b, 0x35, + 0x49, 0x2f, 0x96, 0x2a, 0x00, 0x00, 0x01, 0x0d, 0x13, 0xf8, 0x7d, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, + 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x26, 0xd1, 0x72, 0x94, 0xa4, + 0x34, 0x59, 0x19, 0x11, 0x9e, 0x5a, 0x4d, 0xb4, 0x5b, 0x0c, 0xf4, 0x19, + 0x2d, 0x20, 0x66, 0x8b, 0x76, 0xf4, 0x92, 0x3f, 0x3c, 0xf9, 0x51, 0x6d, + 0x11, 0x92, 0x12, 0xa2, 0x33, 0xcf, 0x95, 0x0f, 0x6c, 0xba, 0x78, 0x52, + 0x7d, 0x1e, 0x5a, 0xda, 0x87, 0xc1, 0x9c, 0xe9, 0x8b, 0x2c, 0x62, 0x99, + 0x76, 0x89, 0x43, 0x4b, 0x59, 0x4a, 0x46, 0x28, 0xff, 0x42, 0x83, 0x0d, + 0xf4, 0x41, 0x4c, 0xbe, 0x7c, 0xaf, 0x56, 0x43, 0xf7, 0xe1, 0xd2, 0xf7, + 0x3a, 0x1e, 0x3d, 0x12, 0xd1, 0xa8, 0xe1, 0x99, 0x33, 0x7b, 0x71, 0x91, + 0xe8, 0xab, 0x68, 0xda, 0x16, 0x03, 0x0d, 0xe1, 0xda, 0xdd, 0x12, 0x23, + 0xc7, 0xea, 0x54, 0x18, 0x84, 0x93, 0x3c, 0x7b, 0x01, 0xa1, 0xa4, 0xac, + 0xab, 0x52, 0x5f, 0xfb, 0x37, 0x5c, 0xdc, 0x31, 0xee, 0x42, 0x11, 0x37, + 0x7b, 0x50, 0x1d, 0x86, 0x24, 0xb6, 0x6f, 0xda, 0xef, 0xe9, 0x63, 0x1c, + 0x57, 0x5e, 0x8f, 0x18, 0x58, 0xfc, 0x24, 0xc0, 0xf3, 0x75, 0x40, 0x0d, + 0xa6, 0xe4, 0xcd, 0xac, 0xf1, 0x35, 0x16, 0xfc, 0x0a, 0x16, 0x26, 0xec, + 0x0c, 0x09, 0xc0, 0x60, 0xb0, 0xee, 0x3a, 0x3c, 0x31, 0x25, 0x24, 0x67, + 0x0e, 0xe3, 0xe5, 0xc3, 0x11, 0xd5, 0xb8, 0x55, 0x4e, 0xd8, 0x9a, 0x81, + 0x78, 0xe9, 0x01, 0x9d, 0x20, 0x03, 0xc4, 0xfc, 0xb3, 0xf1, 0xdc, 0x50, + 0xeb, 0xbb, 0x22, 0x42, 0x83, 0x2a, 0xd0, 0x19, 0x26, 0x29, 0xaa, 0x25, + 0xd2, 0x50, 0x0c, 0x2c, 0x94, 0x53, 0x50, 0xb7, 0xe7, 0x49, 0xfe, 0xf1, + 0x81, 0xab, 0xb2, 0x25, 0x36, 0x6b, 0xb3, 0x6c, 0xcd, 0xd7, 0x10, 0x03, + 0xe2, 0x8f, 0xdd, 0x83, 0xea, 0xc6, 0x50, 0x63, 0xc8, 0x6d, 0x40, 0x60, + 0x7e, 0x7b, 0x7e, 0x05, 0x00, 0x00, 0x01, 0xe0, 0x07, 0xfa, 0x31, 0x00, + 0x03, 0x8e, 0x7d, 0x11, 0x00, 0x03, 0x77, 0x07, 0x37, 0x17, 0x37, 0x01, + 0x32, 0x38, 0xfa, 0xad, 0xbe, 0x84, 0x0d, 0x80, 0x0b, 0x0a, 0xe7, 0xa2, + 0xef, 0x00, 0x3c, 0xf8, 0xe4, 0xf8, 0x01, 0x8f, 0x8f, 0xa9, 0x6a, 0x0c, + 0xf1, 0x8b, 0x80, 0x0a, 0x91, 0x8e, 0xd7, 0x78, 0x18, 0x8f, 0x26, 0x3d, + 0x9c, 0x94, 0x2a, 0x80, 0x62, 0x43, 0x63, 0x81, 0x4d, 0x77, 0x81, 0x8f, + 0x4c, 0x42, 0x73, 0xec, 0xe4, 0xac, 0x2a, 0x3c, 0xaf, 0x03, 0x66, 0x00, + 0x7d, 0xb5, 0xda, 0x03, 0x64, 0x0e, 0xa6, 0x0c, 0x46, 0x32, 0x5e, 0xfc, + 0xed, 0x37, 0x21, 0x06, 0x86, 0x9f, 0xe1, 0xc5, 0xcf, 0xa3, 0x63, 0x90, + 0xfe, 0xe1, 0x64, 0xd0, 0xc2, 0x84, 0xd6, 0x96, 0x03, 0x1f, 0xc9, 0x1a, + 0xab, 0x00, 0x81, 0x06, 0xcb, 0x88, 0x48, 0xc6, 0x49, 0xf4, 0x70, 0xc2, + 0x69, 0x63, 0x8a, 0x11, 0x7a, 0x36, 0x4a, 0x4f, 0x88, 0x0c, 0x71, 0x28, + 0x84, 0x1a, 0x90, 0x1e, 0x36, 0x0f, 0xb2, 0x92, 0xab, 0x40, 0x4e, 0x4c, + 0xe5, 0xa3, 0x20, 0xc7, 0x7f, 0x03, 0x5e, 0x78, 0x07, 0x5f, 0x1e, 0xbb, + 0xea, 0x8c, 0xe2, 0xe8, 0x80, 0xc1, 0xbd, 0x92, 0x9e, 0x56, 0xe0, 0x7d, + 0x9d, 0xac, 0x20, 0x06, 0x94, 0x00, 0x34, 0x15, 0x22, 0x5b, 0x40, 0x0d, + 0xbd, 0xda, 0x03, 0xa0, 0x28, 0x42, 0x21, 0x00, 0x4c, 0xe1, 0xa5, 0xa4, + 0xf2, 0xf9, 0x82, 0x1c, 0xdb, 0x40, 0x06, 0x20, 0x51, 0x21, 0xa0, 0x55, + 0x2c, 0x62, 0x8e, 0x15, 0x72, 0xc0, 0xa0, 0x0c, 0x06, 0x77, 0xac, 0x0d, + 0x00, 0xd0, 0x96, 0x43, 0x4a, 0x7b, 0x9f, 0x31, 0xb4, 0x92, 0xa0, 0x00, + 0x00, 0x01, 0x0e, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x27, 0x17, 0x29, 0x4a, 0x4a, 0x2c, 0xfd, + 0x1e, 0x86, 0x96, 0x62, 0xcb, 0x60, 0x84, 0x1f, 0x3f, 0x16, 0xc5, 0xa4, + 0x62, 0xb2, 0xfc, 0x50, 0x18, 0x31, 0x7d, 0x7f, 0xc8, 0x50, 0x66, 0x42, + 0xfa, 0xfd, 0x3e, 0xa8, 0x94, 0x34, 0xf9, 0x3b, 0x1d, 0x6d, 0xf4, 0x5a, + 0x5f, 0x4f, 0x9e, 0xb4, 0x86, 0x34, 0x3d, 0xb4, 0x1e, 0x34, 0xab, 0x71, + 0x92, 0x3e, 0xd6, 0x3f, 0x50, 0x6d, 0x34, 0x89, 0x3a, 0x76, 0x69, 0x06, + 0xa1, 0xd0, 0xd1, 0x71, 0xa8, 0x32, 0x0e, 0xf4, 0x96, 0x2b, 0x45, 0x91, + 0x94, 0x25, 0x42, 0x94, 0xb4, 0x76, 0xb6, 0x03, 0x1a, 0x80, 0x63, 0x63, + 0xa5, 0xa4, 0x4d, 0xae, 0x52, 0x94, 0x94, 0xae, 0x52, 0x94, 0xcb, 0x89, + 0xfb, 0x9b, 0xb4, 0xad, 0xa8, 0xcd, 0x09, 0x68, 0xb2, 0x32, 0x8d, 0xa1, + 0x4a, 0x62, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x26, 0xd1, 0x70, 0xf8, + 0xed, 0xb1, 0x90, 0xa4, 0xa2, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x36, 0x1d, 0x1e, 0x8d, 0xe1, 0x48, 0x8b, 0x62, 0x56, 0x81, 0x29, + 0x10, 0xa4, 0x45, 0xcd, 0x9a, 0x2c, 0xb7, 0x85, 0x22, 0x20, 0x00, 0x00, + 0x01, 0x0f, 0x13, 0xf8, 0x7d, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, + 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x27, 0xe2, 0xe5, 0x29, 0x32, 0x52, 0x66, 0x5f, + 0x8d, 0x16, 0x0b, 0x2f, 0xe0, 0x8c, 0x7d, 0x10, 0x51, 0x28, 0x4f, 0x3f, + 0xd1, 0x18, 0x66, 0x23, 0xc2, 0x4c, 0xfd, 0xf8, 0x54, 0xae, 0x52, 0x94, + 0x8f, 0x3b, 0x9f, 0x3c, 0xf2, 0x53, 0xe7, 0xab, 0xe8, 0x7b, 0x78, 0xb4, + 0xad, 0x1a, 0xba, 0x25, 0x65, 0xa8, 0xb8, 0x52, 0x63, 0x17, 0x17, 0x22, + 0xd0, 0xa4, 0x89, 0x51, 0x6d, 0x0c, 0x3a, 0x11, 0x6a, 0xbe, 0x68, 0xb1, + 0x48, 0xef, 0x09, 0x21, 0x2f, 0x16, 0xad, 0x4e, 0x54, 0x51, 0xe5, 0xa3, + 0x2e, 0x76, 0xdf, 0x34, 0x64, 0x8b, 0x43, 0x45, 0xb4, 0xa8, 0xa0, 0xc8, + 0x65, 0x46, 0x8b, 0x94, 0xa5, 0x25, 0x17, 0x29, 0x4a, 0x4a, 0x2e, 0x52, + 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, + 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, + 0x8b, 0x94, 0xa5, 0x22, 0x20, 0x00, 0x00, 0x01, 0x10, 0x13, 0xf8, 0x7d, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, + 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, + 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x3c, + 0x45, 0xb2, 0x79, 0x9a, 0x08, 0x40, 0xc8, 0x6c, 0xd4, 0x9b, 0x45, 0xca, + 0x52, 0x91, 0x17, 0x29, 0x4a, 0x4a, 0x2e, 0x52, 0x94, 0x9f, 0x8b, 0x29, + 0xd3, 0x49, 0x3f, 0x9f, 0x8d, 0x72, 0x94, 0xa3, 0xcf, 0xae, 0x2e, 0x34, + 0x06, 0x43, 0x78, 0x4b, 0x6d, 0x16, 0x46, 0x68, 0xfd, 0x2d, 0x23, 0xed, + 0xe2, 0xde, 0x90, 0xfa, 0x35, 0x0c, 0x95, 0xcc, 0xaa, 0x3d, 0x29, 0x3d, + 0xe2, 0xd3, 0x52, 0x6d, 0xda, 0x5d, 0xde, 0x8d, 0xe7, 0x72, 0x94, 0xa4, + 0xb6, 0x8b, 0x94, 0xa5, 0x21, 0xa2, 0xe5, 0x29, 0x49, 0x45, 0xca, 0x52, + 0x91, 0x17, 0x29, 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, + 0x45, 0xca, 0x52, 0x91, 0x17, 0x29, 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, + 0x72, 0x94, 0xa4, 0x44, 0x00, 0x00, 0x01, 0x11, 0x13, 0xf8, 0x7d, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, + 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, + 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, + 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x49, 0xc5, 0xca, + 0x52, 0x91, 0x17, 0x23, 0xf3, 0xc2, 0x90, 0xd1, 0x6e, 0xd4, 0x92, 0x7e, + 0x86, 0xab, 0xe8, 0xb9, 0x0d, 0xe3, 0x48, 0x78, 0xb5, 0x78, 0x4e, 0xf2, + 0xe4, 0xcb, 0x78, 0xb1, 0x4a, 0x52, 0x5a, 0x2c, 0x8c, 0x8b, 0x4b, 0x48, + 0x19, 0x16, 0xf4, 0x76, 0x97, 0xa3, 0x7a, 0x0c, 0x9e, 0x43, 0x45, 0x8a, + 0x52, 0x92, 0xd1, 0x72, 0x94, 0xa4, 0xa2, 0xe5, 0x29, 0x48, 0x8b, 0x94, + 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, + 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, + 0x22, 0xe5, 0x29, 0x48, 0x88, 0x00, 0x00, 0x01, 0x12, 0x13, 0xf8, 0x7d, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, + 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, + 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, + 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xdb, + 0xa2, 0x3f, 0x49, 0x4a, 0x9a, 0x2d, 0xe9, 0x29, 0x2a, 0x69, 0x8c, 0x8b, + 0x0f, 0x0d, 0xe6, 0xa4, 0x9d, 0xa2, 0xd2, 0x93, 0x6f, 0x2b, 0xbc, 0xb7, + 0x8b, 0x94, 0xa5, 0x25, 0x17, 0x29, 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, + 0x72, 0x94, 0xa4, 0x45, 0xca, 0x52, 0x91, 0x17, 0x29, 0x4a, 0x44, 0x5c, + 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, 0x45, 0xca, 0x52, 0x91, 0x17, 0x29, + 0x4a, 0x44, 0x5c, 0xa5, 0x29, 0x11, 0x72, 0x94, 0xa4, 0x44, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x57, 0xff, 0xfb, 0x80, 0x00, 0x00, 0x01, 0xb5, 0x82, + 0x2f, 0xf3, 0x41, 0x80, 0x00, 0x00, 0x01, 0x01, 0x12, 0x70, 0x40, 0x9d, + 0xca, 0x86, 0x70, 0x00, 0x00, 0x01, 0x02, 0x12, 0x70, 0x42, 0xad, 0x34, + 0x7f, 0x0f, 0xd8, 0xda, 0x52, 0x91, 0x10, 0xce, 0x00, 0x00, 0x01, 0x03, + 0x12, 0x70, 0xa6, 0xd5, 0x47, 0xf1, 0x0d, 0xde, 0x14, 0xa5, 0x4f, 0x10, + 0x53, 0x25, 0xff, 0x35, 0x42, 0x8c, 0xa3, 0xa4, 0x3b, 0x39, 0xc2, 0xaa, + 0xd1, 0x3a, 0xe5, 0x89, 0xc2, 0xd9, 0x56, 0x27, 0x87, 0x48, 0x7c, 0x80, + 0x9c, 0x00, 0x2e, 0xe2, 0xaa, 0x15, 0x65, 0x9b, 0x13, 0x1c, 0x70, 0x50, + 0x1f, 0xd8, 0x7e, 0x1f, 0x23, 0x70, 0x16, 0xe9, 0x71, 0x1c, 0x00, 0x00, + 0x01, 0x04, 0x12, 0x71, 0x0f, 0xe1, 0xf4, 0xa5, 0x39, 0xd1, 0xe2, 0xb3, + 0x55, 0x46, 0x3f, 0x87, 0xd2, 0x94, 0x88, 0xa3, 0x94, 0xa5, 0x2a, 0xf9, + 0xa2, 0x0e, 0xea, 0xc7, 0x56, 0x55, 0xd7, 0x6f, 0x6a, 0xc6, 0x29, 0x55, + 0xfa, 0xac, 0x7c, 0x03, 0x07, 0xe3, 0x66, 0xd5, 0x6c, 0xa6, 0x00, 0x65, + 0xcb, 0xe3, 0xe0, 0x13, 0x62, 0x6a, 0x86, 0x17, 0xf6, 0x70, 0x3e, 0x60, + 0xac, 0x91, 0x40, 0x3d, 0xc7, 0x40, 0x18, 0x78, 0x01, 0xd7, 0xb9, 0x16, + 0xee, 0xa0, 0xc6, 0x24, 0x16, 0x77, 0xc6, 0x73, 0x00, 0xe0, 0x83, 0xcf, + 0x8a, 0x51, 0x83, 0xdc, 0x2c, 0x06, 0xb0, 0x06, 0x84, 0x22, 0xc0, 0x48, + 0x67, 0xe1, 0x02, 0x80, 0x05, 0x02, 0x38, 0x1e, 0x16, 0x26, 0x40, 0x1f, + 0xc3, 0x96, 0x07, 0x74, 0x8b, 0xf2, 0x15, 0x19, 0xc0, 0x00, 0x00, 0x01, + 0x05, 0x12, 0x71, 0x0f, 0xe1, 0xf4, 0xa5, 0x21, 0xe2, 0x91, 0xc4, 0xd5, + 0x13, 0xd2, 0x41, 0xb5, 0x74, 0xa2, 0x0c, 0x97, 0xa7, 0xd4, 0x91, 0x95, + 0x20, 0x70, 0x18, 0x24, 0xfe, 0x7f, 0x27, 0x50, 0x69, 0xd9, 0x87, 0x85, + 0xc5, 0x04, 0x0f, 0x73, 0x00, 0x5b, 0x19, 0x22, 0xf3, 0x00, 0x40, 0x06, + 0x12, 0x38, 0x8b, 0x00, 0x5c, 0x9c, 0xca, 0xea, 0x89, 0x9c, 0x35, 0x05, + 0x73, 0xd5, 0xd8, 0xfc, 0x4e, 0x12, 0x4e, 0x80, 0x34, 0x01, 0x3f, 0xe3, + 0x76, 0x28, 0xd7, 0x60, 0x37, 0x72, 0x2a, 0x60, 0x05, 0xc0, 0x63, 0x98, + 0xa1, 0x7f, 0xb0, 0x54, 0x05, 0x0a, 0xfd, 0x59, 0x27, 0x91, 0xc3, 0xc9, + 0xc1, 0x50, 0x14, 0xc5, 0xa1, 0x8e, 0x01, 0x7a, 0xc0, 0x84, 0x03, 0xa1, + 0xa8, 0xdf, 0x2d, 0x63, 0x96, 0xac, 0x3d, 0x63, 0xbc, 0xa8, 0xab, 0x66, + 0x08, 0xb8, 0x07, 0x55, 0x22, 0x68, 0xdb, 0xa0, 0x00, 0x00, 0x01, 0x06, + 0x12, 0x71, 0xe5, 0x20, 0xbb, 0xb8, 0xb2, 0xde, 0xac, 0x26, 0x54, 0xf5, + 0x02, 0x96, 0x88, 0xbe, 0x8b, 0x78, 0x26, 0xaa, 0x4b, 0x7b, 0xb1, 0x91, + 0x75, 0x4e, 0x6a, 0x5c, 0x27, 0x67, 0x1d, 0x6a, 0x80, 0x35, 0xd0, 0x8a, + 0xba, 0x62, 0x37, 0x62, 0x35, 0xad, 0x49, 0xeb, 0x26, 0x61, 0x5e, 0x00, + 0xd0, 0xbd, 0xf7, 0x70, 0xab, 0xdc, 0xfd, 0x06, 0x16, 0x53, 0x81, 0xc9, + 0x1e, 0xa6, 0x00, 0x3c, 0xcf, 0xfa, 0xcc, 0x34, 0x8b, 0x00, 0x3e, 0x4b, + 0xee, 0x04, 0x0f, 0x80, 0x74, 0x81, 0x86, 0x9c, 0x2c, 0x78, 0xe0, 0xe8, + 0x99, 0xc9, 0x4c, 0x78, 0xe6, 0x22, 0x66, 0x93, 0x57, 0x63, 0x00, 0x1d, + 0x70, 0xcc, 0xd9, 0x2b, 0x1c, 0x11, 0xfa, 0x16, 0x6b, 0x88, 0x36, 0x00, + 0x79, 0xb6, 0x12, 0x26, 0x01, 0x80, 0x05, 0xa8, 0x0d, 0x4f, 0x64, 0x6c, + 0x80, 0xd3, 0x72, 0xbf, 0x4e, 0xc7, 0xf1, 0x26, 0x40, 0x3a, 0x03, 0x06, + 0xc9, 0x8a, 0xbc, 0xc0, 0xc0, 0xc5, 0x15, 0x80, 0x69, 0xbc, 0x07, 0x64, + 0x63, 0x80, 0x5b, 0x22, 0xcd, 0xe2, 0x68, 0x74, 0x67, 0x00, 0x00, 0x01, + 0x07, 0x12, 0x74, 0x3f, 0x87, 0xd2, 0x94, 0x9b, 0xc5, 0x1c, 0xa4, 0x7f, + 0x6a, 0x0d, 0xd0, 0xed, 0x17, 0x32, 0x7b, 0x18, 0x5c, 0xec, 0x2b, 0x4e, + 0xaa, 0x3f, 0x89, 0x52, 0x94, 0xb5, 0x79, 0x55, 0x28, 0x3a, 0xa4, 0xd1, + 0x20, 0x6f, 0xbb, 0x12, 0x97, 0x2e, 0xc1, 0x40, 0xb5, 0xd2, 0x31, 0x35, + 0x93, 0x3a, 0x6f, 0x5a, 0x5c, 0x9d, 0x9d, 0xd5, 0x6c, 0xba, 0x22, 0x92, + 0x56, 0x81, 0x68, 0x3e, 0xb9, 0xd5, 0xaa, 0xd1, 0x86, 0x50, 0x5b, 0xe2, + 0x9d, 0x1a, 0x38, 0xef, 0x57, 0x98, 0x03, 0x02, 0x89, 0x5c, 0x07, 0xa9, + 0x35, 0xf3, 0x6c, 0x1d, 0xe0, 0x1d, 0x27, 0xa5, 0x41, 0x08, 0xff, 0x70, + 0x8e, 0xe7, 0x63, 0x47, 0xc0, 0x53, 0x95, 0xe0, 0x0c, 0x9c, 0xbc, 0x6d, + 0xc1, 0x96, 0xf3, 0x00, 0x34, 0x74, 0x1e, 0x85, 0x16, 0x66, 0x67, 0x2b, + 0xf2, 0x77, 0xdd, 0x21, 0x51, 0x09, 0x03, 0x53, 0xb2, 0x39, 0xfc, 0x08, + 0xc0, 0x26, 0x29, 0x01, 0x20, 0x72, 0x18, 0x04, 0xc2, 0xa7, 0x8a, 0xd5, + 0x52, 0x19, 0xb3, 0x07, 0x93, 0xd7, 0x20, 0x80, 0xf2, 0x28, 0xd9, 0x11, + 0x9c, 0x00, 0x00, 0x01, 0x08, 0x12, 0x74, 0x41, 0x7f, 0x8e, 0x40, 0xca, + 0xd3, 0xdc, 0xda, 0x4b, 0xd5, 0x35, 0x85, 0x02, 0xc4, 0x5d, 0xe3, 0x6c, + 0x2c, 0x40, 0xda, 0xf4, 0xab, 0x90, 0x91, 0xd5, 0xea, 0x2d, 0x54, 0x55, + 0x88, 0xa2, 0xef, 0x4f, 0x2d, 0xac, 0x95, 0xed, 0x33, 0x5d, 0x91, 0x2a, + 0xb4, 0x7d, 0x7b, 0xc1, 0x10, 0xe6, 0x48, 0x68, 0xac, 0xb9, 0x17, 0x7a, + 0x85, 0x4a, 0xc8, 0x26, 0x61, 0xf2, 0x3b, 0x39, 0xec, 0xb3, 0x75, 0x9f, + 0x2f, 0x1d, 0xcf, 0xb4, 0x99, 0x79, 0x18, 0x03, 0xb5, 0xc8, 0x4e, 0x51, + 0xee, 0x71, 0xb0, 0x62, 0x0f, 0xf0, 0xb9, 0x0f, 0x68, 0xca, 0x85, 0xc0, + 0x2e, 0xa7, 0xd2, 0x1d, 0xea, 0xec, 0xac, 0x51, 0xfa, 0x99, 0x00, 0x4a, + 0x29, 0xb9, 0x94, 0xfc, 0xd8, 0xae, 0xc2, 0x2d, 0xa6, 0x1c, 0x71, 0xd8, + 0xda, 0x3c, 0x38, 0x07, 0xd1, 0x4b, 0xe6, 0xd6, 0x66, 0x01, 0xa3, 0x58, + 0x99, 0x02, 0xae, 0xaa, 0x47, 0x3e, 0x42, 0x28, 0x78, 0xf6, 0x91, 0x20, + 0xd8, 0xce, 0x00, 0x00, 0x01, 0x09, 0x12, 0x76, 0xec, 0xd4, 0x83, 0x43, + 0x2a, 0x6b, 0x63, 0x27, 0x6b, 0x69, 0x06, 0xba, 0x48, 0x1b, 0xb5, 0x22, + 0x28, 0xfe, 0x27, 0x1f, 0xa1, 0x93, 0x47, 0xba, 0x02, 0x0b, 0x36, 0x55, + 0x1e, 0x69, 0x76, 0xd7, 0x64, 0x9b, 0x6d, 0x14, 0x55, 0xc6, 0x59, 0xd5, + 0x37, 0xb3, 0x32, 0x6a, 0x92, 0x55, 0x2c, 0xdb, 0xa6, 0x77, 0xa2, 0xfe, + 0x46, 0xd2, 0x0d, 0xaa, 0xbd, 0x3c, 0xd1, 0x18, 0x9d, 0x23, 0xa4, 0x75, + 0xd7, 0xe6, 0xfe, 0xda, 0xd2, 0x62, 0xf6, 0x03, 0x9b, 0xc5, 0x72, 0xf8, + 0x71, 0x1c, 0x3e, 0x21, 0x3c, 0x05, 0x24, 0xb4, 0x4c, 0x77, 0x03, 0x94, + 0x7f, 0x29, 0x7a, 0x3d, 0x1a, 0x97, 0x3d, 0xec, 0x51, 0xc7, 0x6a, 0xb4, + 0x00, 0x9d, 0x3b, 0xac, 0xf6, 0x67, 0x14, 0x3b, 0xd6, 0xf3, 0xe9, 0x1d, + 0x70, 0x51, 0x0c, 0xb0, 0xce, 0x11, 0xfe, 0x1e, 0x2e, 0xda, 0x61, 0x08, + 0x40, 0x1c, 0x0b, 0x22, 0x48, 0x00, 0xf6, 0x02, 0x91, 0x0b, 0x7b, 0x80, + 0xa3, 0xad, 0x60, 0x1d, 0x59, 0x66, 0x14, 0xf1, 0xd0, 0x60, 0xd1, 0x0f, + 0x14, 0x17, 0x26, 0x29, 0xf5, 0x99, 0x0c, 0x29, 0xc3, 0x85, 0x48, 0xd8, + 0x78, 0xf8, 0x30, 0x6b, 0x01, 0xe6, 0x17, 0x20, 0x6b, 0xda, 0xe2, 0xb7, + 0x00, 0x00, 0x01, 0xe0, 0x07, 0xfa, 0x31, 0x00, 0x03, 0xa5, 0xf3, 0x11, + 0x00, 0x03, 0x8e, 0x7d, 0xc4, 0x0f, 0x68, 0xc6, 0x39, 0xf0, 0x62, 0xdc, + 0x76, 0x16, 0x68, 0x1d, 0xa7, 0x56, 0xe4, 0xf9, 0x02, 0xde, 0x68, 0x30, + 0x3c, 0x40, 0xbb, 0x79, 0x81, 0x83, 0x43, 0x80, 0x3f, 0xd3, 0x2c, 0xee, + 0xe4, 0x78, 0x85, 0x10, 0x97, 0xb9, 0x17, 0x5c, 0x42, 0x25, 0xf0, 0xe1, + 0xcd, 0x78, 0xd8, 0x60, 0xdf, 0x2f, 0x0f, 0xdb, 0x8e, 0xe6, 0x87, 0xc8, + 0x1a, 0x16, 0x15, 0x6b, 0xc8, 0xda, 0x5a, 0x00, 0x00, 0x01, 0x0a, 0x12, + 0x7a, 0x94, 0xeb, 0x05, 0xf4, 0xa4, 0x75, 0x83, 0x08, 0x4b, 0x8b, 0xf6, + 0x57, 0xae, 0x96, 0x7c, 0x30, 0xb8, 0xbb, 0x0a, 0x06, 0x8e, 0x2e, 0x4b, + 0xb5, 0xdc, 0xc9, 0x36, 0xa9, 0x45, 0xb1, 0x45, 0xaf, 0x54, 0xce, 0x75, + 0x82, 0x88, 0xb8, 0x5d, 0x48, 0x25, 0xd1, 0xfc, 0x57, 0xe8, 0x9d, 0x07, + 0x8b, 0xdd, 0x8a, 0x32, 0x9b, 0x15, 0x09, 0x55, 0x61, 0xee, 0x9e, 0xd0, + 0xa4, 0xee, 0xa8, 0x4d, 0xa9, 0x81, 0x0a, 0x4f, 0x30, 0xd9, 0x18, 0x5c, + 0x18, 0x84, 0x1b, 0xeb, 0x63, 0x69, 0xea, 0x53, 0x52, 0xe8, 0xfc, 0x05, + 0x93, 0x9d, 0x69, 0x31, 0xfa, 0x94, 0xb1, 0x67, 0x44, 0x27, 0x88, 0x4e, + 0x03, 0xf8, 0x98, 0x24, 0xf3, 0x12, 0x41, 0xb8, 0x84, 0x9e, 0x34, 0x49, + 0x94, 0x7f, 0x28, 0xa3, 0x43, 0x21, 0xc4, 0xd0, 0x62, 0x75, 0x85, 0xeb, + 0xb7, 0x1d, 0x47, 0x06, 0x6f, 0x1f, 0x48, 0x3c, 0xa7, 0x46, 0xf4, 0xda, + 0x0d, 0x18, 0x9f, 0xd4, 0x72, 0x8f, 0x08, 0xc4, 0xde, 0x8c, 0x3b, 0x1b, + 0x00, 0x32, 0x91, 0xf3, 0x51, 0xa2, 0x43, 0x7d, 0x1a, 0xbb, 0x9b, 0x17, + 0x65, 0xc5, 0xbd, 0x1a, 0x26, 0xf4, 0x75, 0xe0, 0x1d, 0x97, 0x91, 0x90, + 0xe0, 0x76, 0x6e, 0x5f, 0xeb, 0x9a, 0x90, 0xdb, 0x52, 0x06, 0x4b, 0x4e, + 0x6e, 0x9f, 0xf6, 0xa3, 0x07, 0xca, 0x8e, 0xf3, 0xe9, 0x4a, 0x3f, 0x47, + 0x84, 0x51, 0xd4, 0xd4, 0x90, 0x94, 0x74, 0x46, 0x2c, 0x46, 0x9b, 0xd9, + 0x12, 0xbd, 0xd0, 0xc0, 0xcc, 0x9f, 0x80, 0x68, 0x15, 0x44, 0xb1, 0x58, + 0x2a, 0x26, 0x44, 0x2b, 0x0e, 0x80, 0xa6, 0xe6, 0x6f, 0xf5, 0x4c, 0x29, + 0xce, 0x23, 0xee, 0xf2, 0x1d, 0x03, 0xe0, 0x28, 0x06, 0xe0, 0x13, 0x27, + 0xf3, 0x4e, 0x33, 0x1d, 0xff, 0x16, 0x1c, 0x7b, 0x77, 0x15, 0x25, 0x50, + 0x66, 0xe9, 0x14, 0x15, 0x00, 0x00, 0x00, 0x01, 0x0b, 0x12, 0x76, 0xcd, + 0x0b, 0x90, 0x36, 0x99, 0x66, 0xee, 0x86, 0x49, 0xb3, 0x52, 0x8b, 0x0a, + 0x88, 0x48, 0xdb, 0xa3, 0xf8, 0xb4, 0x5a, 0x14, 0xbd, 0x04, 0xa2, 0x8b, + 0x04, 0x81, 0x04, 0xd6, 0x61, 0x88, 0x2a, 0x6c, 0x8e, 0x75, 0x1f, 0xc5, + 0xa9, 0x48, 0xdd, 0xe3, 0x7e, 0x3e, 0x96, 0xb7, 0x20, 0xfb, 0xf6, 0xa6, + 0x93, 0x6c, 0x80, 0x48, 0x6c, 0x81, 0x92, 0x10, 0x88, 0xfb, 0x3a, 0xca, + 0x30, 0x97, 0x73, 0x5d, 0x20, 0xb1, 0x29, 0x37, 0x64, 0x2c, 0x08, 0xfb, + 0xb4, 0xab, 0x27, 0x09, 0x8a, 0xe1, 0x6e, 0x38, 0x8b, 0x14, 0x34, 0x05, + 0x91, 0x30, 0x9c, 0x22, 0x21, 0x7f, 0x8e, 0x30, 0x7e, 0x23, 0xd1, 0xfc, + 0x99, 0xe0, 0xd2, 0x74, 0x20, 0x86, 0xbc, 0x10, 0x59, 0x3b, 0xce, 0x2b, + 0xab, 0xd8, 0xde, 0xa7, 0x43, 0x0b, 0xc3, 0xc8, 0x36, 0x31, 0xcc, 0x21, + 0x7d, 0xc9, 0x38, 0x04, 0x7a, 0x29, 0x66, 0x1d, 0x15, 0x52, 0x5e, 0x0c, + 0x60, 0xeb, 0x0d, 0x70, 0x94, 0x0d, 0xdc, 0x0f, 0x34, 0x89, 0x54, 0x32, + 0xd8, 0x39, 0x48, 0x68, 0xa9, 0xeb, 0xa3, 0xf3, 0x62, 0xbe, 0xa3, 0xf9, + 0x47, 0x71, 0xd1, 0xfa, 0xaf, 0xa1, 0x8d, 0x79, 0xbe, 0xb9, 0xef, 0x63, + 0xe5, 0x51, 0xb4, 0x61, 0x18, 0x9f, 0xd4, 0x72, 0x94, 0x8b, 0xc4, 0xe8, + 0xc3, 0xfa, 0x52, 0x91, 0x14, 0x72, 0x94, 0xa4, 0x4b, 0x5b, 0x4c, 0x29, + 0x4c, 0x4e, 0x03, 0xb1, 0x4c, 0xa2, 0x7f, 0x80, 0xa3, 0x8b, 0x68, 0xd0, + 0x90, 0xbc, 0x2e, 0xce, 0x89, 0x99, 0x6a, 0x34, 0xc2, 0x28, 0x7d, 0x96, + 0xa2, 0x64, 0x51, 0xc8, 0x7a, 0xae, 0xb8, 0xa1, 0x8a, 0xa9, 0x84, 0x26, + 0xec, 0x28, 0x81, 0x00, 0x64, 0x5f, 0x30, 0x48, 0x59, 0xf2, 0x14, 0xc1, + 0xc4, 0x43, 0xa0, 0x0c, 0x03, 0x4d, 0x1e, 0xf7, 0x06, 0x34, 0x00, 0x00, + 0x01, 0x0c, 0x12, 0x74, 0xc9, 0x0d, 0x06, 0x0d, 0xa8, 0x34, 0xf2, 0x06, + 0x48, 0x19, 0x22, 0xc3, 0x44, 0x17, 0x29, 0x71, 0x4f, 0x1d, 0x47, 0xf1, + 0x28, 0xb4, 0x29, 0x68, 0x94, 0x3c, 0xaa, 0x40, 0xc9, 0x75, 0x4a, 0xed, + 0x98, 0x9c, 0xf5, 0x6b, 0x01, 0xaa, 0x5d, 0x1f, 0x25, 0xed, 0x24, 0x6a, + 0x6b, 0x53, 0x12, 0x5d, 0x31, 0xb7, 0x71, 0x1f, 0xd7, 0xec, 0x26, 0xd9, + 0xe6, 0xa8, 0x22, 0x13, 0xc7, 0x48, 0x46, 0x36, 0x46, 0xc3, 0xe8, 0xd7, + 0xb5, 0x8d, 0xde, 0x6b, 0xa8, 0xff, 0x72, 0x2d, 0x18, 0xc2, 0x6c, 0x5c, + 0x5c, 0xe9, 0x31, 0x7f, 0x8a, 0x93, 0x0e, 0x7b, 0xa1, 0x87, 0x1b, 0x82, + 0x9f, 0x81, 0xa8, 0xaf, 0xdc, 0x06, 0x50, 0x67, 0x3c, 0xf5, 0x87, 0xe8, + 0x31, 0xc0, 0x98, 0x59, 0x06, 0xe2, 0x62, 0x52, 0x02, 0xda, 0x3f, 0x92, + 0x9d, 0x0a, 0x25, 0x09, 0x0c, 0xe3, 0x12, 0x1d, 0xcc, 0xf4, 0x6b, 0x17, + 0xbd, 0x4f, 0xbb, 0xb7, 0x57, 0x1d, 0x47, 0x32, 0xa4, 0x51, 0x0f, 0x32, + 0x54, 0x93, 0x39, 0x12, 0x79, 0x50, 0x89, 0xbc, 0x8a, 0xe6, 0x18, 0x6e, + 0x1f, 0x66, 0x61, 0x82, 0xb2, 0xe5, 0x45, 0x6d, 0x65, 0x43, 0x29, 0x0f, + 0xa4, 0x7e, 0x07, 0x3c, 0x85, 0x8a, 0xf8, 0x9f, 0x70, 0x60, 0x8f, 0x88, + 0xf6, 0xb3, 0x03, 0x06, 0xc1, 0x8e, 0x2b, 0x85, 0x48, 0x50, 0xe6, 0x90, + 0xe8, 0x9a, 0x26, 0x30, 0xf4, 0xe0, 0xe5, 0x5e, 0x61, 0x09, 0x63, 0xa2, + 0x63, 0x71, 0xd3, 0xfc, 0x64, 0x87, 0xf7, 0x13, 0x19, 0x03, 0xec, 0x28, + 0x1c, 0x04, 0x43, 0x53, 0x5c, 0x5c, 0x18, 0xd6, 0x0e, 0x30, 0x14, 0x30, + 0x0c, 0x41, 0x9d, 0x15, 0x70, 0x63, 0x51, 0xfc, 0xa3, 0x15, 0x02, 0x56, + 0xa7, 0x1b, 0x11, 0x85, 0xd8, 0x5e, 0xbb, 0x0a, 0xb8, 0x21, 0x99, 0x32, + 0x28, 0x22, 0x0c, 0x25, 0x06, 0xf3, 0x2f, 0x01, 0x40, 0xd8, 0x2e, 0x40, + 0xc4, 0xa4, 0xe2, 0xb8, 0x55, 0x1f, 0xca, 0x1a, 0x50, 0xc4, 0x81, 0x8e, + 0xe3, 0x49, 0x58, 0xde, 0x64, 0xbc, 0x0a, 0x24, 0xa3, 0xe6, 0x0d, 0x28, + 0x05, 0x05, 0x80, 0xab, 0xd8, 0x7e, 0x37, 0x5e, 0xa0, 0x62, 0x0b, 0x0c, + 0x2d, 0x09, 0x66, 0xfb, 0xbd, 0xa4, 0xc2, 0x60, 0x7e, 0x88, 0x4e, 0x2c, + 0x8f, 0x00, 0x82, 0x01, 0x03, 0xc9, 0x61, 0x7e, 0x0c, 0x7a, 0x98, 0x05, + 0x13, 0xdb, 0x3b, 0xee, 0x62, 0x8f, 0x16, 0x1d, 0x00, 0x5c, 0x5e, 0x7e, + 0xe2, 0x08, 0xda, 0x00, 0xd3, 0xad, 0x42, 0xc9, 0xe3, 0xa0, 0x0d, 0x0b, + 0x24, 0xa8, 0x05, 0xb7, 0x88, 0xf1, 0x50, 0x00, 0x00, 0x01, 0x0d, 0x12, + 0x71, 0xc2, 0x03, 0x27, 0xb0, 0x90, 0xc9, 0xe9, 0x96, 0x50, 0x92, 0x22, + 0xea, 0xd4, 0x8b, 0x1d, 0x05, 0x68, 0xa4, 0xf6, 0x17, 0xe4, 0x1c, 0xbb, + 0x32, 0x18, 0x18, 0x94, 0x8e, 0x8a, 0x46, 0x63, 0xcf, 0x8a, 0xd9, 0x8f, + 0x5f, 0xa8, 0x99, 0x07, 0x59, 0x98, 0x50, 0x3e, 0xa8, 0x5d, 0x86, 0x45, + 0x39, 0x71, 0xd6, 0x3b, 0xa4, 0xcb, 0x2a, 0x01, 0x47, 0x44, 0xc6, 0x15, + 0x53, 0x78, 0xa4, 0xe7, 0x0e, 0xb3, 0xcc, 0x26, 0x38, 0xec, 0x1d, 0xfb, + 0xe0, 0xa2, 0x04, 0x4c, 0x0b, 0x01, 0x73, 0xc8, 0x69, 0x1d, 0x9a, 0xde, + 0x28, 0x67, 0x0e, 0x37, 0x5a, 0x31, 0x85, 0x63, 0x96, 0x70, 0x00, 0xd1, + 0xcd, 0x83, 0x18, 0xc8, 0xa1, 0xb8, 0xc4, 0x24, 0x02, 0x2a, 0x23, 0xdc, + 0x50, 0xc2, 0x71, 0xc4, 0x0b, 0x24, 0xc4, 0x2e, 0x55, 0xdd, 0xcd, 0xad, + 0x14, 0xa4, 0xd2, 0xac, 0xc8, 0xa4, 0x0a, 0x65, 0x4a, 0x63, 0x94, 0x22, + 0x9a, 0x45, 0x05, 0x0a, 0xb1, 0x66, 0x41, 0xf2, 0x15, 0xe9, 0x75, 0x61, + 0xf2, 0x03, 0xac, 0x1e, 0xe3, 0x51, 0xc6, 0xce, 0xd4, 0x2a, 0xc2, 0x90, + 0x15, 0x72, 0xe4, 0x33, 0xd9, 0x98, 0x20, 0xdb, 0x96, 0x3b, 0xea, 0xb2, + 0x28, 0x55, 0x5d, 0xe4, 0x12, 0x87, 0xf9, 0x00, 0x22, 0xb5, 0x98, 0x53, + 0x8b, 0x0a, 0x8a, 0x1b, 0xc2, 0xa9, 0xb6, 0x8e, 0x88, 0xf0, 0x60, 0x48, + 0xa2, 0x2d, 0xb3, 0x01, 0x49, 0x9b, 0x78, 0xa0, 0x3c, 0x9e, 0x03, 0xce, + 0x4f, 0x53, 0x4a, 0x20, 0xcb, 0x90, 0x31, 0x8d, 0xb7, 0x98, 0x02, 0x01, + 0x80, 0x3f, 0x80, 0x61, 0x8a, 0x40, 0x09, 0x7a, 0x4a, 0x41, 0xa9, 0x2b, + 0x12, 0xfe, 0x0e, 0x82, 0x34, 0x11, 0x2e, 0x08, 0xb4, 0xa8, 0x33, 0x24, + 0x30, 0x07, 0x00, 0x26, 0x42, 0x58, 0x0f, 0x93, 0x4b, 0x57, 0xe3, 0xd9, + 0xc0, 0xf8, 0x0f, 0x60, 0x28, 0x4a, 0x5f, 0x14, 0x76, 0x69, 0x4d, 0x43, + 0x10, 0xeb, 0xcb, 0x7a, 0x68, 0x00, 0x00, 0x01, 0x0e, 0x12, 0x70, 0xea, + 0x66, 0x95, 0x90, 0x57, 0x86, 0xf3, 0x0d, 0x8c, 0xb5, 0x64, 0x23, 0xf0, + 0xb1, 0xd2, 0x32, 0x0d, 0xe7, 0xc8, 0xd8, 0x79, 0xfe, 0xc3, 0xa2, 0x85, + 0x93, 0xad, 0x86, 0x21, 0x48, 0xfa, 0x8f, 0xe2, 0xb0, 0xde, 0x3f, 0x35, + 0x2e, 0xb7, 0xe5, 0x53, 0x6e, 0x52, 0x54, 0xdf, 0x19, 0x47, 0xf1, 0x36, + 0xa3, 0x42, 0x96, 0xdb, 0x6e, 0x64, 0xad, 0x0e, 0x9f, 0xed, 0xec, 0xea, + 0x2f, 0xb5, 0x8c, 0x94, 0x0c, 0x1f, 0xff, 0x6a, 0x81, 0x07, 0x47, 0x58, + 0xcb, 0x99, 0x9e, 0x48, 0x21, 0xb6, 0x4e, 0x91, 0xb6, 0xad, 0x5d, 0x6a, + 0x80, 0x00, 0x00, 0x01, 0x0f, 0x12, 0x70, 0xb4, 0x9d, 0xf9, 0x88, 0x0b, + 0x1d, 0x2e, 0xda, 0x08, 0x57, 0xe0, 0x48, 0xf2, 0x35, 0x65, 0x4d, 0xb0, + 0x9e, 0x3e, 0x44, 0xc9, 0xb9, 0x19, 0x37, 0x43, 0xd8, 0x2b, 0x0b, 0x90, + 0x54, 0x86, 0x16, 0x4e, 0xb3, 0x91, 0x35, 0x1f, 0xc4, 0xa9, 0x4a, 0x5b, + 0x6f, 0x2a, 0xa3, 0xde, 0x26, 0xdf, 0xb7, 0x8b, 0xa3, 0xf8, 0x7d, 0x23, + 0x92, 0xf0, 0xa9, 0x5e, 0x2c, 0x16, 0x84, 0x65, 0xd5, 0x20, 0x6a, 0x12, + 0x0b, 0x38, 0x00, 0x00, 0x01, 0x10, 0x12, 0x70, 0xce, 0xc2, 0xb5, 0x45, + 0x84, 0x63, 0xe0, 0x1a, 0xd4, 0x94, 0xf4, 0x81, 0xf0, 0x3f, 0x4a, 0x57, + 0x48, 0x34, 0x5e, 0xfa, 0xaa, 0xa4, 0xfd, 0x48, 0x40, 0xb2, 0x63, 0x54, + 0xf5, 0x4f, 0x06, 0x38, 0x00, 0x00, 0x01, 0x11, 0x12, 0x70, 0x94, 0xe9, + 0xe4, 0x34, 0xc7, 0xf0, 0xfa, 0x52, 0x93, 0x3e, 0x29, 0x03, 0x70, 0x9d, + 0x22, 0x65, 0xb5, 0x2c, 0x7a, 0x46, 0x69, 0xe9, 0x14, 0xda, 0x93, 0x68, + 0x28, 0xe0, 0x00, 0x00, 0x01, 0x12, 0x12, 0x70, 0x5c, 0x82, 0xfc, 0x84, + 0x72, 0x1b, 0x97, 0x84, 0x9c, 0x00, 0x00, 0x01, 0x00, 0x00, 0x97, 0xff, + 0xfb, 0x80, 0x00, 0x00, 0x01, 0xb5, 0x82, 0x2f, 0xf3, 0x41, 0x80, 0x00, + 0x00, 0x01, 0x01, 0x12, 0x70, 0x42, 0xe9, 0x5f, 0xd1, 0xfc, 0x47, 0xa6, + 0x1b, 0xcd, 0x2e, 0xcd, 0x12, 0x86, 0x70, 0x00, 0x00, 0x01, 0x02, 0x12, + 0x70, 0xb5, 0x29, 0x68, 0x21, 0xd8, 0xfb, 0x1c, 0x18, 0x7a, 0x1a, 0x8f, + 0xa4, 0x28, 0x0e, 0x19, 0xc0, 0x00, 0x00, 0x01, 0x03, 0x12, 0x70, 0xa1, + 0xfc, 0x3e, 0x94, 0xa4, 0x45, 0x1c, 0xa5, 0x29, 0x3c, 0xa8, 0x82, 0xdd, + 0xac, 0x70, 0x8d, 0xbf, 0xb0, 0xc0, 0x96, 0xe1, 0xc1, 0x75, 0x30, 0x2a, + 0x7f, 0xa4, 0x38, 0x77, 0x8a, 0x4f, 0xe6, 0x1a, 0x01, 0xcc, 0xaa, 0xa8, + 0x32, 0xf0, 0x98, 0xa5, 0x9e, 0xb7, 0x1d, 0x58, 0xec, 0x4e, 0x20, 0x90, + 0x6f, 0xe8, 0x8e, 0x00, 0x00, 0x01, 0x04, 0x12, 0x71, 0x0f, 0xe1, 0xf4, + 0xa5, 0x27, 0xe2, 0xa2, 0xea, 0x8f, 0xd5, 0x5c, 0x9e, 0x35, 0x29, 0x83, + 0xbb, 0x1e, 0xbb, 0x26, 0x4f, 0x23, 0x52, 0x62, 0x68, 0x65, 0x30, 0xf9, + 0x09, 0x4a, 0x94, 0x78, 0x5c, 0x93, 0x20, 0x18, 0x24, 0x93, 0x19, 0x84, + 0x5a, 0xa9, 0x80, 0x51, 0x24, 0xdf, 0xf8, 0xd4, 0xae, 0x00, 0xd0, 0x06, + 0xfb, 0x20, 0xb4, 0x24, 0x90, 0x5a, 0xdc, 0x02, 0x4e, 0x63, 0xe3, 0xf9, + 0x4e, 0x7b, 0x2f, 0x1f, 0x00, 0x99, 0x3a, 0x00, 0x75, 0xdb, 0x9b, 0x27, + 0xc8, 0x3e, 0xa6, 0x13, 0x0c, 0x50, 0x07, 0xc0, 0x74, 0x73, 0x48, 0x66, + 0x1e, 0x20, 0x70, 0xb8, 0x04, 0x04, 0xc2, 0xd8, 0x21, 0x21, 0xce, 0x3c, + 0x73, 0x80, 0xfa, 0x40, 0x07, 0x32, 0x68, 0x55, 0x4b, 0x5b, 0xdc, 0x9c, + 0xa9, 0xc0, 0x00, 0x00, 0x01, 0x05, 0x12, 0x72, 0x49, 0xa3, 0xa4, 0x54, + 0x87, 0xa8, 0xb9, 0x44, 0xbf, 0x14, 0x36, 0x86, 0xd4, 0x94, 0xf5, 0x61, + 0xc4, 0x4f, 0x61, 0xaa, 0x3c, 0x6d, 0x50, 0x74, 0xcc, 0xe9, 0x4f, 0xe1, + 0xa5, 0xd7, 0x37, 0xa8, 0x20, 0xa9, 0xe4, 0x2f, 0xc8, 0xb1, 0x92, 0x95, + 0x48, 0xaf, 0xd0, 0xc1, 0xce, 0x38, 0xc8, 0x0a, 0x17, 0xb8, 0xd7, 0x41, + 0xc4, 0xe2, 0x7d, 0x13, 0x7f, 0xdb, 0x0e, 0x8a, 0x57, 0xce, 0xa5, 0x0b, + 0xbc, 0x75, 0x76, 0x7b, 0xcc, 0x01, 0x32, 0x4a, 0x4a, 0x8f, 0x68, 0x01, + 0xf7, 0xdf, 0x1f, 0x20, 0x96, 0x82, 0xbe, 0xdf, 0xa9, 0xb2, 0xc5, 0xf0, + 0x3c, 0x71, 0xe4, 0x78, 0x04, 0x00, 0x21, 0x3c, 0x0b, 0x64, 0x0a, 0x73, + 0x48, 0xd2, 0x5e, 0x45, 0x4c, 0x00, 0xc0, 0x0c, 0x24, 0x71, 0x1e, 0x26, + 0x15, 0xc2, 0x16, 0x7e, 0x16, 0x60, 0xf0, 0xa8, 0x98, 0x4b, 0x47, 0x1f, + 0xc3, 0x9c, 0x06, 0xaa, 0x78, 0x0a, 0x3a, 0x0f, 0xdd, 0x8c, 0xf8, 0x06, + 0x51, 0x6f, 0xfc, 0x29, 0x77, 0x60, 0x61, 0xf5, 0x88, 0x84, 0xe9, 0x77, + 0x19, 0xc0, 0x00, 0x00, 0x01, 0x06, 0x12, 0x72, 0x6e, 0x4e, 0xa8, 0xb2, + 0x1b, 0x48, 0x68, 0xa0, 0xfa, 0x3f, 0x89, 0x52, 0x91, 0xf6, 0xbf, 0xfd, + 0x2a, 0x8b, 0x95, 0x21, 0xe0, 0xc1, 0xb6, 0xc8, 0x03, 0x48, 0xd9, 0x73, + 0x37, 0xb6, 0xb0, 0x47, 0x0b, 0x8b, 0xf2, 0x6d, 0xad, 0x8c, 0x7a, 0xef, + 0xe1, 0xd6, 0x08, 0xb2, 0x7f, 0xa6, 0xb9, 0xd3, 0x43, 0x74, 0xa4, 0xf7, + 0xba, 0x2a, 0x79, 0x0d, 0x55, 0x55, 0xaa, 0x74, 0x8a, 0x90, 0x1e, 0xbf, + 0x20, 0x5d, 0xe6, 0x3e, 0x1a, 0x53, 0x0b, 0x5c, 0x01, 0xa2, 0x5f, 0x75, + 0x59, 0x91, 0x31, 0x25, 0x3c, 0x9d, 0x1a, 0xd5, 0x30, 0x02, 0xec, 0xeb, + 0x20, 0xab, 0x40, 0x17, 0x73, 0xf2, 0x83, 0xcc, 0x15, 0x00, 0xe9, 0x0d, + 0xbf, 0x43, 0x38, 0x1b, 0x00, 0xee, 0x2b, 0x92, 0xb2, 0xd2, 0x30, 0x18, + 0xc0, 0x04, 0xe9, 0x2e, 0x2a, 0x45, 0xd8, 0xc0, 0x07, 0x5c, 0x30, 0x0f, + 0xe1, 0xfd, 0xfa, 0x3f, 0x41, 0xc6, 0x76, 0x36, 0x00, 0x79, 0x90, 0xce, + 0x2d, 0x7d, 0xe0, 0x18, 0x20, 0x0a, 0xe0, 0xd2, 0xf8, 0x16, 0xc5, 0x20, + 0xbc, 0xc7, 0x37, 0x25, 0x9c, 0x37, 0x89, 0xd1, 0x08, 0x0c, 0x2e, 0x2f, + 0x55, 0xe8, 0x28, 0x30, 0x07, 0x08, 0xc3, 0xb1, 0x00, 0x00, 0x01, 0xe0, + 0x07, 0xfa, 0x0f, 0x05, 0xb5, 0x48, 0x42, 0xb3, 0x48, 0xcb, 0xd7, 0xe4, + 0xce, 0xaa, 0xdd, 0x00, 0x00, 0x00, 0x01, 0x07, 0x12, 0x73, 0x1f, 0xc3, + 0xe9, 0x4a, 0x4c, 0x6c, 0x57, 0x50, 0xba, 0x58, 0x4d, 0x4e, 0x99, 0xea, + 0x44, 0xa6, 0x9c, 0xaa, 0x3f, 0x8a, 0x51, 0xe1, 0xe9, 0xed, 0xfe, 0x69, + 0x51, 0xc1, 0xb2, 0xe2, 0xe7, 0xa4, 0x62, 0xd2, 0x89, 0x7c, 0xf6, 0x06, + 0x81, 0x80, 0xdd, 0x50, 0x7c, 0x87, 0xa4, 0x24, 0x92, 0x0a, 0xfb, 0x05, + 0x9f, 0xaa, 0xde, 0xe9, 0x57, 0xc5, 0x2a, 0x6d, 0x37, 0x6f, 0x74, 0x31, + 0x12, 0x34, 0x53, 0xbc, 0x82, 0x34, 0x83, 0xe2, 0xed, 0x9e, 0x8d, 0x99, + 0x97, 0x8c, 0x2c, 0xfc, 0x8d, 0x32, 0x83, 0xc8, 0xbe, 0xed, 0x14, 0x54, + 0x6a, 0x59, 0x1c, 0x61, 0xe2, 0xce, 0xae, 0x77, 0xc3, 0xef, 0x5d, 0x8c, + 0x02, 0x85, 0x12, 0xbe, 0x77, 0x1a, 0x93, 0x40, 0x5f, 0x13, 0x12, 0x37, + 0xf0, 0x82, 0xb1, 0x6d, 0xf0, 0xc3, 0xc3, 0xcc, 0x80, 0x75, 0xc3, 0x06, + 0x75, 0x40, 0x19, 0x7e, 0x1a, 0x61, 0xc2, 0x24, 0xc8, 0x27, 0x5b, 0xcc, + 0x01, 0x30, 0x46, 0xe1, 0x1f, 0xa0, 0xbe, 0x76, 0x03, 0xc9, 0xe4, 0x4f, + 0x14, 0x53, 0xf1, 0x9b, 0xe6, 0xff, 0xc0, 0x30, 0x28, 0xae, 0x9e, 0xac, + 0x07, 0x34, 0x73, 0x8d, 0x0a, 0x8b, 0x32, 0x45, 0x50, 0x1d, 0x35, 0x1b, + 0xc3, 0xaa, 0x4c, 0x98, 0xd5, 0x47, 0xf1, 0x0a, 0x3d, 0x23, 0x11, 0x00, + 0x00, 0x00, 0x01, 0x08, 0x12, 0x73, 0x2c, 0x35, 0x4b, 0x54, 0x9a, 0x27, + 0xf6, 0x1e, 0x07, 0x89, 0xd5, 0xe8, 0xfe, 0x29, 0x07, 0x8d, 0x2e, 0x97, + 0xfa, 0x4d, 0x74, 0x17, 0x79, 0x73, 0xf7, 0xa3, 0xf8, 0xa5, 0x36, 0xa5, + 0x1e, 0xe9, 0xc5, 0xc9, 0xac, 0x17, 0xb8, 0x62, 0x1a, 0x79, 0x56, 0x07, + 0x01, 0x84, 0x1b, 0xc7, 0x4c, 0xd6, 0x43, 0x9a, 0x42, 0x2b, 0x8d, 0xd9, + 0xd9, 0x57, 0x70, 0x3c, 0x78, 0x89, 0x04, 0x68, 0x45, 0x2e, 0x32, 0x95, + 0xa4, 0x4d, 0xd5, 0x14, 0x35, 0xc7, 0xb2, 0x80, 0x69, 0x6d, 0x5f, 0x8b, + 0xc1, 0xfe, 0xe8, 0x07, 0x00, 0x1e, 0xd2, 0x77, 0x6c, 0x70, 0x74, 0x84, + 0x49, 0x85, 0x1a, 0x2e, 0xd9, 0x80, 0x82, 0x27, 0x6f, 0x47, 0xc9, 0x96, + 0x21, 0x76, 0xb3, 0x0f, 0x8a, 0xe8, 0x1e, 0xf1, 0x95, 0x26, 0x27, 0x91, + 0x2a, 0xa2, 0xb6, 0x1d, 0xa9, 0xc7, 0x08, 0xc3, 0xab, 0xf0, 0xed, 0x4c, + 0x61, 0x3e, 0x46, 0x0b, 0x37, 0xb9, 0x1a, 0xe8, 0xe1, 0x74, 0x6b, 0xca, + 0x5a, 0xeb, 0x94, 0xc7, 0xf1, 0x07, 0xa3, 0xc3, 0xc6, 0x22, 0x8e, 0x3e, + 0x8c, 0x22, 0xd1, 0x10, 0x00, 0x00, 0x01, 0x09, 0x12, 0x76, 0x93, 0x47, + 0xaa, 0x5b, 0xad, 0x35, 0xb0, 0xeb, 0x4d, 0xa0, 0x62, 0x67, 0x7b, 0x72, + 0x24, 0x70, 0x1b, 0xb6, 0x54, 0x9d, 0xed, 0x50, 0x49, 0x10, 0x64, 0x57, + 0x28, 0x75, 0xd8, 0x50, 0x3c, 0x4d, 0x77, 0x15, 0xae, 0x8f, 0xe2, 0xd4, + 0x7a, 0x35, 0x2e, 0xd1, 0xb4, 0x9d, 0x68, 0xc0, 0x2a, 0xe4, 0x0c, 0x93, + 0xa8, 0xfe, 0x29, 0x47, 0xa1, 0x94, 0xba, 0x65, 0xec, 0x0e, 0xcc, 0x9d, + 0x77, 0x71, 0x79, 0x72, 0x29, 0xc0, 0x65, 0x60, 0x70, 0x1a, 0x2f, 0x3d, + 0x7e, 0xda, 0xb2, 0x73, 0x5c, 0xca, 0x45, 0x11, 0xa4, 0x6c, 0xf7, 0x24, + 0xea, 0x90, 0xa9, 0xe6, 0x8f, 0xa3, 0xf3, 0x09, 0xe4, 0x01, 0xe4, 0x68, + 0xff, 0xdb, 0x46, 0x5a, 0x4c, 0x38, 0xd7, 0x20, 0x85, 0xd1, 0x2d, 0xce, + 0x08, 0x10, 0x49, 0x0f, 0x83, 0x1f, 0x89, 0x83, 0x2f, 0x41, 0x89, 0x4f, + 0x3b, 0x1c, 0x21, 0x89, 0xf4, 0x7f, 0x2d, 0xfe, 0x8f, 0x4a, 0x75, 0x5c, + 0xb7, 0xbb, 0xe8, 0xe1, 0x2d, 0x8e, 0xaa, 0x40, 0x06, 0xa9, 0xcb, 0xe7, + 0xb3, 0x38, 0xa1, 0xde, 0xbb, 0x9f, 0x48, 0xeb, 0x90, 0x61, 0x0c, 0x34, + 0x99, 0xc0, 0xb7, 0xf8, 0x7d, 0xb4, 0xc2, 0x8d, 0x77, 0xc8, 0x23, 0x07, + 0x0e, 0xa7, 0x1f, 0xa2, 0x16, 0x78, 0xa1, 0xa3, 0x08, 0x1e, 0x2f, 0xc4, + 0xc4, 0x76, 0x22, 0xda, 0xc0, 0xf3, 0xc5, 0x6f, 0x87, 0x11, 0x29, 0x40, + 0x03, 0x69, 0x32, 0x1c, 0x77, 0x23, 0xdb, 0xcc, 0x29, 0x67, 0x46, 0x66, + 0x35, 0x71, 0x4e, 0x38, 0x83, 0x4e, 0xac, 0x3f, 0x49, 0xf9, 0x51, 0x5b, + 0xed, 0xcf, 0x5b, 0x0e, 0xb5, 0x98, 0xe7, 0xe1, 0x11, 0x4b, 0xc7, 0x07, + 0x8e, 0xae, 0xb0, 0xe2, 0x70, 0xb9, 0x1f, 0xbe, 0x10, 0x1f, 0x24, 0x55, + 0x7c, 0xab, 0x79, 0x88, 0x1b, 0x80, 0x8b, 0xc7, 0x70, 0xe3, 0x1a, 0x21, + 0x1f, 0x10, 0xb0, 0xae, 0xd2, 0x46, 0x28, 0x74, 0x4c, 0xc9, 0x5a, 0xc9, + 0xed, 0x78, 0x9a, 0x06, 0x8f, 0x6e, 0x2c, 0x0d, 0x47, 0x72, 0x01, 0x00, + 0x07, 0xf2, 0x5b, 0xcd, 0xf7, 0x1e, 0x1f, 0x80, 0x85, 0x1f, 0xc3, 0xc6, + 0xcc, 0xf0, 0x78, 0xc4, 0x51, 0x88, 0xd1, 0xe8, 0xfa, 0x22, 0x00, 0x00, + 0x01, 0x0a, 0x12, 0x75, 0x50, 0xc2, 0x1f, 0x80, 0x5b, 0x39, 0x17, 0x42, + 0xec, 0x42, 0x9b, 0x5d, 0x1f, 0xc5, 0x29, 0x0f, 0x1b, 0xa1, 0x39, 0xa5, + 0xaa, 0x41, 0x36, 0xfa, 0xca, 0x43, 0x42, 0x1e, 0x4d, 0x1f, 0xc5, 0x9e, + 0x0f, 0x1a, 0x5d, 0xc8, 0x0d, 0xa2, 0xc1, 0x04, 0x30, 0xd0, 0xa5, 0x0a, + 0xb6, 0xa3, 0xf8, 0xb5, 0x29, 0x4b, 0xbb, 0x76, 0xa5, 0xac, 0x16, 0x05, + 0x4d, 0x7e, 0xf7, 0x53, 0x50, 0xab, 0xba, 0x8f, 0xc9, 0x49, 0x92, 0x19, + 0xaf, 0x59, 0xa6, 0x15, 0xfc, 0x8c, 0xb9, 0x08, 0x40, 0xf8, 0xc8, 0x98, + 0x30, 0x2a, 0x4d, 0xab, 0x27, 0x79, 0xa3, 0xf7, 0xec, 0x24, 0xdb, 0x97, + 0xb1, 0xfd, 0xad, 0x26, 0x24, 0x56, 0xcb, 0x35, 0x41, 0x47, 0xc4, 0xc3, + 0x60, 0xc3, 0xcd, 0xf1, 0x4e, 0x35, 0x5d, 0x85, 0x79, 0x31, 0x33, 0xaf, + 0x83, 0x0f, 0xff, 0xd1, 0xfc, 0xae, 0x8d, 0x2e, 0x2b, 0xf1, 0x38, 0xc8, + 0x92, 0x92, 0x8b, 0x9a, 0xf6, 0xbe, 0xe3, 0xa8, 0xe3, 0x3c, 0xd0, 0x3a, + 0x9d, 0x71, 0x55, 0x1b, 0xf8, 0xc9, 0xf4, 0x5a, 0x55, 0x74, 0x51, 0x98, + 0x0d, 0x8b, 0x53, 0xc4, 0x51, 0x81, 0xac, 0x6b, 0x43, 0x13, 0x4b, 0x1f, + 0xe7, 0xd0, 0x6d, 0xe0, 0xe8, 0x1b, 0xe8, 0xc3, 0xb9, 0xb1, 0x76, 0x5b, + 0xd0, 0x67, 0x15, 0x16, 0xf1, 0x14, 0x74, 0xa0, 0x04, 0xe1, 0xa3, 0x32, + 0x1c, 0xe2, 0x7c, 0xdc, 0xbf, 0xfb, 0xce, 0x74, 0x1e, 0x1b, 0x6a, 0x40, + 0xc9, 0x69, 0xcd, 0xd3, 0xfe, 0xd4, 0x70, 0xfa, 0xb4, 0x77, 0xad, 0x90, + 0xa5, 0x79, 0xff, 0x08, 0xa3, 0xab, 0xea, 0x18, 0xd5, 0x64, 0xa5, 0x68, + 0x8c, 0x58, 0x8d, 0x37, 0xb1, 0x25, 0x7c, 0xd6, 0x93, 0x09, 0x87, 0x75, + 0x78, 0xa1, 0xa9, 0x03, 0x83, 0xc2, 0xa0, 0xc6, 0x83, 0x24, 0xc4, 0xc5, + 0xe1, 0x15, 0x32, 0xc9, 0x58, 0xe2, 0x25, 0x1e, 0x38, 0x8d, 0x06, 0x0b, + 0xea, 0x1f, 0xe0, 0x1d, 0x74, 0xab, 0xf0, 0x19, 0x80, 0x0f, 0x2d, 0xa4, + 0x3c, 0x00, 0x00, 0x01, 0x0b, 0x12, 0x7a, 0x2b, 0x3e, 0x83, 0x1a, 0x58, + 0xbb, 0xa1, 0x24, 0x48, 0x1b, 0x4c, 0x94, 0x87, 0x56, 0x2d, 0x34, 0xcc, + 0xfc, 0x80, 0xb5, 0x5d, 0x12, 0xac, 0x34, 0x54, 0xd9, 0x57, 0x44, 0xad, + 0xec, 0xae, 0x4e, 0x7a, 0x5a, 0x2a, 0x39, 0x44, 0x6b, 0x7b, 0xa0, 0x84, + 0xf5, 0x20, 0x44, 0x97, 0xb3, 0x10, 0x9d, 0xe1, 0xd5, 0x30, 0xa4, 0xa4, + 0x74, 0x84, 0x0f, 0xa6, 0xc6, 0xd8, 0x8a, 0x65, 0xb9, 0x83, 0xae, 0xd9, + 0x77, 0xd5, 0x4f, 0x52, 0xe8, 0xf1, 0x12, 0xd2, 0x66, 0x73, 0x45, 0x7c, + 0x9e, 0xb7, 0x1a, 0xb5, 0x8f, 0x8a, 0xff, 0xa7, 0x91, 0xa2, 0x63, 0xad, + 0xe2, 0xf0, 0xf8, 0xa4, 0xf7, 0x22, 0x00, 0xca, 0x8f, 0xe5, 0x27, 0xc1, + 0xaa, 0xfa, 0x10, 0x05, 0x4e, 0x02, 0xc5, 0x93, 0xbc, 0xe6, 0x8c, 0x4a, + 0x93, 0xac, 0x1e, 0xf5, 0xf9, 0x4c, 0xb7, 0x7d, 0xcd, 0x22, 0x71, 0xd6, + 0x73, 0x18, 0x50, 0x0f, 0x49, 0xd0, 0x60, 0xd4, 0x87, 0x56, 0x51, 0x02, + 0x22, 0x49, 0x89, 0x8c, 0x2d, 0x64, 0x7b, 0x56, 0x02, 0x94, 0x37, 0x81, + 0x29, 0x17, 0x72, 0x1b, 0xdb, 0x05, 0x80, 0xd3, 0x5f, 0x95, 0xc0, 0x9b, + 0x5c, 0x81, 0x94, 0x7f, 0x2b, 0xee, 0x3a, 0x3e, 0x44, 0xa1, 0x8d, 0x79, + 0xbe, 0xb9, 0x6f, 0x6f, 0xa1, 0xb5, 0x1b, 0xd2, 0x5f, 0x34, 0x57, 0xf3, + 0x51, 0x9a, 0x52, 0x91, 0x3a, 0x38, 0xfe, 0x8f, 0x4a, 0x44, 0x51, 0xc7, + 0x83, 0xb4, 0x61, 0x12, 0xba, 0x18, 0x8d, 0xc6, 0xac, 0xdc, 0x60, 0xf1, + 0x04, 0x58, 0x30, 0x8b, 0x10, 0xb3, 0xe3, 0x8c, 0x8e, 0x4e, 0xdf, 0x2a, + 0x2e, 0x0c, 0x47, 0xc6, 0xda, 0x30, 0x16, 0x68, 0xa8, 0xe5, 0x2c, 0xe2, + 0x3d, 0xbc, 0x81, 0x95, 0x30, 0x31, 0x23, 0x87, 0xc0, 0x20, 0x2d, 0xb2, + 0x87, 0x28, 0x83, 0x5d, 0x4f, 0xc7, 0x40, 0x18, 0x24, 0xf3, 0x40, 0x6b, + 0x27, 0x77, 0x0e, 0x90, 0x74, 0x00, 0x00, 0x01, 0x0c, 0x12, 0x76, 0x61, + 0xdc, 0x56, 0x95, 0x2a, 0x43, 0x5f, 0xd0, 0xb9, 0x0f, 0x52, 0x1e, 0x8f, + 0xe2, 0x25, 0xf7, 0xf1, 0xa5, 0x2b, 0x54, 0xab, 0x6b, 0xbb, 0x02, 0xad, + 0xe9, 0xe4, 0x33, 0x48, 0x3a, 0xa2, 0xe8, 0x90, 0xf4, 0xf6, 0x79, 0x25, + 0xcb, 0x73, 0x2c, 0x45, 0x4b, 0xeb, 0x51, 0x93, 0xd8, 0xee, 0x9b, 0xd9, + 0x05, 0x11, 0x6a, 0x73, 0x25, 0xb1, 0xf7, 0x50, 0x24, 0xec, 0xa3, 0x64, + 0x09, 0xad, 0x8d, 0x36, 0x61, 0x72, 0x45, 0x6b, 0x10, 0x62, 0x29, 0x7a, + 0x7b, 0x30, 0x84, 0x1e, 0xea, 0x07, 0x3a, 0x79, 0x6c, 0x03, 0x2b, 0x90, + 0xec, 0x7f, 0x56, 0x36, 0xa6, 0x3a, 0x87, 0xaa, 0x0c, 0x71, 0xf0, 0x63, + 0xf3, 0x09, 0xe0, 0x76, 0x0c, 0x57, 0x53, 0x2c, 0x05, 0xd6, 0xd1, 0x5d, + 0xf9, 0xac, 0xb0, 0x34, 0xf4, 0x7f, 0x27, 0xa5, 0x0b, 0x29, 0x21, 0x9c, + 0x62, 0x43, 0xb9, 0x9c, 0x45, 0x06, 0x58, 0x6b, 0xd7, 0xfb, 0xef, 0xf7, + 0x57, 0xd4, 0x73, 0x2a, 0xad, 0xf0, 0x15, 0xcc, 0x95, 0x17, 0x8e, 0x49, + 0x12, 0x7d, 0xa5, 0x42, 0x20, 0xf9, 0x14, 0xa5, 0x1f, 0x8d, 0xc3, 0xed, + 0x9c, 0x0c, 0x8c, 0xf5, 0x6a, 0x8b, 0xad, 0x53, 0x28, 0xa0, 0xf8, 0x90, + 0x04, 0x24, 0x07, 0x5c, 0x8f, 0x69, 0x30, 0xa7, 0xda, 0x0c, 0x16, 0x7d, + 0x07, 0x53, 0xc9, 0x0e, 0xf2, 0x1a, 0xf3, 0x03, 0x1b, 0x8e, 0x83, 0x38, + 0xd9, 0x03, 0x45, 0x48, 0x58, 0x0f, 0xa2, 0xe2, 0x67, 0xc3, 0x9c, 0x89, + 0x61, 0x50, 0xe3, 0x11, 0xf5, 0x0c, 0x93, 0x3e, 0x97, 0x43, 0x2c, 0x24, + 0xe6, 0x14, 0x06, 0x29, 0xb0, 0xe9, 0x53, 0xaa, 0x48, 0xd8, 0xa6, 0x01, + 0xa5, 0xc1, 0x51, 0x81, 0x10, 0x16, 0xd3, 0xbc, 0x86, 0x4c, 0x95, 0xc8, + 0x50, 0xeb, 0xa9, 0x8a, 0x44, 0x74, 0x8c, 0x51, 0x35, 0x26, 0x45, 0xe0, + 0x1d, 0x13, 0x79, 0x96, 0x1f, 0x23, 0x20, 0xb2, 0xc9, 0x05, 0x7e, 0x1d, + 0x70, 0x40, 0x30, 0x98, 0xf1, 0x09, 0x46, 0xf1, 0x8c, 0x07, 0xc0, 0xd4, + 0x81, 0x90, 0x64, 0x95, 0x1d, 0x10, 0x8e, 0x0e, 0x6b, 0x44, 0x30, 0x31, + 0xc0, 0x7b, 0x13, 0x03, 0xf0, 0x07, 0x50, 0x0c, 0x20, 0x1d, 0x5d, 0x38, + 0x8a, 0x98, 0x05, 0x13, 0xdb, 0x1e, 0x79, 0x16, 0x00, 0xd1, 0x23, 0xb0, + 0xe3, 0xa0, 0x10, 0x75, 0xfd, 0xa0, 0x0d, 0x13, 0x98, 0x2b, 0x67, 0x0e, + 0x6b, 0x66, 0xaf, 0xdd, 0x7d, 0xa0, 0x00, 0x00, 0x01, 0x0d, 0x12, 0x72, + 0x20, 0x94, 0xd2, 0x3b, 0x60, 0xbc, 0x74, 0xae, 0xe3, 0x93, 0x4e, 0x6f, + 0xae, 0xc8, 0x10, 0x07, 0x9a, 0xed, 0xa5, 0x0b, 0xb0, 0xa8, 0x89, 0x55, + 0xab, 0x13, 0xda, 0xd1, 0x61, 0xe6, 0x0c, 0x97, 0x14, 0x9e, 0x30, 0x05, + 0x66, 0x48, 0x48, 0xfb, 0x1c, 0xa0, 0x44, 0x25, 0x2c, 0xac, 0x7d, 0x6d, + 0xb2, 0xcf, 0xad, 0x98, 0x8b, 0x20, 0x48, 0x54, 0x97, 0x32, 0xde, 0x18, + 0xfd, 0xea, 0x39, 0x76, 0x88, 0xbe, 0xc4, 0x75, 0xe7, 0xdb, 0xcc, 0xf8, + 0xf9, 0x00, 0x35, 0x97, 0x6d, 0x25, 0x4d, 0x5f, 0x3d, 0xba, 0x01, 0x4a, + 0x27, 0x93, 0xc0, 0x39, 0x83, 0x3a, 0xc1, 0x87, 0xff, 0xe9, 0xa4, 0xc5, + 0x30, 0x11, 0xd7, 0x63, 0x10, 0x2b, 0x81, 0xa8, 0xa6, 0x5b, 0x56, 0x11, + 0xe3, 0x43, 0x8e, 0x97, 0x14, 0xca, 0x16, 0x3c, 0x55, 0xab, 0x99, 0x2e, + 0x55, 0xc9, 0x93, 0xf8, 0x0f, 0xe5, 0x0f, 0xa8, 0x1e, 0xe7, 0x49, 0x0a, + 0x9e, 0x5d, 0x5b, 0x44, 0xa1, 0x5e, 0x43, 0x09, 0x22, 0x49, 0x0f, 0xa6, + 0x31, 0x8e, 0x27, 0x5a, 0xc0, 0x81, 0xeb, 0x82, 0x22, 0x7d, 0xd7, 0x0b, + 0xb3, 0xcc, 0x43, 0x55, 0x4a, 0x8b, 0x7a, 0x19, 0xac, 0x8c, 0x10, 0xaa, + 0x6b, 0x5d, 0x35, 0xac, 0xc4, 0x37, 0xad, 0x6a, 0x1f, 0x2a, 0xdc, 0x50, + 0x07, 0x10, 0x45, 0xb2, 0x01, 0xa6, 0x97, 0x4b, 0xf2, 0x69, 0x87, 0x2e, + 0xf3, 0x25, 0x1b, 0x14, 0xe3, 0xa0, 0x8d, 0x4d, 0x72, 0x19, 0x22, 0x35, + 0xb3, 0x18, 0x53, 0x0f, 0x8a, 0xea, 0xdc, 0x2a, 0xe7, 0x5d, 0xc8, 0x19, + 0x6f, 0x30, 0x06, 0x0c, 0xd1, 0x0b, 0x21, 0x09, 0x52, 0x4b, 0xe5, 0x00, + 0xf5, 0x18, 0x6f, 0x0a, 0x01, 0xf4, 0x81, 0x95, 0x91, 0x26, 0x45, 0x4c, + 0x02, 0x99, 0x42, 0x79, 0xa0, 0x35, 0x20, 0x40, 0x26, 0xe8, 0x7e, 0xa1, + 0x11, 0x5a, 0x29, 0x9f, 0xba, 0xe2, 0xf7, 0xa5, 0xc0, 0x00, 0x00, 0x01, + 0x0e, 0x12, 0x70, 0xf8, 0x1b, 0x91, 0xf7, 0xb9, 0x22, 0x34, 0x57, 0x4b, + 0x75, 0x2f, 0x91, 0xa3, 0x8f, 0xf7, 0xb3, 0xd4, 0xc4, 0x7e, 0xca, 0xc6, + 0x9a, 0x3a, 0xb6, 0x67, 0x1e, 0x6c, 0xc8, 0x18, 0x45, 0x8e, 0xa1, 0x8b, + 0x7e, 0x1c, 0x2a, 0x48, 0xab, 0x98, 0x97, 0x5d, 0x0f, 0x72, 0x80, 0xa9, + 0x11, 0x32, 0xe8, 0xfe, 0x28, 0x7d, 0x3a, 0xa3, 0x0d, 0xee, 0xa2, 0x8b, + 0xde, 0x9b, 0x0e, 0x1b, 0x27, 0xaa, 0x6b, 0x0e, 0x62, 0x2a, 0x89, 0xd5, + 0x4f, 0xa9, 0x43, 0x32, 0x11, 0xcd, 0x5a, 0x94, 0xbd, 0x6a, 0xad, 0x2a, + 0x45, 0xba, 0x2c, 0x8e, 0x95, 0xa0, 0x00, 0x00, 0x01, 0x0f, 0x12, 0x70, + 0xca, 0x6a, 0x93, 0x77, 0x0f, 0xf3, 0xb6, 0x3e, 0xa0, 0x4b, 0x8e, 0x3e, + 0xb2, 0x02, 0xe9, 0x86, 0x07, 0xcc, 0x06, 0x85, 0x01, 0xd9, 0x66, 0x6a, + 0xa6, 0xd4, 0x8d, 0xc6, 0x1c, 0x92, 0x4f, 0x95, 0x67, 0x1d, 0x3f, 0x40, + 0x8b, 0x86, 0x8a, 0xd2, 0x0e, 0xa0, 0xea, 0xcc, 0xa9, 0x0f, 0x68, 0xc5, + 0xda, 0xa8, 0xfe, 0x1f, 0x4a, 0x52, 0x7a, 0x2c, 0x22, 0x0d, 0x4f, 0x48, + 0x21, 0x04, 0xe9, 0x0b, 0x54, 0x18, 0xe0, 0x00, 0x00, 0x01, 0x10, 0x12, + 0x70, 0xce, 0xdf, 0x85, 0xf2, 0x75, 0xd8, 0xc4, 0x7f, 0xde, 0x2b, 0x36, + 0xc4, 0x71, 0x74, 0xcc, 0x24, 0xda, 0xfa, 0xae, 0xa4, 0x83, 0x1e, 0x6f, + 0x35, 0x36, 0xa4, 0x17, 0x64, 0x1e, 0x13, 0xc1, 0x20, 0x69, 0x24, 0xa7, + 0x4a, 0x55, 0x8a, 0x7c, 0xec, 0x35, 0x12, 0xa5, 0xda, 0x06, 0x90, 0xee, + 0xce, 0xe9, 0x4c, 0x14, 0x00, 0x00, 0x01, 0xe0, 0x07, 0x51, 0x31, 0x00, + 0x03, 0xbd, 0x69, 0x11, 0x00, 0x03, 0xa5, 0xf3, 0x70, 0x00, 0x00, 0x01, + 0x11, 0x12, 0x70, 0xa4, 0x5a, 0xf9, 0xe2, 0x64, 0x81, 0x97, 0x30, 0x35, + 0xa4, 0x37, 0xa3, 0xa4, 0x3b, 0x54, 0x93, 0x2e, 0x6f, 0x31, 0xfc, 0x3e, + 0x94, 0xa4, 0xe2, 0x8e, 0x52, 0x93, 0x75, 0x4f, 0xc5, 0x94, 0x6c, 0x5d, + 0x52, 0xab, 0x2d, 0x33, 0xd8, 0x86, 0x24, 0xd3, 0x55, 0x3c, 0x16, 0x70, + 0x00, 0x00, 0x01, 0x12, 0x12, 0x70, 0x5e, 0x0b, 0xe9, 0xbd, 0xce, 0x93, + 0x29, 0x05, 0x39, 0x9c, 0x24, 0xe0, 0x00, 0x00, 0x01, 0x00, 0x00, 0xd7, + 0xff, 0xfb, 0x80, 0x00, 0x00, 0x01, 0xb5, 0x83, 0x3f, 0xf3, 0x41, 0x80, + 0x00, 0x00, 0x01, 0x01, 0x1a, 0x70, 0x42, 0x57, 0x97, 0x28, 0x67, 0x00, + 0x00, 0x01, 0x02, 0x1a, 0x70, 0x44, 0x57, 0xb5, 0x42, 0x72, 0x78, 0x00, + 0x00, 0x01, 0x03, 0x1a, 0x70, 0x46, 0x69, 0x8f, 0xe2, 0x3f, 0xd2, 0x34, + 0x9c, 0xaa, 0xda, 0xaa, 0xa0, 0xe2, 0x64, 0x3e, 0x90, 0x0c, 0xa0, 0x03, + 0x75, 0x99, 0x40, 0x46, 0xb7, 0xae, 0xd5, 0x9d, 0x54, 0x7f, 0x0f, 0x8c, + 0x5e, 0x91, 0x14, 0x62, 0x94, 0x8c, 0x45, 0x1c, 0x84, 0x69, 0x11, 0x00, + 0x00, 0x00, 0x01, 0x04, 0x1a, 0x71, 0x36, 0x87, 0xb9, 0x59, 0x53, 0x71, + 0xa9, 0xe0, 0xe4, 0x8c, 0x7f, 0x12, 0xfd, 0x74, 0x3e, 0x94, 0xd3, 0x95, + 0xb3, 0x2b, 0xd5, 0xa9, 0x8a, 0xcc, 0x96, 0xa8, 0xbd, 0x06, 0x3a, 0xee, + 0xd4, 0x41, 0x83, 0x40, 0xaa, 0x5d, 0xff, 0xef, 0x10, 0x92, 0x1b, 0x89, + 0x45, 0xee, 0xa1, 0xab, 0x14, 0x84, 0x8f, 0xf8, 0x70, 0xf6, 0x3a, 0x21, + 0x25, 0xa0, 0x0c, 0x92, 0xd2, 0x64, 0x54, 0xc2, 0xb0, 0xf9, 0x1a, 0x01, + 0x81, 0x5e, 0xae, 0xae, 0x81, 0x54, 0x48, 0xba, 0x3f, 0x88, 0xae, 0x94, + 0x8c, 0x45, 0x18, 0x8d, 0x29, 0x11, 0x47, 0x29, 0x4a, 0x44, 0x51, 0xca, + 0x52, 0x91, 0x10, 0x00, 0x00, 0x01, 0x05, 0x1a, 0x73, 0x53, 0x52, 0x15, + 0x8a, 0x9a, 0xa7, 0xa9, 0xa9, 0x73, 0x25, 0x88, 0x25, 0x3c, 0x46, 0x44, + 0x7f, 0x12, 0xfd, 0xfc, 0x68, 0x7c, 0xad, 0x3a, 0x69, 0xb9, 0xaa, 0xa0, + 0x28, 0xce, 0x64, 0x89, 0x0f, 0x87, 0xd5, 0x54, 0x03, 0x01, 0x9c, 0x74, + 0x02, 0x06, 0x5c, 0x18, 0x37, 0x40, 0x30, 0xe9, 0x09, 0xaa, 0x98, 0x02, + 0x61, 0x9e, 0x0c, 0x43, 0x80, 0xbe, 0x0c, 0x1b, 0x80, 0x07, 0xd1, 0x31, + 0xd0, 0xfa, 0xea, 0xe8, 0x65, 0x53, 0xd1, 0xfc, 0x47, 0xc6, 0x0f, 0x18, + 0x8a, 0x39, 0x4a, 0x52, 0x22, 0x8e, 0x52, 0x94, 0x88, 0xa3, 0x94, 0xa5, + 0x22, 0x20, 0x00, 0x00, 0x01, 0x06, 0x1a, 0x72, 0x21, 0x19, 0x3a, 0xd3, + 0x75, 0xd6, 0x4e, 0x8a, 0xbc, 0x5d, 0x12, 0xe4, 0x0d, 0x8d, 0xd4, 0x6f, + 0x37, 0x27, 0x88, 0xb0, 0x8d, 0xac, 0x14, 0x8f, 0xaa, 0xad, 0x47, 0xcd, + 0xda, 0xd1, 0x05, 0x70, 0x1c, 0x40, 0x30, 0xf9, 0x97, 0x15, 0xd1, 0x2e, + 0xa6, 0x00, 0x9a, 0x01, 0x07, 0x89, 0x99, 0x8d, 0x91, 0xc6, 0x0f, 0x56, + 0xba, 0xbb, 0x0c, 0x00, 0xcb, 0x95, 0xba, 0xc9, 0xf9, 0x4b, 0x80, 0x34, + 0xda, 0x21, 0x62, 0x6e, 0x2f, 0x92, 0x19, 0x09, 0x23, 0xe3, 0x7c, 0x18, + 0x4a, 0x1d, 0x75, 0x58, 0x21, 0x04, 0x8a, 0x32, 0x8f, 0xe2, 0x54, 0x84, + 0x62, 0x28, 0xe5, 0x29, 0x48, 0x8a, 0x39, 0x4a, 0x52, 0x22, 0x8e, 0x52, + 0x94, 0x88, 0x80, 0x00, 0x00, 0x01, 0x07, 0x1a, 0x73, 0x86, 0x09, 0x4f, + 0x48, 0x61, 0xb2, 0xbd, 0x4d, 0x68, 0x79, 0x15, 0x48, 0xa3, 0xf8, 0xb4, + 0x1e, 0x0d, 0x16, 0xba, 0xfa, 0x3e, 0xa6, 0xa2, 0xf4, 0x88, 0xaa, 0x3f, + 0x88, 0xc6, 0x6d, 0xe5, 0xb5, 0x41, 0x63, 0x65, 0x47, 0x29, 0x4a, 0x53, + 0x3a, 0x39, 0x4a, 0x52, 0x22, 0x8e, 0x52, 0x94, 0x88, 0xac, 0x90, 0xb9, + 0x7e, 0xb9, 0x4f, 0x52, 0xfb, 0x43, 0x0f, 0x8f, 0xa8, 0xf4, 0x46, 0xab, + 0x44, 0x65, 0xd2, 0xc8, 0xed, 0x96, 0x46, 0x84, 0x4f, 0x76, 0x18, 0x4c, + 0x40, 0xc6, 0x5b, 0xf4, 0xc1, 0x89, 0x71, 0xdb, 0x8e, 0x5c, 0x4c, 0xe8, + 0x60, 0x39, 0x00, 0xe9, 0xf8, 0xfb, 0x91, 0x6d, 0x98, 0x05, 0x02, 0x00, + 0x48, 0xa4, 0x98, 0x3b, 0xf1, 0x43, 0xbf, 0x0a, 0x8a, 0xc1, 0x2c, 0x3e, + 0x21, 0x21, 0x0b, 0xb4, 0x01, 0x30, 0xab, 0x91, 0x5f, 0x1d, 0x55, 0x35, + 0x1f, 0xc4, 0xa9, 0x4a, 0x44, 0x51, 0xca, 0x52, 0x91, 0x14, 0x72, 0x94, + 0xa4, 0x45, 0x1c, 0xa5, 0x29, 0x11, 0x00, 0x00, 0x00, 0x01, 0x08, 0x1a, + 0x74, 0x91, 0x47, 0xaf, 0x60, 0xb7, 0x4f, 0xe7, 0x0a, 0x78, 0xf7, 0x86, + 0x52, 0x28, 0xea, 0x3f, 0x8a, 0xef, 0x2b, 0xcf, 0x4b, 0xaf, 0x27, 0xea, + 0x6c, 0x36, 0x21, 0x3d, 0x31, 0x1a, 0xde, 0x39, 0x4a, 0xd7, 0x47, 0xf1, + 0x2a, 0x46, 0x8f, 0x6c, 0x82, 0xe5, 0x66, 0x91, 0x56, 0xbb, 0x08, 0xcd, + 0x2a, 0xc8, 0x0e, 0xa7, 0xad, 0x54, 0xa9, 0x9b, 0x92, 0x24, 0x8a, 0xd0, + 0x9b, 0x7a, 0xd2, 0xa4, 0x97, 0x44, 0x76, 0xba, 0x02, 0xe9, 0xf3, 0x01, + 0xcf, 0x59, 0xaa, 0xaf, 0xa8, 0x45, 0x5a, 0x20, 0x45, 0x07, 0xc5, 0x35, + 0x35, 0xd5, 0x40, 0xc8, 0xda, 0xab, 0x1d, 0x74, 0x03, 0xfb, 0xb1, 0x15, + 0x55, 0x6b, 0xa3, 0xf8, 0x95, 0x29, 0x48, 0x8a, 0x39, 0x4a, 0x52, 0x22, + 0x8e, 0x52, 0x94, 0x88, 0xa3, 0x94, 0xa5, 0x22, 0x20, 0x00, 0x00, 0x01, + 0x09, 0x1a, 0x7b, 0x77, 0xb0, 0x84, 0x55, 0x55, 0x3a, 0x7a, 0x5d, 0x82, + 0xd3, 0x09, 0x4f, 0x2e, 0x8f, 0xe2, 0x54, 0xa5, 0x2d, 0x3c, 0xaa, 0x4e, + 0xaa, 0x54, 0x4c, 0x7f, 0x16, 0xa5, 0x29, 0x77, 0x75, 0x51, 0xa8, 0xe5, + 0x29, 0x49, 0xc5, 0x21, 0xc0, 0x41, 0x4b, 0x91, 0x1f, 0xc5, 0xa9, 0x4a, + 0x5d, 0xd4, 0xd8, 0x7c, 0x14, 0x53, 0xdc, 0x91, 0x7d, 0xa5, 0x45, 0xb5, + 0x9e, 0x90, 0x5e, 0xde, 0x54, 0x90, 0x9b, 0x06, 0x01, 0x18, 0x3e, 0x87, + 0xa7, 0xbb, 0x6a, 0x00, 0x97, 0xad, 0x51, 0xab, 0xb9, 0x3a, 0x87, 0xb4, + 0x4c, 0x5e, 0x1f, 0x20, 0x6f, 0x31, 0x5a, 0x29, 0xc5, 0xc1, 0x97, 0x15, + 0xfd, 0x1f, 0xcc, 0x3d, 0x37, 0xa4, 0x7e, 0xb9, 0x2f, 0xa1, 0xf4, 0x60, + 0x6f, 0xd5, 0x48, 0x01, 0x8a, 0x72, 0xf9, 0xe3, 0xc7, 0xe1, 0xde, 0xbc, + 0xda, 0x44, 0x90, 0x4d, 0x2c, 0x30, 0x91, 0xfe, 0xb6, 0x54, 0x80, 0x1f, + 0x18, 0x1c, 0x40, 0xa2, 0x74, 0x19, 0x15, 0xbf, 0x83, 0x1e, 0xf0, 0x3d, + 0xea, 0xbf, 0xb6, 0x90, 0xfa, 0xd0, 0x80, 0x32, 0x29, 0xc0, 0x78, 0xd2, + 0xde, 0xe4, 0x2a, 0xa0, 0x74, 0x54, 0x8b, 0xaf, 0x6c, 0xa9, 0x0f, 0x09, + 0xd0, 0x64, 0x53, 0xc5, 0x3f, 0x20, 0xde, 0xa2, 0xa0, 0xc9, 0x0f, 0x44, + 0x7a, 0x7a, 0x3f, 0x89, 0x52, 0x94, 0x88, 0xa3, 0x94, 0xa5, 0x22, 0x20, + 0x00, 0x00, 0x01, 0x0a, 0x1a, 0x74, 0x56, 0x88, 0xfe, 0x25, 0x47, 0xa5, + 0x2d, 0x25, 0x46, 0x3c, 0x69, 0x49, 0x45, 0x22, 0xf5, 0x34, 0xc7, 0xf1, + 0x6a, 0x52, 0x97, 0x7f, 0xd4, 0x51, 0xca, 0x52, 0x90, 0xb8, 0xa3, 0x94, + 0x6a, 0x35, 0x27, 0xc5, 0xe8, 0xa9, 0xa5, 0x5d, 0x1f, 0xc5, 0xa9, 0x4a, + 0x5d, 0xf9, 0x34, 0xd4, 0x35, 0x15, 0x15, 0x75, 0x21, 0x15, 0x2a, 0xbf, + 0x6a, 0xbb, 0x4c, 0x2a, 0x2a, 0x44, 0x3e, 0x42, 0x07, 0x93, 0xaf, 0xa9, + 0x5a, 0x4e, 0xde, 0xd1, 0x30, 0x72, 0xa2, 0xa2, 0xa2, 0xb2, 0xee, 0x2b, + 0xfa, 0x3f, 0x97, 0x52, 0x19, 0x0e, 0x26, 0x83, 0x3e, 0xb9, 0x6f, 0x79, + 0x85, 0x51, 0x96, 0x79, 0xa5, 0xa7, 0x95, 0x54, 0x76, 0x7a, 0x4a, 0xd1, + 0x68, 0x9f, 0xd4, 0x65, 0xda, 0x0f, 0x46, 0x8c, 0x55, 0x46, 0x1c, 0x3a, + 0x04, 0xb4, 0x8f, 0x9a, 0x8d, 0x29, 0x3f, 0xa3, 0x57, 0x73, 0x68, 0xf1, + 0x68, 0xae, 0x27, 0x47, 0x56, 0x02, 0xa5, 0x8c, 0xd8, 0x08, 0xcd, 0xcb, + 0xfd, 0x73, 0xc2, 0x6d, 0x47, 0x0d, 0x4a, 0x73, 0x7f, 0xfe, 0xd6, 0x68, + 0x36, 0x65, 0x71, 0x50, 0xc3, 0xee, 0x2b, 0x51, 0xfc, 0xa5, 0xa9, 0x54, + 0x31, 0x53, 0x32, 0xc4, 0x6b, 0x9a, 0xf6, 0x7a, 0x1a, 0xa6, 0x22, 0x43, + 0xc5, 0x41, 0x97, 0x06, 0x3d, 0x4c, 0x43, 0xd4, 0x54, 0x05, 0x3f, 0x03, + 0x98, 0x7d, 0xc8, 0xdf, 0xc0, 0x00, 0x00, 0x01, 0x0b, 0x1a, 0xda, 0x29, + 0x0d, 0x90, 0xc9, 0xa9, 0xca, 0x0e, 0x12, 0x5c, 0xf5, 0x4f, 0x47, 0xf1, + 0x2a, 0x51, 0xe9, 0x6b, 0xbc, 0xa6, 0xa5, 0x54, 0x92, 0xb8, 0xfe, 0x2d, + 0x4a, 0x52, 0xef, 0xf4, 0x4c, 0x7f, 0x16, 0xa4, 0x5e, 0x17, 0xa0, 0xa4, + 0x9d, 0x45, 0x19, 0xa5, 0x29, 0x33, 0xa2, 0xe8, 0x1f, 0xbf, 0x95, 0xa3, + 0x6d, 0x90, 0x22, 0x29, 0xab, 0x22, 0x43, 0x78, 0x3a, 0x96, 0x35, 0xba, + 0xbb, 0x44, 0xc0, 0x19, 0xd7, 0x1f, 0x23, 0xf8, 0xa2, 0x75, 0xc8, 0xfc, + 0x4d, 0x1f, 0xcb, 0x0f, 0xa3, 0x55, 0x74, 0x62, 0x69, 0xc1, 0x09, 0x27, + 0x79, 0xf1, 0xed, 0xd5, 0xee, 0x67, 0xbd, 0xbe, 0x86, 0x17, 0x87, 0xdb, + 0x9a, 0x04, 0x2b, 0x81, 0x30, 0xb8, 0xa5, 0xd5, 0xc5, 0x59, 0x2e, 0x54, + 0xe2, 0xaa, 0xee, 0x55, 0x9e, 0x78, 0x75, 0x1e, 0x3e, 0x55, 0x89, 0x1c, + 0x1f, 0x4f, 0x54, 0x7f, 0x32, 0xa4, 0xbe, 0x6b, 0x92, 0xfa, 0x2f, 0xa8, + 0xcc, 0x1e, 0x30, 0x89, 0xd1, 0xc7, 0xf4, 0x7a, 0x46, 0x22, 0x8c, 0x43, + 0x76, 0x8d, 0x22, 0x5a, 0xe8, 0x54, 0x61, 0x12, 0x44, 0x18, 0x2e, 0x98, + 0xd0, 0xb8, 0xac, 0xb5, 0x5d, 0xa6, 0x55, 0x2f, 0x4b, 0x5d, 0xd3, 0x55, + 0x45, 0x34, 0x03, 0xa4, 0xd0, 0x1b, 0x80, 0x60, 0x9a, 0x80, 0x00, 0x00, + 0x01, 0x0c, 0x1a, 0x76, 0x67, 0xf2, 0x13, 0x51, 0xfc, 0x4a, 0x94, 0xa5, + 0x72, 0xa3, 0x94, 0xa5, 0x27, 0x15, 0x4d, 0x48, 0x61, 0x8c, 0xd1, 0xb2, + 0x9e, 0x94, 0xa6, 0x9b, 0xdd, 0xa2, 0x4d, 0xfb, 0x55, 0xe0, 0x47, 0xf3, + 0x6a, 0x6a, 0x80, 0x6b, 0x77, 0x27, 0xa5, 0x0a, 0xbb, 0x54, 0xc2, 0x3c, + 0x57, 0x8a, 0x01, 0x94, 0x55, 0xc5, 0x39, 0x94, 0x7f, 0x2a, 0xa5, 0x12, + 0x84, 0x95, 0xd9, 0x21, 0xdc, 0xcf, 0x46, 0xb9, 0xf5, 0xed, 0xfd, 0xf7, + 0xfb, 0xaa, 0x8e, 0x65, 0x55, 0xa8, 0x9b, 0x9b, 0xa9, 0x38, 0xef, 0x3b, + 0x4b, 0xb3, 0xca, 0x94, 0x3e, 0x17, 0x8d, 0xd6, 0xd6, 0x0c, 0x46, 0x4a, + 0xad, 0xad, 0x48, 0x53, 0x6a, 0xa0, 0x21, 0xcc, 0x11, 0x52, 0x2f, 0x52, + 0x22, 0xa9, 0x55, 0x14, 0xd8, 0x7d, 0xe1, 0x25, 0x45, 0x30, 0xaa, 0x78, + 0x31, 0x42, 0x6c, 0x59, 0x83, 0x15, 0xd3, 0x58, 0x71, 0xa1, 0x15, 0x5b, + 0x45, 0x35, 0x1f, 0xcb, 0xb2, 0x28, 0x32, 0x0d, 0xe2, 0xc9, 0xb9, 0x2f, + 0x7d, 0x85, 0x5c, 0x27, 0x0a, 0x4a, 0xa0, 0x82, 0xfc, 0x9c, 0x42, 0x0d, + 0xe6, 0x4d, 0x93, 0xce, 0x2b, 0x85, 0x5c, 0x22, 0x30, 0x32, 0x26, 0x71, + 0xfd, 0x5a, 0x47, 0xcd, 0x15, 0x70, 0x65, 0xa1, 0x0a, 0x2a, 0x28, 0x3e, + 0x21, 0x40, 0x52, 0x43, 0xd4, 0xc0, 0xcf, 0xc5, 0xc0, 0x3a, 0xf0, 0x14, + 0xf9, 0xe0, 0x28, 0x93, 0xee, 0xa0, 0x00, 0x00, 0x01, 0x0d, 0x1a, 0x73, + 0x29, 0x36, 0x6d, 0x94, 0xe3, 0xf8, 0x95, 0x29, 0x4b, 0x46, 0x95, 0x1c, + 0x8b, 0x42, 0x93, 0x19, 0x17, 0x3c, 0x8a, 0xa3, 0xac, 0x28, 0x29, 0x2d, + 0x48, 0xe6, 0x49, 0x89, 0xda, 0x90, 0x24, 0xf4, 0xcd, 0x5b, 0x48, 0xd6, + 0x75, 0x52, 0x53, 0xdd, 0xc4, 0x79, 0x76, 0xa4, 0xa5, 0x2f, 0x6d, 0x40, + 0x96, 0x74, 0x8e, 0xf7, 0x5e, 0xf3, 0x10, 0x01, 0xf4, 0x85, 0x53, 0x53, + 0x49, 0x91, 0x6d, 0x61, 0x88, 0xc3, 0xb8, 0x1a, 0x91, 0xa8, 0x46, 0xe4, + 0x48, 0xd1, 0x32, 0x64, 0x35, 0xa5, 0x81, 0xd3, 0x5c, 0xab, 0xa2, 0xcd, + 0xb6, 0xa0, 0x24, 0x3e, 0xaa, 0x95, 0x69, 0x87, 0xd5, 0x4d, 0xaf, 0x1a, + 0x9a, 0xa9, 0x87, 0x5d, 0x83, 0xfd, 0xd3, 0x5b, 0x18, 0x48, 0xeb, 0xb4, + 0x20, 0x0f, 0x52, 0xe0, 0x8b, 0xab, 0xa0, 0x07, 0x3d, 0x34, 0x75, 0x5b, + 0x18, 0x12, 0x53, 0x48, 0xe7, 0x4a, 0x27, 0x48, 0x6b, 0x6c, 0x0a, 0x42, + 0x63, 0x22, 0x63, 0x6e, 0x7f, 0x18, 0x2f, 0x67, 0x95, 0x75, 0x55, 0x13, + 0x1b, 0x44, 0x2f, 0x43, 0x22, 0x99, 0x74, 0xd0, 0x00, 0x00, 0x01, 0x0e, + 0x1a, 0x71, 0x18, 0x76, 0x43, 0xa1, 0xdc, 0x79, 0x76, 0x97, 0xd4, 0x82, + 0xd8, 0x63, 0xa0, 0x9d, 0xfc, 0xbb, 0xc0, 0x8b, 0xbd, 0x00, 0xd6, 0x48, + 0x98, 0x45, 0x43, 0x6a, 0xab, 0x64, 0x8d, 0x22, 0xdd, 0xca, 0x8f, 0xe2, + 0x94, 0xa4, 0x2e, 0x86, 0xde, 0x55, 0x4d, 0x54, 0xae, 0xd1, 0x62, 0xa5, + 0x4b, 0xaa, 0xe9, 0xb4, 0xaa, 0x58, 0xc0, 0xe7, 0x00, 0x00, 0x01, 0x0f, + 0x1a, 0x70, 0xed, 0xdf, 0x51, 0xfc, 0x4a, 0x1a, 0x1f, 0x4d, 0x5f, 0x8a, + 0x8b, 0xcf, 0x4f, 0x55, 0x04, 0x5c, 0xd3, 0x54, 0xca, 0xb2, 0xc6, 0x6d, + 0xa5, 0x0d, 0x61, 0x28, 0xda, 0x5d, 0x48, 0x55, 0x47, 0xf1, 0x2a, 0x52, + 0x96, 0x9b, 0xca, 0xa4, 0x90, 0xf5, 0x32, 0xd7, 0xfe, 0x1f, 0x06, 0x38, + 0x00, 0x00, 0x01, 0x10, 0x1a, 0x70, 0xcd, 0xde, 0xec, 0x72, 0x05, 0x6a, + 0x6a, 0xa5, 0x8a, 0x46, 0xe6, 0x3f, 0x89, 0x52, 0x94, 0xb4, 0x19, 0x16, + 0x0f, 0x8f, 0x4f, 0x54, 0xd4, 0x7f, 0x12, 0x86, 0xf1, 0xa5, 0x7a, 0x0f, + 0xa4, 0xc2, 0x02, 0x8e, 0x00, 0x00, 0x01, 0x11, 0x1a, 0x70, 0xa8, 0x8a, + 0xfa, 0x46, 0x32, 0x47, 0xb5, 0x37, 0x6a, 0x50, 0x99, 0x79, 0xf2, 0xa5, + 0xcb, 0x14, 0x14, 0x70, 0x00, 0x00, 0x01, 0x12, 0x1a, 0x70, 0x92, 0x83, + 0x28, 0xb2, 0x1a, 0xa9, 0xaa, 0x9a, 0xa9, 0xa6, 0x53, 0x07, 0x38, 0x00, + 0x00, 0x01, 0xbe, 0x00, 0xa3, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x0a + }; + + const static uint8_t NoStartCode[] = { + 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, 0x29, 0x48, 0x8b, + 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x4a, 0x52, 0x22, 0xe5, + 0x29, 0x48, 0x8b, 0x94, 0xa5, 0x22, 0x2e, 0x52, 0x94, 0x88, 0xb9, 0x11, + 0xbe, 0x14, 0x9f, 0xd1, 0x72, 0x91, 0x66, 0xa6, 0xef, 0x3d, 0xda, 0x2c, + }; + + class VaapiDecoderMPEG2Test + : public FactoryTest { + protected: + /* invoked by gtest before the test */ + virtual void SetUp() { return; } + + /* invoked by gtest after the test */ + virtual void TearDown() { return; } + }; + +#define VAAPIDECODER_MPEG2_TEST(name) TEST_F(VaapiDecoderMPEG2Test, name) + + VAAPIDECODER_MPEG2_TEST(Factory) + { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_MPEG2); + doFactoryTest(mimeTypes); + } + +} //namespace MPEG2 +} //namespace YamiMediaCodec diff --git a/decoder/vaapidecoder_vc1.cpp b/decoder/vaapidecoder_vc1.cpp new file mode 100644 index 0000000..10affbb --- /dev/null +++ b/decoder/vaapidecoder_vc1.cpp @@ -0,0 +1,420 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "common/log.h" +#include "vaapidecoder_vc1.h" + +namespace YamiMediaCodec { +using namespace ::YamiParser::VC1; +VaapiDecoderVC1::VaapiDecoderVC1() +{ + m_dpbIdx = 0; +} + +VaapiDecoderVC1::~VaapiDecoderVC1() +{ + stop(); +} + +YamiStatus VaapiDecoderVC1::start(VideoConfigBuffer* buffer) +{ + if (!buffer || !buffer->data || !buffer->size) + return YAMI_INVALID_PARAM; + uint32_t width = buffer->width; + uint32_t height = buffer->height; + m_parser.m_seqHdr.coded_width = width; + m_parser.m_seqHdr.coded_height = height; + if (!m_parser.parseCodecData(buffer->data, buffer->size)) + return YAMI_FAIL; + setFormat(width, height, width, height, VC1_MAX_REFRENCE_SURFACE_NUMBER + 1); + return YAMI_SUCCESS; +} + +void VaapiDecoderVC1::stop(void) +{ + flush(); + VaapiDecoderBase::stop(); +} + +void VaapiDecoderVC1::flush(void) +{ + bumpAll(); + VaapiDecoderBase::flush(); +} + +YamiStatus VaapiDecoderVC1::ensureContext() +{ + return ensureProfile(VAProfileVC1Main); +} + +bool VaapiDecoderVC1::makeBitPlanes(PicturePtr& picture, VAPictureParameterBufferVC1* param) +{ + uint8_t val = 0; + uint32_t i = 0, j = 0, k = 0, t = 0, dstIdx = 0, srcIdx = 0; + uint8_t* bitPlanes[3] = { NULL, NULL, NULL }; + uint8_t* bitPlanesPayLoad = NULL; + if ((m_parser.m_frameHdr.picture_type == FRAME_I) + || (m_parser.m_frameHdr.picture_type == FRAME_BI)) { + if (param->bitplane_present.flags.bp_ac_pred) + bitPlanes[1] = &m_parser.m_bitPlanes.acpred[0]; + if (param->bitplane_present.flags.bp_overflags) + bitPlanes[2] = &m_parser.m_bitPlanes.overflags[0]; + } + else if (m_parser.m_frameHdr.picture_type == FRAME_P) { + if (param->bitplane_present.flags.bp_direct_mb) + bitPlanes[0] = &m_parser.m_bitPlanes.directmb[0]; + if (param->bitplane_present.flags.bp_skip_mb) + bitPlanes[1] = &m_parser.m_bitPlanes.skipmb[0]; + if (param->bitplane_present.flags.bp_mv_type_mb) + bitPlanes[2] = &m_parser.m_bitPlanes.mvtypemb[0]; + } + else if (m_parser.m_frameHdr.picture_type == FRAME_B) { + if (param->bitplane_present.flags.bp_direct_mb) + bitPlanes[0] = &m_parser.m_bitPlanes.directmb[0]; + if (param->bitplane_present.flags.bp_skip_mb) + bitPlanes[1] = &m_parser.m_bitPlanes.skipmb[0]; + } + picture->editBitPlane(bitPlanesPayLoad, (m_parser.m_mbWidth * m_parser.m_mbHeight + 1) >> 1); + if (!bitPlanesPayLoad) + return false; + for (i = 0; i < m_parser.m_mbHeight; i++) { + for (j = 0; j < m_parser.m_mbWidth; j++) { + dstIdx = t++ >> 1; + srcIdx = i * m_parser.m_mbWidth + j; + val = 0; + for (k = 0; k < 3; k++) { + if (bitPlanes[k]) + val |= bitPlanes[k][srcIdx] << k; + } + bitPlanesPayLoad[dstIdx] = (bitPlanesPayLoad[dstIdx] << 4) | val; + } + } + if (t & 1) + bitPlanesPayLoad[(t >> 1)] <<= 4; + return true; +} + +bool VaapiDecoderVC1::ensurePicture(PicturePtr& picture) +{ + VAPictureParameterBufferVC1* param; + SeqHdr* seqHdr = &m_parser.m_seqHdr; + EntryPointHdr* entryPointHdr = &m_parser.m_entryPointHdr; + FrameHdr* frameHdr = &m_parser.m_frameHdr; + if (!picture->editPicture(param)) + return false; + + param->forward_reference_picture = VA_INVALID_ID; + param->backward_reference_picture = VA_INVALID_ID; + param->inloop_decoded_picture = VA_INVALID_ID; + param->coded_width = m_parser.m_seqHdr.coded_width; + param->coded_height = m_parser.m_seqHdr.coded_height; + +#define FILL(h, f) param->f = h->f +#define FILL_MV(h, f) param->mv_fields.bits.f = h->f +#define FILL_RAWCODING(h, f) param->raw_coding.flags.f = h->f +#define FILL_SEQUENCE(h, f) param->sequence_fields.bits.f = h->f +#define FILL_REFERENCE(h, f) param->reference_fields.bits.f = h->f +#define FILL_TRANSFORM(h, f) param->transform_fields.bits.f = h->f +#define FILL_ENTRYPOINT(h, f) param->entrypoint_fields.bits.f = h->f +#define FILL_PICTUREFIELDS(h, f) param->picture_fields.bits.f = h->f +#define FILL_PICQUANTIZER(h, f) param->pic_quantizer_fields.bits.f = h->f + FILL_PICTUREFIELDS(frameHdr, picture_type); + FILL_PICQUANTIZER(frameHdr, dq_frame); + FILL_PICQUANTIZER(frameHdr, dq_profile); + FILL_PICQUANTIZER(frameHdr, dq_binary_level); + FILL_PICQUANTIZER(frameHdr, alt_pic_quantizer); + param->pic_quantizer_fields.bits.half_qp = frameHdr->halfqp; + param->pic_quantizer_fields.bits.pic_quantizer_scale = frameHdr->pquant; + param->pic_quantizer_fields.bits.pic_quantizer_type = frameHdr->pquantizer; + if (frameHdr->dq_profile == DQPROFILE_SINGLE_EDGE) + FILL_PICQUANTIZER(frameHdr, dq_sb_edge); + + if (frameHdr->dq_profile == DQPROFILE_DOUBLE_EDGE) + FILL_PICQUANTIZER(frameHdr, dq_db_edge); + + FILL_TRANSFORM(frameHdr, intra_transform_dc_table); + FILL_TRANSFORM(frameHdr, mb_level_transform_type_flag); + FILL_TRANSFORM(frameHdr, frame_level_transform_type); + param->transform_fields.bits.transform_ac_codingset_idx1 = frameHdr->transacfrm; + param->transform_fields.bits.transform_ac_codingset_idx2 = frameHdr->transacfrm2; + FILL_SEQUENCE(seqHdr, profile); + + FILL_RAWCODING(frameHdr, mv_type_mb); + FILL_RAWCODING(frameHdr, direct_mb); + FILL_RAWCODING(frameHdr, skip_mb); + + FILL_MV(frameHdr, mv_table); + FILL_MV(frameHdr, extended_mv_range); + if (frameHdr->picture_type == FRAME_P + || frameHdr->picture_type == FRAME_B) + FILL_MV(frameHdr, mv_mode); + + if (frameHdr->picture_type == FRAME_P + && frameHdr->mv_mode == MVMODE_INTENSITY_COMPENSATION) + FILL_MV(frameHdr, mv_mode2); + + FILL(frameHdr, cbp_table); + param->luma_scale = frameHdr->lumscale; + param->luma_shift = frameHdr->lumshift; + param->b_picture_fraction = frameHdr->bfraction; + if ((!(frameHdr->mv_type_mb)) + && (frameHdr->picture_type == FRAME_P + && (frameHdr->mv_mode == MVMODE_MIXED_MV + || (frameHdr->mv_mode == MVMODE_INTENSITY_COMPENSATION + && frameHdr->mv_mode2 == MVMODE_MIXED_MV)))) + param->bitplane_present.flags.bp_mv_type_mb = 1; + + if ((!(frameHdr->direct_mb)) + && (frameHdr->picture_type == FRAME_B)) + param->bitplane_present.flags.bp_direct_mb = 1; + + if ((!(frameHdr->skip_mb)) + && (frameHdr->picture_type == FRAME_P + || frameHdr->picture_type == FRAME_B)) + param->bitplane_present.flags.bp_skip_mb = 1; + + if (seqHdr->profile == PROFILE_ADVANCED) { + FILL_SEQUENCE(seqHdr, pulldown); + FILL_SEQUENCE(seqHdr, interlace); + FILL_SEQUENCE(seqHdr, tfcntrflag); + FILL_SEQUENCE(seqHdr, finterpflag); + FILL_SEQUENCE(seqHdr, psf); + FILL_SEQUENCE(entryPointHdr, overlap); + + FILL_ENTRYPOINT(entryPointHdr, broken_link); + FILL_ENTRYPOINT(entryPointHdr, closed_entry); + FILL_ENTRYPOINT(entryPointHdr, panscan_flag); + FILL_ENTRYPOINT(entryPointHdr, loopfilter); + + FILL(frameHdr, rounding_control); + FILL(frameHdr, post_processing); + param->fast_uvmc_flag = entryPointHdr->fastuvmc; + param->conditional_overlap_flag = frameHdr->condover; + + param->picture_fields.bits.top_field_first = frameHdr->tff; + param->picture_fields.bits.frame_coding_mode = frameHdr->fcm; + param->picture_fields.bits.is_first_field = frameHdr->fcm == 0; + + FILL_RAWCODING(frameHdr, ac_pred); + FILL_RAWCODING(frameHdr, overflags); + FILL_REFERENCE(entryPointHdr, reference_distance_flag); + + param->mv_fields.bits.extended_mv_flag = entryPointHdr->extended_mv; + FILL_MV(entryPointHdr, extended_dmv_flag); + + FILL_PICQUANTIZER(entryPointHdr, dquant); + FILL_PICQUANTIZER(entryPointHdr, quantizer); + FILL_TRANSFORM(entryPointHdr, variable_sized_transform_flag); + param->range_mapping_fields.bits.luma_flag = entryPointHdr->range_mapy_flag; + param->range_mapping_fields.bits.luma = entryPointHdr->range_mapy; + param->range_mapping_fields.bits.chroma_flag = entryPointHdr->range_mapuv_flag; + param->range_mapping_fields.bits.chroma = entryPointHdr->range_mapuv; + + if (frameHdr->mv_mode == MVMODE_INTENSITY_COMPENSATION) + param->picture_fields.bits.intensity_compensation = 1; + if ((!(frameHdr->ac_pred)) + && (frameHdr->picture_type == FRAME_I + || frameHdr->picture_type == FRAME_BI)) + param->bitplane_present.flags.bp_ac_pred = 1; + + if ((!(frameHdr->overflags)) + && ((frameHdr->picture_type == FRAME_I + || frameHdr->picture_type == FRAME_BI) + && (entryPointHdr->overlap + && frameHdr->pquant <= 8) + && frameHdr->condover == 2)) + param->bitplane_present.flags.bp_overflags = 1; + } + else { + FILL_SEQUENCE(seqHdr, finterpflag); + FILL_SEQUENCE(seqHdr, multires); + FILL_SEQUENCE(seqHdr, overlap); + FILL_SEQUENCE(seqHdr, syncmarker); + FILL_SEQUENCE(seqHdr, rangered); + FILL_SEQUENCE(seqHdr, max_b_frames); + FILL(frameHdr, range_reduction_frame); + FILL(frameHdr, picture_resolution_index); + param->fast_uvmc_flag = seqHdr->fastuvmc; + param->mv_fields.bits.extended_mv_flag = seqHdr->extended_mv; + FILL_TRANSFORM(seqHdr, variable_sized_transform_flag); + + /* 8.3.7 Rounding control */ + if (frameHdr->picture_type == FRAME_I + || frameHdr->picture_type == FRAME_BI) { + param->rounding_control = 1; + } + else if (frameHdr->picture_type == FRAME_P) { + param->rounding_control ^= 1; + } + } + + if (frameHdr->picture_type == FRAME_P + || frameHdr->picture_type == FRAME_SKIPPED) { + param->forward_reference_picture = m_dpb[m_dpbIdx-1]->getSurfaceID(); + } + else if (frameHdr->picture_type == FRAME_B) { + param->forward_reference_picture = m_dpb[0]->getSurfaceID(); + param->backward_reference_picture = m_dpb[1]->getSurfaceID(); + } + + if (param->bitplane_present.value) + return makeBitPlanes(picture, param); + +#undef FILL +#undef FILL_MV +#undef FILL_RAWCODING +#undef FILL_SEQUENCE +#undef FILL_REFERENCE +#undef FILL_TRANSFORM +#undef FILL_ENTRYPOINT +#undef FILL_PICTUREFIELDS +#undef FILL_PICQUANTIZER + + return true; +} + +bool VaapiDecoderVC1::ensureSlice(PicturePtr& picture, void* data, int size) +{ + VASliceParameterBufferVC1* slice = NULL; + if (!picture->newSlice(slice, data, size)) + return false; + + slice->macroblock_offset = m_parser.m_frameHdr.macroblock_offset; + + if (m_sliceFlag) { + slice->macroblock_offset = m_parser.m_sliceHdr.macroblock_offset; + slice->slice_vertical_position = m_parser.m_sliceHdr.slice_addr; + } + return true; +} + +YamiStatus VaapiDecoderVC1::outputPicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_SUCCESS; + if (!picture->m_picOutputFlag) { + ret = VaapiDecoderBase::outputPicture(picture);; + picture->m_picOutputFlag = true; + } + return ret; +} + +void VaapiDecoderVC1:: bumpAll() +{ + for(int32_t i = 0; i < m_dpbIdx; i++) + outputPicture(m_dpb[i]); + m_dpbIdx = 0; + m_dpb[0].reset(); + m_dpb[1].reset(); +} + +YamiStatus VaapiDecoderVC1::decode(uint8_t* data, uint32_t size, uint64_t pts) +{ + YamiStatus ret; + SurfacePtr surface; + PicturePtr picture; + int32_t offset, len; + bool isReference = true; + SeqHdr* seqHdr = &m_parser.m_seqHdr; + m_sliceFlag = false; + ret = ensureContext(); + if (ret != YAMI_SUCCESS) + return ret; + surface = VaapiDecoderBase::createSurface(); + if (!surface) { + ret = YAMI_DECODE_NO_SURFACE; + } else { + picture.reset( + new VaapiDecPictureVC1(m_context, surface, pts)); + } + if (!ensurePicture(picture)) + return YAMI_FAIL; + if (seqHdr->profile == PROFILE_ADVANCED) { + while(1) { + offset = m_parser.searchStartCode(data, size); + len = (offset < 0) ? size : offset; + if (m_sliceFlag) + m_parser.parseSliceHeader(data, len); + + if (!ensureSlice(picture, data, len)) + return YAMI_FAIL; + + if (offset < 0) + break; + if (data[offset+3] == 0xB) + m_sliceFlag = true; + else + m_sliceFlag = false; + data += (offset + 4); + size -= (offset + 4); + } + } else { + if (!ensureSlice(picture, data, size)) + return YAMI_FAIL; + } + if (!picture->decode()) { + return YAMI_FAIL; + } + + if (m_parser.m_frameHdr.picture_type == FRAME_B) + isReference = false; + if (m_dpbIdx == 2) { + if (!isReference) { + outputPicture(m_dpb[0]); + outputPicture(picture); + } else { + outputPicture(m_dpb[0]); + m_dpb[0] = m_dpb[1]; + m_dpb[1] = picture; + } + } else { + if (isReference) { + m_dpb[m_dpbIdx] = picture; + m_dpbIdx++; + } + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderVC1::decode(VideoDecodeBuffer* buffer) +{ + uint8_t* data; + uint32_t size; + FrameHdr* frameHdr = &m_parser.m_frameHdr; + if (!buffer || !(buffer->data) || !(buffer->size)) { + bumpAll(); + return YAMI_SUCCESS; + } + size = buffer->size; + data = buffer->data; + if (!m_parser.parseFrameHeader(data, size)) + return YAMI_DECODE_INVALID_DATA; + if (((frameHdr->picture_type == FRAME_P + || frameHdr->picture_type == FRAME_SKIPPED) + && (m_dpbIdx < 1)) + || ((frameHdr->picture_type == FRAME_B) + && (m_dpbIdx < 2))) { + return YAMI_FAIL; + } + return decode(data, size, buffer->timeStamp); +} + +} diff --git a/decoder/vaapidecoder_vc1.h b/decoder/vaapidecoder_vc1.h new file mode 100644 index 0000000..25e522e --- /dev/null +++ b/decoder/vaapidecoder_vc1.h @@ -0,0 +1,74 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_vc1_h +#define vaapidecoder_vc1_h + +#include "codecparsers/vc1Parser.h" +#include "vaapidecoder_base.h" +#include "va/va.h" + +namespace YamiMediaCodec { +class VaapiDecPictureVC1 : public VaapiDecPicture { +public: + VaapiDecPictureVC1(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiDecPicture(context, surface, timeStamp) + , m_picOutputFlag(false) + { + } + VaapiDecPictureVC1() {} + bool m_picOutputFlag; +private: +}; +class VaapiDecoderVC1 : public VaapiDecoderBase { +public: + typedef SharedPtr PicturePtr; + VaapiDecoderVC1(); + virtual ~VaapiDecoderVC1(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual void stop(void); + virtual void flush(void); + virtual YamiStatus decode(VideoDecodeBuffer*); + +private: + friend class FactoryTest; + friend class VaapiDecoderVC1Test; + void bumpAll(); + YamiStatus ensureContext(); + YamiStatus outputPicture(const PicturePtr& picture); + YamiStatus decode(uint8_t*, uint32_t, uint64_t); + bool ensureSlice(PicturePtr&, void*, int); + bool ensurePicture(PicturePtr&); + bool makeBitPlanes(PicturePtr&, VAPictureParameterBufferVC1*); + YamiParser::VC1::Parser m_parser; + + const static uint32_t VC1_MAX_REFRENCE_SURFACE_NUMBER = 2; + + //m_dpb[0] stores forward reference picture + //m_dpb[1] stores backward reference picture + PicturePtr m_dpb[2]; + int32_t m_dpbIdx; + bool m_sliceFlag; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; +} // namespace YamiMediaCodec +#endif diff --git a/decoder/vaapidecoder_vc1_unittest.cpp b/decoder/vaapidecoder_vc1_unittest.cpp new file mode 100644 index 0000000..b2cf9eb --- /dev/null +++ b/decoder/vaapidecoder_vc1_unittest.cpp @@ -0,0 +1,464 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapidecoder_vc1.h" + +// library headers +#include "common/Array.h" + +namespace YamiMediaCodec { + +const static std::array g_SimpleVC1 = { + 0x80, 0x6b, 0x97, 0x00, 0xf3, 0xe3, 0xc1, 0x06, 0xdb, 0x3e, 0x88, 0x60, 0x8c, 0xec, 0x31, 0x92, + 0xa0, 0xaa, 0x42, 0xf6, 0x4d, 0xf7, 0x01, 0xcc, 0x73, 0x00, 0x79, 0xea, 0xc8, 0x3a, 0xb9, 0x53, + 0xb0, 0x1c, 0xb6, 0x21, 0x99, 0x60, 0x95, 0x3f, 0x38, 0x53, 0x10, 0x79, 0xa5, 0x5a, 0x8b, 0x01, + 0xc1, 0x76, 0xe9, 0xf1, 0x03, 0xe6, 0xdd, 0xb1, 0x88, 0xf8, 0x70, 0x88, 0xac, 0xce, 0x12, 0x99, + 0x59, 0xd5, 0x42, 0x9c, 0xa5, 0x82, 0x83, 0xc7, 0x54, 0xc5, 0xa4, 0x96, 0xf0, 0xbe, 0x05, 0x9d, + 0x77, 0xa6, 0xfc, 0xe8, 0x4e, 0x0a, 0xb0, 0x6c, 0xc2, 0x1b, 0xed, 0x0b, 0xc7, 0xcb, 0x57, 0x2e, + 0x0b, 0x11, 0xde, 0x61, 0x0d, 0x07, 0x06, 0xc6, 0x7b, 0x3b, 0x1f, 0x72, 0x2f, 0x33, 0x09, 0xf1, + 0x3f, 0xb9, 0x86, 0x01, 0x5e, 0xbe, 0xa0, 0x0b, 0x8f, 0x21, 0x68, 0xe3, 0x01, 0x8b, 0x6d, 0x1b, + 0x7b, 0x56, 0x7c, 0xba, 0x69, 0x94, 0xc7, 0x35, 0xb3, 0x89, 0x89, 0xa1, 0x2d, 0x16, 0x5f, 0x2c, + 0x41, 0x8a, 0x22, 0x64, 0xdf, 0x26, 0x7a, 0x30, 0x2f, 0xce, 0x4f, 0x05, 0xd8, 0x6c, 0x05, 0x23, + 0xac, 0x62, 0xbc, 0x12, 0x32, 0x59, 0x1a, 0x4f, 0x0a, 0xeb, 0x3c, 0x32, 0x00, 0xa2, 0x31, 0xbd, + 0x77, 0x42, 0x49, 0xb1, 0x6a, 0xc2, 0x07, 0x59, 0xe0, 0xd2, 0x88, 0x92, 0x6f, 0xfa, 0x13, 0x1b, + 0xec, 0x4b, 0xd8, 0x85, 0xc2, 0x7a, 0x36, 0xee, 0x8a, 0xbf, 0xa4, 0x91, 0xb7, 0xb6, 0x5b, 0xe0, + 0x45, 0x99, 0x80, 0x82, 0x26, 0xd0, 0x44, 0x7a, 0x10, 0xc6, 0x48, 0x3f, 0x53, 0x8e, 0x30, 0x13, + 0x87, 0xf6, 0x26, 0x34, 0xfc, 0x8d, 0x89, 0x6c, 0xd2, 0x9a, 0xbc, 0x77, 0x1b, 0x80, 0x08, 0x18, + 0x62, 0x31, 0xb5, 0x79, 0xc7, 0x8f, 0xf3, 0x83, 0x12, 0x11, 0xd3, 0x84, 0x5e, 0x18, 0x6e, 0xa1, + 0x0c, 0xb6, 0xc1, 0x2b, 0x36, 0x02, 0x8d, 0x36, 0x09, 0xe8, 0x95, 0x8a, 0xed, 0xb8, 0x0a, 0x70, + 0xa0, 0x1e, 0xbb, 0xe8, 0x85, 0xcd, 0xc5, 0xc5, 0x93, 0x31, 0x22, 0x73, 0x4a, 0xa0, 0xf4, 0x0b, + 0xd2, 0xee, 0xb7, 0x0b, 0x4d, 0x08, 0xbe, 0xfe, 0x5c, 0x33, 0x02, 0x10, 0x63, 0xf8, 0xc1, 0x44, + 0x36, 0x5a, 0x13, 0xa9, 0x72, 0x58, 0x47, 0x76, 0x0f, 0xac, 0x16, 0x39, 0xe5, 0x28, 0x90, 0x0c, + 0x7a, 0x4b, 0xc9, 0xad, 0xb1, 0xf2, 0xb9, 0xd5, 0x62, 0x54, 0xb1, 0xa3, 0xc5, 0x38, 0x8c, 0xe4, + 0x90, 0x99, 0xe3, 0xa4, 0x58, 0xe6, 0x38, 0xec, 0xf0, 0x4e, 0x7d, 0xbc, 0x55, 0x31, 0x82, 0x30, + 0x4a, 0x0f, 0xa1, 0x2c, 0xd1, 0xce, 0x3b, 0x41, 0xfe, 0xda, 0x1c, 0x98, 0x84, 0x2c, 0x19, 0x16, + 0x94, 0x68, 0x16, 0x05, 0x06, 0xe1, 0xf0, 0x28, 0xc4, 0x39, 0x43, 0xd9, 0x69, 0xbe, 0x08, 0x7f, + 0xca, 0xd0, 0xbc, 0x57, 0x05, 0x75, 0x07, 0xa8, 0x20, 0x93, 0xba, 0x23, 0x47, 0x06, 0xb4, 0x19, + 0xfb, 0x68, 0x73, 0xd5, 0x41, 0x1a, 0xc9, 0xa4, 0xa6, 0x20, 0xdc, 0xcc, 0xaa, 0x6b, 0xfb, 0x75, + 0x64, 0x7a, 0xaa, 0xb3, 0xa8, 0x18, 0x51, 0x1b, 0xdc, 0x05, 0x7c, 0x61, 0x48, 0x74, 0x31, 0x64, + 0xca, 0x9a, 0xa5, 0x32, 0xeb, 0xb9, 0x50, 0x77, 0x9b, 0x70, 0x83, 0xaf, 0x8c, 0xb0, 0x60, 0x19, + 0xc4, 0x5f, 0xa3, 0xe0, 0x3e, 0x4b, 0x49, 0x72, 0xac, 0x11, 0x95, 0x54, 0x59, 0x75, 0xe9, 0x5e, + 0x6b, 0x9b, 0x5c, 0xe9, 0x2e, 0xea, 0xa5, 0xf3, 0x5d, 0x57, 0x0f, 0x1c, 0x8f, 0xfb, 0x7e, 0x4f, + 0x8b, 0xcc, 0xf8, 0x2e, 0xb9, 0xe8, 0x09, 0x24, 0xdb, 0xf0, 0x46, 0x2a, 0xa8, 0x64, 0xce, 0xe6, + 0x8d, 0x1e, 0x83, 0x1a, 0x3d, 0x06, 0x87, 0x8c, 0xe1, 0x31, 0x4c, 0xf4, 0xba, 0xc1, 0x00, 0x4b, + 0xed, 0x10, 0x98, 0xe3, 0x39, 0x14, 0x79, 0xaf, 0xc8, 0x30, 0x31, 0x9b, 0x26, 0x83, 0x4f, 0x89, + 0x54, 0x91, 0xcc, 0x13, 0x04, 0x61, 0xe1, 0x8f, 0xd6, 0xbe, 0xe9, 0xc5, 0xed, 0xd0, 0xd4, 0xd8, + 0xde, 0xf7, 0xef, 0x0c, 0x91, 0x65, 0xbd, 0x27, 0xe5, 0xe2, 0xc7, 0x82, 0x1b, 0x7a, 0xb0, 0xa0, + 0xe2, 0x1b, 0x61, 0xe3, 0x88, 0xc2, 0xde, 0x25, 0x28, 0xc6, 0x73, 0x71, 0x8c, 0x1e, 0xf0, 0x33, + 0xb8, 0x63, 0x1c, 0x80, 0x9d, 0xfd, 0x8c, 0x64, 0x8e, 0x38, 0xc4, 0x40, 0x70, 0x36, 0x98, 0x92, + 0x1b, 0x68, 0xe3, 0x7d, 0xd1, 0x37, 0x50, 0x2d, 0x91, 0x7d, 0x79, 0x94, 0x88, 0x42, 0x0f, 0x15, + 0xaf, 0x21, 0x8c, 0x15, 0x83, 0xb2, 0xc5, 0xd5, 0x13, 0x1e, 0xe2, 0x89, 0x6f, 0xef, 0x5d, 0x8b, + 0x66, 0xd5, 0xb6, 0xbc, 0xce, 0xda, 0x68, 0xf1, 0x75, 0x44, 0x61, 0xc5, 0xc3, 0xea, 0xb4, 0x01, + 0xf3, 0x66, 0x85, 0x14, 0xac, 0x17, 0xa0, 0xd5, 0xd1, 0xd0, 0x17, 0x8d, 0xe0, 0xea, 0xb2, 0xd0, + 0x28, 0xfa, 0xe3, 0xdc, 0xea, 0x09, 0xf3, 0x45, 0x9b, 0xda, 0xa2, 0x82, 0x16, 0xe4, 0x1b, 0x50, + 0xb7, 0x3c, 0x91, 0xb7, 0xd5, 0x77, 0x98, 0x44, 0x27, 0xaf, 0xcc, 0xaa, 0x8a, 0x85, 0x24, 0xc1, + 0xb6, 0x59, 0x6c, 0x09, 0xbe, 0xe6, 0x83, 0xe9, 0x69, 0x20, 0x73, 0x1b, 0x17, 0xfc, 0xc3, 0x99, + 0x94, 0xfa, 0xba, 0x0b, 0xe4, 0x6f, 0xd5, 0xa9, 0xb0, 0x66, 0xe6, 0x60, 0x0a, 0x14, 0x3c, 0x09, + 0x42, 0x7a, 0xfc, 0xca, 0xab, 0x42, 0x35, 0xd3, 0x02, 0xb7, 0x0d, 0x38, 0x7b, 0xb0, 0xa9, 0x38, + 0x50, 0x3e, 0xc7, 0xdd, 0x15, 0x31, 0x95, 0x10, 0x00, 0x18, 0xe6, 0xc1, 0x41, 0xf8, 0xea, 0x88, + 0xa5, 0x27, 0x26, 0xad, 0x1d, 0x6a, 0x9b, 0xad, 0x31, 0xd6, 0x6a, 0x4a, 0xab, 0xbe, 0xa6, 0x6c, + 0x90, 0x3b, 0x67, 0xe4, 0xd0, 0x93, 0x54, 0x59, 0x38, 0x64, 0x64, 0x67, 0x1a, 0x24, 0x3f, 0x20, + 0x7c, 0x48, 0x38, 0xd4, 0xe2, 0x4d, 0x86, 0x26, 0x41, 0xe9, 0x1b, 0xef, 0x09, 0x07, 0x00, 0xa7, + 0x19, 0x73, 0xab, 0xdb, 0x1c, 0x4b, 0x13, 0x25, 0xe6, 0x0a, 0x23, 0x75, 0x82, 0xc1, 0x06, 0xbc, + 0x77, 0x91, 0xc8, 0x76, 0x91, 0x2c, 0x49, 0xce, 0x8d, 0x17, 0xd7, 0x1b, 0x37, 0x17, 0x1f, 0x15, + 0x52, 0x89, 0xa5, 0x1b, 0x27, 0xb0, 0x26, 0xdc, 0xca, 0x2e, 0x22, 0x30, 0xc0, 0xd8, 0x91, 0xc6, + 0x27, 0x40, 0xca, 0x17, 0x9c, 0x79, 0xac, 0x4e, 0xed, 0x43, 0x25, 0x77, 0x5b, 0x75, 0xfc, 0x43, + 0xef, 0x2f, 0x9a, 0x65, 0xbf, 0x60, 0x88, 0xdd, 0xc4, 0x24, 0x73, 0x09, 0x26, 0xfc, 0x10, 0xb8, + 0xca, 0xb3, 0x90, 0x58, 0xeb, 0xec, 0x81, 0x90, 0x0e, 0x15, 0x3e, 0xb4, 0x34, 0x77, 0x81, 0x52, + 0x04, 0x6c, 0xf0, 0x85, 0xfd, 0xcd, 0x16, 0xde, 0x88, 0x7c, 0x68, 0x07, 0x89, 0x68, 0x85, 0x1e, + 0x03, 0x97, 0x4e, 0xb1, 0xad, 0x3c, 0x48, 0x03, 0x75, 0x2b, 0x54, 0x03, 0x75, 0x1a, 0xd5, 0x07, + 0x8a, 0xc3, 0xa2, 0xa9, 0x40, 0xa1, 0x21, 0xac, 0xe5, 0xd1, 0x61, 0xba, 0x4c, 0xba, 0x2f, 0x66, + 0xb0, 0x03, 0x9e, 0xa9, 0x0c, 0x60, 0x9e, 0x15, 0xe1, 0xa0, 0x8d, 0xac, 0x34, 0xf8, 0x03, 0x08, + 0xd8, 0x1a, 0xc3, 0xcb, 0x5e, 0x91, 0xe9, 0x7a, 0x3e, 0x05, 0x1f, 0x0b, 0x42, 0x7d, 0x51, 0x56, + 0xbe, 0x46, 0x33, 0x43, 0x0c, 0x9a, 0xda, 0xe7, 0xbe, 0x50, 0x10, 0x8e, 0xc6, 0xb4, 0xd1, 0x42, + 0xbb, 0x09, 0x18, 0x65, 0x1a, 0xdc, 0x0f, 0x82, 0x30, 0x34, 0xf8, 0xe9, 0xf8, 0x59, 0xf4, 0x9f, + 0x4c, 0xba, 0x1d, 0x16, 0xbf, 0xa2, 0xb0, 0x3b, 0xc4, 0xda, 0x7d, 0x65, 0xcc, 0xaa, 0x0e, 0xe0, + 0xcd, 0x2c, 0xb6, 0x01, 0x8d, 0x80, 0xa9, 0x04, 0xa8, 0x43, 0x69, 0xa3, 0x37, 0xc1, 0xf0, 0x2f, + 0x27, 0xf0, 0x83, 0x57, 0x60, 0x17, 0x21, 0xe2, 0xe8, 0x71, 0x89, 0x83, 0x0e, 0xbb, 0x91, 0x84, + 0xb9, 0xf6, 0xc5, 0xd0, 0xd5, 0x68, 0xb2, 0xeb, 0xd9, 0x5c, 0x65, 0x37, 0xd1, 0xcb, 0xab, 0x43, + 0x4c, 0xd7, 0x55, 0x28, 0x44, 0x97, 0x7d, 0x4d, 0x7a, 0xeb, 0x47, 0x3c, 0x49, 0x53, 0x1f, 0x22, + 0x12, 0x8b, 0x83, 0xd1, 0x4f, 0x72, 0x35, 0x71, 0xf1, 0x47, 0xa9, 0xb9, 0xd4, 0x49, 0xd5, 0xe4, + 0xd2, 0xdc, 0xee, 0x90, 0x82, 0xe6, 0xe8, 0x47, 0xa9, 0xfb, 0x3c, 0x9e, 0x8d, 0xa3, 0xe6, 0x1a, + 0x19, 0x29, 0x08, 0x68, 0x85, 0x10, 0xb2, 0x3f, 0x12, 0x3b, 0x89, 0x7c, 0x78, 0x64, 0x20, 0x09, + 0x24, 0x69, 0xc4, 0xf1, 0x0b, 0x27, 0xba, 0xd0, 0x3f, 0xb9, 0x08, 0x80, 0x76, 0x10, 0x23, 0x7a, + 0xa7, 0xb6, 0xc8, 0x30, 0x27, 0xbf, 0x42, 0xcc, 0x28, 0x27, 0x37, 0x35, 0x13, 0x32, 0xcd, 0x19, + 0xdc, 0x63, 0xa2, 0x5f, 0x0a, 0xc8, 0xf1, 0x69, 0x08, 0x7e, 0x05, 0x20, 0x2d, 0xff, 0xf1, 0x70, + 0x8a, 0x41, 0xed, 0x87, 0x13, 0x7a, 0x87, 0x90, 0x2e, 0x14, 0xc6, 0x4b, 0x19, 0x40, 0xdc, 0x4f, + 0xb1, 0x13, 0x80, 0xf2, 0x90, 0xd7, 0x27, 0x11, 0x85, 0x5e, 0x16, 0x6a, 0x01, 0x6f, 0x7b, 0x5e, + 0x88, 0x91, 0x02, 0x94, 0x88, 0x32, 0x3d, 0x45, 0xd2, 0xe7, 0xbd, 0xaa, 0xff, 0xd8, 0x0e, 0x50, + 0xa4, 0xf7, 0x85, 0x18, 0xb3, 0x04, 0x0e, 0xca, 0x60, 0xe4, 0x61, 0x44, 0x2b, 0x0f, 0xa8, 0x7a, + 0x57, 0x57, 0x6c, 0x04, 0xbb, 0x95, 0x5b, 0x94, 0x21, 0xb5, 0x50, 0x14, 0x67, 0xce, 0x0d, 0xae, + 0xfd, 0xa9, 0xf8, 0x36, 0x66, 0xda, 0x04, 0x94, 0x49, 0xc3, 0x19, 0xd9, 0x86, 0xad, 0xd0, 0xd1, + 0x65, 0xc1, 0x92, 0x46, 0x1e, 0x04, 0xfe, 0xad, 0xc1, 0x68, 0x12, 0xe8, 0x79, 0x82, 0x3b, 0x2e, + 0x31, 0x14, 0x26, 0x98, 0xcf, 0x87, 0xb8, 0x08, 0xab, 0x23, 0x05, 0x6e, 0x20, 0xe0, 0x57, 0x81, + 0x81, 0x55, 0x07, 0xbf, 0x16, 0xf4, 0xb1, 0x86, 0x64, 0x45, 0x54, 0xf0, 0x15, 0xf1, 0x8e, 0x38, + 0xd8, 0xf8, 0x8e, 0x19, 0xb9, 0x86, 0x0c, 0x05, 0xb7, 0x09, 0x6e, 0x91, 0xda, 0x07, 0xbf, 0xf4, + 0x61, 0x6f, 0xdb, 0x65, 0x09, 0x92, 0xd9, 0x2e, 0x18, 0x15, 0x3a, 0x78, 0x19, 0x80, 0x25, 0x99, + 0x3d, 0x49, 0x0a, 0xe2, 0x48, 0x5d, 0xc8, 0x01, 0x33, 0xf8, 0x08, 0x54, 0x2c, 0x4c, 0x38, 0x66, + 0x69, 0x2b, 0x27, 0x19, 0xc5, 0xad, 0xaf, 0x5d, 0x5b, 0x8e, 0x3a, 0xa8, 0xb2, 0xea, 0xa1, 0xb5, + 0x5a, 0x2c, 0xba, 0xdd, 0x89, 0x6b, 0x5b, 0x10, 0xbb, 0x67, 0x20, 0x00, 0xc9, 0x73, 0x51, 0x52, + 0x00, 0x99, 0xf1, 0xb4, 0x8a, 0x97, 0x49, 0x24, 0x4b, 0xb6, 0x8b, 0x1e, 0x01, 0x35, 0xf2, 0xc2, + 0x91, 0x8b, 0x84, 0x7f, 0x8d, 0x70, 0x83, 0x3c, 0x08, 0x50, 0x3e, 0xf8, 0xd9, 0x31, 0x92, 0x35, + 0x3d, 0x3f, 0xda, 0x90, 0xf4, 0x10, 0xfd, 0x5d, 0x99, 0x7a, 0xa2, 0x67, 0x7b, 0x6f, 0x6d, 0x64, + 0xa1, 0x5c, 0x05, 0x8a, 0x57, 0x67, 0x81, 0x9e, 0xdb, 0x01, 0x73, 0x5e, 0x4f, 0x2e, 0x8f, 0xd7, + 0x90, 0xc4, 0x4d, 0xe3, 0x6d, 0x12, 0x84, 0x94, 0xc5, 0x1d, 0x59, 0x91, 0xea, 0x4a, 0x76, 0x24, + 0x80, 0x89, 0x23, 0x6d, 0x06, 0x1c, 0xcb, 0x80, 0xc2, 0x5b, 0x43, 0xa8, 0xf0, 0x09, 0x78, 0x96, + 0xfb, 0x47, 0x8f, 0x30, 0x39, 0x24, 0x63, 0xee, 0x22, 0x03, 0x68, 0x08, 0x45, 0x23, 0x8f, 0xe4, + 0xf6, 0x19, 0xd0, 0x30, 0x16, 0x1f, 0xda, 0x48, 0x79, 0xaf, 0x5a, 0x62, 0x19, 0x07, 0x1f, 0x7e, + 0x0f, 0x73, 0x3c, 0x34, 0xd9, 0x31, 0xe0, 0xca, 0xfb, 0x53, 0x09, 0x02, 0xc4, 0x9a, 0x5b, 0x88, + 0x7c, 0x63, 0x07, 0x91, 0xc5, 0x0a, 0x6f, 0x41, 0x1b, 0x20, 0x69, 0x19, 0xde, 0x1d, 0x71, 0x8b, + 0xe2, 0x0c, 0x6d, 0xb6, 0xa2, 0x3f, 0xcb, 0x79, 0x91, 0x02, 0x2c, 0xfc, 0xea, 0x70, 0x5c, 0x67, + 0x9b, 0x63, 0xc0, 0x4f, 0x0f, 0x6e, 0x14, 0x7c, 0x11, 0x90, 0x54, 0x04, 0x51, 0xbe, 0x22, 0x81, + 0x31, 0x90, 0x49, 0x9c, 0xdd, 0x1d, 0x40, 0xd0, 0x43, 0x00, 0x6b, 0xea, 0x78, 0x26, 0xd6, 0x09, + 0x83, 0x61, 0x3b, 0xc9, 0x76, 0xeb, 0xc4, 0x01, 0x08, 0x46, 0xe1, 0xfb, 0xd7, 0x7d, 0xba, 0x62, + 0xeb, 0xeb, 0xb3, 0x0a, 0x8a, 0xed, 0xe5, 0x0b, 0xaf, 0x62, 0x5e, 0x6d, 0x47, 0x11, 0xde, 0xce, + 0x93, 0x60, 0x00, 0x2e, 0x47, 0x52, 0x38, 0xd3, 0x49, 0x5c, 0x6c, 0x1b, 0xdc, 0xdd, 0x86, 0x93, + 0x38, 0x2e, 0x42, 0x0e, 0xc7, 0x32, 0x41, 0x0e, 0xbb, 0x56, 0x57, 0x11, 0x9a, 0xfb, 0x58, 0x13, + 0xa4, 0x5a, 0x9f, 0x7e, 0x42, 0x3e, 0x3e, 0x98, 0x43, 0xae, 0x4c, 0x86, 0xb0, 0xed, 0x51, 0x21, + 0x09, 0xa6, 0x08, 0x36, 0x13, 0x97, 0xaf, 0x5f, 0xd7, 0x67, 0x8d, 0xdc, 0x1a, 0x08, 0xcd, 0xf9, + 0xc0, 0xac, 0x12, 0xfa, 0x90, 0x5a, 0xef, 0x17, 0xf5, 0xb5, 0x37, 0xd7, 0xed, 0x20, 0xf4, 0x24, + 0x93, 0xa3, 0x42, 0xed, 0xad, 0x54, 0x23, 0x4b, 0x30, 0x15, 0x0f, 0x04, 0x61, 0xdd, 0xa1, 0xc6, + 0x69, 0xde, 0xfd, 0x87, 0x51, 0xd2, 0x8b, 0x23, 0x8d, 0x0c, 0xf4, 0x3b, 0x4f, 0x07, 0xc9, 0xda, + 0xd0, 0x41, 0x38, 0x88, 0xb9, 0x90, 0x4f, 0x72, 0x92, 0x44, 0x04, 0x62, 0x0f, 0x18, 0xf9, 0x89, + 0xe1, 0x06, 0xc8, 0x84, 0x50, 0xc9, 0x43, 0x5d, 0x8c, 0xac, 0x38, 0xd7, 0x90, 0x36, 0x6b, 0x91, + 0x2e, 0xcd, 0x96, 0xcd, 0x8b, 0x13, 0xd8, 0x85, 0x13, 0x99, 0x79, 0xd4, 0x0a, 0x74, 0x8f, 0xa6, + 0x26, 0x19, 0xa2, 0x20, 0xd8, 0x5d, 0xc0, 0xe4, 0xf7, 0xa3, 0x5d, 0x21, 0x22, 0xbf, 0xd3, 0x05, + 0x86, 0x60, 0xf6, 0xd5, 0x00, 0x36, 0x5e, 0x5a, 0xb9, 0xa8, 0xc7, 0xf3, 0xdc, 0xea, 0x83, 0x08, + 0x57, 0x24, 0x56, 0xf7, 0x2b, 0x40, 0x2a, 0x0d, 0x56, 0x8e, 0x31, 0x50, 0xb9, 0xd6, 0x57, 0x44, + 0x72, 0x09, 0x44, 0x79, 0xe7, 0x7f, 0xb1, 0x83, 0xa9, 0xc4, 0xbb, 0xcd, 0x20, 0x06, 0x4b, 0xae, + 0xf1, 0xe0, 0x13, 0x9a, 0x54, 0x72, 0xef, 0xbc, 0x5c, 0x24, 0x75, 0x87, 0x49, 0x1b, 0xb2, 0xc9, + 0x97, 0x0f, 0x49, 0x37, 0x71, 0x93, 0x56, 0x59, 0x34, 0x03, 0x26, 0x58, 0xc3, 0xdd, 0x98, 0x30, + 0x2d, 0x54, 0x8f, 0xdc, 0x75, 0xf6, 0xaf, 0x25, 0x04, 0xe8, 0xce, 0x70, 0x00, 0xc4, 0x45, 0x09, + 0xdc, 0x68, 0x3a, 0x65, 0x03, 0x41, 0xfd, 0x09, 0xc4, 0x3f, 0xe1, 0x31, 0x78, 0xb0, 0x0c, 0x37, + 0x10, 0xf6, 0xa7, 0x14, 0x3a, 0xe9, 0xa9, 0xcf, 0xb2, 0x5d, 0xfc, 0x9d, 0xe4, 0x1a, 0xa2, 0xff, + 0xc4, 0x65, 0x5b, 0x3c, 0xbe, 0x8f, 0x12, 0xfa, 0x13, 0x42, 0xeb, 0x82, 0x16, 0xf1, 0x12, 0xc4, + 0xcf, 0x45, 0xaa, 0xfe, 0x70, 0xd0, 0xb0, 0x14, 0xf9, 0xc8, 0xc4, 0xe7, 0x50, 0x86, 0xc8, 0x8d, + 0x31, 0x65, 0xbd, 0xa2, 0x4d, 0x1a, 0xec, 0x8c, 0x62, 0x28, 0xa2, 0x69, 0x14, 0x24, 0xb4, 0xc3, + 0x34, 0x25, 0x80, 0xc8, 0x29, 0x71, 0xdf, 0x8a, 0xe1, 0x0d, 0xe3, 0x15, 0xe6, 0xbe, 0x74, 0x1a, + 0xbb, 0x66, 0xbb, 0xa3, 0x30, 0x76, 0x22, 0x7b, 0xef, 0xdb, 0x19, 0x13, 0xb9, 0x84, 0x14, 0xa3, + 0x98, 0xb8, 0x60, 0x00, 0x2d, 0xdb, 0x04, 0x81, 0x12, 0x8f, 0xb8, 0x81, 0x48, 0x36, 0x18, 0x08, + 0x93, 0x7d, 0x04, 0x16, 0x73, 0xe3, 0xbc, 0x41, 0x7b, 0x22, 0x1b, 0x23, 0xba, 0x24, 0xe9, 0x3a, + 0x25, 0x31, 0x90, 0xaf, 0xc5, 0x80, 0xff, 0xf5, 0x84, 0xad, 0x8d, 0x67, 0x13, 0x2f, 0x9e, 0x4d, + 0x8f, 0x46, 0x07, 0x03, 0xbe, 0xb4, 0xb4, 0xe8, 0xcd, 0x23, 0x2e, 0x97, 0x7e, 0x36, 0x05, 0x7c, + 0x25, 0x5c, 0x1e, 0x72, 0xa0, 0x74, 0xfa, 0x92, 0x97, 0x66, 0x3d, 0xfb, 0x51, 0xa8, 0x9b, 0xee, + 0x2a, 0xf9, 0x6c, 0xc9, 0xa6, 0xc2, 0x03, 0x9b, 0x52, 0x05, 0x95, 0xb7, 0x29, 0xb4, 0xd1, 0xac, + 0x0b, 0x78, 0x0a, 0x30, 0xd1, 0x41, 0xee, 0x7d, 0xaa, 0x9b, 0x85, 0xad, 0x1d, 0x55, 0x05, 0xaa, + 0x38, 0x9c, 0x39, 0xe7, 0x70, 0xa8, 0xb2, 0x19, 0x5c, 0x5d, 0x16, 0x06, 0x83, 0xdd, 0xc0, 0xe8, + 0x4d, 0x2f, 0x88, 0x9f, 0xe9, 0xb0, 0x20, 0x38, 0x96, 0x96, 0x22, 0x5a, 0x5d, 0xea, 0xc6, 0x9a, + 0x3c, 0x8c, 0x71, 0x31, 0xb5, 0xf4, 0xe7, 0x48, 0x02, 0x21, 0x4a, 0x5c, 0x1c, 0x07, 0x37, 0x29, + 0xa7, 0x2a, 0xd6, 0x8e, 0x83, 0x8e, 0x16, 0x46, 0x03, 0x38, 0x8b, 0xfe, 0x03, 0xd8, 0x38, 0x9e, + 0x57, 0x59, 0x79, 0x89, 0x03, 0x7b, 0x90, 0xad, 0xff, 0x26, 0x86, 0x50, 0x0a, 0x71, 0xa9, 0x71, + 0xd6, 0xc6, 0x76, 0xf4, 0x1c, 0x7d, 0x9d, 0x73, 0xc8, 0xbe, 0x8e, 0x94, 0x61, 0x09, 0x49, 0x87, + 0x3c, 0x0b, 0x9c, 0x98, 0xb6, 0x92, 0xe3, 0x8c, 0x90, 0xe4, 0xed, 0xd3, 0x9f, 0x23, 0x12, 0x89, + 0xf6, 0x14, 0x68, 0x0e, 0xd2, 0x4f, 0x9b, 0x9c, 0x33, 0x89, 0xa2, 0x80, 0xd1, 0xdc, 0x93, 0x39, + 0x76, 0xb0, 0x7b, 0x42, 0x94, 0x32, 0x2c, 0x04, 0xfe, 0xfb, 0x2d, 0x88, 0x98, 0xfc, 0x32, 0x82, + 0x62, 0x11, 0x09, 0x11, 0x10, 0xb8, 0x63, 0x1d, 0xf7, 0xa9, 0x03, 0x6a, 0x3b, 0x97, 0x49, 0x64, + 0x13, 0xa2, 0xb7, 0xb8, 0xb4, 0x96, 0xdb, 0x68, 0xe6, 0x2e, 0xec, 0x9a, 0x18, 0xc1, 0x08, 0x98, + 0x04, 0x71, 0x18, 0x24, 0x40, 0xa3, 0x32, 0x05, 0xe6, 0x84, 0x42, 0xc3, 0xa2, 0x4c, 0x67, 0x49, + 0x14, 0x43, 0xe5, 0xe2, 0x36, 0x1f, 0x51, 0x61, 0x59, 0x88, 0x5e, 0x6f, 0xb8, 0xc6, 0xfb, 0xb6, + 0x1a, 0x75, 0xc3, 0xad, 0x25, 0x3c, 0x10, 0x90, 0xf8, 0xe8, 0x64, 0x9a, 0x7d, 0x6b, 0x5f, 0xfa, + 0x6c, 0x08, 0xa0, 0x53, 0x4e, 0x0f, 0xab, 0x81, 0x0a, 0x0e, 0x9a, 0x13, 0x2e, 0x54, 0x10, 0xd1, + 0x07, 0x02, 0xf2, 0xaf, 0xb0, 0x05, 0xf5, 0xd4, 0xd2, 0x94, 0x15, 0x17, 0x93, 0x2d, 0x4c, 0x3e, + 0x3e, 0x16, 0x61, 0x62, 0xb5, 0xb6, 0xe7, 0x3c, 0x86, 0x34, 0xaf, 0xa8, 0x0c, 0xd7, 0x8c, 0x79, + 0xc9, 0xc3, 0xad, 0xeb, 0xa8, 0x75, 0x5d, 0x03, 0x54, 0x5e, 0xc4, 0xbf, 0xba, 0x1d, 0x75, 0x05, + 0xed, 0x64, 0x4d, 0x84, 0xe7, 0xe1, 0x3f, 0x6a, 0x61, 0xd5, 0xe2, 0x90, 0xe7, 0xf3, 0xff, 0xe7, + 0xba, 0xee, 0x5f, 0x94, 0x2a, 0x17, 0x36, 0xec, 0x13, 0x5d, 0xea, 0x7e, 0x86, 0xb5, 0x47, 0x13, + 0xf6, 0x31, 0x70, 0xbc, 0x13, 0xe4, 0xcd, 0x2e, 0x50, 0xb6, 0x32, 0xf0, 0x1c, 0xdd, 0xc1, 0xac, + 0xd8, 0xd8, 0xe9, 0xd4, 0x44, 0xb0, 0x3e, 0x62, 0x69, 0x46, 0x0a, 0x5f, 0xa4, 0xb8, 0x01, 0x5b, + 0x03, 0xdc, 0xc1, 0xb3, 0xf1, 0x27, 0x0e, 0xbc, 0x21, 0xae, 0x3d, 0x7a, 0xce, 0xb3, 0x40, 0x61, + 0xb2, 0xe4, 0xc2, 0x13, 0x11, 0xfb, 0x9c, 0x29, 0x21, 0x5e, 0x41, 0xdb, 0x8e, 0x20, 0xdb, 0x87, + 0x70, 0x88, 0x25, 0xa5, 0x52, 0x08, 0xeb, 0x21, 0x06, 0x85, 0x4b, 0xbb, 0x0c, 0x37, 0x18, 0x94, + 0xb8, 0x72, 0xb8, 0x11, 0xdc, 0x8c, 0x08, 0x85, 0x61, 0x8c, 0xd0, 0x26, 0x18, 0x86, 0x50, 0xba, + 0x03, 0xc6, 0xbb, 0x0b, 0x88, 0x93, 0x43, 0x32, 0x53, 0x42, 0x89, 0x92, 0x50, 0x6e, 0xd1, 0xb1, + 0xa0, 0x95, 0xdc, 0xf8, 0x46, 0x35, 0xdc, 0xd2, 0x8d, 0x5c, 0x01, 0x56, 0x84, 0x22, 0xe1, 0x49, + 0x24, 0x70, 0x75, 0xc2, 0xbf, 0xa8, 0x7a, 0xa0, 0xe3, 0x09, 0x2e, 0x15, 0x7e, 0x90, 0x84, 0xba, + 0xe7, 0xdc, 0x85, 0xc4, 0x01, 0x8b, 0xef, 0x0a, 0x71, 0xea, 0x38, 0x01, 0x1d, 0x63, 0x6b, 0xb1, + 0x22, 0x57, 0xa4, 0x75, 0x10, 0x85, 0xda, 0x77, 0xbd, 0x30, 0x24, 0xf4, 0x62, 0xe1, 0x15, 0x56, + 0xf4, 0x96, 0x86, 0xb4, 0x8b, 0x88, 0xc6, 0x87, 0xee, 0xc9, 0x89, 0x61, 0x69, 0xb9, 0x27, 0xa1, + 0xf3, 0x6a, 0x0c, 0x91, 0xf9, 0xf8, 0x78, 0x91, 0x82, 0xa0, 0x50, 0x9b, 0x97, 0x84, 0xdd, 0xc3, + 0x10, 0xc1, 0x3e, 0xf6, 0xf1, 0x9c, 0x64, 0x21, 0x00, 0xa6, 0x43, 0xc6, 0xe2, 0x05, 0xfe, 0xfc, + 0x4b, 0x63, 0x18, 0xe2, 0x02, 0x2d, 0x94, 0x24, 0x35, 0x77, 0xc0, 0x89, 0x0a, 0x53, 0x85, 0x9b, + 0x6e, 0xbf, 0x7b, 0xd1, 0xeb, 0x15, 0xd3, 0x91, 0x31, 0xb1, 0xa2, 0x44, 0x65, 0x08, 0x3f, 0x32, + 0xb3, 0xc1, 0xd6, 0x0a, 0x0d, 0x9f, 0x58, 0xec, 0xc4, 0xcd, 0x6c, 0x4d, 0x3d, 0x67, 0x13, 0x88, + 0x1d, 0x79, 0x4a, 0x21, 0xa2, 0x69, 0xc9, 0x93, 0x2f, 0x2c, 0x27, 0xf7, 0x1d, 0x0d, 0x52, 0x68, + 0x98, 0x98, 0xda, 0x66, 0x9a, 0x03, 0x2d, 0x9d, 0x6e, 0x0b, 0x7e, 0x0c, 0x29, 0x88, 0x67, 0x62, + 0x77, 0x0c, 0xcd, 0x26, 0x87, 0xa3, 0x39, 0xca, 0x7e, 0xc7, 0x0c, 0x06, 0x3b, 0x6b, 0x10, 0x07, + 0x9c, 0x97, 0x26, 0xf4, 0x72, 0x12, 0xcd, 0xc8, 0x8c, 0x76, 0x1b, 0x4c, 0x76, 0x73, 0xc0, 0x4b, + 0xc7, 0xa6, 0x10, 0x1f, 0x16, 0x17, 0x5a, 0x5e, 0xd9, 0x8c, 0xdd, 0x14, 0x33, 0x30, 0xa1, 0x15, + 0x86, 0x1b, 0x73, 0x7e, 0x9b, 0xf9, 0x28, 0x1f, 0x42, 0xc0, 0x56, 0x46, 0x18, 0x4a, 0x8c, 0xaf, + 0x2b, 0x98, 0x51, 0xf6, 0xa2, 0xeb, 0xca, 0x4f, 0xa2, 0x25, 0x52, 0xeb, 0xeb, 0xc3, 0x10, 0x38, + 0x29, 0xaf, 0x1b, 0xd1, 0xda, 0x73, 0xe9, 0x16, 0x83, 0xba, 0x69, 0x45, 0xf5, 0xd5, 0xd9, 0xa6, + 0x5f, 0x53, 0xa6, 0x54, 0x75, 0x36, 0x2c, 0xba, 0xbc, 0xbc, 0x2b, 0x95, 0x8a, 0x1a, 0x6e, 0x78, + 0x70, 0xda, 0xf6, 0x23, 0x82, 0xc3, 0xb7, 0x5e, 0x06, 0x7d, 0x88, 0x24, 0x66, 0xe8, 0x69, 0x92, + 0x87, 0xf1, 0x31, 0xb4, 0x83, 0x8c, 0xf3, 0x5f, 0x25, 0x0e, 0xff, 0x94, 0x14, 0x50, 0x8f, 0x0d, + 0xc1, 0xe1, 0x4f, 0x25, 0x7b, 0x2d, 0xf0, 0xdb, 0x56, 0xe2, 0x10, 0xc8, 0x10, 0xa3, 0x64, 0x33, + 0xb8, 0xd1, 0x42, 0x7f, 0xc2, 0x54, 0xe3, 0x38, 0x4d, 0x14, 0xb0, 0x80, 0x9c, 0xa8, 0x15, 0x79, + 0x4c, 0xdc, 0xf3, 0x4e, 0x26, 0x2b, 0x37, 0x17, 0x17, 0xf1, 0x9b, 0x87, 0x3a, 0xcf, 0x4e, 0xc9, + 0x50, 0x67, 0xb1, 0x9b, 0x23, 0x88, 0x29, 0x3d, 0x5d, 0xcc, 0xd9, 0x2b, 0xa9, 0xad, 0x08, 0xdb, + 0x05, 0x25, 0xf7, 0x73, 0x19, 0xcb, 0xdd, 0xe3, 0x65, 0xfd, 0x40, 0xed, 0x30, 0xb6, 0x01, 0x7b, + 0x82, 0x19, 0xbe, 0x39, 0x86, 0x8a, 0xa0, 0x05, 0xd0, 0x4a, 0x1e, 0xdf, 0x08, 0xa6, 0xe2, 0x62, + 0x8f, 0xb2, 0xd1, 0x89, 0x08, 0xe0, 0xbe, 0x36, 0x90, 0x86, 0x89, 0x20, 0xa2, 0x13, 0x37, 0xe7, + 0x78, 0x61, 0x05, 0x03, 0xba, 0xeb, 0xda, 0x90, 0x7c, 0x70, 0x4c, 0x47, 0x1e, 0x8d, 0x24, 0x21, + 0x37, 0x39, 0x9a, 0x26, 0x4b, 0x61, 0xcc, 0x4d, 0x31, 0x93, 0x0b, 0x81, 0x7b, 0x1a, 0x59, 0x26, + 0x5a, 0x63, 0x13, 0xf0, 0x32, 0xe3, 0x80, 0x11, 0x24, 0x85, 0x74, 0xc5, 0x21, 0x00, 0x32, 0x23, + 0xf3, 0xf2, 0x62, 0x8c, 0xa8, 0xea, 0xfd, 0xd9, 0x3e, 0xfd, 0x3d, 0x6f, 0x15, 0xe8, 0xa9, 0x27, + 0x3d, 0x89, 0x0d, 0x1d, 0x28, 0x28, 0x6a, 0x23, 0x8f, 0x18, 0xb0, 0x96, 0xcb, 0xd6, 0x24, 0xce, + 0x0e, 0x5f, 0x12, 0x8f, 0xe0, 0x86, 0x87, 0xdd, 0xc3, 0x14, 0x69, 0x44, 0xb2, 0x3f, 0x8b, 0xb2, + 0x7b, 0x85, 0x1b, 0xdc, 0x82, 0x98, 0xce, 0x90, 0x91, 0xdd, 0x64, 0xd5, 0x3b, 0x48, 0xfb, 0xb3, + 0xfe, 0xf4, 0x66, 0x3e, 0x0b, 0x26, 0xc4, 0xe7, 0x20, 0x5f, 0x70, 0xa7, 0x3f, 0xf4, 0x19, 0xfb, + 0x8e, 0xa9, 0x5f, 0xc1, 0x16, 0x62, 0x3c, 0x28, 0x10, 0x20, 0x81, 0x45, 0x1e, 0x05, 0xde, 0xa6, + 0x48, 0x94, 0xe3, 0x25, 0x5d, 0x7f, 0x72, 0x15, 0x0d, 0x62, 0x51, 0x68, 0xc6, 0x21, 0x93, 0x8f, + 0xb9, 0x7d, 0x8b, 0x8d, 0x21, 0x91, 0x28, 0xd6, 0x98, 0x79, 0xa1, 0xc5, 0x88, 0x86, 0x42, 0x9c, + 0x11, 0xc1, 0xb6, 0x40, 0xe2, 0x11, 0xd6, 0x22, 0x4e, 0x80, 0x09, 0xee, 0x0b, 0xd8, 0xd6, 0x60, + 0x88, 0x48, 0xdd, 0x24, 0x70, 0x18, 0x57, 0xf4, 0x33, 0xa8, 0x1e, 0xa6, 0xd0, 0xd8, 0xd8, 0x58, + 0x6d, 0xa3, 0x4b, 0xac, 0x4a, 0x88, 0x41, 0x45, 0x51, 0x0c, 0x8f, 0x1c, 0x22, 0x1f, 0xea, 0xed, + 0x56, 0x2b, 0x6a, 0x06, 0x35, 0x10, 0xda, 0xb1, 0x09, 0x3e, 0xc8, 0x31, 0xc9, 0xa6, 0x1f, 0xc2, + 0x44, 0x34, 0x7a, 0xe1, 0x34, 0xe8, 0x17, 0x3e, 0x11, 0xf4, 0x1f, 0xd9, 0x38, 0xc1, 0xc7, 0x2a, + 0x68, 0xc4, 0x2e, 0x61, 0x04, 0xf3, 0xa0, 0x4d, 0x3d, 0x7d, 0x70, 0x3b, 0x98, 0x91, 0x72, 0xa3, + 0x51, 0x49, 0xf1, 0x31, 0xd0, 0x9a, 0xc4, 0x8e, 0xcb, 0x90, 0xc6, 0x00, 0xa8, 0xaf, 0xc8, 0x90, + 0x37, 0xfa, 0x0a, 0x94, 0xe6, 0x1a, 0x77, 0x5f, 0x52, 0x0d, 0x2e, 0xab, 0x8e, 0x6b, 0xaf, 0xa6, + 0x08, 0x4a, 0xfb, 0xe4, 0x2e, 0xd3, 0x4d, 0x0c, 0x91, 0xf9, 0x49, 0x25, 0x16, 0xc6, 0x97, 0x09, + 0xf1, 0x88, 0xd9, 0x9d, 0xc1, 0x88, 0xd9, 0x92, 0x39, 0xbd, 0xc5, 0xba, 0xe3, 0x49, 0xd0, 0x78, + 0x50, 0x20, 0x65, 0xb6, 0x3f, 0xc0, 0x31, 0xc6, 0xb1, 0x49, 0x1e, 0x28, 0xfd, 0x9a, 0x71, 0xb1, + 0x0c, 0x8b, 0xae, 0x7f, 0xc3, 0xb7, 0x21, 0xb4, 0x19, 0x8e, 0xe6, 0x2a, 0x16, 0xc2, 0x9f, 0xd9, + 0x82, 0x23, 0x34, 0x14, 0x60, 0xe8, 0xb6, 0x65, 0x66, 0x24, 0xbb, 0xf3, 0x13, 0x52, 0x1b, 0x07, + 0x83, 0xd8, 0x4e, 0x9d, 0x83, 0xf6, 0x36, 0x31, 0x36, 0x31, 0xa1, 0x88, 0xb3, 0x78, 0x3c, 0x80, + 0x19, 0xab, 0x51, 0x5e, 0xac, 0x9e, 0x34, 0x64, 0xb4, 0x0f, 0x8b, 0xde, 0x7a, 0x22, 0x01, 0x5b, + 0x6c, 0xdb, 0x09, 0x89, 0x06, 0x62, 0xb9, 0x77, 0x9e, 0x8c, 0x40, 0x8a, 0x80, 0x06, 0x0e, 0xd7, + 0x4d, 0xab, 0x98, 0x8b, 0xe7, 0x01, 0xee, 0x93, 0x4c, 0xb2, 0x61, 0xf1, 0xfb, 0x71, 0xc6, 0xbf, + 0xdf, 0x0b, 0x57, 0xfb, 0x87, 0xc4, 0xc7, 0x68, 0x20, 0x38, 0x67, 0x07, 0x0d, 0x07, 0x0b, 0x08, + 0x8b, 0xba, 0x1e, 0xec, 0x5b, 0x78, 0x2a, 0x49, 0x0f, 0x0e, 0x90, 0x42, 0xe1, 0xdf, 0x27, 0x02, + 0x98, 0x8e, 0x1c, 0x7a, 0x71, 0x31, 0x8a, 0x4e, 0x21, 0x09, 0xe4, 0x7e, 0x88, 0xe3, 0x4b, 0xf6, + 0xb5, 0x7b, 0x40, 0xa9, 0x14, 0x33, 0xad, 0x34, 0x92, 0x43, 0x3b, 0x08, 0xc8, 0x5f, 0xa0, 0xef, + 0xc5, 0x89, 0x18, 0x79, 0x62, 0x3a, 0xa0, 0x79, 0xeb, 0x37, 0x8c, 0x86, 0xcd, 0xa2, 0xbc, 0x0c, + 0x90, 0x9a, 0x04, 0x6c, 0x88, 0xce, 0xf6, 0x0d, 0x8d, 0x08, 0x43, 0x99, 0x61, 0xb3, 0x23, 0x28, + 0x82, 0xdf, 0x8d, 0xa5, 0xa3, 0x89, 0x2b, 0x86, 0x21, 0x07, 0x0a, 0xf1, 0x8d, 0x76, 0x06, 0x83, + 0x60, 0x40, 0xff, 0xec, 0x40, 0xab, 0x22, 0xec, 0x39, 0xd3, 0x71, 0x2e, 0x0f, 0x0c, 0xcf, 0x29, + 0x7a, 0xec, 0xfa, 0x45, 0xed, 0xc8, 0x3a, 0xf4, 0x42, 0x47, 0x1c, 0xc0, 0xdd, 0xb0, 0x42, 0x2c, + 0xa7, 0x12, 0x37, 0x8d, 0x08, 0x80, 0x22, 0x97, 0x54, 0xce, 0x5e, 0x65, 0x6d, 0xe6, 0x0d, 0x26, + 0x1b, 0xfc, 0x0a, 0x5f, 0x53, 0xac, 0x61, 0x2d, 0x1b, 0x3e, 0x5f, 0xd4, 0xca, 0x8f, 0x01, 0x30, + 0x7c, 0x04, 0x68, 0xb8, 0x0c, 0x87, 0x57, 0x84, 0x36, 0x0d, 0x81, 0x8c, 0x1d, 0x8d, 0x35, 0x28, + 0xde, 0x50, 0x59, 0x47, 0xb7, 0x6e, 0xe1, 0x29, 0x60, 0x01, 0x9a, 0x5c, 0x0a, 0xa2, 0x5a, 0x22, + 0x62, 0x06, 0xa3, 0x74, 0x15, 0x2a, 0x16, 0xf6, 0xe9, 0x5a, 0x56, 0xbc, 0x27, 0x27, 0xb8, 0x1b, + 0x9c, 0xcb, 0x6e, 0x7f, 0x70, 0xbc, 0x72, 0x13, 0xfe, 0x9e, 0x9e, 0x89, 0x1d, 0xdd, 0x21, 0x51, + 0xdb, 0x71, 0xce, 0xf3, 0x68, 0xe9, 0xb0, 0x83, 0xd0, 0x2d, 0x90, 0x54, 0x2e, 0x91, 0x19, 0x47, + 0xcb, 0x86, 0x89, 0xa7, 0x3d, 0x98, 0x2e, 0xb4, 0x28, 0xbd, 0x33, 0xfe, 0x6e, 0x0a, 0x56, 0x2c, + 0x5e, 0x17, 0xc1, 0x17, 0x62, 0x17, 0x1d, 0x67, 0xeb, 0x9d, 0xa9, 0x74, 0x9d, 0x8d, 0xbc, 0xa4, + 0x6e, 0x6b, 0xbe, 0xfc, 0x6a, 0x8b, 0xdf, 0x2b, 0x00, 0xe5, 0x51, 0x5e, 0xd0, 0x56, 0x68, 0xe6, + 0xe7, 0x40, 0xfc, 0x6b, 0x51, 0xf7, 0xc7, 0xaa, 0x26, 0x5f, 0xe2, 0x6a, 0xe6, 0xf1, 0x0c, 0x47, + 0x48, 0x9c, 0x75, 0x10, 0xac, 0x2b, 0x08, 0xa2, 0x95, 0x99, 0xfc, 0x0d, 0x78, 0xd6, 0xfd, 0x02, + 0x45, 0x19, 0x0b, 0x47, 0x78, 0x8e, 0xa4, 0x3b, 0x85, 0x7f, 0x0e, 0xec, 0x62, 0x8c, 0x49, 0xca, + 0x4d, 0x70, 0x09, 0xb4, 0x98, 0x87, 0xac, 0x48, 0xe8, 0xa7, 0x06, 0x36, 0x8a, 0x1f, 0x49, 0x0d, + 0x71, 0x79, 0x93, 0xae, 0x12, 0x91, 0x15, 0xe9, 0xda, 0x44, 0xad, 0x38, 0x10, 0x4d, 0xa3, 0xf0, + 0xc2, 0xfd, 0xd0, 0xf8, 0x9c, 0x41, 0x4e, 0x2e, 0x28, 0x4e, 0xff, 0xaf, 0x35, 0x0c, 0x10, 0x82, + 0x01, 0x57, 0x08, 0x92, 0x75, 0x8c, 0x77, 0x12, 0x3b, 0x88, 0x64, 0x34, 0x4d, 0x0a, 0x0a, 0x84, + 0x40, 0xc6, 0xf8, 0x1d, 0xc4, 0x48, 0x65, 0xe4, 0x11, 0x5c, 0x3a, 0xce, 0x0c, 0x6f, 0xe6, 0x14, + 0x25, 0x5a, 0x5c, 0x00, 0xaf, 0x12, 0x87, 0x5b, 0x89, 0x48, 0xfa, 0x42, 0x12, 0xe0, 0x33, 0xeb, + 0x9e, 0x80, 0x91, 0x58, 0x25, 0x40, 0xb1, 0x1c, 0xef, 0xa3, 0x22, 0x83, 0x11, 0x70, 0xdd, 0xe7, + 0x04, 0xda, 0xeb, 0x94, 0x52, 0x90, 0xcd, 0xc8, 0x13, 0x01, 0x2e, 0xdb, 0x13, 0x15, 0xe7, 0xab, + 0x5c, 0x25, 0xdc, 0x89, 0x56, 0x31, 0x21, 0x02, 0xf7, 0x24, 0xd6, 0xd2, 0xf8, 0xc3, 0x08, 0x25, + 0x76, 0x71, 0x20, 0xdd, 0x42, 0x84, 0x72, 0xaa, 0x71, 0x63, 0x4b, 0x31, 0xe7, 0xfe, 0x83, 0x44, + 0xf5, 0x0b, 0x19, 0x1a, 0x71, 0x0d, 0x86, 0x8c, 0x40, 0x63, 0x66, 0x45, 0xe4, 0x4a, 0x19, 0x96, + 0x36, 0x22, 0x18, 0x12, 0x12, 0x45, 0x01, 0xc6, 0xb1, 0x67, 0x89, 0x8d, 0x04, 0xa5, 0x25, 0x37, + 0x11, 0xe2, 0x86, 0x30, 0xdd, 0x44, 0xdc, 0x35, 0xcd, 0xf7, 0x3e, 0xc8, 0xfc, 0x1d, 0xdc, 0x26, + 0xe1, 0xb4, 0xaf, 0x0c, 0x29, 0x20, 0xe2, 0xd7, 0xa5, 0x58, 0x45, 0x87, 0x3d, 0x32, 0x82, 0x66, + 0x4f, 0x4c, 0x2a, 0x90, 0x17, 0x2d, 0x41, 0x3b, 0x84, 0x07, 0x18, 0xed, 0x8b, 0xb0, 0x17, 0xd0, + 0x4d, 0x43, 0x84, 0x56, 0x8f, 0x56, 0x61, 0x02, 0x3b, 0x39, 0xb8, 0x74, 0x0e, 0x4b, 0x75, 0x0d, + 0x9d, 0x07, 0xb4, 0x15, 0x54, 0xc7, 0x9c, 0x50, 0x64, 0xb8, 0x80, 0xf3, 0x4b, 0xc8, 0xcf, 0x86, + 0xa9, 0x1b, 0x84, 0x06, 0xd4, 0xe8, 0xb5, 0x06, 0x03, 0x21, 0x98, 0xd8, 0xca, 0xfa, 0x2e, 0xa0, + 0x18, 0xbc, 0xe7, 0x2d, 0xf3, 0x2b, 0xf4, 0x0b, 0xae, 0x2f, 0x07, 0x9a, 0x59, 0x0e, 0x3e, 0x1b, + 0x33, 0xe2, 0xec, 0x7b, 0xdd, 0x99, 0xf8, 0x99, 0x77, 0x31, 0x43, 0xc5, 0x05, 0x1d, 0x22, 0x35, + 0xdb, 0x66, 0xd4, 0x9f, 0x14, 0x98, 0x18, 0xa0, 0x20, 0x40, 0x34, 0x41, 0x57, 0x1f, 0x89, 0x96, + 0xe3, 0x5f, 0x31, 0xcc, 0x41, 0x27, 0xa7, 0x11, 0x23, 0xd0, 0xe5, 0x97, 0x0d, 0x2e, 0x3c, 0xa9, + 0x4f, 0x90, 0x0c, 0xf1, 0xf1, 0x95, 0x2e, 0x26, 0x0e, 0xa1, 0x3c, 0x63, 0xed, 0xba, 0x55, 0x67, + 0xa2, 0x71, 0x85, 0x74, 0x44, 0x97, 0x86, 0xfd, 0xe5, 0x64, 0xe6, 0xd6, 0x7f, 0xed, 0xad, 0xe3, + 0x42, 0x5c, 0xef, 0xe7, 0xbf, 0xba, 0x4c, 0xdc, 0x92, 0x2a, 0xb3, 0x4d, 0x4d, 0xff, 0xef, 0xe3, + 0x79, 0x85, 0x0b, 0x2e, 0x67, 0x06, 0xc6, 0x4a, 0x21, 0xb1, 0x12, 0x83, 0x8b, 0x9e, 0xb4, 0x3a, + 0x10, 0x16, 0x31, 0xde, 0x31, 0x6b, 0x5c, 0x63, 0xc7, 0x78, 0xbb, 0x2e, 0xe7, 0x55, 0x7f, 0xe2, + 0x4b, 0x2c, 0x25, 0xff, 0x67, 0xba, 0x17, 0x1e, 0x9c, 0xe1, 0x08, 0x6f, 0x10, 0x6f, 0xa6, 0xfe, + 0x99, 0x3d, 0x16, 0xff, 0xf7, 0x7f, 0x96, 0x47, 0xb1, 0x91, 0xae, 0xf5, 0xdc, 0x82, 0x19, 0x2e, + 0xee, 0x05, 0x2e, 0xa4, 0xed, 0x2d, 0x21, 0xa1, 0x85, 0x7d, 0xc8, 0x99, 0xa1, 0xa2, 0x55, 0x4e, + 0xa8, 0xed, 0x10, 0x81, 0x7e, 0x26, 0x4a, 0x68, 0x93, 0xb8, 0x32, 0x7c, 0x0b, 0x12, 0xf0, 0x71, + 0xa2, 0x26, 0xfe, 0xd4, 0x65, 0x01, 0x79, 0x92, 0x98, 0xcd, 0xcf, 0x8c, 0x7c, 0x38, 0x81, 0x1e, + 0x3c, 0xdf, 0x37, 0x1b, 0x42, 0x12, 0x4b, 0x75, 0xa4, 0x97, 0x72, 0x7f, 0x7b, 0x0c, 0x5d, 0xea, + 0xa8, 0x91, 0xc6, 0x3f, 0xf5, 0x91, 0xa8, 0x3b, 0xb9, 0x00, 0x27, 0x2c, 0x2c, 0x85, 0xa4, 0x91, + 0x97, 0xe1, 0x4b, 0xcd, 0x24, 0x42, 0x21, 0x3d, 0x16, 0x0a, 0x3a, 0x16, 0xd2, 0x9d, 0xcc, 0x83, + 0xf7, 0x90, 0x63, 0x16, 0xad, 0xcc, 0xd7, 0xe4, 0x3c, 0xdd, 0x28, 0x58, 0x23, 0x59, 0x64, 0xb1, + 0x9c, 0xf2, 0x9e, 0xcf, 0x57, 0x40, 0x12, 0x19, 0xc0, 0x38, 0x1e, 0xb0, 0xe6, 0x39, 0xf0, 0x64, + 0x19, 0x4c, 0x63, 0x27, 0x74, 0xa6, 0x32, 0x84, 0xdb, 0x88, 0xb6, 0x65, 0x33, 0x21, 0x2e, 0x83, + 0x58, 0x9d, 0xe8, 0x7d, 0xd9, 0xc1, 0xdf, 0x3b, 0x10, 0xa3, 0x7d, 0x73, 0xd1, 0x39, 0xf3, 0xd7, + 0x62, 0xdd, 0xdd, 0xd1, 0x91, 0x10, 0xdd, 0xd9, 0x97, 0xb1, 0x06, 0xeb, 0xcf, 0x47, 0x7f, 0x3f, + 0xc0, 0x44, 0x09, 0x76, 0x4a, 0xe0, 0x9d, 0x79, 0xba, 0x50, 0x65, 0xde, 0xec, 0xe2, 0x25, 0xa0, + 0xde, 0x2c, 0x89, 0xc6, 0x25, 0x59, 0xd8, 0xbe, 0xb4, 0xa1, 0x89, 0x14, 0xf7, 0xd7, 0x84, 0x8b, + 0x3b, 0xf2, 0xe2, 0x49, 0x28, 0x8a, 0x43, 0x48, 0x16, 0x2d, 0x0c, 0xfa, 0xe0, 0x44, 0x8f, 0x5a, + 0xba, 0xd0, 0x9b, 0x80, 0x98, 0xaf, 0xd6, 0xae, 0x10, 0x56, 0x68, 0x3f, 0x74, 0xb3, 0xc7, 0x05, + 0xd8, 0x97, 0x66, 0x3e, 0x2f, 0xf6, 0xee, 0xa2, 0x2d, 0x06, 0x8e, 0xd9, 0x22, 0x4d, 0x3f, 0xec, + 0xf8, 0x13, 0x1c, 0x4d, 0x1e, 0x64, 0x26, 0xd8, 0xd6, 0x32, 0x22, 0x10, 0xcd, 0x2f, 0x11, 0x00, + 0x29, 0x60, 0x42, 0x9d, 0xc1, 0x03, 0xc6, 0x15, 0x89, 0x89, 0xf7, 0x20, 0x66, 0xd9, 0xcc, 0x09, + 0x8d, 0xbe, 0xdd, 0xc8, 0xb3, 0xef, 0xbe, 0xee, 0x0f, 0x13, 0x64, 0x0b, 0xd6, 0x82, 0x8a, 0x72, + 0xf2, 0x74, 0x48, 0x82, 0x39, 0xa4, 0x84, 0x34, 0x6a, 0x21, 0x6a, 0x68, 0x57, 0xb2, 0x41, 0xcc, + 0x64, 0x85, 0x1c, 0x81, 0xed, 0x94, 0x57, 0x63, 0x5e, 0x53, 0x24, 0x37, 0x67, 0xf4, 0x27, 0x0d, + 0x71, 0xdb, 0xee, 0xa1, 0x86, 0x26, 0xb0, 0xbf, 0x8b, 0x88, 0xf5, 0x8e, 0x21, 0x24, 0x49, 0xaf, + 0x2c, 0x4e, 0x0d, 0x10, 0xee, 0x85, 0x93, 0xde, 0xf5, 0xfa, 0xca, 0x31, 0xef, 0x65, 0xcd, 0x9f, + 0xc8, 0xcd, 0x06, 0x26, 0xf8, 0xa1, 0x68, 0x12, 0x26, 0xf3, 0x5c, 0x4c, 0xc2, 0xaa, 0x4e, 0x2f, + 0x7f, 0x25, 0x4c, 0x98, 0x17, 0x0e, 0xe6, 0x11, 0x8e, 0x30, 0x97, 0x56, 0x77, 0x6e, 0x14, 0x18, + 0xcc, 0x40, 0x90, 0x59, 0x0d, 0x12, 0x33, 0xf4, 0x3a, 0x5d, 0x9f, 0x50, 0x5e, 0xbf, 0x84, 0xa0, + 0xa7, 0x35, 0x71, 0x28, 0xb8, 0x83, 0xad, 0x2b, 0x67, 0x10, 0x87, 0x25, 0xca, 0x7f, 0x4c, 0xf3, + 0x15, 0xe3, 0xec, 0x7e, 0x38, 0x5a, 0xfa, 0xb7, 0xe8, 0xa4, 0x6d, 0x89, 0x48, 0x7f, 0x00, 0x18, + 0x64, 0x48, 0xb8, 0x41, 0xe4, 0x6f, 0xe7, 0xc2, 0x84, 0x7e, 0xce, 0x50, 0x6d, 0x85, 0x63, 0x05, + 0xfa, 0x86, 0x05, 0xc0, 0xc8, 0x05, 0x65, 0xb6, 0x2c, 0xcb, 0xc4, 0x39, 0xd2, 0x09, 0x94, 0xe9, + 0x3a, 0xe7, 0xc5, 0xeb, 0x11, 0x24, 0x42, 0x85, 0x0e, 0x6b, 0xa6, 0xa6, 0x08, 0xcd, 0x77, 0xbb, + 0x34, 0x89, 0x1c, 0x4b, 0xa0, 0xd0, 0x03, 0xf8, 0x08, 0x79, 0xf1, 0xf9, 0x1d, 0x8d, 0x30, 0x50, + 0x70, 0x02, 0x30, 0x36, 0xc1, 0x02, 0x7d, 0x36, 0x40, 0x8e, 0x85, 0x55, 0x4e, 0xb9, 0x47, 0x39, + 0x13, 0x13, 0x19, 0x43, 0x0c, 0x10, 0xf8, 0xd0, 0xca, 0x0c, 0xea, 0xc2, 0x33, 0x10, 0x65, 0x07, + 0xf0, 0x49, 0x10, 0xb1, 0x3b, 0x52, 0x7d, 0xd2, 0x71, 0x0f, 0xb8, 0xc5, 0xdc, 0xe2, 0x3f, 0x14, + 0x61, 0xfb, 0x2c, 0x4c, 0x7a, 0x4b, 0x14, 0xe0, 0x99, 0xc7, 0xde, 0xee, 0x75, 0x3b, 0xe9, 0x96, + 0x06, 0x5f, 0xc1, 0x88, 0xa0, 0x5c, 0x13, 0x45, 0x28, 0x94, 0x49, 0x03, 0x62, 0x0c, 0x18, 0x86, + 0x74, 0xd9, 0x95, 0x4a, 0xd0, 0xdc, 0xe3, 0x48, 0xb4, 0x08, 0xd8, 0x86, 0xcf, 0x42, 0x63, 0x07, + 0x09, 0x35, 0x73, 0x68, 0x55, 0x19, 0x9a, 0xfc, 0x34, 0x42, 0xe5, 0x1f, 0x0b, 0x59, 0xae, 0x49, + 0xae, 0x38, 0xf1, 0x75, 0x59, 0x05, 0xc4, 0xbe, 0x70, 0x08, 0xb1, 0x53, 0x15, 0xc4, 0x15, 0x1a, + 0x36, 0xba, 0xa8, 0x49, 0x9a, 0xd0, 0xaf, 0xa4, 0x01, 0x61, 0x3e, 0x78, 0x65, 0xd1, 0x99, 0x00, + 0xb7, 0x14, 0xef, 0xdf, 0x6c, 0x24, 0x30, 0x98, 0x6c, 0xd3, 0x36, 0x0d, 0x53, 0xcf, 0xfc, 0xdf, + 0x18, 0x2c, 0xe1, 0xc7, 0xd2, 0x09, 0x1c, 0x60, 0x33, 0x66, 0x40, 0x53, 0xec, 0xe1, 0xb0, 0xc0, + 0xc1, 0xae, 0x65, 0xbd, 0x20, 0x9e, 0x88, 0x38, 0xda, 0xd6, 0x26, 0xf8, 0x4c, 0x92, 0x3b, 0xe8, + 0xc5, 0xc2, 0xca, 0x0d, 0xdb, 0x48, 0xf1, 0xac, 0x44, 0x62, 0xcc, 0x56, 0xa8, 0x33, 0x80, 0x88, + 0x98, 0x87, 0xde, 0x34, 0xe2, 0x7d, 0x99, 0x22, 0x15, 0xd2, 0xb1, 0x8b, 0x0b, 0xea, 0x4b, 0xcd, + 0x89, 0xde, 0xce, 0x08, 0x1e, 0x2e, 0x32, 0x04, 0x24, 0xe1, 0xb5, 0x96, 0x18, 0x89, 0x88, 0x9f, + 0x2e, 0x1a, 0x8f, 0x09, 0xe2, 0x64, 0x93, 0xc4, 0x34, 0x29, 0x45, 0xd9, 0x3e, 0xbf, 0x01, 0x25, + 0xe4, 0x24, 0x43, 0x43, 0x16, 0x45, 0xbd, 0xc4, 0x84, 0x34, 0xdd, 0xe8, 0x7d, 0xd0, 0xd0, 0xe5, + 0x37, 0x25, 0xfc, 0xb3, 0x1d, 0xe3, 0x73, 0x10, 0x61, 0xe1, 0x31, 0xcb, 0x3a, 0x54, 0x00, 0x53, + 0x1f, 0xb1, 0x36, 0x42, 0x16, 0x7c, 0xf7, 0x69, 0x1b, 0xbe, 0xbf, 0x18, 0x00, 0x98, 0x05, 0xd9, + 0x80, 0x40, 0x7f, 0x58, 0x39, 0xd6, 0x40, 0xf4, 0x78, 0x90, 0x34, 0xae, 0x80, 0x0b, 0x91, 0x41, + 0xa9, 0xac, 0x03, 0xdf, 0xc7, 0x03, 0x09, 0x89, 0xde, 0xb5, 0x4a, 0x66, 0x6c, 0x1c, 0x9a, 0x7b, + 0xe1, 0x1f, 0x28, 0xbe, 0xdf, 0x09, 0x00, 0x2e, 0x09, 0xe0, 0xfc, 0xd2, 0x0c, 0xe4, 0x00, 0x4b, + 0xe2, 0x12, 0xe0, 0xa1, 0x10, 0x05, 0xc8, 0xde, 0x09, 0xab, 0x3c, 0x39, 0x3d, 0x42, 0xfe, 0x4c, + 0x76, 0x02, 0xb1, 0xd4, 0x82, 0x20, 0x03, 0x0c, 0x5e, 0x04, 0x0e, 0x0b, 0x0d, 0x3c, 0xcb, 0x2c, + 0xfa, 0x50, 0x88, 0xe4, 0x24, 0x08, 0x84, 0x4c, 0x67, 0x3f, 0x63, 0xf7, 0x65, 0x97, 0xb0, 0x32, + 0x45, 0x90, 0x55, 0x06, 0x08, 0x6f, 0xdf, 0x5d, 0x6a, 0x58, 0xc0, 0x9a, 0x61, 0x41, 0xad, 0x74, + 0xa0, 0xa5, 0x71, 0x47, 0x21, 0x34, 0x3c, 0x31, 0x36, 0x10, 0x9a, 0x9a, 0xcc, 0x06, 0xae, 0xcf, + 0x94, 0x82, 0x35, 0xd9, 0x69, 0xf0, 0x28, 0x8b, 0xfd, 0xaa, 0x66, 0x95, 0x90, 0x2c, 0x9f, 0xb3, + 0xcf, 0x62, 0x1b, 0x86, 0x33, 0xca, 0x5b, 0x8e, 0x05, 0x9b, 0x91, 0xda, 0x1a, 0x37, 0xa0, 0xcc, + 0xab, 0x06, 0x29, 0x4a, 0x51, 0x16, 0x05, 0xc6, 0x00, 0xc1, 0xc0, 0x44, 0xb1, 0xe3, 0x70, 0x5e, + 0x85, 0xa3, 0xb0, 0x07, 0x10, 0xc8, 0x0e, 0x98, 0xf5, 0xf3, 0x86, 0x31, 0x50, 0x26, 0x48, 0x89, + 0x80, 0x25, 0xe0, 0x26, 0x5d, 0x89, 0x72, 0x5e, 0xd1, 0x94, 0xac, 0xb0, 0x49, 0x54, 0xef, 0xec, + 0x12, 0xa0, 0x1a, 0x66, 0xe4, 0x86, 0x93, 0x85, 0xec, 0x11, 0x7b, 0x86, 0x9a, 0x02, 0x81, 0x97, + 0xfd, 0x3a, 0x0b, 0x86, 0x95, 0xcb, 0xb9, 0x5e, 0xd1, 0x2b, 0xd4, 0xb7, 0x7d, 0x25, 0xaa, 0x48, + 0x55, 0x5c, 0xee, 0x69, 0xaa, 0xfd, 0xf2, 0xe3, 0x6c, 0xc9, 0x13, 0xdb, 0x1c, 0x45, 0x17, 0x8c, + 0xd8, 0x27, 0x93, 0xda, 0xa2, 0x1a, 0xa8, 0x99, 0x68, 0xe3, 0xd8, 0xd2, 0x4c, 0xe3, 0x48, 0x3b, + 0x6a, 0x55, 0x04, 0x71, 0xeb, 0x7e, 0xd0, 0x2a, 0x71, 0x68, 0xbf, 0x82, 0x43, 0xb8, 0x5a, 0xd8, + 0x91, 0x02, 0xba, 0x82, 0x16, 0xfc, 0x17, 0x75, 0xa1, 0xa4, 0xc4, 0x21, 0x1b, 0x08, 0x93, 0x73, + 0xa1, 0x9c, 0x82, 0xd6, 0x3b, 0x88, 0xed, 0x0e, 0x14, 0xc1, 0x0a, 0xed, 0x79, 0x5c, 0x15, 0x10, + 0x96, 0xc0, 0x87, 0xbf, 0xec, 0xd2, 0x92, 0x4d, 0xd1, 0xec, 0x73, 0x12, 0x78, 0x21, 0xae, 0x2d, + 0x8c, 0x48, 0x86, 0x26, 0x83, 0x47, 0x71, 0x13, 0x13, 0x50, 0x60, 0x05, 0x83, 0x55, 0x4d, 0xcf, + 0xb7, 0x2e, 0xe4, 0xc8, 0xb8, 0x8e, 0x41, 0x18, 0xda, 0x1c, 0x85, 0x4e, 0x62, 0x28, 0x6d, 0x63, + 0x1b, 0x64, 0xd6, 0x77, 0x55, 0xb0, 0x72, 0x3b, 0x7c, 0xee, 0x60, 0xce, 0x29, 0x2e, 0xde, 0x4b, + 0x33, 0xf7, 0x13, 0x38, 0x93, 0xf9, 0x66, 0x01, 0xaa, 0xbf, 0x51, 0x36, 0x0a, 0x19, 0x41, 0x38, + 0xb8, 0x67, 0x1f, 0x14, 0x62, 0x24, 0x3a, 0x2c, 0x43, 0x9c, 0x43, 0x22, 0xe1, 0xe2, 0x46, 0xe8, + 0xbd, 0x60, 0xf2, 0x5a, 0xb9, 0x48, 0xfb, 0xf1, 0x8d, 0xfa, 0x71, 0x1d, 0x19, 0x03, 0x0c, 0x43, + 0x17, 0x39, 0xbb, 0xd0, 0x22, 0x28, 0x19, 0x06, 0x81, 0xe3, 0x02, 0x92, 0x6e, 0x29, 0x8d, 0x77, + 0xe8, 0x15, 0x25, 0x3b, 0x52, 0x1e, 0x34, 0x50, 0x9d, 0xd8, 0xf0, 0x65, 0x3c, 0x02, 0x82, 0x0b, + 0xfa, 0x86, 0xad, 0xd2, 0x7b, 0x3d, 0x3b, 0x8a, 0x2c, 0xf1, 0xae, 0x4b, 0xe5, 0x03, 0xbe, 0xf2, + 0x46, 0xdb, 0x7c, 0xd0, 0xcd, 0x89, 0x12, 0x83, 0x50, 0x52, 0x13, 0xa0, 0x0a, 0x2d, 0x82, 0x25, + 0xa3, 0x5f, 0xfc, 0x77, 0x46, 0x4d, 0xcc, 0xe9, 0x22, 0x11, 0x9f, 0xd9, 0x15, 0xde, 0x64, 0x77, + 0xb9, 0x89, 0x9e, 0x6f, 0xba, 0x56, 0xe8, 0xfe, 0x99, 0x87, 0x7e, 0x93, 0xbb, 0xc0, 0xf2, 0x98, + 0xbd, 0xa0, 0x97, 0x05, 0x2c, 0xb8, 0x90, 0xb2, 0x34, 0x0a, 0x24, 0x4a, 0x18, 0x88, 0x77, 0x15, + 0xfe, 0xae, 0x80, 0xbe, 0xf8, 0x44, 0x03, 0xe9, 0x42, 0x67, 0xe0, 0xaf, 0x01, 0x74, 0x63, 0x68, + 0x26, 0x46, 0x95, 0xcd, 0x20, 0x2e, 0x0c, 0xa5, 0x67, 0x96, 0xf4, 0xab, 0x71, 0xa9, 0xdf, 0x34, + 0x02, 0x68, 0x3b, 0x8f, 0x0e, 0x04, 0x4c, 0x11, 0x33, 0xdc, 0xc8, 0xa3, 0x41, 0xa1, 0x45, 0x41, + 0xe6, 0x94, 0xd3, 0x0b, 0x95, 0x90, 0x7e, 0x89, 0xf6, 0xe3, 0x6a, 0x56, 0x94, 0x0f, 0xda, 0x84, + 0xd0, 0xa6, 0xae, 0x59, 0xb8, 0x2c, 0x2d, 0xf5, 0xd3, 0x21, 0xd2, 0xff, 0xd6, 0x31, 0x31, 0x64, + 0x28, 0x3c, 0xe9, 0x6f, 0x4b, 0x9f, 0x0a, 0xc0, 0x82, 0x40, 0x8b, 0x0a, 0xd2, 0x91, 0x7e, 0xde, + 0xf8, 0x14, 0xd0, 0xff, 0x87, 0xb6, 0x3e, 0x90, 0x2a, 0x78, 0xd3, 0x7d, 0x98, 0x64, 0x59, 0x42, + 0x77, 0xcc, 0x49, 0xe8, 0xb1, 0x0c, 0x00, 0xfc, 0xf8, 0xad, 0x08, 0xa7, 0x6f, 0x9f, 0xbe, 0x84, + 0x8a, 0x36, 0x87, 0x8f, 0x73, 0xff, 0xfd, 0x39, 0xca, 0x09, 0x26, 0x8f, 0xff, 0x6f, 0xfd, 0xe9, + 0x40, 0x42, 0x9e, 0x9b, 0x00 +}; + +class VaapiDecoderVC1Test + : public FactoryTest { +protected: + /* invoked by gtest before the test */ + virtual void SetUp() + { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() + { + return; + } +}; + +#define VAAPIDECODER_VC1_TEST(name) \ + TEST_F(VaapiDecoderVC1Test, name) + +VAAPIDECODER_VC1_TEST(Factory) +{ + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_VC1); + + doFactoryTest(mimeTypes); +} + +VAAPIDECODER_VC1_TEST(Decode_Simple) +{ + VaapiDecoderVC1 decoder; + VideoConfigBuffer configBuffer; + VideoDecodeBuffer buffer; + + memset(&configBuffer, 0, sizeof(VideoConfigBuffer)); + + configBuffer.data = (uint8_t*)new uint8_t[5]; + configBuffer.data[0] = 0x4e; + configBuffer.data[1] = 0x39; + configBuffer.data[2] = 0x0a; + configBuffer.data[3] = 0x81; + configBuffer.data[4] = 0x00; + configBuffer.size = 5; + configBuffer.width = 320; + configBuffer.height = 240; + + buffer.data = const_cast(g_SimpleVC1.data()); + buffer.size = g_SimpleVC1.size(); + buffer.timeStamp = 0; + ASSERT_EQ(YAMI_SUCCESS, decoder.start(&configBuffer)); + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(&buffer)); + /* pass a NULL buffer to flush output */ + ASSERT_EQ(YAMI_SUCCESS, decoder.decode(NULL)); + + EXPECT_TRUE(bool(decoder.getOutput())); + delete[] configBuffer.data; +} +} diff --git a/decoder/vaapidecoder_vp8.cpp b/decoder/vaapidecoder_vp8.cpp new file mode 100644 index 0000000..9ebf4c3 --- /dev/null +++ b/decoder/vaapidecoder_vp8.cpp @@ -0,0 +1,592 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "common/log.h" +#include "vaapidecoder_vp8.h" +#include + +using ::YamiParser::Vp8Parser; +using ::YamiParser::Vp8FrameHeader; +using ::YamiParser::Vp8ParserResult; +using ::YamiParser::Vp8SegmentationHeader; + +namespace YamiMediaCodec{ +typedef VaapiDecoderVP8::PicturePtr PicturePtr; + +// the following parameter apply to Intra-Predicted Macroblocks, +// $11.2 $11.4: key frame default probs +static const uint8_t keyFrameYModeProbs[4] = { 145, 156, 163, 128 }; +static const uint8_t keyFrameUVModeProbs[3] = { 142, 114, 183 }; + +// $16.1: non-key frame default probs +static const uint8_t nonKeyFrameDefaultYModeProbs[4] = { 112, 86, 140, 37 }; +static const uint8_t nonKeyFrameDefaultUVModeProbs[3] = { 162, 101, 204 }; + +static const uint32_t surfaceNumVP8 = 3; + +static YamiStatus getStatus(Vp8ParserResult result) +{ + YamiStatus status; + + switch (result) { + case YamiParser::VP8_PARSER_OK: + status = YAMI_SUCCESS; + break; + default: + /* we should return no faltal error for parser failed */ + status = YAMI_DECODE_INVALID_DATA; + break; + } + return status; +} + +///////////////////////////////////////////////////// + +YamiStatus VaapiDecoderVP8::ensureContext() +{ + if (m_frameHdr.key_frame != Vp8FrameHeader::KEYFRAME) { + return YAMI_SUCCESS; + } + + /* + - for VP8 spec, there are two resolution, + 1. one is frame resolution, it may (or may not) change upon key frame: m_frameWidth/m_frameHeight. + 2. another is stream resolution, it is the max resolution of frames. (for example, resolution in ivf header). + (represented by m_configBuffer width/height below) + - for codec, there are two set of resolution, + 1. one is in m_configBuffer: width/height and graphicsBufferWidth/graphicsBufferHeight + it is set from upper layer to config codec + 2. another is m_videoFormatInfo: width/height and surfaceWidth/surfaceHeight + it is reported to upper layer for configured codec + - solution here: + 1. vp8 decoder only update m_configBuffer, since VaapiDecoderBase::start() will copy + m_configBuffer resolution to m_videoFormatInfo. (todo, is it ok to mark m_videoFormatInfo as private?) + 2. we use the resolution in m_configBuffer as stream resolution of VP8 spec. + so, m_confiBuffer width/height may update upon key frame + 3. we don't care m_configBuffer graphicBufferWidth/graphicBufferHeight for now, + since that is used for android + */ + + m_frameWidth = m_frameHdr.width; + m_frameHeight = m_frameHdr.height; + if (setFormat(m_frameWidth, m_frameHeight, m_frameWidth, m_frameHeight, surfaceNumVP8)) { + return YAMI_DECODE_FORMAT_CHANGE; + } + return ensureProfile(VAProfileVP8Version0_3); +} + +bool VaapiDecoderVP8::fillSliceParam(VASliceParameterBufferVP8* sliceParam) +{ + /* Fill in VASliceParameterBufferVP8 */ + sliceParam->slice_data_offset = 0; //uncompressed data chunk is parsed + sliceParam->macroblock_offset = m_frameHdr.macroblock_bit_offset; // m_frameHdr.header_size; + sliceParam->num_of_partitions = m_frameHdr.num_of_dct_partitions + 1; + sliceParam->partition_size[0] = + m_frameHdr.first_part_size - ((sliceParam->macroblock_offset + 7) >> 3); + for (int32_t i = 1; i < sliceParam->num_of_partitions; i++) + sliceParam->partition_size[i] = m_frameHdr.dct_partition_sizes[i - 1]; + return TRUE; +} + +bool VaapiDecoderVP8::fillPictureParam(const PicturePtr& picture) +{ + uint32_t i; + VAPictureParameterBufferVP8 *picParam = NULL; + + if (!picture->editPicture(picParam)) + return false; + + /* Fill in VAPictureParameterBufferVP8 */ + Vp8SegmentationHeader *seg = &m_frameHdr.segmentation_hdr; + + /* Fill in VAPictureParameterBufferVP8 */ + if (m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) { + if (m_frameHdr.horizontal_scale || m_frameHdr.vertical_scale) + WARNING + ("horizontal_scale or vertical_scale in VP8 isn't supported yet"); + } + + picParam->frame_width = m_frameWidth; + picParam->frame_height = m_frameHeight; + if (m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) { + picParam->last_ref_frame = VA_INVALID_SURFACE; + picParam->golden_ref_frame = VA_INVALID_SURFACE; + picParam->alt_ref_frame = VA_INVALID_SURFACE; + } else { + picParam->last_ref_frame = + m_lastPicture ? m_lastPicture->getSurfaceID() : + VA_INVALID_SURFACE; + picParam->golden_ref_frame = + m_goldenRefPicture ? m_goldenRefPicture->getSurfaceID() : + VA_INVALID_SURFACE; + picParam->alt_ref_frame = + m_altRefPicture ? m_altRefPicture->getSurfaceID() : + VA_INVALID_SURFACE; + } + picParam->out_of_loop_frame = VA_INVALID_SURFACE; // not used currently + + picParam->pic_fields.bits.key_frame = (m_frameHdr.key_frame != Vp8FrameHeader::KEYFRAME); + picParam->pic_fields.bits.version = m_frameHdr.version; + picParam->pic_fields.bits.segmentation_enabled = + seg->segmentation_enabled; + picParam->pic_fields.bits.update_mb_segmentation_map = + seg->update_mb_segmentation_map; + picParam->pic_fields.bits.update_segment_feature_data = + seg->update_segment_feature_data; + picParam->pic_fields.bits.filter_type = m_frameHdr.loopfilter_hdr.type; + picParam->pic_fields.bits.sharpness_level = m_frameHdr.loopfilter_hdr.sharpness_level; + picParam->pic_fields.bits.loop_filter_adj_enable = + m_frameHdr.loopfilter_hdr.loop_filter_adj_enable; + picParam->pic_fields.bits.mode_ref_lf_delta_update = + m_frameHdr.loopfilter_hdr.mode_ref_lf_delta_update; + picParam->pic_fields.bits.sign_bias_golden = + m_frameHdr.sign_bias_golden; + picParam->pic_fields.bits.sign_bias_alternate = + m_frameHdr.sign_bias_alternate; + picParam->pic_fields.bits.mb_no_coeff_skip = + m_frameHdr.mb_no_skip_coeff; + + //using arraysize as the real limit + for (i = 0; i < arraysize(seg->segment_prob); i++) { + picParam->mb_segment_tree_probs[i] = seg->segment_prob[i]; + } + + for (i = 0; i < arraysize(seg->lf_update_value); ++i) { + if (seg->segmentation_enabled) { + if (seg->segment_feature_mode != + Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE){ + seg->lf_update_value[i] += + m_frameHdr.loopfilter_hdr.level; + } + picParam->loop_filter_level[i] = CLAMP(seg->lf_update_value[i], 0, 63); + } else + picParam->loop_filter_level[i] = CLAMP(m_frameHdr.loopfilter_hdr.level, 0, 63); + + picParam->loop_filter_deltas_ref_frame[i] = + m_frameHdr.loopfilter_hdr.ref_frame_delta[i]; + picParam->loop_filter_deltas_mode[i] = + m_frameHdr.loopfilter_hdr.mb_mode_delta[i]; + } + + picParam->pic_fields.bits.loop_filter_disable = + m_frameHdr.loopfilter_hdr.level == 0; + + picParam->prob_skip_false = m_frameHdr.prob_skip_false; + picParam->prob_intra = m_frameHdr.prob_intra; + picParam->prob_last = m_frameHdr.prob_last; + picParam->prob_gf = m_frameHdr.prob_gf; + + memcpy (picParam->y_mode_probs, m_frameHdr.entropy_hdr.y_mode_probs, + sizeof (m_frameHdr.entropy_hdr.y_mode_probs)); + memcpy (picParam->uv_mode_probs, m_frameHdr.entropy_hdr.uv_mode_probs, + sizeof (m_frameHdr.entropy_hdr.uv_mode_probs)); + memcpy (picParam->mv_probs, m_frameHdr.entropy_hdr.mv_probs, + sizeof (m_frameHdr.entropy_hdr.mv_probs)); + + picParam->bool_coder_ctx.range = m_frameHdr.bool_dec_range; + picParam->bool_coder_ctx.value = m_frameHdr.bool_dec_value; + picParam->bool_coder_ctx.count = m_frameHdr.bool_dec_count; + + return true; +} + +/* fill quant parameter buffers functions*/ +bool VaapiDecoderVP8::ensureQuantMatrix(const PicturePtr& pic) +{ + Vp8SegmentationHeader *seg = &m_frameHdr.segmentation_hdr; + VAIQMatrixBufferVP8 *iqMatrix; + int32_t baseQI, i; + + if (!pic->editIqMatrix(iqMatrix)) + return false; + + for (i = 0; i < 4; i++) { + int32_t tempIndex; + const int32_t MAX_QI_INDEX = 127; + if (seg->segmentation_enabled) { + baseQI = seg->quantizer_update_value[i]; + if (!seg->segment_feature_mode) // 0 means delta update + baseQI += m_frameHdr.quantization_hdr.y_ac_qi;; + } else + baseQI = m_frameHdr.quantization_hdr.y_ac_qi; + + // the first component is y_ac_qi + tempIndex = + baseQI < 0 ? 0 : (baseQI > + MAX_QI_INDEX ? MAX_QI_INDEX : baseQI); + iqMatrix->quantization_index[i][0] = tempIndex; + + tempIndex = baseQI + m_frameHdr.quantization_hdr.y_dc_delta; + tempIndex = + tempIndex < 0 ? 0 : (tempIndex > + MAX_QI_INDEX ? MAX_QI_INDEX : tempIndex); + iqMatrix->quantization_index[i][1] = tempIndex; + + tempIndex = baseQI + m_frameHdr.quantization_hdr.y2_dc_delta; + tempIndex = + tempIndex < 0 ? 0 : (tempIndex > + MAX_QI_INDEX ? MAX_QI_INDEX : tempIndex); + iqMatrix->quantization_index[i][2] = tempIndex; + + tempIndex = baseQI + m_frameHdr.quantization_hdr.y2_ac_delta; + tempIndex = + tempIndex < 0 ? 0 : (tempIndex > + MAX_QI_INDEX ? MAX_QI_INDEX : tempIndex); + iqMatrix->quantization_index[i][3] = tempIndex; + + tempIndex = baseQI + m_frameHdr.quantization_hdr.uv_dc_delta; + tempIndex = + tempIndex < 0 ? 0 : (tempIndex > + MAX_QI_INDEX ? MAX_QI_INDEX : tempIndex); + iqMatrix->quantization_index[i][4] = tempIndex; + + tempIndex = baseQI + m_frameHdr.quantization_hdr.uv_ac_delta; + tempIndex = + tempIndex < 0 ? 0 : (tempIndex > + MAX_QI_INDEX ? MAX_QI_INDEX : tempIndex); + iqMatrix->quantization_index[i][5] = tempIndex; + } + + return true; +} + +/* fill quant parameter buffers functions*/ +bool VaapiDecoderVP8::ensureProbabilityTable(const PicturePtr& pic) +{ + VAProbabilityDataBufferVP8 *probTable = NULL; + + // XXX, create/render VAProbabilityDataBufferVP8 in base class + if (!pic->editProbTable(probTable)) + return false; + memcpy(probTable->dct_coeff_probs, + m_frameHdr.entropy_hdr.coeff_probs, + sizeof(m_frameHdr.entropy_hdr.coeff_probs)); + return true; +} + +void VaapiDecoderVP8::updateReferencePictures() +{ + const PicturePtr& picture = m_currentPicture; + + // update picture reference + if (m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) { + m_goldenRefPicture = picture; + m_altRefPicture = picture; + } else { + // process refresh_alternate_frame/copy_buffer_to_alternate first + if (m_frameHdr.refresh_alternate_frame) { + m_altRefPicture = picture; + } else { + switch (m_frameHdr.copy_buffer_to_alternate) { + case Vp8FrameHeader::COPY_LAST_TO_ALT: + m_altRefPicture = m_lastPicture; + break; + case Vp8FrameHeader::COPY_GOLDEN_TO_ALT: + m_altRefPicture = m_goldenRefPicture; + break; + default: + WARNING + ("WARNING: VP8 decoder: unrecognized copy_buffer_to_alternate"); + } + } + + if (m_frameHdr.refresh_golden_frame) { + m_goldenRefPicture = picture; + } else { + switch (m_frameHdr.copy_buffer_to_golden) { + case 1: + m_goldenRefPicture = m_lastPicture; + break; + case 2: + m_goldenRefPicture = m_altRefPicture; + break; + default: + WARNING + ("WARNING: VP8 decoder: unrecognized copy_buffer_to_golden"); + } + } + } + if ((m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) || m_frameHdr.refresh_last) + m_lastPicture = picture; + if (m_goldenRefPicture) + DEBUG("m_goldenRefPicture: %p, SurfaceID: %x", + m_goldenRefPicture.get(), m_goldenRefPicture->getSurfaceID()); + if (m_altRefPicture) + DEBUG("m_altRefPicture: %p, SurfaceID: %x", m_altRefPicture.get(), + m_altRefPicture->getSurfaceID()); + if (m_lastPicture) + DEBUG("m_lastPicture: %p, SurfaceID: %x", m_lastPicture.get(), + m_lastPicture->getSurfaceID()); + if (m_currentPicture) + DEBUG("m_currentPicture: %p, SurfaceID: %x", m_currentPicture.get(), + m_currentPicture->getSurfaceID()); + +} + +YamiStatus VaapiDecoderVP8::allocNewPicture() +{ + YamiStatus status = createPicture(m_currentPicture, m_currentPTS); + + if (status != YAMI_SUCCESS) + return status; + + SurfacePtr surface = m_currentPicture->getSurface(); + ASSERT(m_frameWidth && m_frameHeight); + if (!surface->setCrop(0, 0, m_frameWidth, m_frameHeight)) { + ASSERT(0 && "frame size is bigger than internal surface resolution"); + return YAMI_FAIL; + } + + DEBUG ("alloc new picture: %p with surface ID: %x", + m_currentPicture.get(), m_currentPicture->getSurfaceID()); + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderVP8::decodePicture() +{ + YamiStatus status = YAMI_SUCCESS; + + status = allocNewPicture(); + if (status != YAMI_SUCCESS) + return status; + + if (!ensureQuantMatrix(m_currentPicture)) { + ERROR("failed to reset quantizer matrix"); + return YAMI_FAIL; + } + + if (!ensureProbabilityTable(m_currentPicture)) { + ERROR("failed to reset probability table"); + return YAMI_FAIL; + } + + if (!fillPictureParam(m_currentPicture)) { + ERROR("failed to fill picture parameters"); + return YAMI_FAIL; + } + + VASliceParameterBufferVP8* sliceParam = NULL; + const void* sliceData = m_buffer + m_frameHdr.first_part_offset; + uint32_t sliceSize = m_frameSize - m_frameHdr.first_part_offset; +DEBUG("sliceData %p sliceSize %d", sliceData, sliceSize); + + if (!m_currentPicture->newSlice(sliceParam, sliceData, sliceSize)) + return YAMI_FAIL; + + if (!fillSliceParam(sliceParam)) + return YAMI_FAIL; + if (!m_currentPicture->decode()) + return YAMI_FAIL; + + DEBUG("VaapiDecoderVP8::decodePicture success"); + return status; +} + +VaapiDecoderVP8::VaapiDecoderVP8() +{ + m_frameWidth = 0; + m_frameHeight = 0; + m_buffer = 0; + m_frameSize = 0; + + // m_yModeProbs[4]; + // m_uvModeProbs[3]; + m_sizeChanged = 0; + m_hasContext = false; + m_gotKeyFrame = false; +} + +VaapiDecoderVP8::~VaapiDecoderVP8() +{ + stop(); +} + +YamiStatus VaapiDecoderVP8::start(VideoConfigBuffer* buffer) +{ + DEBUG("VP8: start() buffer size: %d x %d", buffer->width, + buffer->height); + + if ((buffer->flag & HAS_SURFACE_NUMBER) + && (buffer->flag & HAS_VA_PROFILE)) { + } + + buffer->profile = VAProfileVP8Version0_3; + buffer->surfaceNumber = 3; + + + DEBUG("disable native graphics buffer"); + m_configBuffer = *buffer; + m_configBuffer.data = NULL; + m_configBuffer.size = 0; + + // it is a good timing to report resolution change (gst-omx does), however, it fails on chromeos + // so we force to update resolution on first key frame + m_configBuffer.width = 0; + m_configBuffer.height = 0; +#if __PSB_CACHE_DRAIN_FOR_FIRST_FRAME__ + m_isFirstFrame = true; +#endif + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderVP8::reset(VideoConfigBuffer* buffer) +{ + DEBUG("VP8: reset()"); + return VaapiDecoderBase::reset(buffer); +} + +void VaapiDecoderVP8::stop(void) +{ + DEBUG("VP8: stop()"); + flush(); + VaapiDecoderBase::stop(); +} + +void VaapiDecoderVP8::flush(bool discardOutput) +{ + DEBUG("VP8: flush()"); + /*FIXME: should output all surfaces in drain mode*/ + m_currentPicture.reset(); + m_lastPicture.reset(); + m_goldenRefPicture.reset(); + m_altRefPicture.reset(); + m_gotKeyFrame = false; + + if (discardOutput) + VaapiDecoderBase::flush(); +} + +void VaapiDecoderVP8::flush(void) +{ + DEBUG("VP8: flush()"); + /*FIXME: should output all surfaces in drain mode*/ + flush(true); +} + +YamiStatus VaapiDecoderVP8::decode(VideoDecodeBuffer* buffer) +{ + YamiStatus status; + Vp8ParserResult result; + if (!buffer || !buffer->data) { + flush(false); + return YAMI_SUCCESS; + } + + m_currentPTS = buffer->timeStamp; + + m_buffer = buffer->data; + m_frameSize = buffer->size; + + DEBUG("VP8: Decode(bufsize =%d, timestamp=%" PRIu64 ")", m_frameSize, + m_currentPTS); + + do { + if (m_frameSize == 0) { + status = YAMI_FAIL; + break; + } + + m_frameHdr = Vp8FrameHeader(); + result = m_parser.ParseFrame(m_buffer,m_frameSize,&m_frameHdr); + status = getStatus(result); + if (status != YAMI_SUCCESS) { + break; + } + + if (!targetTemporalFrame()) + return YAMI_SUCCESS; + + if (m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) { + status = ensureContext(); + if (status != YAMI_SUCCESS) + return status; + m_gotKeyFrame = true; + } + else { + if (!m_gotKeyFrame) { + WARNING("we can't decode p frame without key"); + return YAMI_DECODE_INVALID_DATA; + } + } +#if __PSB_CACHE_DRAIN_FOR_FIRST_FRAME__ + int ii = 0; + int decodeCount = 1; + + if (m_isFirstFrame) { + decodeCount = 1280 * 720 / m_frameWidth / m_frameHeight * 2; + m_isFirstFrame = false; + } + + do { + status = decodePicture(); + } while (status == YAMI_SUCCESS && ++ii < decodeCount); + +#else + status = decodePicture(); +#endif + + if (status != YAMI_SUCCESS) + break; + + if (m_frameHdr.show_frame) { + m_currentPicture->m_timeStamp = m_currentPTS; + //FIXME: add output + outputPicture(m_currentPicture); + } else { + WARNING("warning: this picture isn't sent to render"); + } + + updateReferencePictures(); + + } while (0); + + if (status != YAMI_SUCCESS) { + DEBUG("decode fail!!"); + } + + return status; +} + +bool VaapiDecoderVP8::targetTemporalFrame() +{ + switch (m_configBuffer.temporalLayer) { + case 0: //decode all layers. + return true; + case 1: + if ((m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) || + m_frameHdr.refresh_last) + return true; + break; + case 2: + if ((m_frameHdr.key_frame == Vp8FrameHeader::KEYFRAME) || + m_frameHdr.refresh_last || m_frameHdr.refresh_golden_frame) + return true; + break; + case 3: + return true; + default: //decode all layers. + return true; + } + + return false; +} +} diff --git a/decoder/vaapidecoder_vp8.h b/decoder/vaapidecoder_vp8.h new file mode 100644 index 0000000..e591bbe --- /dev/null +++ b/decoder/vaapidecoder_vp8.h @@ -0,0 +1,127 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_vp8_h +#define vaapidecoder_vp8_h + +#include "codecparsers/vp8_parser.h" +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" +#include "va/va_dec_vp8.h" + +#if __PLATFORM_BYT__ +#define __PSB_CACHE_DRAIN_FOR_FIRST_FRAME__ 0 +#define __PSB_VP8_INTERFACE_WORK_AROUND__ 1 +#else +#define __PSB_CACHE_DRAIN_FOR_FIRST_FRAME__ 0 +#define __PSB_VP8_INTERFACE_WORK_AROUND__ 0 +#endif + +namespace YamiMediaCodec{ + +// function below taken from: +// https://src.chromium.org/svn/trunk/src/third_party/cld/base/macros.h +// The arraysize(arr) macro returns the # of elements in an array arr. +// The expression is a compile-time constant, and therefore can be +// used in defining new arrays, for example. If you use arraysize on +// a pointer by mistake, you will get a compile-time error. +// +// One caveat is that arraysize() doesn't accept any array of an +// anonymous type or a type defined inside a function. This is +// due to a limitation in C++'s template system. The limitation might +// eventually be removed, but it hasn't happened yet. + +// This template function declaration is used in defining arraysize. +// Note that the function doesn't need an implementation, as we only +// use its type. +template +char (&ArraySizeHelper(T (&array)[N]))[N]; + +// That gcc wants both of these prototypes seems mysterious. VC, for +// its part, can't decide which to use (another mystery). Matching of +// template overloads: the final frontier. +template +char (&ArraySizeHelper(const T (&array)[N]))[N]; + +#define arraysize(array) (sizeof(ArraySizeHelper(array))) + +enum { + VP8_MAX_PICTURE_COUNT = 5, // gold_ref, alt_ref, last_ref, previous (m_currentPicture, optional), and the newly allocated one +}; + +class VaapiDecoderVP8:public VaapiDecoderBase { + public: + typedef SharedPtr PicturePtr; + VaapiDecoderVP8(); + virtual ~ VaapiDecoderVP8(); + virtual YamiStatus start(VideoConfigBuffer* buffer); + virtual YamiStatus reset(VideoConfigBuffer* buffer); + virtual void stop(void); + virtual void flush(void); + virtual YamiStatus decode(VideoDecodeBuffer* buffer); + bool targetTemporalFrame(); + + private: + YamiStatus allocNewPicture(); + bool fillPictureParam(const PicturePtr& picture); + /* fill Quant matrix parameters */ + bool ensureQuantMatrix(const PicturePtr& pic); + bool ensureProbabilityTable(const PicturePtr& pic); + bool fillSliceParam(VASliceParameterBufferVP8* sliceParam); + /* check the context reset senerios */ + YamiStatus ensureContext(); + /* decoding functions */ + YamiStatus decodePicture(); + void updateReferencePictures(); + void flush(bool discardOutput); + + private: + friend class FactoryTest; + friend class VaapiDecoderVP8Test; + + PicturePtr m_currentPicture; + PicturePtr m_lastPicture; + PicturePtr m_goldenRefPicture; + PicturePtr m_altRefPicture; + + uint32_t m_hasContext:1; + + // resolution of current frame, VP8 may change frame resolution starting with a key frame + uint32_t m_frameWidth; + uint32_t m_frameHeight; + const uint8_t *m_buffer; + uint32_t m_frameSize; + YamiParser::Vp8FrameHeader m_frameHdr; + YamiParser::Vp8Parser m_parser; + uint8_t m_yModeProbs[4]; + uint8_t m_uvModeProbs[3]; + uint32_t m_sizeChanged:1; + //we can not decode P frame if we do not get key. + bool m_gotKeyFrame; + +#if __PSB_CACHE_DRAIN_FOR_FIRST_FRAME__ + bool m_isFirstFrame; +#endif + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; +} // namespace YamiMediaCodec + +#endif diff --git a/decoder/vaapidecoder_vp8_unittest.cpp b/decoder/vaapidecoder_vp8_unittest.cpp new file mode 100644 index 0000000..18d9780 --- /dev/null +++ b/decoder/vaapidecoder_vp8_unittest.cpp @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapidecoder_vp8.h" + +namespace YamiMediaCodec { + +class VaapiDecoderVP8Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIDECODER_VP8_TEST(name) \ + TEST_F(VaapiDecoderVP8Test, name) + +VAAPIDECODER_VP8_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_VP8); + doFactoryTest(mimeTypes); +} + +} diff --git a/decoder/vaapidecoder_vp9.cpp b/decoder/vaapidecoder_vp9.cpp new file mode 100644 index 0000000..b7fb156 --- /dev/null +++ b/decoder/vaapidecoder_vp9.cpp @@ -0,0 +1,365 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "common/log.h" +#include "vaapidecoder_vp9.h" + +namespace YamiMediaCodec{ +#define VP9_SURFACE_NUM 8 + +typedef VaapiDecoderVP9::PicturePtr PicturePtr; + +static VAProfile profileMap(VP9_PROFILE src_profile) +{ + switch (src_profile) { + case VP9_PROFILE_0: + return VAProfileVP9Profile0; + case VP9_PROFILE_1: + return VAProfileVP9Profile1; + case VP9_PROFILE_2: + return VAProfileVP9Profile2; + case VP9_PROFILE_3: + return VAProfileVP9Profile3; + case MAX_VP9_PROFILES: + default: + return VAProfileNone; + } +} + +VaapiDecoderVP9::VaapiDecoderVP9() + : m_gotKeyFrame(false) +{ + m_parser.reset(vp9_parser_new(), vp9_parser_free); + m_reference.resize(VP9_REF_FRAMES); +} + +VaapiDecoderVP9::~VaapiDecoderVP9() +{ + stop(); +} + +YamiStatus VaapiDecoderVP9::start(VideoConfigBuffer* buffer) +{ + DEBUG("VP9: start() buffer size: %d x %d", buffer->width, + buffer->height); + if (!(buffer->flag & HAS_VA_PROFILE)) + buffer->profile = VAProfileVP9Profile0; + //VP9_SURFACE_NUM reference frame + if (!(buffer->flag & HAS_SURFACE_NUMBER)) + buffer->surfaceNumber = VP9_SURFACE_NUM; + + m_parser->bit_depth = VP9_BITS_8; + + DEBUG("disable native graphics buffer"); + m_configBuffer = *buffer; + m_configBuffer.data = NULL; + m_configBuffer.size = 0; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderVP9::reset(VideoConfigBuffer* buffer) +{ + DEBUG("VP9: reset()"); + return VaapiDecoderBase::reset(buffer); +} + +void VaapiDecoderVP9::stop(void) +{ + DEBUG("VP9: stop()"); + flush(); + VaapiDecoderBase::stop(); +} + +void VaapiDecoderVP9::flush(void) +{ + flush(true); +} + +void VaapiDecoderVP9::flush(bool discardOutput) +{ + m_gotKeyFrame = false; + m_parser.reset(vp9_parser_new(), vp9_parser_free); + m_reference.clear(); + m_reference.resize(VP9_REF_FRAMES); + if (discardOutput) + VaapiDecoderBase::flush(); +} + +YamiStatus VaapiDecoderVP9::ensureContext(const Vp9FrameHdr* hdr) +{ + VAProfile vp9_profile = profileMap(hdr->profile); + if (vp9_profile == VAProfileNone) { + return YAMI_FATAL_ERROR; + } + + uint32_t fourcc = (m_parser->bit_depth == VP9_BITS_10) ? YAMI_FOURCC_P010 : YAMI_FOURCC_NV12; + + if (setFormat(hdr->width, hdr->height, ALIGN8(hdr->width), ALIGN32(hdr->height), VP9_SURFACE_NUM, fourcc)) { + return YAMI_DECODE_FORMAT_CHANGE; + } + + return ensureProfile(vp9_profile); +} + +bool VaapiDecoderVP9::fillReference(VADecPictureParameterBufferVP9* param, const Vp9FrameHdr* hdr) +{ +#define FILL_REFERENCE(vafield, ref) \ + do { \ + int idx = ref - VP9_LAST_FRAME; \ + if (!m_reference[idx]) { \ + ERROR("reference to %d is invalid", idx); \ + return false; \ + } \ + param->pic_fields.bits.vafield = hdr->ref_frame_indices[idx]; \ + param->pic_fields.bits.vafield##_sign_bias = hdr->ref_frame_sign_bias[idx]; \ + } while (0) + + + if (hdr->frame_type == VP9_KEY_FRAME) { + m_reference.clear(); + m_reference.resize(VP9_REF_FRAMES); + } else { + FILL_REFERENCE(last_ref_frame, VP9_LAST_FRAME); + FILL_REFERENCE(golden_ref_frame, VP9_GOLDEN_FRAME); + FILL_REFERENCE(alt_ref_frame, VP9_ALTREF_FRAME); + } + for (size_t i = 0; i < m_reference.size(); i++) { + SurfacePtr& surface = m_reference[i]; + param->reference_frames[i] = surface.get() ? surface->getID():VA_INVALID_SURFACE; + } + return true; +#undef FILL_REFERENCE +} + +void VaapiDecoderVP9::updateReference(const PicturePtr& picture, const Vp9FrameHdr* hdr) +{ + uint8_t flag = 1; + uint8_t refresh_frame_flags; + if (hdr->frame_type == VP9_KEY_FRAME) { + refresh_frame_flags = 0xff; + } else { + refresh_frame_flags = hdr->refresh_frame_flags; + } + + for (int i = 0; i < VP9_REF_FRAMES; i++) { + if (refresh_frame_flags & flag) { + m_reference[i] = picture->getSurface(); + } + flag <<= 1; + } +} + +bool VaapiDecoderVP9::ensurePicture(const PicturePtr& picture, const Vp9FrameHdr* hdr) +{ + VADecPictureParameterBufferVP9* param; + if (!picture->editPicture(param)) + return false; + param->frame_width = hdr->width; + param->frame_height = hdr->height; + if (!fillReference(param, hdr)) + return false; + + +#define FILL_PIC_FIELD(field) param->pic_fields.bits.field = hdr->field; + FILL_PIC_FIELD(subsampling_x) + FILL_PIC_FIELD(subsampling_y) + FILL_PIC_FIELD(frame_type) + FILL_PIC_FIELD(show_frame) + FILL_PIC_FIELD(error_resilient_mode) + FILL_PIC_FIELD(intra_only) + FILL_PIC_FIELD(allow_high_precision_mv) + FILL_PIC_FIELD(mcomp_filter_type) + FILL_PIC_FIELD(frame_parallel_decoding_mode) + FILL_PIC_FIELD(reset_frame_context) + FILL_PIC_FIELD(refresh_frame_context) + FILL_PIC_FIELD(frame_context_idx) +#undef FILL_PIC_FIELD + + param->pic_fields.bits.segmentation_enabled = hdr->segmentation.enabled; + param->pic_fields.bits.segmentation_temporal_update = hdr->segmentation.temporal_update; + param->pic_fields.bits.segmentation_update_map = hdr->segmentation.update_map; + param->pic_fields.bits.lossless_flag = m_parser->lossless_flag; + + param->filter_level = hdr->loopfilter.filter_level; + param->sharpness_level = hdr->loopfilter.sharpness_level; + + +#define FILL_FIELD(field) param->field = hdr->field; + FILL_FIELD(log2_tile_rows); + FILL_FIELD(log2_tile_columns); + FILL_FIELD(frame_header_length_in_bytes) + FILL_FIELD(first_partition_size) +#undef FILL_FIELD + param->profile = hdr->profile; + param->bit_depth = 8 + m_parser->bit_depth * 2; + + assert(sizeof(param->mb_segment_tree_probs) == sizeof(m_parser->mb_segment_tree_probs)); + assert(sizeof(param->segment_pred_probs) == sizeof(m_parser->segment_pred_probs)); + memcpy(param->mb_segment_tree_probs, m_parser->mb_segment_tree_probs, sizeof(m_parser->mb_segment_tree_probs)); + memcpy(param->segment_pred_probs, m_parser->segment_pred_probs, sizeof(m_parser->segment_pred_probs)); + + return true; +} + +bool VaapiDecoderVP9::ensureSlice(const PicturePtr& picture, const void* data, int size) +{ +#define FILL_FIELD(field) vaseg.field = seg.field; + + VASliceParameterBufferVP9* slice; + if (!picture->newSlice(slice, data, size)) + return false; + for (int i = 0; i < VP9_MAX_SEGMENTS; i++) { + VASegmentParameterVP9& vaseg = slice->seg_param[i]; + Vp9Segmentation& seg = m_parser->segmentation[i]; + memcpy(vaseg.filter_level, seg.filter_level, sizeof(seg.filter_level)); + FILL_FIELD(luma_ac_quant_scale) + FILL_FIELD(luma_dc_quant_scale) + FILL_FIELD(chroma_ac_quant_scale) + FILL_FIELD(chroma_dc_quant_scale) + + vaseg.segment_flags.fields.segment_reference_skipped = seg.reference_skip; + vaseg.segment_flags.fields.segment_reference_enabled = seg.reference_frame_enabled; + vaseg.segment_flags.fields.segment_reference = seg.reference_frame; + + } +#undef FILL_FIELD + return true; +} + +YamiStatus VaapiDecoderVP9::decode(const Vp9FrameHdr* hdr, const uint8_t* data, uint32_t size, uint64_t timeStamp) +{ + + YamiStatus ret; + ret = ensureContext(hdr); + if (ret != YAMI_SUCCESS) + return ret; + + PicturePtr picture; + ret = createPicture(picture, timeStamp); + if (ret != YAMI_SUCCESS) + return ret; + + if (hdr->show_existing_frame) { + SurfacePtr& surface = m_reference[hdr->frame_to_show]; + if (!surface) { + ERROR("frame to show is invalid, idx = %d", hdr->frame_to_show); + return YAMI_SUCCESS; + } + picture->setSurface(surface); + return outputPicture(picture); + } + + if (!picture->getSurface()->setCrop(0, 0, hdr->width, hdr->height)) { + ERROR("resize to %dx%d failed", hdr->width, hdr->height); + return YAMI_OUT_MEMORY; + } + + if (!ensurePicture(picture, hdr)) + return YAMI_FAIL; + if (!ensureSlice(picture, data, size)) + return YAMI_FAIL; + if (!picture->decode()) + return YAMI_FAIL; + updateReference(picture, hdr); + if (hdr->show_frame) + return outputPicture(picture); + return YAMI_SUCCESS; +} + +static bool parse_super_frame(std::vector& frameSize, const uint8_t* data, const size_t size) +{ + if (!data || !size) + return false; + uint8_t marker; + marker = *(data + size - 1); + if ((marker & 0xe0) != 0xc0) { + frameSize.push_back(size); + return true; + } + const uint32_t frames = (marker & 0x7) + 1; + const uint32_t mag = ((marker >> 3) & 0x3) + 1; + const size_t indexSz = 2 + mag * frames; + if (size < indexSz) + return false; + data += size - indexSz; + const uint8_t marker2 = *data++; + if (marker != marker2) + return false; + for (uint32_t i = 0; i < frames; i++) { + uint32_t sz = 0; + for (uint32_t j = 0; j < mag; j++) { + sz |= (*data++) << (j * 8); + } + frameSize.push_back(sz); + } + return true; +} + +YamiStatus VaapiDecoderVP9::decode(VideoDecodeBuffer* buffer) +{ + YamiStatus status; + if (!buffer || !buffer->data) { + flush(false); + return YAMI_SUCCESS; + } + uint8_t* data = buffer->data; + size_t size = buffer->size; + uint8_t* end = data + size; + std::vector frameSize; + if (!parse_super_frame(frameSize, data, size)) + return YAMI_DECODE_INVALID_DATA; + for (size_t i = 0; i < frameSize.size(); i++) { + uint32_t sz = frameSize[i]; + if (data + sz > end) + return YAMI_DECODE_INVALID_DATA; + status = decode(data, sz, buffer->timeStamp); + if (status != YAMI_SUCCESS) + return status; + data += sz; + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecoderVP9::decode(const uint8_t* data, uint32_t size, uint64_t timeStamp) +{ + Vp9FrameHdr hdr; + if (!m_parser) + return YAMI_OUT_MEMORY; + if (vp9_parse_frame_header(m_parser.get(), &hdr, data, size) != VP9_PARSER_OK) + return YAMI_DECODE_INVALID_DATA; + if (VP9_KEY_FRAME == hdr.frame_type) { + m_gotKeyFrame = true; + } + else { + if (!m_gotKeyFrame) { + WARNING("Can't decode p frame without key"); + return YAMI_DECODE_INVALID_DATA; + } + } + if (hdr.first_partition_size + hdr.frame_header_length_in_bytes > size) + return YAMI_DECODE_INVALID_DATA; + return decode(&hdr, data, size, timeStamp); +} + +} diff --git a/decoder/vaapidecoder_vp9.h b/decoder/vaapidecoder_vp9.h new file mode 100644 index 0000000..1cb3c66 --- /dev/null +++ b/decoder/vaapidecoder_vp9.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidecoder_vp9_h +#define vaapidecoder_vp9_h + +#include "codecparsers/vp9parser.h" +#include "vaapidecoder_base.h" +#include "vaapidecpicture.h" +#include "va/va_dec_vp9.h" +#include + +namespace YamiMediaCodec{ + +class VaapiDecoderVP9:public VaapiDecoderBase { + public: + typedef SharedPtr PicturePtr; + VaapiDecoderVP9(); + virtual ~ VaapiDecoderVP9(); + virtual YamiStatus start(VideoConfigBuffer*); + virtual YamiStatus reset(VideoConfigBuffer*); + virtual void stop(void); + virtual void flush(void); + void flush(bool discardOutput); + virtual YamiStatus decode(VideoDecodeBuffer*); + + private: + friend class FactoryTest; + friend class VaapiDecoderVP9Test; + + YamiStatus ensureContext(const Vp9FrameHdr*); + YamiStatus decode(const uint8_t* data, uint32_t size, uint64_t timeStamp); + YamiStatus decode(const Vp9FrameHdr* hdr, const uint8_t* data, uint32_t size, uint64_t timeStamp); + bool ensureSlice(const PicturePtr& , const void* data, int size); + bool ensurePicture(const PicturePtr& , const Vp9FrameHdr* ); + //reference related + bool fillReference(VADecPictureParameterBufferVP9* , const Vp9FrameHdr*); + void updateReference(const PicturePtr&, const Vp9FrameHdr*); + + typedef SharedPtr ParserPtr; + ParserPtr m_parser; + std::vector m_reference; + + //Can't decode p frame without key. + bool m_gotKeyFrame; + + /** + * VaapiDecoderFactory registration result. This decoder is registered in + * vaapidecoder_host.cpp + */ + static const bool s_registered; +}; + +} // namespace YamiMediaCodec + +#endif diff --git a/decoder/vaapidecoder_vp9_unittest.cpp b/decoder/vaapidecoder_vp9_unittest.cpp new file mode 100644 index 0000000..eab564f --- /dev/null +++ b/decoder/vaapidecoder_vp9_unittest.cpp @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +#include "vaapidecoder_vp9.h" + +namespace YamiMediaCodec { + +class VaapiDecoderVP9Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIDECODER_VP9_TEST(name) \ + TEST_F(VaapiDecoderVP9Test, name) + +VAAPIDECODER_VP9_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_VP9); + doFactoryTest(mimeTypes); +} + +} diff --git a/decoder/vaapidecpicture.cpp b/decoder/vaapidecpicture.cpp new file mode 100644 index 0000000..c7907fe --- /dev/null +++ b/decoder/vaapidecpicture.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapidecpicture.h" + +#include "common/log.h" + +namespace YamiMediaCodec{ +VaapiDecPicture::VaapiDecPicture(const ContextPtr& context, + const SurfacePtr& surface, int64_t timeStamp) + :VaapiPicture(context, surface, timeStamp) +{ +} + +VaapiDecPicture::VaapiDecPicture() +{ +} + +bool VaapiDecPicture::decode() +{ + return render(); +} + +bool VaapiDecPicture::doRender() +{ + RENDER_OBJECT(m_picture); + RENDER_OBJECT(m_probTable); + RENDER_OBJECT(m_iqMatrix); + RENDER_OBJECT(m_bitPlane); + RENDER_OBJECT(m_hufTable); + RENDER_OBJECT(m_slices); + return true; +} +} diff --git a/decoder/vaapidecpicture.h b/decoder/vaapidecpicture.h new file mode 100644 index 0000000..02b3405 --- /dev/null +++ b/decoder/vaapidecpicture.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef vaapidecpicture_h +#define vaapidecpicture_h + +#include "vaapi/vaapipicture.h" + +namespace YamiMediaCodec{ +class VaapiDecPicture : public VaapiPicture +{ +public: + VaapiDecPicture(const ContextPtr&, const SurfacePtr&, int64_t timeStamp); + virtual ~VaapiDecPicture() {}; + + + template + bool editPicture(T*& picParam); + + template + bool editIqMatrix(T*& matrix); + + template + bool editBitPlane(T*& plane, size_t size); + + template + bool editHufTable(T*& hufTable); + + template + bool editProbTable(T*& probTable); + + template + bool newSlice(T*& sliceParam, const void* sliceData, uint32_t sliceSize); + + bool decode(); + +protected: + VaapiDecPicture(); + +private: + virtual bool doRender(); + + BufObjectPtr m_picture; + BufObjectPtr m_iqMatrix; + BufObjectPtr m_bitPlane; + BufObjectPtr m_hufTable; + BufObjectPtr m_probTable; + std::vector > m_slices; +}; + +template +bool VaapiDecPicture::editPicture(T*& picParam) +{ + return editObject(m_picture, VAPictureParameterBufferType, picParam); +} + +template +bool VaapiDecPicture::editIqMatrix(T*& matrix) +{ + return editObject(m_iqMatrix, VAIQMatrixBufferType, matrix); +} + +template +bool VaapiDecPicture::editBitPlane(T*& plane, size_t size) +{ + if (m_bitPlane) + return false; + m_bitPlane = createBufferObject(VABitPlaneBufferType, size, NULL, (void**)&plane); + if (m_bitPlane && plane) { + memset(plane, 0, size); + return true; + } + return false; +} + +template +bool VaapiDecPicture::editHufTable(T*& hufTable) +{ + return editObject(m_hufTable, VAHuffmanTableBufferType, hufTable); +} + +template +bool VaapiDecPicture::editProbTable(T*& probTable) +{ + return editObject(m_probTable, VAProbabilityBufferType, probTable); +} + +template +bool VaapiDecPicture::newSlice(T*& sliceParam, const void* sliceData, uint32_t sliceSize) +{ + BufObjectPtr data = createBufferObject(VASliceDataBufferType, sliceSize, sliceData, NULL); + BufObjectPtr param = createBufferObject(VASliceParameterBufferType, sliceParam); + + bool ret = addObject(m_slices, param, data); + if (ret && sliceParam) { + sliceParam->slice_data_size = sliceSize; + sliceParam->slice_data_offset = 0; + sliceParam->slice_data_flag = VA_SLICE_DATA_FLAG_ALL; + return true; + } + + return false; +} +} +#endif //#ifndef vaapidecpicture_h diff --git a/decoder/vaapidecsurfacepool.cpp b/decoder/vaapidecsurfacepool.cpp new file mode 100644 index 0000000..3a1bce3 --- /dev/null +++ b/decoder/vaapidecsurfacepool.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapidecsurfacepool.h" + +#include "common/log.h" +#include "vaapi/VaapiSurface.h" +#include "decoder/vaapidecoder_base.h" +#include +#include + +namespace YamiMediaCodec{ + +YamiStatus VaapiDecSurfacePool::getSurface(SurfaceAllocParams* param, intptr_t* surface) +{ + VaapiDecSurfacePool* p = (VaapiDecSurfacePool*)param->user; + return p->getSurface(surface); +} + +YamiStatus VaapiDecSurfacePool::putSurface(SurfaceAllocParams* param, intptr_t surface) +{ + VaapiDecSurfacePool* p = (VaapiDecSurfacePool*)param->user; + return p->putSurface(surface); +} + +YamiStatus VaapiDecSurfacePool::getSurface(intptr_t* surface) +{ + AutoLock lock(m_lock); + + if (m_freed.empty()) + return YAMI_DECODE_NO_SURFACE; + *surface = m_freed.front(); + m_used.insert(*surface); + m_freed.pop_front(); + return YAMI_SUCCESS; +} + +YamiStatus VaapiDecSurfacePool::putSurface(intptr_t surface) +{ + AutoLock lock(m_lock); + + if (m_used.find(surface) == m_used.end()) { + ERROR("put wrong surface, id = %p", (void*)surface); + return YAMI_INVALID_PARAM; + } + m_used.erase(surface); + m_freed.push_back(surface); + return YAMI_SUCCESS; +} + +DecSurfacePoolPtr VaapiDecSurfacePool::create(VideoConfigBuffer* config, + const SharedPtr& allocator) +{ + VideoDecoderConfig conf; + conf.width = config->surfaceWidth; + conf.height = config->surfaceHeight; + conf.fourcc = config->fourcc; + conf.surfaceNumber = config->surfaceNumber; + return create(&conf, allocator); +} + +DecSurfacePoolPtr VaapiDecSurfacePool::create(VideoDecoderConfig* config, + const SharedPtr& allocator) +{ + DecSurfacePoolPtr pool(new VaapiDecSurfacePool); + if (!pool->init(config, allocator)) + pool.reset(); + return pool; +} + +bool VaapiDecSurfacePool::init(VideoDecoderConfig* config, + const SharedPtr& allocator) +{ + m_allocator = allocator; + m_allocParams.width = config->width; + m_allocParams.height = config->height; + m_allocParams.fourcc = config->fourcc; + m_allocParams.size = config->surfaceNumber; + if (m_allocator->alloc(m_allocator.get(), &m_allocParams) != YAMI_SUCCESS) { + ERROR("allocate surface failed (%dx%d), size = %d", + m_allocParams.width, m_allocParams.height , m_allocParams.size); + return false; + } + uint32_t size = m_allocParams.size; + uint32_t width = m_allocParams.width; + uint32_t height = m_allocParams.height; + uint32_t fourcc = config->fourcc; + if (!m_allocParams.getSurface || !m_allocParams.putSurface) { + m_allocParams.getSurface = getSurface; + m_allocParams.putSurface = putSurface; + m_allocParams.user = this; + } + + for (uint32_t i = 0; i < size; i++) { + intptr_t s = m_allocParams.surfaces[i]; + SurfacePtr surface(new VaapiSurface(s, width, height, fourcc)); + + m_surfaceMap[s] = surface.get(); + m_surfaces.push_back(surface); + + m_freed.push_back(s); + } + return true; +} + +VaapiDecSurfacePool::VaapiDecSurfacePool() +{ + memset(&m_allocParams, 0, sizeof(m_allocParams)); +} + +VaapiDecSurfacePool::~VaapiDecSurfacePool() +{ + if (m_allocator && m_allocParams.surfaces) { + m_allocator->free(m_allocator.get(), &m_allocParams); + } +} + +void VaapiDecSurfacePool::getSurfaceIDs(std::vector& ids) +{ + //no need hold lock, it never changed from start + assert(!ids.size()); + size_t size = m_surfaces.size(); + ids.reserve(size); + + for (size_t i = 0; i < size; ++i) + ids.push_back(m_surfaces[i]->getID()); +} + +struct VaapiDecSurfacePool::SurfaceRecycler +{ + SurfaceRecycler(const DecSurfacePoolPtr& pool): m_pool(pool) {} + void operator()(VaapiSurface* surface) + { + SurfaceAllocParams& params = m_pool->m_allocParams; + params.putSurface(¶ms, (intptr_t)surface->getID()); + } + +private: + DecSurfacePoolPtr m_pool; +}; + +SurfacePtr VaapiDecSurfacePool::acquire() +{ + SurfacePtr surface; + intptr_t p; + YamiStatus status = m_allocParams.getSurface(&m_allocParams, &p); + if (status != YAMI_SUCCESS) + return surface; + //we only hold this lock after getSurface, since getSurface will do the lock + AutoLock lock(m_lock); + SurfaceMap::iterator it = m_surfaceMap.find(p); + if (it == m_surfaceMap.end()) { + ERROR("surface getter turn a invalid surface ptr, %p", (void*)p); + return surface; + } + surface.reset(it->second, SurfaceRecycler(shared_from_this())); + return surface; +} + +} //namespace YamiMediaCodec diff --git a/decoder/vaapidecsurfacepool.h b/decoder/vaapidecsurfacepool.h new file mode 100644 index 0000000..48a8b47 --- /dev/null +++ b/decoder/vaapidecsurfacepool.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef vaapidecsurfacepool_h +#define vaapidecsurfacepool_h + +#include "common/condition.h" +#include "common/common_def.h" +#include "common/lock.h" +#include "vaapi/vaapiptrs.h" +#include "VideoCommonDefs.h" +#include "VideoDecoderDefs.h" +#include +#include +#include +#include +#include + +namespace YamiMediaCodec{ + +struct VideoDecoderConfig; +/*** + * \class VaapiDecSurfacePool + * \brief surface pool used for decoding rendering + *
+ * 1. the surface status is described by 2 bitwise flag: | SURFACE_RENDERING | SURFACE_DECODING |
+ *      SURFACE_DECODING is set when the buffer is used for decoding, usually set when decoder create a new #VaapiPicture.
+ *      SURFACE_DECODING is cleared when decoder doesn't use the buffer any more, usually when decoder delete the corresponding #VaapiPicture.
+ *      SURFACE_TO_RENDER is set when #VaapiPicture is ready to output (VaapiPicture::output() is called).
+ *      SURFACE_TO_RENDER is cleared when VASurface is sent to client for rendering (VaapiDecoderBase::getOutput())
+ *      SURFACE_RENDERING is set when VASurface is sent to client for rendering (VaapiDecoderBase::getOutput())
+ *      SURFACE_RENDERING is cleared when the surface is returned back from client (VaapiDecoderBase::renderDone())
+ *  if no flag is set, the buffer/surface can be reused -- associate with a new VaapiPicture
+ * 2. the free surface is in a first-in-first-out queue to be friendly to graphics fence
+ * 3. most functions in this class do not support multithread except recycle.
+ * 4. flush need called in decoder thread and it will make all following acuireWithWait return null surface.
+ *    until all surface recycled.
+ *
+*/ +class VaapiDecSurfacePool : public EnableSharedFromThis +{ +public: + /* TODO: remove this after all caller change to VideoDecoderConfig*/ + static DecSurfacePoolPtr create(VideoConfigBuffer* config, + const SharedPtr& allocator); + static DecSurfacePoolPtr create(VideoDecoderConfig* config, + const SharedPtr& allocator); + void getSurfaceIDs(std::vector& ids); + /// get a free surface + SurfacePtr acquire(); + ~VaapiDecSurfacePool(); + + +private: + VaapiDecSurfacePool(); + bool init(VideoDecoderConfig* config, + const SharedPtr& allocator); + + static YamiStatus getSurface(SurfaceAllocParams* param, intptr_t* surface); + static YamiStatus putSurface(SurfaceAllocParams* param, intptr_t surface); + YamiStatus getSurface(intptr_t* surface); + YamiStatus putSurface(intptr_t surface); + + //following member only change in constructor. + std::vector m_surfaces; + + typedef std::map SurfaceMap; + SurfaceMap m_surfaceMap; + + //free and allocted. + std::deque m_freed; + std::set m_used; + + Lock m_lock; + + //for external allocator + SharedPtr m_allocator; + SurfaceAllocParams m_allocParams; + + struct SurfaceRecycler; + + DISALLOW_COPY_AND_ASSIGN(VaapiDecSurfacePool); +}; + +} //namespace YamiMediaCodec + +#endif //vaapidecsurfacepool_h diff --git a/doc/Makefile.am b/doc/Makefile.am new file mode 100644 index 0000000..739510c --- /dev/null +++ b/doc/Makefile.am @@ -0,0 +1,57 @@ +all: html +install-data-local: install-html + +EXTRA_DIST = \ + doc.config \ + $(NULL) + +LIBYAMI_DOC_STRIP_DIR = $(top_srcdir)/common $(top_srcdir)/vaapi $(top_srcdir)/decoder $(top_srcdir)/encoder $(top_srcdir)/interface +LIBYAMI_DOC_STRIP_FILES = vaapibuffer.h \ + $(top_srcdir)/vaapi/vaapiimage.h \ + $(top_srcdir)/vaapi/vaapiptrs.h \ + $(top_srcdir)/vaapi/vaapisurface.h \ + $(top_srcdir)/vaapi/vaapiutils.h \ + $(top_srcdir)/decoder/vaapidecoder_base.h \ + $(top_srcdir)/decoder/vaapidecoder_h264.h \ + $(top_srcdir)/decoder/vaapidecoder_jpeg.h \ + $(top_srcdir)/decoder/vaapidecoder_vp8.h \ + $(top_srcdir)/decoder/vaapidecsurfacepool.h \ + $(top_srcdir)/decoder/vaapipicture.h \ + $(top_srcdir)/decoder/vaapisurfacebuf_pool.h \ + $(top_srcdir)/encoder/vaapicodedbuffer.h \ + $(top_srcdir)/encoder/vaapiencoder_base.h \ + $(top_srcdir)/encoder/vaapiencoder_h264.h \ + $(top_srcdir)/encoder/vaapiencpicture.h \ + $(top_srcdir)/interface/VideoDecoderDefs.h \ + $(top_srcdir)/interface/VideoDecoderHost.h \ + $(top_srcdir)/interface/VideoDecoderInterface.h \ + $(top_srcdir)/interface/VideoEncoderAVC.h \ + $(top_srcdir)/interface/VideoEncoderBase.h \ + $(top_srcdir)/interface/VideoEncoderDefs.h \ + $(top_srcdir)/interface/VideoEncoderHost.h \ + $(top_srcdir)/interface/VideoEncoderInterface.h \ + $(NULL) + +export LIBYAMI_DOC_STRIP_DIR +export LIBYAMI_DOC_STRIP_FILES +html/index.html: doc.config + $(DOXYGEN) $< + +if ENABLE_DOCS +html: html/index.html +install-html-local: + install -d $(DESTDIR)$(docdir)/html + for file in `ls html/` ; do \ + if test -f html/$$file ; then \ + install -m 0644 html/$$file $(DESTDIR)$(docdir)/html ; \ + else \ + install -d $(DESTDIR)$(docdir)/html/$$file ; \ + install -m 0644 html/$$file/* $(DESTDIR)$(docdir)/html/$$file; \ + fi ; \ + done +uninstall-local: + rm -rf $(DESTDIR)$(docdir)/html +endif + +# Extra clean files so that maintainer-clean removes *everything* +MAINTAINERCLEANFILES = Makefile.in diff --git a/doc/doc.config b/doc/doc.config new file mode 100644 index 0000000..da8432c --- /dev/null +++ b/doc/doc.config @@ -0,0 +1,1891 @@ +# Doxyfile 1.8.4 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed +# in front of the TAG it is preceding . +# All text after a hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" "). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or sequence of words) that should +# identify the project. Note that if you do not use Doxywizard you need +# to put quotes around the project name if it contains spaces. + +PROJECT_NAME = "libyami" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer +# a quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = "libyami is core codec library basing on VAAPI" + +# With the PROJECT_LOGO tag one can specify an logo or icon that is +# included in the documentation. The maximum height of the logo should not +# exceed 55 pixels and the maximum width should not exceed 200 pixels. +# Doxygen will copy the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Latvian, Lithuanian, Norwegian, Macedonian, +# Persian, Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, +# Slovak, Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. Note that you specify absolute paths here, but also +# relative paths, which will be relative from the directory where doxygen is +# started. + +STRIP_FROM_PATH = $(LIBYAMI_DOC_STRIP_PATH) + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful if your file system +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = NO + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding +# "class=itcl::class" will allow you to use the command class in the +# itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, +# and language is one of the parsers supported by doxygen: IDL, Java, +# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, +# C++. For instance to make doxygen treat .inc files as Fortran files (default +# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note +# that for custom extensions you also need to set FILE_PATTERNS otherwise the +# files are not read by doxygen. + +EXTENSION_MAPPING = + +# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all +# comments according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you +# can mix doxygen, HTML, and XML commands with Markdown formatting. +# Disable only in case of backward compatibilities issues. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by by putting a % sign in front of the word +# or globally by setting AUTOLINK_SUPPORT to NO. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also makes the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES (the +# default) will make doxygen replace the get and set methods by a property in +# the documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and +# unions are shown inside the group in which they are included (e.g. using +# @ingroup) instead of on a separate page (for HTML and Man pages) or +# section (for LaTeX and RTF). + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and +# unions with only public data fields or simple typedef fields will be shown +# inline in the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO (the default), structs, classes, and unions are shown on a separate +# page (for HTML and Man pages) or section (for LaTeX and RTF). + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can +# be an expensive process and often the same symbol appear multiple times in +# the code, doxygen keeps a cache of pre-resolved symbols. If the cache is too +# small doxygen will become slower. If the cache is too large, memory is wasted. +# The cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid +# range is 0..9, the default is 0, corresponding to a cache size of 2^16 = 65536 +# symbols. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal +# scope will be included in the documentation. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespaces are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen +# will sort the (brief and detailed) documentation of class members so that +# constructors and destructors are listed first. If set to NO (the default) +# the constructors will appear in the respective orders defined by +# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. +# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO +# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to +# do proper type resolution of all parameters of a function it will reject a +# match between the prototype and the implementation of a member function even +# if there is only one candidate or it is obvious which candidate to choose +# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen +# will still accept a match between prototype and implementation in such cases. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if section-label ... \endif +# and \cond section-label ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or macro consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and macros in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. +# You can optionally specify a file name after the option, if omitted +# DoxygenLayout.xml will be used as the name of the layout file. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files +# containing the references data. This must be a list of .bib files. The +# .bib extension is automatically appended if omitted. Using this command +# requires the bibtex tool to be installed. See also +# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style +# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this +# feature you need bibtex and perl available in the search path. Do not use +# file names with spaces, bibtex cannot handle them. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# The WARN_NO_PARAMDOC option can be enabled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = $(LIBYAMI_DOC_STRIP_FILES) +INPUT += mainpage.dox + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh +# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py +# *.f90 *.f *.for *.vhd *.vhdl + +FILE_PATTERNS = *.c *.cpp *.h + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = */test/* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be ignored. +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty or if +# non of the patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) +# and it is also possible to disable source filtering for a specific pattern +# using *.ext= (so without naming a filter). This option only has effect when +# FILTER_SOURCE_FILES is enabled. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C, C++ and Fortran comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. Note that when using a custom header you are responsible +# for the proper inclusion of any scripts and style sheets that doxygen +# needs, which is dependent on the configuration options used. +# It is advised to generate a default header using "doxygen -w html +# header.html footer.html stylesheet.css YourConfigFile" and then modify +# that header. Note that the header is subject to change so you typically +# have to redo this when upgrading to a newer version of doxygen or when +# changing the value of configuration settings such as GENERATE_TREEVIEW! + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If left blank doxygen will +# generate a default style sheet. Note that it is recommended to use +# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this +# tag will in the future become obsolete. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional +# user-defined cascading style sheet that is included after the standard +# style sheets created by doxygen. Using this option one can overrule +# certain style aspects. This is preferred over using HTML_STYLESHEET +# since it does not replace the standard style sheet and is therefor more +# robust against future updates. Doxygen will copy the style sheet file to +# the output directory. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that +# the files will be copied as-is; there are no commands or markers available. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. +# Doxygen will adjust the colors in the style sheet and background images +# according to this color. Hue is specified as an angle on a colorwheel, +# see http://en.wikipedia.org/wiki/Hue for more information. +# For instance the value 0 represents red, 60 is yellow, 120 is green, +# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. +# The allowed range is 0 to 359. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of +# the colors in the HTML output. For a value of 0 the output will use +# grayscales only. A value of 255 will produce the most vivid colors. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to +# the luminance component of the colors in the HTML output. Values below +# 100 gradually make the output lighter, whereas values above 100 make +# the output darker. The value divided by 100 is the actual gamma applied, +# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, +# and 100 does not change the gamma. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of +# entries shown in the various tree structured indices initially; the user +# can expand and collapse entries dynamically later on. Doxygen will expand +# the tree to such a level that at most the specified number of entries are +# visible (unless a fully collapsed tree already exceeds this amount). +# So setting the number of entries 1 will produce a full collapsed tree by +# default. 0 is a special value representing an infinite number of entries +# and will result in a full expanded tree by default. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely +# identify the documentation publisher. This should be a reverse domain-name +# style string, e.g. com.mycompany.MyDocSet.documentation. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated +# that can be used as input for Qt's qhelpgenerator to generate a +# Qt Compressed Help (.qch) of the generated HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to +# add. For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see +#
+# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's +# filter section matches. +# +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before +# the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) +# at top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. Since the tabs have the same information as the +# navigation tree you can set this option to NO if you already set +# GENERATE_TREEVIEW to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. +# Since the tree basically has the same information as the tab index you +# could consider to set DISABLE_INDEX to NO when enabling this option. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values +# (range [0,1..20]) that doxygen will group on one line in the generated HTML +# documentation. Note that a value of 0 will completely suppress the enum +# values from appearing in the overview section. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open +# links to external symbols imported via tag files in a separate window. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are +# not supported properly for IE 6.0, but are supported on all modern browsers. +# Note that when changing this option you need to delete any form_*.png files +# in the HTML output before the changes have effect. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax +# (see http://www.mathjax.org) which uses client side Javascript for the +# rendering instead of using prerendered bitmaps. Use this if you do not +# have LaTeX installed or if you want to formulas look prettier in the HTML +# output. When enabled you may also need to install MathJax separately and +# configure the path to it using the MATHJAX_RELPATH option. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and +# SVG. The default value is HTML-CSS, which is slower, but has the best +# compatibility. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the +# HTML output directory using the MATHJAX_RELPATH option. The destination +# directory should contain the MathJax.js script. For instance, if the mathjax +# directory is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to +# the MathJax Content Delivery Network so you can quickly see the result without +# installing MathJax. +# However, it is strongly recommended to install a local +# copy of MathJax from http://www.mathjax.org before deployment. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension +# names that should be enabled during MathJax rendering. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript +# pieces of code that will be used on startup of the MathJax code. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box +# for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using +# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets +# (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a web server instead of a web client using Javascript. +# There are two flavours of web server based search depending on the +# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for +# searching and an index file used by the script. When EXTERNAL_SEARCH is +# enabled the indexing and searching needs to be provided by external tools. +# See the manual for details. + +SERVER_BASED_SEARCH = NO + +# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain +# the search results. Doxygen ships with an example indexer (doxyindexer) and +# search engine (doxysearch.cgi) which are based on the open source search +# engine library Xapian. See the manual for configuration details. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will returned the search results when EXTERNAL_SEARCH is enabled. +# Doxygen ships with an example search engine (doxysearch) which is based on +# the open source search engine library Xapian. See the manual for configuration +# details. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id +# of to a relative location where the documentation can be found. +# The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... + +EXTRA_SEARCH_MAPPINGS = + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, letter, legal and +# executive. If left blank a4 will be used. + +PAPER_TYPE = a4 + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for +# the generated latex document. The footer should contain everything after +# the last chapter. If it is left blank doxygen will generate a +# standard footer. Notice: only use this tag if you know what you are doing! + +LATEX_FOOTER = + +# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images +# or other source files which should be copied to the LaTeX output directory. +# Note that the files will be copied as-is; there are no commands or markers +# available. + +LATEX_EXTRA_FILES = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include +# source code with syntax highlighting in the LaTeX output. +# Note that which sources are shown also depends on other settings +# such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See +# http://en.wikipedia.org/wiki/BibTeX for more info. + +LATEX_BIB_STYLE = plain + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load style sheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- + +# If the GENERATE_DOCBOOK tag is set to YES Doxygen will generate DOCBOOK files +# that can be used to generate PDF. + +GENERATE_DOCBOOK = NO + +# The DOCBOOK_OUTPUT tag is used to specify where the DOCBOOK pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in +# front of it. If left blank docbook will be used as the default path. + +DOCBOOK_OUTPUT = docbook + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# pointed to by INCLUDE_PATH will be searched when a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition that +# overrules the definition found in the source code. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all references to function-like macros +# that are alone on a line, have an all uppercase name, and do not end with a +# semicolon, because these will confuse the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. For each +# tag file the location of the external documentation should be added. The +# format of a tag file without this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths +# or URLs. Note that each tag file must have a unique name (where the name does +# NOT include the path). If a tag file is not located in the directory in which +# doxygen is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed +# in the related pages index. If set to NO, only the current project's +# pages will be listed. + +EXTERNAL_PAGES = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option also works with HAVE_DOT disabled, but it is recommended to +# install and use dot, since it yields more powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is +# allowed to run in parallel. When set to 0 (the default) doxygen will +# base this on the number of processors available in the system. You can set it +# explicitly to a value larger than 0 to get control over the balance +# between CPU load and processing speed. + +DOT_NUM_THREADS = 0 + +# By default doxygen will use the Helvetica font for all dot files that +# doxygen generates. When you want a differently looking font you can specify +# the font name using DOT_FONTNAME. You need to make sure dot is able to find +# the font, which can be done by putting it in a standard location or by setting +# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the +# directory containing the font. + +DOT_FONTNAME = Helvetica + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the Helvetica font. +# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to +# set the path where dot can find it. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside +# the class node. If there are many fields or methods and many nodes the +# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS +# threshold limits the number of items for each type to make the size more +# manageable. Set this to 0 for no limit. Note that the threshold may be +# exceeded by 50% before the limit is enforced. + +UML_LIMIT_NUM_FIELDS = 10 + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will generate a graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are svg, png, jpg, or gif. +# If left blank png will be used. If you choose svg you need to set +# HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible in IE 9+ (other browsers do not have this requirement). + +DOT_IMAGE_FORMAT = png + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# Note that this requires a modern browser other than Internet Explorer. +# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you +# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible. Older versions of IE do not have SVG support. + +INTERACTIVE_SVG = NO + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the +# \mscfile command). + +MSCFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = YES + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/doc/infrastructure.png b/doc/infrastructure.png new file mode 100644 index 0000000..d7e7b29 Binary files /dev/null and b/doc/infrastructure.png differ diff --git a/doc/infrastructure.vsdx b/doc/infrastructure.vsdx new file mode 100644 index 0000000..04c70e5 Binary files /dev/null and b/doc/infrastructure.vsdx differ diff --git a/doc/mainpage.dox b/doc/mainpage.dox new file mode 100644 index 0000000..d180ca6 --- /dev/null +++ b/doc/mainpage.dox @@ -0,0 +1,18 @@ +/** +* \mainpage Entrance to the interested document +*
+* ==== Here are API of libyami
+* == Decoder APIs
+* class YamiMediaCodec::IVideoDecoder
+* func createVideoDecoder()
+* func releaseVideoDecoder()
+*
+* == Encoder APIs
+* class YamiMediaCodec::IVideoEncoder
+* func createVideoEncoder()
+* func releaseVideoEncoder()
+*
+* ==== More information on internal implementation:
+* class YamiMediaCodec::VaapiDecSurfacePool
+* 
+*/ diff --git a/egl/egl_util.c b/egl/egl_util.c new file mode 100644 index 0000000..3c6d1c5 --- /dev/null +++ b/egl/egl_util.c @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "egl_util.h" +#include "common/log.h" +#if __ENABLE_DMABUF__ +#include "libdrm/drm_fourcc.h" +#endif + +static PFNEGLCREATEIMAGEKHRPROC createImageProc = NULL; +static PFNEGLDESTROYIMAGEKHRPROC destroyImageProc = NULL; + +EGLImageKHR createImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, + EGLClientBuffer buffer, const EGLint *attrib_list) +{ + if (!createImageProc) { + createImageProc = (void *) eglGetProcAddress("eglCreateImageKHR"); + } + return createImageProc(dpy, ctx, target, buffer, attrib_list); +} + +EGLBoolean destroyImage(EGLDisplay dpy, EGLImageKHR image) +{ + if (!destroyImageProc) { + destroyImageProc = (void *) eglGetProcAddress("eglDestroyImageKHR"); + } + return destroyImageProc(dpy, image); +} + +static EGLImageKHR createEglImageFromDrmBuffer(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t drmName, int width, int height, int pitch) +{ + EGLImageKHR eglImage = EGL_NO_IMAGE_KHR; + EGLint attribs[] = { + EGL_WIDTH, width, + EGL_HEIGHT, height, + EGL_DRM_BUFFER_STRIDE_MESA, pitch/4, + EGL_DRM_BUFFER_FORMAT_MESA, + EGL_DRM_BUFFER_FORMAT_ARGB32_MESA, + EGL_DRM_BUFFER_USE_MESA, + EGL_DRM_BUFFER_USE_SHARE_MESA, + EGL_NONE + }; + + eglImage = createImage(eglDisplay, eglContext, EGL_DRM_BUFFER_MESA, + (EGLClientBuffer)(intptr_t)drmName, attribs); + return eglImage; +} + +static EGLImageKHR createEglImageFromDmaBuf(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t dmaBuf, int width, int height, int pitch) +{ + EGLImageKHR eglImage = EGL_NO_IMAGE_KHR; +#if __ENABLE_DMABUF__ + EGLint attribs[] = { + EGL_WIDTH, width, + EGL_HEIGHT, height, + EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_XRGB8888, + EGL_DMA_BUF_PLANE0_FD_EXT, dmaBuf, + EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, + EGL_DMA_BUF_PLANE0_PITCH_EXT, pitch, + EGL_NONE + }; + + eglImage = createImage(eglDisplay, EGL_NO_CONTEXT, + EGL_LINUX_DMA_BUF_EXT, NULL, attribs); + ASSERT(eglImage != EGL_NO_IMAGE_KHR); + return eglImage; +#else + ERROR("dma_buf is enabled with --enable-dmabuf option"); + return eglImage; +#endif +} + +EGLImageKHR createEglImageFromHandle(EGLDisplay eglDisplay, EGLContext eglContext, VideoDataMemoryType type, uint32_t handle, int width, int height, int pitch) +{ + EGLImageKHR eglImage = EGL_NO_IMAGE_KHR; + if (type == VIDEO_DATA_MEMORY_TYPE_DRM_NAME) + eglImage = createEglImageFromDrmBuffer(eglDisplay, eglContext, handle, width, height, pitch); + else if (type == VIDEO_DATA_MEMORY_TYPE_DMA_BUF) + eglImage = createEglImageFromDmaBuf(eglDisplay, eglContext, handle, width, height, pitch); + + return eglImage; +} diff --git a/egl/egl_util.h b/egl/egl_util.h new file mode 100644 index 0000000..1dc4b18 --- /dev/null +++ b/egl/egl_util.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EGL_UTIL_H__ +#define __EGL_UTIL_H__ +#include +#include + +#include "VideoCommonDefs.h" +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +EGLImageKHR createImage(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *); +EGLBoolean destroyImage(EGLDisplay, EGLImageKHR); +EGLImageKHR createEglImageFromHandle(EGLDisplay eglDisplay, EGLContext eglContext, VideoDataMemoryType type, uint32_t dmaBuf, int width, int height, int pitch); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif diff --git a/egl/egl_vaapi_image.cpp b/egl/egl_vaapi_image.cpp new file mode 100644 index 0000000..2dac578 --- /dev/null +++ b/egl/egl_vaapi_image.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "egl_util.h" +#include "egl_vaapi_image.h" +#include "common/log.h" +#include "vaapi/VaapiUtils.h" +#if __ENABLE_DMABUF__ +#include "libdrm/drm_fourcc.h" +#endif +#include +#include +#include + +namespace YamiMediaCodec { + +EglVaapiImage::EglVaapiImage(VADisplay display, int width, int height) + : m_display(display), m_width(width), m_height(height), m_inited(false) + , m_acquired(false), m_eglImage(EGL_NO_IMAGE_KHR) +{ + +} + +bool getVaFormat(VADisplay display, VAImageFormat& format); +bool EglVaapiImage::init() +{ + if (m_inited) { + ERROR("do not init twice"); + return false; + } + if (!getVaFormat(m_display, m_format)) + return false; + VAStatus vaStatus = vaCreateImage(m_display, &m_format, m_width, m_height, &m_image); + if (!checkVaapiStatus(vaStatus, "vaCreateImage")) + return false; + m_inited = true; + return true; +} + +bool EglVaapiImage::acquireBufferHandle(VideoDataMemoryType memoryType) +{ + uint32_t i; + if (m_acquired) { + ASSERT(memoryType = m_frameInfo.memoryType); + return true; + } + + // FIXME, more type can be supported + if (memoryType == VIDEO_DATA_MEMORY_TYPE_DRM_NAME) + m_bufferInfo.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM; + else if (memoryType == VIDEO_DATA_MEMORY_TYPE_DMA_BUF) + m_bufferInfo.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME; + else + ASSERT(0); + VAStatus vaStatus = vaAcquireBufferHandle(m_display, m_image.buf, &m_bufferInfo); + m_frameInfo.memoryType = memoryType; + m_frameInfo.width = m_width; + m_frameInfo.height = m_height; + for (i=0; i& src) +{ + if (!m_inited) { + ERROR("call init before blt!"); + return false; + } + if (m_acquired) + vaReleaseBufferHandle(m_display, m_image.buf); + + VAStatus vaStatus = vaGetImage(m_display, (VASurfaceID)src->surface, src->crop.x, src->crop.y, src->crop.width, src->crop.height, m_image.image_id); + + // incomplete data yet + m_frameInfo.timeStamp = src->timeStamp; + m_frameInfo.flags = src->flags; + return checkVaapiStatus(vaStatus, "vaGetImage"); +} + +EglVaapiImage::~EglVaapiImage() +{ + if (m_inited) { + if (m_acquired) + vaReleaseBufferHandle(m_display, m_image.buf); + vaDestroyImage(m_display, m_image.image_id); + } +} + +bool getVaFormat(VADisplay display, VAImageFormat& format) +{ + int num = vaMaxNumImageFormats(display); + if (!num) + return false; + std::vector vaFormats; + vaFormats.resize(num); + VAStatus vaStatus = vaQueryImageFormats(display, &vaFormats[0], &num); + if (!checkVaapiStatus(vaStatus, "vaQueryImageFormats")) + return false; + if (vaStatus != VA_STATUS_SUCCESS) { + ERROR("query image formats return %d", vaStatus); + return false; + } + vaFormats.resize(num); + for (size_t i = 0; i < vaFormats.size(); i++) + { + const VAImageFormat& fmt = vaFormats[i]; + if (fmt.fourcc == VA_FOURCC_BGRX) { + format = fmt; + return true; + } + } + return false; +} + +}//namespace YamiMediaCodec diff --git a/egl/egl_vaapi_image.h b/egl/egl_vaapi_image.h new file mode 100644 index 0000000..3f49447 --- /dev/null +++ b/egl/egl_vaapi_image.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef egl_vaapi_image_h +#define egl_vaapi_image_h + +#include +#define EGL_EGLEXT_PROTOTYPES +#include +#include + +#include "VideoCommonDefs.h" + +namespace YamiMediaCodec { + +class EglVaapiImage +{ +public: + EglVaapiImage(VADisplay, int width, int height); + bool init(); + EGLImageKHR createEglImage(EGLDisplay, EGLContext, VideoDataMemoryType); + bool blt(const SharedPtr& src); + bool exportFrame(VideoDataMemoryType memoryType, VideoFrameRawData &frame); + ~EglVaapiImage(); +private: + bool acquireBufferHandle(VideoDataMemoryType); + VADisplay m_display; + VAImageFormat m_format; + VAImage m_image; + VABufferInfo m_bufferInfo; + + int m_width; + int m_height; + bool m_inited; + bool m_acquired; // acquired buffer handle + VideoFrameRawData m_frameInfo; + + EGLImageKHR m_eglImage; +}; + +}//namespace YamiMediaCodec + +#endif diff --git a/encoder/Android.mk b/encoder/Android.mk new file mode 100644 index 0000000..c874bca --- /dev/null +++ b/encoder/Android.mk @@ -0,0 +1,49 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + vaapicodedbuffer.cpp \ + vaapiencpicture.cpp \ + vaapiencoder_base.cpp \ + vaapiencoder_host.cpp \ + +LOCAL_SRC_FILES += \ + vaapiencoder_h264.cpp \ + vaapilayerid.cpp + +LOCAL_SRC_FILES += \ + vaapiencoder_jpeg.cpp + +LOCAL_SRC_FILES += \ + vaapiencoder_vp8.cpp + +LOCAL_SRC_FILES += \ + vaapiencoder_vp9.cpp + +LOCAL_SRC_FILES += \ + vaapiencoder_hevc.cpp + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../common \ + $(LOCAL_PATH)/../interface \ + $(LOCAL_PATH)/../vaapi \ + $(LOCAL_PATH)/../codecparsers \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva \ + +LOCAL_CFLAGS := \ + -D__BUILD_H264_ENCODER__=1 \ + -D__BUILD_H265_ENCODER__=1 \ + -D__BUILD_VP8_ENCODER__=1 \ + -D__BUILD_VP9_ENCODER__=1 \ + -D__BUILD_JPEG_ENCODER__=1 \ + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libc++ + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_encoder +include $(BUILD_STATIC_LIBRARY) diff --git a/encoder/Makefile.am b/encoder/Makefile.am new file mode 100755 index 0000000..c80b687 --- /dev/null +++ b/encoder/Makefile.am @@ -0,0 +1,103 @@ +libyami_encoder_source_c = \ + vaapicodedbuffer.cpp \ + vaapiencpicture.cpp \ + vaapiencoder_base.cpp \ + vaapiencoder_host.cpp \ + vaapilayerid.cpp \ + $(NULL) + +if BUILD_H264_ENCODER +libyami_encoder_source_c += vaapiencoder_h264.cpp +endif + +if BUILD_JPEG_ENCODER +libyami_encoder_source_c += vaapiencoder_jpeg.cpp +endif + +if BUILD_VP8_ENCODER +libyami_encoder_source_c += vaapiencoder_vp8.cpp +endif + +if BUILD_H265_ENCODER +libyami_encoder_source_c += vaapiencoder_hevc.cpp +endif + +if BUILD_VP9_ENCODER +libyami_encoder_source_c += vaapiencoder_vp9.cpp +endif + +libyami_encoder_source_h = \ + ../interface/VideoCommonDefs.h \ + ../interface/VideoEncoderDefs.h \ + ../interface/VideoEncoderInterface.h \ + ../interface/VideoEncoderHost.h \ + $(NULL) + +libyami_encoder_source_h_priv = \ + vaapicodedbuffer.h \ + vaapiencpicture.h \ + vaapiencoder_base.h \ + vaapilayerid.h \ + $(NULL) + +if BUILD_H264_ENCODER +libyami_encoder_source_h_priv += vaapiencoder_h264.h +endif + +if BUILD_JPEG_ENCODER +libyami_encoder_source_h_priv += vaapiencoder_jpeg.h +endif + +if BUILD_VP8_ENCODER +libyami_encoder_source_h_priv += vaapiencoder_vp8.h +endif + +if BUILD_H265_ENCODER +libyami_encoder_source_h_priv += vaapiencoder_hevc.h +endif + +if BUILD_VP9_ENCODER +libyami_encoder_source_h_priv += vaapiencoder_vp9.h +endif + +libyami_encoder_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + -ldl \ + $(NULL) + +if ENABLE_X11 +libyami_encoder_ldflags += $(LIBVA_X11_LIBS) $(X11_LIBS) +endif + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_encoder_cppflags = \ + $(LIBVA_CFLAGS) \ + $(LIBVA_DRM_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +if ENABLE_X11 +libyami_encoder_cppflags += $(LIBVA_X11_CFLAGS) +endif + +noinst_LTLIBRARIES = libyami_encoder.la +libyami_encoderincludedir = $(includedir)/libyami +libyami_encoderinclude_HEADERS = $(libyami_encoder_source_h) +noinst_HEADERS = $(libyami_encoder_source_h_priv) +libyami_encoder_la_SOURCES = $(libyami_encoder_source_c) +libyami_encoder_la_LDFLAGS = $(libyami_encoder_ldflags) $(AM_LDFLAGS) +libyami_encoder_la_CPPFLAGS = $(libyami_encoder_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in diff --git a/encoder/Makefile.unittest b/encoder/Makefile.unittest new file mode 100644 index 0000000..4ce8afe --- /dev/null +++ b/encoder/Makefile.unittest @@ -0,0 +1,87 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + $(NULL) + +if BUILD_H264_ENCODER +unittest_SOURCES += vaapiencoder_h264_unittest.cpp +endif + +if BUILD_H265_ENCODER +unittest_SOURCES += vaapiencoder_hevc_unittest.cpp +endif + +if BUILD_JPEG_ENCODER +unittest_SOURCES += vaapiencoder_jpeg_unittest.cpp +endif + +if BUILD_VP8_ENCODER +unittest_SOURCES += vaapiencoder_vp8_unittest.cpp +endif + +if BUILD_VP9_ENCODER +unittest_SOURCES += vaapiencoder_vp9_unittest.cpp +endif + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_encoder.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/codecparsers/libyami_codecparser.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +# Separate the vaapiencoder_host_unittest so that we can detect static +# initialization bugs with the encoder factory. Separation is required +# since any derived encoder that is explicitly constructed in another test +# would hide such bugs. +noinst_PROGRAMS += unittest_host +unittest_host_SOURCES = \ + unittest_main.cpp \ + vaapiencoder_host_unittest.cpp \ + $(NULL) + +unittest_host_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_host_LDADD = \ + libyami_encoder.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/codecparsers/libyami_codecparser.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_host_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_host_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest unittest_host + $(builddir)/unittest + $(builddir)/unittest_host diff --git a/encoder/unittest_main.cpp b/encoder/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/encoder/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/encoder/vaapicodedbuffer.cpp b/encoder/vaapicodedbuffer.cpp new file mode 100644 index 0000000..0808fb3 --- /dev/null +++ b/encoder/vaapicodedbuffer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapicodedbuffer.h" + +#include "vaapi/vaapicontext.h" +#include + +namespace YamiMediaCodec{ +CodedBufferPtr VaapiCodedBuffer::create(const ContextPtr& context, uint32_t bufSize) +{ + CodedBufferPtr coded; + BufObjectPtr buf = VaapiBuffer::create(context, VAEncCodedBufferType, bufSize); + if (buf) + coded.reset(new VaapiCodedBuffer(buf)); + return coded; +} + +bool VaapiCodedBuffer::map() +{ + if (!m_segments) + m_segments = static_cast(m_buf->map()); + return m_segments != NULL; +} + +uint32_t VaapiCodedBuffer::size() +{ + if (!map()) + return 0; + uint32_t size = 0; + VACodedBufferSegment* segment = m_segments; + while (segment != NULL) { + size += segment->size; + segment = static_cast(segment->next); + } + return size; +} + +bool VaapiCodedBuffer::copyInto(void* data) +{ + if (!data) + return false; + if (!map()) + return false; + uint8_t* dest = static_cast(data); + VACodedBufferSegment* segment = m_segments; + while (segment != NULL) { + memcpy(dest, segment->buf, segment->size); + dest += segment->size; + segment = static_cast(segment->next); + } + return true; +} +} diff --git a/encoder/vaapicodedbuffer.h b/encoder/vaapicodedbuffer.h new file mode 100644 index 0000000..d4a6d4a --- /dev/null +++ b/encoder/vaapicodedbuffer.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef vaapicodedbuffer_h +#define vaapicodedbuffer_h + +#include "vaapi/VaapiBuffer.h" +#include "vaapi/vaapiptrs.h" +#include + +namespace YamiMediaCodec{ +class VaapiCodedBuffer +{ +public: + static CodedBufferPtr create(const ContextPtr&, uint32_t bufSize); + ~VaapiCodedBuffer() {} + uint32_t size(); + VABufferID getID() const { + return m_buf->getID(); + } + bool copyInto(void* data); + bool setFlag(uint32_t flag) { m_flags |= flag; return true; } + bool clearFlag(uint32_t flag) { m_flags &= ~flag; return true; } + uint32_t getFlags() { return m_flags; } + +private: + VaapiCodedBuffer(const BufObjectPtr& buf):m_buf(buf), m_segments(NULL), m_flags(0) {} + bool map(); + BufObjectPtr m_buf; + VACodedBufferSegment* m_segments; + uint32_t m_flags; +}; +} +#endif //vaapicodedbuffer_h diff --git a/encoder/vaapiencoder_base.cpp b/encoder/vaapiencoder_base.cpp new file mode 100644 index 0000000..a7c1e89 --- /dev/null +++ b/encoder/vaapiencoder_base.cpp @@ -0,0 +1,808 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_base.h" +#include +#include +#include +#include "common/common_def.h" +#include "common/utils.h" +#include "common/scopedlogger.h" +#include "vaapicodedbuffer.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapisurfaceallocator.h" +#include "vaapi/VaapiUtils.h" + +#define ADJUST_TO_RANGE(v, min, max, promp) \ + do { \ + if (v < min) { \ + WARNING("%s: %s is out of the range", promp, #v); \ + v = min; \ + } \ + if (v > max) { \ + WARNING("%s: %s is out of the range", promp, #v); \ + v = max; \ + } \ + } while (0) + +const uint32_t MaxOutputBuffer=5; +namespace YamiMediaCodec{ +VaapiEncoderBase::VaapiEncoderBase(): + m_entrypoint(VAEntrypointEncSlice), + m_maxOutputBuffer(MaxOutputBuffer), + m_maxCodedbufSize(0) +{ + FUNC_ENTER(); + m_externalDisplay.handle = 0, + m_externalDisplay.type = NATIVE_DISPLAY_AUTO, + + memset(&m_videoParamCommon, 0, sizeof(m_videoParamCommon)); + m_videoParamCommon.size = sizeof(m_videoParamCommon); + m_videoParamCommon.frameRate.frameRateNum = 30; + m_videoParamCommon.frameRate.frameRateDenom = 1; + m_videoParamCommon.intraPeriod = 15; + m_videoParamCommon.ipPeriod = 1; + m_videoParamCommon.numRefFrames = 1; + m_videoParamCommon.rcMode = RATE_CONTROL_CQP; + m_videoParamCommon.rcParams.initQP = 26; + m_videoParamCommon.rcParams.minQP = 1; + m_videoParamCommon.rcParams.maxQP = 51; + m_videoParamCommon.rcParams.disableBitsStuffing = 1; + m_videoParamCommon.bitDepth = 8; + memset(&m_videoParamsHRD, 0, sizeof(m_videoParamsHRD)); + m_videoParamsHRD.windowSize = 1000; + m_videoParamsHRD.targetPercentage = 95; + m_videoParamQualityLevelUpdate = false; + m_videoParamQualityLevel.size = sizeof(m_videoParamQualityLevel); + m_videoParamQualityLevel.level = 0; + m_vaVideoParamQualityLevel = 0; + updateMaxOutputBufferCount(); +} + +VaapiEncoderBase::~VaapiEncoderBase() +{ + cleanupVA(); + INFO("~VaapiEncoderBase"); +} + +void VaapiEncoderBase::setNativeDisplay(NativeDisplay * nativeDisplay) +{ + if (!nativeDisplay || nativeDisplay->type == NATIVE_DISPLAY_AUTO) + return; + + m_externalDisplay = *nativeDisplay; +} + +YamiStatus VaapiEncoderBase::start(void) +{ + FUNC_ENTER(); + if (!initVA()) + return YAMI_FAIL; + + return YAMI_SUCCESS; +} + +void VaapiEncoderBase::flush(void) +{ + /* Current version of VaapiEncoderBase::flush is empty fucntion + * But we may add something in future.All derive class need call this in derive::flush() + */ +} + +YamiStatus VaapiEncoderBase::stop(void) +{ + FUNC_ENTER(); + m_output.clear(); + cleanupVA(); + return YAMI_SUCCESS; +} + +bool VaapiEncoderBase::isBusy() +{ + AutoLock l(m_lock); + return m_output.size() >= m_maxOutputBuffer; +} + +YamiStatus VaapiEncoderBase::encode(VideoEncRawBuffer* inBuffer) +{ + FUNC_ENTER(); + + if (!inBuffer) + return YAMI_SUCCESS; + if (!inBuffer->data && !inBuffer->size) { + // XXX handle EOS when there is B frames + inBuffer->bufAvailable = true; + return YAMI_SUCCESS; + } + VideoFrameRawData frame; + if (!fillFrameRawData(&frame, inBuffer->fourcc, width(), height(), inBuffer->data)) + return YAMI_INVALID_PARAM; + inBuffer->bufAvailable = true; + if (inBuffer->forceKeyFrame) + frame.flags |= VIDEO_FRAME_FLAGS_KEY; + frame.timeStamp = inBuffer->timeStamp; + return encode(&frame); +} + +YamiStatus VaapiEncoderBase::encode(VideoFrameRawData* frame) +{ + if (!frame || !frame->width || !frame->height || !frame->fourcc) + return YAMI_INVALID_PARAM; + + FUNC_ENTER(); + + if (isBusy()) + return YAMI_ENCODE_IS_BUSY; + SurfacePtr surface = createSurface(frame); + if (!surface) + return YAMI_OUT_MEMORY; + return doEncode(surface, frame->timeStamp, frame->flags & VIDEO_FRAME_FLAGS_KEY); +} + +YamiStatus VaapiEncoderBase::encode(const SharedPtr& frame) +{ + if (!frame) + return YAMI_INVALID_PARAM; + if (isBusy()) + return YAMI_ENCODE_IS_BUSY; + SurfacePtr surface = createSurface(frame); + if (!surface) + return YAMI_INVALID_PARAM; + return doEncode(surface, frame->timeStamp, frame->flags & VIDEO_FRAME_FLAGS_KEY); +} + +YamiStatus VaapiEncoderBase::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + FUNC_ENTER(); + YamiStatus ret = YAMI_INVALID_PARAM; + if (!videoEncParams) + return ret; + + DEBUG("type = 0x%08x", type); + switch (type) { + case VideoParamsTypeCommon: { + VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams; + if (common->size == sizeof(VideoParamsCommon)) { + PARAMETER_ASSIGN(*common, m_videoParamCommon); + ret = YAMI_SUCCESS; + } + break; + } + case VideoParamsTypeHRD: { + VideoParamsHRD* videoParamsHRD = (VideoParamsHRD*)videoEncParams; + if (videoParamsHRD->size == sizeof(VideoParamsHRD)) { + PARAMETER_ASSIGN(*videoParamsHRD, m_videoParamsHRD); + ret = YAMI_SUCCESS; + } + break; + } + case VideoParamsTypeQualityLevel: { + VideoParamsQualityLevel* qualityLevel = (VideoParamsQualityLevel*)videoEncParams; + if (qualityLevel->size == sizeof(VideoParamsQualityLevel)) { + PARAMETER_ASSIGN(*qualityLevel, m_videoParamQualityLevel); + ret = YAMI_SUCCESS; + } + + break; + } + default: + ret = YAMI_SUCCESS; + break; + } + return ret; +} + +YamiStatus VaapiEncoderBase::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + FUNC_ENTER(); + YamiStatus ret = YAMI_SUCCESS; + if (!videoEncParams) + return ret; + + DEBUG("type = 0x%08x", type); + switch (type) { + case VideoParamsTypeCommon: { + VideoParamsCommon* common = (VideoParamsCommon*)videoEncParams; + if (common->size == sizeof(VideoParamsCommon)) { + PARAMETER_ASSIGN(m_videoParamCommon, *common); + if(m_videoParamCommon.rcParams.bitRate > 0){ + if(m_videoParamCommon.rcMode != RATE_CONTROL_VBR) + m_videoParamCommon.rcMode = RATE_CONTROL_CBR; + } else{ + m_videoParamCommon.rcMode = RATE_CONTROL_CQP; + } + } else + ret = YAMI_INVALID_PARAM; + m_maxCodedbufSize = 0; // resolution may change, recalculate max codec buffer size when it is requested + + break; + } + case VideoConfigTypeFrameRate: { + VideoConfigFrameRate* frameRateConfig = (VideoConfigFrameRate*)videoEncParams; + if (frameRateConfig->size == sizeof(VideoConfigFrameRate)) { + m_videoParamCommon.frameRate = frameRateConfig->frameRate; + } else + ret = YAMI_INVALID_PARAM; + } + break; + case VideoConfigTypeBitRate: { + VideoConfigBitRate* rcParamsConfig = (VideoConfigBitRate*)videoEncParams; + if (rcParamsConfig->size == sizeof(VideoConfigBitRate)) { + m_videoParamCommon.rcParams = rcParamsConfig->rcParams; + } else + ret = YAMI_INVALID_PARAM; + } + break; + case VideoParamsTypeHRD: { + VideoParamsHRD* videoParamsHRD = (VideoParamsHRD*)videoEncParams; + if (videoParamsHRD->size == sizeof(VideoParamsHRD)) { + PARAMETER_ASSIGN(m_videoParamsHRD, *videoParamsHRD); + ADJUST_TO_RANGE(m_videoParamsHRD.targetPercentage, 50, 100, "target percentage"); + } else + ret = YAMI_INVALID_PARAM; + } + break; + case VideoParamsTypeQualityLevel: { + VideoParamsQualityLevel* videoQualityLevel = (VideoParamsQualityLevel*)videoEncParams; + if (videoQualityLevel->size == sizeof(VideoParamsQualityLevel)) { + if (videoQualityLevel->level != m_videoParamQualityLevel.level) { + PARAMETER_ASSIGN(m_videoParamQualityLevel, *videoQualityLevel); + ADJUST_TO_RANGE(m_videoParamQualityLevel.level, VIDEO_PARAMS_QUALITYLEVEL_NONE, + VIDEO_PARAMS_QUALITYLEVEL_MAX, "quality level"); + m_videoParamQualityLevelUpdate = true; + } + } + else + ret = YAMI_INVALID_PARAM; + } break; + default: + ret = YAMI_INVALID_PARAM; + break; + } + INFO("bitrate: %d", bitRate()); + return ret; +} + +YamiStatus VaapiEncoderBase::setConfig(VideoParamConfigType type, Yami_PTR videoEncConfig) +{ + FUNC_ENTER(); + DEBUG("type = %d", type); + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderBase::getConfig(VideoParamConfigType type, Yami_PTR videoEncConfig) +{ + FUNC_ENTER(); + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderBase::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + *maxSize = 0; + return YAMI_SUCCESS; +} + +#ifdef __BUILD_GET_MV__ +YamiStatus VaapiEncoderBase::getMVBufferSize(uint32_t* Size) +{ + FUNC_ENTER(); + *Size = 0; + return YAMI_SUCCESS; +} +#endif + +struct SurfaceDestroyer { + SurfaceDestroyer(DisplayPtr display) + : m_display(display) + { + } + void operator()(VaapiSurface* surface) + { + VASurfaceID id = surface->getID(); + checkVaapiStatus(vaDestroySurfaces(m_display->getID(), &id, 1), + "vaDestroySurfaces"); + delete surface; + } + +private: + DisplayPtr m_display; +}; + +SurfacePtr VaapiEncoderBase::createNewSurface(uint32_t fourcc) +{ + VASurfaceAttrib attrib; + uint32_t rtFormat; + SurfacePtr surface; + + attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; + attrib.type = VASurfaceAttribPixelFormat; + attrib.value.type = VAGenericValueTypeInteger; + attrib.value.value.i = fourcc; + + rtFormat = getRtFormat(fourcc); + if (!rtFormat) { + ERROR("unsupported fourcc %x", fourcc); + return surface; + } + + VASurfaceID id; + uint32_t width = m_videoParamCommon.resolution.width; + uint32_t height = m_videoParamCommon.resolution.height; + VAStatus status = vaCreateSurfaces(m_display->getID(), rtFormat, width, height, + &id, 1, &attrib, 1); + if (!checkVaapiStatus(status, "vaCreateSurfaces")) + return surface; + surface.reset(new VaapiSurface((intptr_t)id, width, height, fourcc), + SurfaceDestroyer(m_display)); + return surface; +} + +SurfacePtr VaapiEncoderBase::createSurface() +{ + SurfacePtr s; + if (m_pool) { + s = m_pool->alloc(); + } else { + ERROR("BUG!: surface pool not created"); + } + return s; +} + +static bool copyImage(uint8_t* destBase, + const uint32_t destOffsets[3], const uint32_t destPitches[3], + const uint8_t* srcBase, + const uint32_t srcOffsets[3], const uint32_t srcPitches[3], + const uint32_t width[3], const uint32_t height[3], uint32_t planes) +{ + for (uint32_t i = 0; i < planes; i++) { + uint32_t w = width[i]; + uint32_t h = height[i]; + if (w > destPitches[i] || w > srcPitches[i]) { + ERROR("can't copy, plane = %d, width = %d, srcPitch = %d, destPitch = %d", + i, w, srcPitches[i], destPitches[i]); + return false; + } + const uint8_t* src = srcBase + srcOffsets[i]; + uint8_t* dest = destBase + destOffsets[i]; + + for (uint32_t j = 0; j < h; j++) { + memcpy(dest, src, w); + src += srcPitches[i]; + dest += destPitches[i]; + } + } + return true; +} + +SurfacePtr VaapiEncoderBase::createSurface(VideoFrameRawData* frame) +{ + uint32_t fourcc = frame->fourcc; + + SurfacePtr surface = createNewSurface(fourcc); + SurfacePtr nil; + if (!surface) + return nil; + + uint32_t width[3]; + uint32_t height[3]; + uint32_t planes; + if (!getPlaneResolution(fourcc, frame->width, frame->height, width, height, planes)) { + ERROR("invalid input format"); + return nil; + } + + VAImage image; + VADisplay display = m_display->getID(); + uint8_t* dest = mapSurfaceToImage(display, surface->getID(), image); + if (!dest) { + ERROR("map image failed"); + return nil; + } + uint8_t* src = reinterpret_cast(frame->handle); + if (!copyImage(dest, image.offsets, image.pitches, src, + frame->offset, frame->pitch, width, height, planes)) { + ERROR("failed to copy image"); + unmapImage(display, image); + return nil; + } + unmapImage(display, image); + return surface; +} + +SurfacePtr VaapiEncoderBase::createSurface(const SharedPtr& frame) +{ + SurfacePtr surface(new VaapiSurface(frame)); + return surface; +} + +void VaapiEncoderBase::fill(VAEncMiscParameterHRD* hrd) const +{ + if (m_videoParamsHRD.bufferSize && m_videoParamsHRD.initBufferFullness) { + hrd->buffer_size = m_videoParamsHRD.bufferSize; + hrd->initial_buffer_fullness = m_videoParamsHRD.initBufferFullness; + } + else { + hrd->initial_buffer_fullness = m_videoParamCommon.rcParams.bitRate; + hrd->buffer_size = hrd->initial_buffer_fullness * 2; + } + + DEBUG("bitRate: %d, hrd->buffer_size: %d, hrd->initial_buffer_fullness: %d", + m_videoParamCommon.rcParams.bitRate, hrd->buffer_size,hrd->initial_buffer_fullness); +} + +void VaapiEncoderBase::fill(VAEncMiscParameterRateControl* rateControl, uint32_t temporalID) const +{ +#if VA_CHECK_VERSION(0, 39, 4) + rateControl->rc_flags.bits.temporal_id = temporalID; +#endif + //The highest layer's bitrate is bitRate() + rateControl->bits_per_second = (temporalID == m_videoParamCommon.temporalLayers.numLayersMinus1) ? bitRate() : m_videoParamCommon.temporalLayers.bitRate[temporalID]; + rateControl->initial_qp = m_videoParamCommon.rcParams.initQP; + rateControl->min_qp = m_videoParamCommon.rcParams.minQP; + /*FIXME: where to find max_qp */ + rateControl->window_size = m_videoParamsHRD.windowSize; + rateControl->target_percentage = m_videoParamsHRD.targetPercentage; + rateControl->rc_flags.bits.disable_frame_skip = m_videoParamCommon.rcParams.disableFrameSkip; + rateControl->rc_flags.bits.disable_bit_stuffing = m_videoParamCommon.rcParams.disableBitsStuffing; + +} + +void VaapiEncoderBase::fill(VAEncMiscParameterFrameRate* frameRate, uint32_t temporalID) const +{ +#if VA_CHECK_VERSION(0, 39, 4) + frameRate->framerate_flags.bits.temporal_id = temporalID; +#endif + //The highest layer's framerate is fps() + frameRate->framerate = (temporalID == m_videoParamCommon.temporalLayers.numLayersMinus1) ? fps() : m_svctFrameRate[temporalID].frameRateNum | (m_svctFrameRate[temporalID].frameRateDenom << 16); +} + +bool VaapiEncoderBase::ensureRateControl(VaapiEncPicture* picture, uint32_t temporalID) +{ + VAEncMiscParameterRateControl* rateControl = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeRateControl, rateControl)) + return false; + if (rateControl) + fill(rateControl, temporalID); + return true; +} +bool VaapiEncoderBase::ensureFrameRate(VaapiEncPicture* picture, uint32_t temporalID) +{ + VAEncMiscParameterFrameRate* frameRate = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeFrameRate, frameRate)) + return false; + if (frameRate) + fill(frameRate, temporalID); + return true; +} + +/* Generates additional control parameters */ +bool VaapiEncoderBase::ensureMiscParams (VaapiEncPicture* picture) +{ + VAEncMiscParameterHRD* hrd = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeHRD, hrd)) + return false; + if (hrd) + fill(hrd); + + if (!fillQualityLevel(picture)) + return false; + + VideoRateControl mode = rateControlMode(); + if (mode == RATE_CONTROL_CBR || mode == RATE_CONTROL_VBR) { + //+1 for the highest layer + uint32_t layers = m_videoParamCommon.temporalLayers.numLayersMinus1 + 1; + for (uint32_t i = 0; i < layers; i++) { + if (!ensureRateControl(picture, i)) + return false; + if (!ensureFrameRate(picture, i)) + return false; + } + } +#ifdef __ENABLE_H265_ENC_ON_STUDIO_VA__ + //need to create misc parameter even though don't fill any value, + //or else the picture's quality will be low. + else { + VAEncMiscParameterRateControl* rateControl = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeRateControl, rateControl)) + return false; + } +#endif + return true; +} + +struct ProfileMapItem { + VideoProfile videoProfile; + VAProfile vaProfile; +}; + +const ProfileMapItem g_profileMap[] = { + { PROFILE_H264_CONSTRAINED_BASELINE, VAProfileH264ConstrainedBaseline }, + { PROFILE_H264_MAIN, VAProfileH264Main }, + { PROFILE_H264_HIGH, VAProfileH264High }, + { PROFILE_JPEG_BASELINE, VAProfileJPEGBaseline }, +#if VA_CHECK_VERSION(0, 38, 0) + { PROFILE_H265_MAIN, VAProfileHEVCMain }, + { PROFILE_H265_MAIN10, VAProfileHEVCMain10 }, +#endif +}; + +VideoProfile VaapiEncoderBase::profile() const +{ + for (size_t i = 0; i < N_ELEMENTS(g_profileMap); i++) { + if (m_videoParamCommon.profile == g_profileMap[i].vaProfile) + return g_profileMap[i].videoProfile; + } + return PROFILE_INVALID; +} + +void VaapiEncoderBase::cleanupVA() +{ + m_pool.reset(); + m_alloc.reset(); + m_context.reset(); + m_display.reset(); +} + +void unrefAllocator(SurfaceAllocator* allocator) +{ + allocator->unref(allocator); +} + +bool VaapiEncoderBase::initVA() +{ + VAConfigAttrib attrib[2], *pAttrib = NULL; + ConfigPtr config; + int32_t attribCount = 0; + FUNC_ENTER(); + + m_display = VaapiDisplay::create(m_externalDisplay); + if (!m_display) { + ERROR("failed to create display"); + return false; + } + + if (RATE_CONTROL_NONE != m_videoParamCommon.rcMode) { + attrib[0].type = VAConfigAttribRateControl; + attrib[0].value = m_videoParamCommon.rcMode; + pAttrib = attrib; + attribCount = 1; +#ifdef __ENABLE_H265_ENC_ON_STUDIO_VA__ + /* + It's necessary to pass two attribute: + VAConfigAttribRTFormat and VAConfigAttribRateControl to libva; + The value of VAConfigAttribRateControl should be "VA_RC_MB|VA_RC_CBR" not RATE_CONTROL_CBR; + Or else, HEVC encoding will end up with an error: attribute not supported. + */ + if (RATE_CONTROL_CBR == m_videoParamCommon.rcMode) { + attrib[0].type = VAConfigAttribRTFormat; + attrib[0].value = 0; + attrib[1].type = VAConfigAttribRateControl; + attrib[1].value = VA_RC_MB | VA_RC_CBR; //RATE_CONTROL_CBR + pAttrib = attrib; + attribCount = 2; + } +#endif + } + + YamiStatus status = VaapiConfig::create(m_display, m_videoParamCommon.profile, m_entrypoint, pAttrib, attribCount, config); + if (YAMI_SUCCESS != status) { + ERROR("failed to create config"); + return false; + } + + m_alloc.reset(new VaapiSurfaceAllocator(m_display->getID()), unrefAllocator); + + int32_t surfaceWidth = ALIGN16(m_videoParamCommon.resolution.width); + int32_t surfaceHeight = ALIGN16(m_videoParamCommon.resolution.height); + uint32_t fourcc = YAMI_FOURCC_NV12; + if (m_videoParamCommon.bitDepth != 10 && m_videoParamCommon.bitDepth != 8) { + ERROR("unsupported bit depth(%d)", m_videoParamCommon.bitDepth); + return false; + } + if (10 == m_videoParamCommon.bitDepth) + fourcc = YAMI_FOURCC_P010; + m_pool = SurfacePool::create(m_alloc, fourcc, (uint32_t)surfaceWidth, (uint32_t)surfaceHeight, m_maxOutputBuffer); + if (!m_pool) + return false; + + std::vector surfaces; + m_pool->peekSurfaces(surfaces); + + m_context = VaapiContext::create(config, + surfaceWidth, + surfaceHeight, + VA_PROGRESSIVE, &surfaces[0], surfaces.size()); + if (!m_context) { + ERROR("failed to create context"); + return false; + } + + return true; +} + +YamiStatus VaapiEncoderBase::checkEmpty(VideoEncOutputBuffer* outBuffer, bool* outEmpty) +{ + bool isEmpty; + FUNC_ENTER(); + if (!outBuffer) + return YAMI_INVALID_PARAM; + + AutoLock l(m_lock); + isEmpty = m_output.empty(); + INFO("output queue size: %zu\n", m_output.size()); + + *outEmpty = isEmpty; + + if (isEmpty) { + if (outBuffer->format == OUTPUT_CODEC_DATA) + return getCodecConfig(outBuffer); + return YAMI_ENCODE_BUFFER_NO_MORE; + } + return YAMI_SUCCESS; +} + +void VaapiEncoderBase::getPicture(PicturePtr &outPicture) +{ + outPicture = m_output.front(); + outPicture->sync(); +} + +YamiStatus VaapiEncoderBase::checkCodecData(VideoEncOutputBuffer* outBuffer) +{ + if (outBuffer->format != OUTPUT_CODEC_DATA) { + AutoLock l(m_lock); + m_output.pop_front(); + } + return YAMI_SUCCESS; +} + +#ifndef __BUILD_GET_MV__ +YamiStatus VaapiEncoderBase::getOutput(VideoEncOutputBuffer* outBuffer, bool withWait) +{ + bool isEmpty; + PicturePtr picture; + YamiStatus ret; + FUNC_ENTER(); + ret = checkEmpty(outBuffer, &isEmpty); + if (isEmpty) + return ret; + + getPicture(picture); + ret = picture->getOutput(outBuffer); + if (ret != YAMI_SUCCESS) + return ret; + + outBuffer->timeStamp = picture->m_timeStamp; + outBuffer->temporalID = picture->m_temporalID; + checkCodecData(outBuffer); + return YAMI_SUCCESS; +} + +#else + +YamiStatus VaapiEncoderBase::getOutput(VideoEncOutputBuffer* outBuffer, VideoEncMVBuffer* MVBuffer, bool withWait) +{ + void *data = NULL; + uint32_t mappedSize; + bool isEmpty; + PicturePtr picture; + YamiStatus ret; + FUNC_ENTER(); + + ret = checkEmpty(outBuffer, &isEmpty); + if (isEmpty) + return ret; + getPicture(picture); + + ret = picture->getOutput(outBuffer); + if (ret != YAMI_SUCCESS) + return ret; + if (!picture->editMVBuffer(data, &mappedSize)) + return ret; + if (data) + memcpy(MVBuffer->data, data, mappedSize); + outBuffer->timeStamp = picture->m_timeStamp; + outBuffer->temporalID = picture->m_temporalID; + checkCodecData(outBuffer); + return YAMI_SUCCESS; +} + +#endif + +YamiStatus VaapiEncoderBase::getCodecConfig(VideoEncOutputBuffer* outBuffer) +{ + ASSERT(outBuffer && (outBuffer->format == OUTPUT_CODEC_DATA)); + outBuffer->dataSize = 0; + return YAMI_SUCCESS; +} + +bool VaapiEncoderBase::mapToRange(uint32_t& value, + uint32_t min, uint32_t max, + uint32_t level, + uint32_t minLevel, uint32_t maxLevel) +{ + float fValue; + if (minLevel >= maxLevel) { + ERROR("minLevel(%d) >= maxLevel(%d)", minLevel, maxLevel); + return false; + } + if (level > maxLevel || level < minLevel) { + ERROR("level(%d) not in the range[minLevel(%d), maxLevel(%d)]", level, minLevel, maxLevel); + return false; + } + if (min > max) { + ERROR("min(%d) > max(%d)", min, max); + return false; + } + + fValue = min + 1.0 * (max - min) / (maxLevel - minLevel) * (level - minLevel); + value = roundf(fValue); + + return true; +} + +bool VaapiEncoderBase::mapQualityLevel() +{ + VAConfigAttrib attrib; + uint32_t qualityLevel; + + attrib.type = VAConfigAttribEncQualityRange; + VAStatus vaStatus = vaGetConfigAttributes(m_display->getID(), + m_videoParamCommon.profile, m_entrypoint, + &attrib, 1); + if (vaStatus != VA_STATUS_SUCCESS || VA_ATTRIB_NOT_SUPPORTED == attrib.value) { + ERROR("unsupported params encode quality level setting!"); + return false; + } + + if (!mapToRange(qualityLevel, + 0, attrib.value, + m_videoParamQualityLevel.level, + VIDEO_PARAMS_QUALITYLEVEL_NONE, VIDEO_PARAMS_QUALITYLEVEL_MAX)) + return false; + + m_vaVideoParamQualityLevel = qualityLevel; + return true; +} + +bool VaapiEncoderBase::fillQualityLevel(VaapiEncPicture* picture) +{ + if (m_videoParamQualityLevelUpdate) { + if (mapQualityLevel()) + m_videoParamQualityLevelUpdate = false; + else + return false; + } + + if (0 == m_vaVideoParamQualityLevel) + return true; + + VAEncMiscParameterBufferQualityLevel* qualityLevel = NULL; + if (picture->newMisc(VAEncMiscParameterTypeQualityLevel, qualityLevel)) + if (qualityLevel) { + qualityLevel->quality_level = m_vaVideoParamQualityLevel; + return true; + } + + return false; +} +} diff --git a/encoder/vaapiencoder_base.h b/encoder/vaapiencoder_base.h new file mode 100644 index 0000000..678e780 --- /dev/null +++ b/encoder/vaapiencoder_base.h @@ -0,0 +1,226 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_base_h +#define vaapiencoder_base_h + +#include "VideoEncoderDefs.h" +#include "VideoEncoderInterface.h" +#include "common/lock.h" +#include "common/log.h" +#include "common/surfacepool.h" +#include "vaapiencpicture.h" +#include "vaapilayerid.h" +#include "vaapi/VaapiBuffer.h" +#include "vaapi/vaapiptrs.h" +#include "vaapi/VaapiSurface.h" + +#include +#include + +template class FactoryTest; + +namespace YamiMediaCodec{ +enum VaapiEncReorderState +{ + VAAPI_ENC_REORD_NONE = 0, + VAAPI_ENC_REORD_DUMP_FRAMES = 1, + VAAPI_ENC_REORD_WAIT_FRAMES = 2 +}; + +class VaapiEncoderBase : public IVideoEncoder { + typedef SharedPtr PicturePtr; +public: + VaapiEncoderBase(); + virtual ~VaapiEncoderBase(); + + virtual void setNativeDisplay(NativeDisplay * nativeDisplay); + virtual YamiStatus start(void) = 0; + virtual void flush(void) = 0; + virtual YamiStatus stop(void) = 0; + virtual YamiStatus encode(VideoEncRawBuffer* inBuffer); + virtual YamiStatus encode(VideoFrameRawData* frame); + virtual YamiStatus encode(const SharedPtr& frame); + +/* + * getOutput can be called several time for a frame (such as first time codec data, and second time others) + * encode will provide encoded data according to the format (whole frame, codec_data, sigle NAL etc) + * If the buffer passed to encoded is not big enough, this API call will return YAMI_ENCODE_BUFFER_TOO_SMALL + * and caller should provide a big enough buffer and call again + */ +#ifndef __BUILD_GET_MV__ + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, bool withWait = false); +#else + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, VideoEncMVBuffer* MVBuffer, bool withWait = false); +#endif + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setConfig(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus getConfig(VideoParamConfigType type, Yami_PTR); + + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); + +#ifdef __BUILD_GET_MV__ + /// get MV buffer size. + virtual YamiStatus getMVBufferSize(uint32_t* Size); +#endif + virtual void getPicture(PicturePtr &outPicture); + virtual YamiStatus checkCodecData(VideoEncOutputBuffer* outBuffer); + virtual YamiStatus checkEmpty(VideoEncOutputBuffer* outBuffer, bool* outEmpty); + virtual YamiStatus getStatistics(VideoStatistics* videoStat) + { + return YAMI_SUCCESS; + }; + +protected: + //utils functions for derived class + SurfacePtr createNewSurface(uint32_t fourcc); + SurfacePtr createSurface(); + SurfacePtr createSurface(VideoFrameRawData* frame); + SurfacePtr createSurface(const SharedPtr& frame); + + template + bool output(const SharedPtr&); + virtual YamiStatus getCodecConfig(VideoEncOutputBuffer* outBuffer); + + //virtual functions + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, bool forceKeyFrame = false) = 0; + + //rate control related things + void fill(VAEncMiscParameterHRD*) const ; + void fill(VAEncMiscParameterRateControl*, uint32_t temporalID = 0) const; + void fill(VAEncMiscParameterFrameRate*, uint32_t temporalID) const; + virtual bool ensureMiscParams(VaapiEncPicture*); + bool ensureRateControl(VaapiEncPicture* picture, uint32_t temporalID); + bool ensureFrameRate(VaapiEncPicture* picture, uint32_t temporalID); + + //properties + VideoProfile profile() const; + uint8_t level () const { + return m_videoParamCommon.level; + } + uint32_t width() const { + return m_videoParamCommon.resolution.width; + } + uint32_t height() const { + return m_videoParamCommon.resolution.height; + } + uint32_t intraPeriod() const { + return m_videoParamCommon.intraPeriod; + } + uint32_t ipPeriod() const { + return m_videoParamCommon.ipPeriod; + } + + uint32_t numRefFrames() const { + return m_videoParamCommon.numRefFrames; + } + + uint32_t frameRateDenom() const { + return m_videoParamCommon.frameRate.frameRateDenom; + } + uint32_t frameRateNum() const { + return m_videoParamCommon.frameRate.frameRateNum; + } + + uint32_t fps() const { + return m_videoParamCommon.frameRate.frameRateNum / m_videoParamCommon.frameRate.frameRateDenom; + } + + //rate control + VideoRateControl rateControlMode() const { + return m_videoParamCommon.rcMode; + } + uint32_t bitRate() const { + return m_videoParamCommon.rcParams.bitRate; + } + uint32_t initQP() const { + return m_videoParamCommon.rcParams.initQP; + } + + uint32_t& initQP() { return m_videoParamCommon.rcParams.initQP; } + + uint32_t minQP() const { + return m_videoParamCommon.rcParams.minQP; + } + + uint32_t& minQP() { + return m_videoParamCommon.rcParams.minQP; + } + + uint32_t maxQP() const { + return m_videoParamCommon.rcParams.maxQP; + } + + bool isBusy(); + + bool mapToRange(uint32_t& value, + uint32_t min, uint32_t max, + uint32_t level, + uint32_t minLevel, uint32_t maxLevel); + bool mapQualityLevel(); + bool fillQualityLevel(VaapiEncPicture*); + + DisplayPtr m_display; + ContextPtr m_context; + VAEntrypoint m_entrypoint; + VideoParamsCommon m_videoParamCommon; + VideoParamsHRD m_videoParamsHRD; + bool m_videoParamQualityLevelUpdate; + VideoParamsQualityLevel m_videoParamQualityLevel; + uint32_t m_vaVideoParamQualityLevel; + uint32_t m_maxOutputBuffer; // max count of frames are encoding in parallel, it hurts performance when m_maxOutputBuffer is too big. + uint32_t m_maxCodedbufSize; + LayerFrameRates m_svctFrameRate; + +private: + bool initVA(); + void cleanupVA(); + NativeDisplay m_externalDisplay; + + SharedPtr m_pool; + SharedPtr m_alloc; + + Lock m_lock; + typedef std::deque OutputQueue; + OutputQueue m_output; + + bool updateMaxOutputBufferCount() { + if (m_maxOutputBuffer < m_videoParamCommon.leastInputCount + 3) + m_maxOutputBuffer = m_videoParamCommon.leastInputCount + 3; + return true; + } +}; + +template +bool VaapiEncoderBase::output(const SharedPtr& pic) +{ + bool ret; + PicturePtr picture; + AutoLock l(m_lock); + picture = DynamicPointerCast(pic); + if (picture) { + m_output.push_back(picture); + ret = true; + } else { + ERROR("output need a subclass of VaapiEncPicutre"); + ret = false; + } + return ret; +} + +} +#endif /* vaapiencoder_base_h */ diff --git a/encoder/vaapiencoder_factory.h b/encoder/vaapiencoder_factory.h new file mode 100644 index 0000000..d03f149 --- /dev/null +++ b/encoder/vaapiencoder_factory.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_factory_h +#define vaapiencoder_factory_h + +#include "common/factory.h" +#include "VideoEncoderInterface.h" + +namespace YamiMediaCodec { + +typedef Factory VaapiEncoderFactory; + +} // namespace YamiMediaCodec +#endif // vaapiencoder_factory_h diff --git a/encoder/vaapiencoder_h264.cpp b/encoder/vaapiencoder_h264.cpp new file mode 100644 index 0000000..f64147b --- /dev/null +++ b/encoder/vaapiencoder_h264.cpp @@ -0,0 +1,1951 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_h264.h" +#include +#include "codecparsers/bitWriter.h" +#include "common/scopedlogger.h" +#include "common/common_def.h" +#include "common/Functional.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapicodedbuffer.h" +#include "vaapiencpicture.h" +#include +#include + +namespace YamiMediaCodec{ +//shortcuts +typedef VaapiEncoderH264::PicturePtr PicturePtr; +typedef VaapiEncoderH264::ReferencePtr ReferencePtr; +typedef VaapiEncoderH264::StreamHeaderPtr StreamHeaderPtr; + +using YamiParser::BitWriter; +using std::list; +using std::vector; + +#define LEVEL51_MAX_MBPS 983040 +#define H264_FRAME_FR 172 +#define H264_MIN_CR 2 +#define H264_NAL_START_CODE 0x000001 + +#define VAAPI_ENCODER_H264_NAL_REF_IDC_NONE 0 +#define VAAPI_ENCODER_H264_NAL_REF_IDC_LOW 1 +#define VAAPI_ENCODER_H264_NAL_REF_IDC_MEDIUM 2 +#define VAAPI_ENCODER_H264_NAL_REF_IDC_HIGH 3 + +#define H264_SLICE_TYPE_P 0 +#define H264_SLICE_TYPE_B 1 +#define H264_SLICE_TYPE_I 2 + +typedef enum { + VAAPI_ENCODER_H264_NAL_UNKNOWN = 0, + VAAPI_ENCODER_H264_NAL_NON_IDR = 1, + VAAPI_ENCODER_H264_NAL_IDR = 5, /* ref_idc != 0 */ + VAAPI_ENCODER_H264_NAL_SEI = 6, /* ref_idc == 0 */ + VAAPI_ENCODER_H264_NAL_SPS = 7, + VAAPI_ENCODER_H264_NAL_PPS = 8, + VAAPI_ENCODER_H264_NAL_PREFIX = 14, + VAAPI_ENCODER_H264_NAL_SUBSET_SPS = 15 +} VaapiEncoderH264NalType; + +/* Refer to H.264 spec Table A-1 l Level limits */ +struct H264LevelLimits { + uint32_t levelIdc; + uint32_t maxMBPS; + uint32_t minCR; +}; + +#define SCALABILITY_INFO_PAYLOAD_TYPE 24 + +static const H264LevelLimits LevelLimits[] = { + {40, 245760, 4}, + {41, 245760, 2}, + {42, 522240, 2}, + {50, 589824, 2}, + {51, 983040, 2}, +}; + +static inline bool +_poc_greater_than (uint32_t poc1, uint32_t poc2, uint32_t max_poc) +{ + return (((poc1 - poc2) & (max_poc - 1)) < max_poc / 2); +} + +/* Get slice_type value for H.264 specification */ +static uint8_t +h264_get_slice_type (VaapiPictureType type) +{ + switch (type) { + case VAAPI_PICTURE_I: + return 2; + case VAAPI_PICTURE_P: + return 0; + case VAAPI_PICTURE_B: + return 1; + default: + return -1; + } + return -1; +} + +/* Get log2_max_frame_num value for H.264 specification */ +static uint32_t +h264_get_log2_max_frame_num (uint32_t num) +{ + uint32_t ret = 0; + + while (num) { + ++ret; + num >>= 1; + } + if (ret <= 4) + ret = 4; + else if (ret > 10) + ret = 10; + /* must be greater than 4 */ + return ret; +} + +/* Determines the cpbBrNalFactor based on the supplied profile */ +static uint32_t +h264_get_cpb_nal_factor(VideoProfile profile) +{ + uint32_t f; + + /* Table A-2 */ + switch (profile) { + case PROFILE_H264_HIGH: + f = 1500; + break; + case PROFILE_H264_HIGH10: + f = 3600; + break; + case PROFILE_H264_HIGH422: + case PROFILE_H264_HIGH444: + f = 4800; + break; + default: + f = 1200; + break; + } + return f; +} + +static uint8_t h264_get_profile_idc(VideoProfile profile) +{ + uint8_t idc; + switch (profile) { + case PROFILE_H264_CONSTRAINED_BASELINE: + idc = 66; + break; + case PROFILE_H264_MAIN: + idc = 77; + break; + case PROFILE_H264_HIGH: + idc = 100; + break; + default: + assert(0); + } + return idc; + +} + +BOOL +bit_writer_put_ue(BitWriter *bitwriter, uint32_t value) +{ + uint32_t size_in_bits = 0; + uint32_t tmp_value = ++value; + + while (tmp_value) { + ++size_in_bits; + tmp_value >>= 1; + } + if (size_in_bits > 1 + && !bitwriter->writeBits(0, size_in_bits - 1)) + return FALSE; + if (!bitwriter->writeBits(value, size_in_bits)) + return FALSE; + return TRUE; +} + +BOOL +bit_writer_put_se(BitWriter *bitwriter, int32_t value) +{ + uint32_t new_val; + + if (value <= 0) + new_val = -(value<<1); + else + new_val = (value<<1) - 1; + + if (!bit_writer_put_ue(bitwriter, new_val)) + return FALSE; + return TRUE; +} + + +static BOOL +bit_writer_write_nal_header( + BitWriter *bitwriter, + uint32_t nal_ref_idc, + uint32_t nal_unit_type +) +{ + bitwriter->writeBits(0, 1); + bitwriter->writeBits(nal_ref_idc, 2); + bitwriter->writeBits(nal_unit_type, 5); + return TRUE; +} + +static BOOL +bit_writer_write_trailing_bits(BitWriter *bitwriter) +{ + bitwriter->writeBits(1, 1); + bitwriter->writeToBytesAligned(); + return TRUE; +} + +static BOOL +bit_writer_write_sei(BitWriter* bitwriter, + const VAEncSequenceParameterBufferH264* const seq, + uint32_t temporalLayerNum, const LayerFrameRates& svctFrameRate) +{ + BitWriter scalabilityInfoWriter; + uint32_t i; + + /* Write scalability_info */ + scalabilityInfoWriter.writeBits(0, 1); // temporal_id_nesting_flag: false + scalabilityInfoWriter.writeBits( + 0, 1); // priority_layer_info_present_flag: false + scalabilityInfoWriter.writeBits(0, 1); // priority_id_setting_flag: false + bit_writer_put_ue(&scalabilityInfoWriter, + temporalLayerNum - 1); // num_layers_minus1 + + for (i = 0; i < temporalLayerNum; i++) { + bit_writer_put_ue(&scalabilityInfoWriter, i); // layer_id[i] + scalabilityInfoWriter.writeBits(0, 6); // priority_id[i] + scalabilityInfoWriter.writeBits(0, 1); // discardable_flag[i] + scalabilityInfoWriter.writeBits(0, 3); // dependency_id[i] + scalabilityInfoWriter.writeBits(0, 4); // quality_id[i] + scalabilityInfoWriter.writeBits(i, 3); // temporal_id[i] + scalabilityInfoWriter.writeBits(0, 1); // sub_pic_layer_flag[i] + scalabilityInfoWriter.writeBits(0, 1); // sub_region_layer_flag[i] + scalabilityInfoWriter.writeBits( + 0, 1); // iroi_division_info_present_flag[i] + scalabilityInfoWriter.writeBits( + 0, 1); // profile_level_info_present_flag[i] + scalabilityInfoWriter.writeBits(0, 1); // bitrate_info_present_flag[i] + scalabilityInfoWriter.writeBits(1, 1); // frm_rate_info_present_flag[i] + scalabilityInfoWriter.writeBits(1, 1); // frm_size_info_present_flag[i] + scalabilityInfoWriter.writeBits( + 0, 1); // layer_dependency_info_present_flag[i] + scalabilityInfoWriter.writeBits( + 0, 1); // parameter_sets_info_present_flag[i] + scalabilityInfoWriter.writeBits( + 0, 1); // bitstream_restriction_info_present_flag[i] + scalabilityInfoWriter.writeBits(0, 1); // exact_interlayer_pred_flag[i] + scalabilityInfoWriter.writeBits(0, 1); // layer_conversion_flag[i] + scalabilityInfoWriter.writeBits(0, 1); // layer_output_flag[i] + + scalabilityInfoWriter.writeBits(0, 2); // constant_frm_bitrate_idc[i] + float layerFps = (1.0 * svctFrameRate[i].frameRateNum) / svctFrameRate[i].frameRateDenom; + scalabilityInfoWriter.writeBits((int)floor(layerFps * 256 + 0.5), + 16); // avg_frm_rate + + bit_writer_put_ue(&scalabilityInfoWriter, + seq->picture_width_in_mbs + - 1); // frm_width_in_mbs_minus1 + bit_writer_put_ue(&scalabilityInfoWriter, + seq->picture_height_in_mbs + - 1); // frm_height_in_mbs_minus1 + + bit_writer_put_ue(&scalabilityInfoWriter, + 0); // layer_dependency_info_src_layer_id_delta[i] + bit_writer_put_ue(&scalabilityInfoWriter, + 0); // parameter_sets_info_src_layer_id_delta[i] + } + + /* rbsp_trailing_bits */ + bit_writer_write_trailing_bits(&scalabilityInfoWriter); + + uint32_t scalabilityInfoBytes = scalabilityInfoWriter.getCodedBitsCount() + / 8; + uint8_t* scalabilityInfoData = scalabilityInfoWriter.getBitWriterData(); + ASSERT(scalabilityInfoBytes && scalabilityInfoData); + + bit_writer_write_nal_header(bitwriter, VAAPI_ENCODER_H264_NAL_REF_IDC_NONE, + VAAPI_ENCODER_H264_NAL_SEI); + + DEBUG("scalabilityInfoBytes is %d", scalabilityInfoBytes); + + bitwriter->writeBits(SCALABILITY_INFO_PAYLOAD_TYPE, 8); + bitwriter->writeBits(scalabilityInfoBytes, 8); + + for (i = 0; i < scalabilityInfoBytes; i++) { + bitwriter->writeBits(scalabilityInfoData[i], 8); + } + /* rbsp_trailing_bits */ + bit_writer_write_trailing_bits(bitwriter); + + return TRUE; +} + +static BOOL +bit_writer_write_sps(BitWriter* bitwriter, + const VAEncSequenceParameterBufferH264* const seq, + VideoProfile profile) +{ + uint32_t constraint_set0_flag, constraint_set1_flag; + uint32_t constraint_set2_flag, constraint_set3_flag; + uint32_t gaps_in_frame_num_value_allowed_flag = 0; // ?? + BOOL nal_hrd_parameters_present_flag; + + uint32_t b_qpprime_y_zero_transform_bypass = 0; + uint32_t residual_color_transform_flag = 0; + uint32_t pic_height_in_map_units = + (seq->seq_fields.bits.frame_mbs_only_flag ? + seq->picture_height_in_mbs : seq->picture_height_in_mbs/2); + uint32_t mb_adaptive_frame_field = !seq->seq_fields.bits.frame_mbs_only_flag; + uint32_t i = 0; + + constraint_set0_flag = 0; + constraint_set1_flag = profile <= PROFILE_H264_MAIN; + constraint_set2_flag = 0; + constraint_set3_flag = 0; + + bit_writer_write_nal_header (bitwriter, + VAAPI_ENCODER_H264_NAL_REF_IDC_HIGH, VAAPI_ENCODER_H264_NAL_SPS); + /* profile_idc */ + bitwriter->writeBits(h264_get_profile_idc(profile), 8); + /* constraint_set0_flag */ + bitwriter->writeBits(constraint_set0_flag, 1); + /* constraint_set1_flag */ + bitwriter->writeBits(constraint_set1_flag, 1); + /* constraint_set2_flag */ + bitwriter->writeBits(constraint_set2_flag, 1); + /* constraint_set3_flag */ + bitwriter->writeBits(constraint_set3_flag, 1); + /* reserved_zero_4bits */ + bitwriter->writeBits(0, 4); + /* level_idc */ + bitwriter->writeBits(seq->level_idc, 8); + /* seq_parameter_set_id */ + bit_writer_put_ue(bitwriter, seq->seq_parameter_set_id); + + if (profile == PROFILE_H264_HIGH) { + /* for high profile */ + /* chroma_format_idc = 1, 4:2:0*/ + bit_writer_put_ue(bitwriter, seq->seq_fields.bits.chroma_format_idc); + if (3 == seq->seq_fields.bits.chroma_format_idc) { + bitwriter->writeBits(residual_color_transform_flag, 1); + } + /* bit_depth_luma_minus8 */ + bit_writer_put_ue(bitwriter, seq->bit_depth_luma_minus8); + /* bit_depth_chroma_minus8 */ + bit_writer_put_ue(bitwriter, seq->bit_depth_chroma_minus8); + /* b_qpprime_y_zero_transform_bypass */ + bitwriter->writeBits(b_qpprime_y_zero_transform_bypass, 1); + assert(seq->seq_fields.bits.seq_scaling_matrix_present_flag == 0); + /*seq_scaling_matrix_present_flag */ + bitwriter->writeBits(seq->seq_fields.bits.seq_scaling_matrix_present_flag, 1); + + #if 0 + if (seq->seq_fields.bits.seq_scaling_matrix_present_flag) { + for (i = 0; i < (seq->seq_fields.bits.chroma_format_idc != 3 ? 8 : 12); i++) { + bit_writer_put_bits_uint8(bitwriter, seq->seq_fields.bits.seq_scaling_list_present_flag, 1); + if (seq->seq_fields.bits.seq_scaling_list_present_flag) { + assert(0); + /* FIXME, need write scaling list if seq_scaling_matrix_present_flag ==1*/ + } + } + } + #endif + } + + /* log2_max_frame_num_minus4 */ + bit_writer_put_ue(bitwriter, + seq->seq_fields.bits.log2_max_frame_num_minus4); + /* pic_order_cnt_type */ + bit_writer_put_ue(bitwriter, seq->seq_fields.bits.pic_order_cnt_type); + + if (seq->seq_fields.bits.pic_order_cnt_type == 0) { + /* log2_max_pic_order_cnt_lsb_minus4 */ + bit_writer_put_ue(bitwriter, + seq->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4); + } else if (seq->seq_fields.bits.pic_order_cnt_type == 1) { + assert(0); + bitwriter->writeBits(seq->seq_fields.bits.delta_pic_order_always_zero_flag, 1); + bit_writer_put_se(bitwriter, seq->offset_for_non_ref_pic); + bit_writer_put_se(bitwriter, seq->offset_for_top_to_bottom_field); + bit_writer_put_ue(bitwriter, + seq->num_ref_frames_in_pic_order_cnt_cycle); + for ( i = 0; i < seq->num_ref_frames_in_pic_order_cnt_cycle; i++) { + bit_writer_put_se(bitwriter, seq->offset_for_ref_frame[i]); + } + } + + /* num_ref_frames */ + bit_writer_put_ue(bitwriter, seq->max_num_ref_frames); + /* gaps_in_frame_num_value_allowed_flag */ + bitwriter->writeBits(gaps_in_frame_num_value_allowed_flag, 1); + + /* pic_width_in_mbs_minus1 */ + bit_writer_put_ue(bitwriter, seq->picture_width_in_mbs - 1); + /* pic_height_in_map_units_minus1 */ + bit_writer_put_ue(bitwriter, pic_height_in_map_units - 1); + /* frame_mbs_only_flag */ + bitwriter->writeBits(seq->seq_fields.bits.frame_mbs_only_flag, 1); + + if (!seq->seq_fields.bits.frame_mbs_only_flag) { //ONLY mbs + assert(0); + bitwriter->writeBits(mb_adaptive_frame_field, 1); + } + + /* direct_8x8_inference_flag */ + bitwriter->writeBits(0, 1); + /* frame_cropping_flag */ + bitwriter->writeBits(seq->frame_cropping_flag, 1); + + if (seq->frame_cropping_flag) { + /* frame_crop_left_offset */ + bit_writer_put_ue(bitwriter, seq->frame_crop_left_offset); + /* frame_crop_right_offset */ + bit_writer_put_ue(bitwriter, seq->frame_crop_right_offset); + /* frame_crop_top_offset */ + bit_writer_put_ue(bitwriter, seq->frame_crop_top_offset); + /* frame_crop_bottom_offset */ + bit_writer_put_ue(bitwriter, seq->frame_crop_bottom_offset); + } + + /* vui_parameters_present_flag */ + bitwriter->writeBits(seq->vui_parameters_present_flag, 1); + if (seq->vui_parameters_present_flag) { + /* aspect_ratio_info_present_flag */ + bitwriter->writeBits(seq->vui_fields.bits.aspect_ratio_info_present_flag, + 1); + if (seq->vui_fields.bits.aspect_ratio_info_present_flag) { + bitwriter->writeBits(seq->aspect_ratio_idc, 8); + if (seq->aspect_ratio_idc == 0xFF) { + bitwriter->writeBits(seq->sar_width, 16); + bitwriter->writeBits(seq->sar_height, 16); + } + } + + /* overscan_info_present_flag */ + bitwriter->writeBits(0, 1); + /* video_signal_type_present_flag */ + bitwriter->writeBits(0, 1); + /* chroma_loc_info_present_flag */ + bitwriter->writeBits(0, 1); + + /* timing_info_present_flag */ + bitwriter->writeBits(seq->vui_fields.bits.timing_info_present_flag, 1); + if (seq->vui_fields.bits.timing_info_present_flag) { + bitwriter->writeBits(seq->num_units_in_tick, 32); + bitwriter->writeBits(seq->time_scale, 32); + bitwriter->writeBits(1, 1); /* fixed_frame_rate_flag */ + } + + nal_hrd_parameters_present_flag = (seq->bits_per_second > 0 ? TRUE : FALSE); + /* nal_hrd_parameters_present_flag */ + bitwriter->writeBits(nal_hrd_parameters_present_flag, 1); + if (nal_hrd_parameters_present_flag) { + /* hrd_parameters */ + /* cpb_cnt_minus1 */ + bit_writer_put_ue(bitwriter, 0); + bitwriter->writeBits(4, 4); /* bit_rate_scale */ + bitwriter->writeBits(6, 4); /* cpb_size_scale */ + + for (i = 0; i < 1; ++i) { + /* bit_rate_value_minus1[0] */ + bit_writer_put_ue(bitwriter, seq->bits_per_second/1024- 1); + /* cpb_size_value_minus1[0] */ + bit_writer_put_ue(bitwriter, seq->bits_per_second/1024*8 - 1); + /* cbr_flag[0] */ + bitwriter->writeBits(1, 1); + } + /* initial_cpb_removal_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + /* cpb_removal_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + /* dpb_output_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + /* time_offset_length */ + bitwriter->writeBits(23, 5); + } + /* vcl_hrd_parameters_present_flag */ + bitwriter->writeBits(0, 1); + if (nal_hrd_parameters_present_flag || 0/*vcl_hrd_parameters_present_flag*/) { + /* low_delay_hrd_flag */ + bitwriter->writeBits(0, 1); + } + /* pic_struct_present_flag */ + bitwriter->writeBits(0, 1); + /* bitwriter_restriction_flag */ + bitwriter->writeBits(0, 1); + } + + /* rbsp_trailing_bits */ + bit_writer_write_trailing_bits(bitwriter); + return TRUE; +} + +static BOOL +bit_writer_write_pps( + BitWriter *bitwriter, + const VAEncPictureParameterBufferH264* const pic +) +{ + uint32_t num_slice_groups_minus1 = 0; + uint32_t pic_init_qs_minus26 = 0; + uint32_t redundant_pic_cnt_present_flag = 0; + + bit_writer_write_nal_header (bitwriter, + VAAPI_ENCODER_H264_NAL_REF_IDC_HIGH, VAAPI_ENCODER_H264_NAL_PPS); + /* pic_parameter_set_id */ + bit_writer_put_ue(bitwriter, pic->pic_parameter_set_id); + /* seq_parameter_set_id */ + bit_writer_put_ue(bitwriter, pic->seq_parameter_set_id); + /* entropy_coding_mode_flag */ + bitwriter->writeBits(pic->pic_fields.bits.entropy_coding_mode_flag, 1); + /* pic_order_present_flag */ + bitwriter->writeBits(pic->pic_fields.bits.pic_order_present_flag, 1); + /*slice_groups-1*/ + bit_writer_put_ue(bitwriter, num_slice_groups_minus1); + + if (num_slice_groups_minus1 > 0) { + /*FIXME*/ + assert(0); + } + bit_writer_put_ue(bitwriter, pic->num_ref_idx_l0_active_minus1); + bit_writer_put_ue(bitwriter, pic->num_ref_idx_l1_active_minus1); + bitwriter->writeBits(pic->pic_fields.bits.weighted_pred_flag, 1); + bitwriter->writeBits(pic->pic_fields.bits.weighted_bipred_idc, 2); + /* pic_init_qp_minus26 */ + bit_writer_put_se(bitwriter, pic->pic_init_qp-26); + /* pic_init_qs_minus26 */ + bit_writer_put_se(bitwriter, pic_init_qs_minus26); + /*chroma_qp_index_offset*/ + bit_writer_put_se(bitwriter, pic->chroma_qp_index_offset); + + bitwriter->writeBits(pic->pic_fields.bits.deblocking_filter_control_present_flag, 1); + bitwriter->writeBits(pic->pic_fields.bits.constrained_intra_pred_flag, 1); + bitwriter->writeBits(redundant_pic_cnt_present_flag, 1); + + /*more_rbsp_data*/ + bitwriter->writeBits(pic->pic_fields.bits.transform_8x8_mode_flag, 1); + bitwriter->writeBits(pic->pic_fields.bits.pic_scaling_matrix_present_flag, 1); + if (pic->pic_fields.bits.pic_scaling_matrix_present_flag) { + assert(0); + /* FIXME */ + /* + for (i = 0; i < + (6+(-( (chroma_format_idc ! = 3) ? 2 : 6) * -pic->pic_fields.bits.transform_8x8_mode_flag)); + i++) { + bit_writer_put_bits_uint8(bitwriter, pic->pic_fields.bits.pic_scaling_list_present_flag, 1); + } + */ + } + + bit_writer_put_se(bitwriter, pic->second_chroma_qp_index_offset); + bit_writer_write_trailing_bits(bitwriter); + + return TRUE; +} + +class VaapiEncStreamHeaderH264 +{ + typedef std::vector Header; +public: + void setSEI(const VAEncSequenceParameterBufferH264* const seqParam, + uint32_t temporalLayerNum, const LayerFrameRates& svctFrameRate) + { + ASSERT(m_sei.empty()); + BitWriter bs; + bit_writer_write_sei(&bs, seqParam, temporalLayerNum, svctFrameRate); + bsToHeader(m_sei, bs); + } + + void setSPS(const VAEncSequenceParameterBufferH264* const sequence, VideoProfile profile) + { + ASSERT(m_sps.empty()); + BitWriter bs; + bit_writer_write_sps (&bs, sequence, profile); + bsToHeader(m_sps, bs); + } + + /* + void setSubSetSps(const VAEncSequenceParameterBufferH264* const + sequence, VideoProfile profile) + { + ASSERT(m_sps.empty()); + BitWriter bs; + bit_writer_write_sps (&bs, sequence, profile); + bit_writer_write_svc_extension (&bs, sequence, profile); + bit_writer_write_vui_extension (&bs, sequence, profile); + bit_writer_write_addtional_extension (&bs, sequence, profile); + bsToHeader(m_sps, bs); + } + */ + void addPPS(const VAEncPictureParameterBufferH264* const picParam) + { + ASSERT(m_sps.size() && m_pps.empty()); + BitWriter bs; + bit_writer_write_pps (&bs, picParam); + bsToHeader(m_pps, bs); + } + + void generateCodecConfig(bool isAVCc) + { + ASSERT(m_sps.size() && (m_sps.size() > 4)&& m_pps.size() && m_headers.empty()); + if (isAVCc) + generateCodecConfigAVCc(); + else + generateCodecConfigAnnexB(); + } + + YamiStatus getCodecConfig(VideoEncOutputBuffer* outBuffer) + { + ASSERT(outBuffer && ((outBuffer->format == OUTPUT_CODEC_DATA) || (outBuffer->format == OUTPUT_EVERYTHING))); + if (outBuffer->bufferSize < m_headers.size()) + return YAMI_ENCODE_BUFFER_TOO_SMALL; + if (m_headers.empty()) + return YAMI_ENCODE_NO_REQUEST_DATA; + std::copy(m_headers.begin(), m_headers.end(), outBuffer->data); + outBuffer->dataSize = m_headers.size(); + outBuffer->flag |= ENCODE_BUFFERFLAG_CODECCONFIG; + return YAMI_SUCCESS; + } +private: + static void bsToHeader(Header& param, BitWriter& bs) + { + uint64_t codedBits = bs.getCodedBitsCount(); + uint64_t codedBytes = codedBits / 8; + ASSERT(codedBytes && codedBits % 8 == 0); + + uint8_t* codedData = bs.getBitWriterData(); + ASSERT(codedData); + + param.insert(param.end(), codedData, codedData + codedBytes); + } + + void appendHeaderWithEmulation(Header& h) + { + Header::iterator s = h.begin(); + Header::iterator e; + uint8_t zeros[] = {0, 0}; + uint8_t emulation[] = {0, 0, 3}; + do { + e = std::search(s, h.end(), zeros, zeros + N_ELEMENTS(zeros)); + m_headers.insert(m_headers.end(), s, e); + if (e == h.end()) + break; + + s = e + N_ELEMENTS(zeros); + + /* only when bitstream contains 0x000000/0x000001/0x000002/0x000003 + need to insert emulation prevention byte 0x03 */ + if (*s <= 3) + m_headers.insert(m_headers.end(), emulation, emulation + N_ELEMENTS(emulation)); + else + m_headers.insert(m_headers.end(), zeros, zeros + N_ELEMENTS(zeros)); + } while (1); + } + + void generateCodecConfigAnnexB() + { + std::vector headers; + if (m_sei.size()) + headers.push_back(&m_sei); + headers.push_back(&m_sps); + headers.push_back(&m_pps); + uint8_t sync[] = {0, 0, 0, 1}; + for (size_t i = 0; i < headers.size(); i++) { + m_headers.insert(m_headers.end(), sync, sync + N_ELEMENTS(sync)); + appendHeaderWithEmulation(*headers[i]); + } + } + + void generateCodecConfigAVCc() + { + const uint32_t configurationVersion = 0x01; + const uint32_t nalLengthSize = 4; + uint8_t profileIdc, profileComp, levelIdc; + BitWriter bs; + vector& sps = m_sps; + vector& pps = m_pps; + /* skip sps[0], which is the nal_unit_type */ + profileIdc = sps[1]; + profileComp = sps[2]; + levelIdc = sps[3]; + /* Header */ + bs.writeBits(configurationVersion, 8); + bs.writeBits(profileIdc, 8); + bs.writeBits(profileComp, 8); + bs.writeBits(levelIdc, 8); + bs.writeBits(0x3f, 6); /* 111111 */ + bs.writeBits(nalLengthSize - 1, 2); + bs.writeBits(0x07, 3); /* 111 */ + + /* Write SPS */ + bs.writeBits(1, 5); /* SPS count = 1 */ + assert(bs.getCodedBitsCount() % 8 == 0); + bs.writeBits(sps.size(), 16); + bs.writeBytes(&sps[0], sps.size()); + /* Write PPS */ + bs.writeBits(1, 8); /* PPS count = 1 */ + bs.writeBits(pps.size(), 16); + bs.writeBytes(&pps[0], pps.size()); + + bsToHeader(m_headers, bs); + } + + Header m_sei; + Header m_sps; + Header m_pps; + Header m_headers; +}; + +class VaapiEncPictureH264:public VaapiEncPicture +{ + friend class VaapiEncoderH264; + friend class VaapiEncoderH264Ref; + + typedef std::function Function; + +public: + virtual ~VaapiEncPictureH264() {} + + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer) + { + ASSERT(outBuffer); + VideoOutputFormat format = outBuffer->format; + //make a local copy of out Buffer; + VideoEncOutputBuffer out = *outBuffer; + out.flag = 0; + + std::vector functions; + if (format == OUTPUT_CODEC_DATA || ((format == OUTPUT_EVERYTHING) && isIdr())) + functions.push_back(std::bind(&VaapiEncStreamHeaderH264::getCodecConfig, m_headers,&out)); + if (format == OUTPUT_EVERYTHING || format == OUTPUT_FRAME_DATA) + functions.push_back(std::bind(getOutputHelper, this, &out)); + YamiStatus ret = getOutput(&out, functions); + if (ret == YAMI_SUCCESS) { + outBuffer->dataSize = out.data - outBuffer->data; + outBuffer->flag = out.flag; + } + return ret; + } + +private: + VaapiEncPictureH264(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiEncPicture(context, surface, timeStamp) + , m_frameNum(0) + , m_poc(0) + , m_isReference(true) + , m_priorityId(0) + { + } + + bool isIdr() const { + return m_type == VAAPI_PICTURE_I && !m_frameNum; + } + + //getOutput is a virutal function, we need this to help bind + static YamiStatus getOutputHelper(VaapiEncPictureH264* p, VideoEncOutputBuffer* out) + { + return p->VaapiEncPicture::getOutput(out); + } + + YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, std::vector& functions) + { + ASSERT(outBuffer); + + outBuffer->dataSize = 0; + + YamiStatus ret; + for (size_t i = 0; i < functions.size(); i++) { + ret = functions[i](); + if (ret != YAMI_SUCCESS) + return ret; + outBuffer->bufferSize -= outBuffer->dataSize; + outBuffer->data += outBuffer->dataSize; + } + return YAMI_SUCCESS; + } + + uint32_t m_frameNum; + uint32_t m_poc; + StreamHeaderPtr m_headers; + bool m_isReference; + uint32_t m_priorityId; +}; + +class VaapiEncoderH264Ref +{ +public: + VaapiEncoderH264Ref(const PicturePtr& picture, const SurfacePtr& surface) + : m_frameNum(picture->m_frameNum) + , m_poc(picture->m_poc) + , m_pic(surface) + , m_temporalId(picture->m_temporalID) + , m_diffPicNumMinus1(0) + { + } + uint32_t m_frameNum; + uint32_t m_poc; + SurfacePtr m_pic; + uint32_t m_temporalId; + uint8_t m_diffPicNumMinus1; // abs_diff_pic_num_minus1 + +}; + +VaapiEncoderH264::VaapiEncoderH264() + : m_numBFrames(0) + , m_isSvcT(false) + , m_temporalLayerNum(1) + , m_reorderState(VAAPI_ENC_REORD_WAIT_FRAMES) + , m_streamFormat(AVC_STREAM_FORMAT_ANNEXB) + , m_frameIndex(0) + , m_keyPeriod(30) + , m_ppsQp(26) + , m_idrNum(0) +{ + m_videoParamCommon.profile = VAProfileH264Main; + m_videoParamCommon.level = 40; + m_videoParamCommon.rcParams.initQP = 26; + m_videoParamCommon.rcParams.minQP = 1; + + memset(&m_videoParamAVC, 0, sizeof(m_videoParamAVC)); + m_videoParamAVC.idrInterval = 0; + m_videoParamAVC.enableCabac = true; + m_videoParamAVC.enableDct8x8 = false; + m_videoParamAVC.enableDeblockFilter = true; + m_videoParamAVC.deblockAlphaOffsetDiv2 = 2; + m_videoParamAVC.deblockBetaOffsetDiv2 = 2; + m_videoParamAVC.priorityId = 0; + m_videoParamAVC.enablePrefixNalUnit = false; + m_maxOutputBuffer = H264_MIN_TEMPORAL_GOP; +} + +VaapiEncoderH264::~VaapiEncoderH264() +{ + FUNC_ENTER(); +} + +bool VaapiEncoderH264::ensureCodedBufferSize() +{ + AutoLock locker(m_paramLock); + uint32_t mbSize; + + FUNC_ENTER(); + + if (m_maxCodedbufSize) + return true; + + if (!width() || !height()) { + return false; + } + + m_mbWidth = (width() + 15) / 16; + m_mbHeight = (height() + 15)/ 16; + //FIXME: + m_numSlices = 1; + mbSize = m_mbWidth * m_mbHeight; + if (m_numSlices > (mbSize + 1) / 2) + m_numSlices = (mbSize + 1) / 2; + ASSERT (m_numSlices); + + /* As spec A.3.1, max coded buffer size should be: + * 384 *( Max( PicSizeInMbs, fR * MaxMBPS ) + MaxMBPS / fps ) ÷ MinCR + * The max level we support now is 5.1*/ + uint32_t maxMBPS = LEVEL51_MAX_MBPS; + uint32_t minCR = H264_MIN_CR; + for (uint32_t i = 0; i < N_ELEMENTS(LevelLimits); i++) { + if (m_levelIdc <= LevelLimits[i].levelIdc) { + maxMBPS = LevelLimits[i].maxMBPS; + minCR = LevelLimits[i].minCR; + break; + } + } + m_maxCodedbufSize = + 384 * (MAX(mbSize, maxMBPS / H264_FRAME_FR) + maxMBPS / fps()) / minCR; + + DEBUG("m_maxCodedbufSize: %u", m_maxCodedbufSize); + + return true; +} + +void VaapiEncoderH264::checkProfileLimitation() +{ + VAProfile& profile = m_videoParamCommon.profile; + + switch (profile) { + case VAProfileH264ConstrainedBaseline: + if (ipPeriod() > 1) { + WARNING("H264 baseline profile can not support B frame encoding"); + m_videoParamCommon.ipPeriod = 1; // without B frame + } + assert(m_numBFrames == 0); + + m_videoParamAVC.enableCabac = false; // don't support cabac + m_videoParamAVC.enableDct8x8 = false; // only high profile can support 8x8 dtc + break; + case VAProfileH264Main: + m_videoParamAVC.enableDct8x8 = false; + break; + case VAProfileH264High: + break; + default: + ERROR("unsupported profile"); + assert(0); + } +} + +void VaapiEncoderH264::checkSvcTempLimitaion() +{ + if (m_temporalLayerNum > H264_MAX_TEMPORAL_LAYER_NUM) { + WARNING("only support %d temporal layers", H264_MAX_TEMPORAL_LAYER_NUM); + m_temporalLayerNum = H264_MAX_TEMPORAL_LAYER_NUM; + } else if (m_temporalLayerNum <= 1) + m_temporalLayerNum = 1; + + if (m_temporalLayerNum > 1) { + m_isSvcT = true; + m_videoParamCommon.ipPeriod = 1; // only support IP mode for svc-t + + if (m_videoParamCommon.intraPeriod < H264_MIN_TEMPORAL_GOP) + m_videoParamCommon.intraPeriod = H264_MIN_TEMPORAL_GOP; + + m_videoParamCommon.intraPeriod + = 1 << (uint32_t)ceil(log2(intraPeriod())); // make sure Gop is 2^n. + } + +} + +void VaapiEncoderH264::resetParams () +{ + if (m_videoParamCommon.enableLowPower) { +#if VA_CHECK_VERSION(0, 39, 2) + if (ipPeriod() > 1) { + WARNING("Low power mode can not support B frame encoding"); + m_videoParamCommon.ipPeriod = 1; // without B frame + } + m_entrypoint = VAEntrypointEncSliceLP; +#else + ERROR("For AVC lowpower mode, please make sure libva version >= 0.39.2"); +#endif + } + + m_levelIdc = level(); + + DEBUG("resetParams, ensureCodedBufferSize"); + ensureCodedBufferSize(); + + m_temporalLayerNum = m_videoParamCommon.temporalLayers.numLayersMinus1 + 1; + + // enable prefix nal unit for simulcast or svc-t + if (m_temporalLayerNum > 1 || m_videoParamAVC.priorityId) + m_videoParamAVC.enablePrefixNalUnit = true; + + checkProfileLimitation(); + checkSvcTempLimitaion(); + if (m_isSvcT) { + VideoFrameRate frameRate; + frameRate.frameRateDenom = frameRateDenom(); + frameRate.frameRateNum = frameRateNum(); + m_temporalLayerID.reset(new AvcLayerID(frameRate, m_videoParamCommon.temporalLayerIDs, m_videoParamCommon.temporalLayers.numLayersMinus1)); + m_temporalLayerID->getLayerFrameRates(m_svctFrameRate); + assert(m_temporalLayerID->getLayerNum() == (m_videoParamCommon.temporalLayers.numLayersMinus1 + 1)); + } + + if (intraPeriod() == 0) { + ERROR("intra period must larger than 0"); + m_videoParamCommon.intraPeriod = 1; + } + + if (intraPeriod() <= ipPeriod()) { + WARNING("intra period is not larger than ip period"); + m_videoParamCommon.ipPeriod = intraPeriod() - 1; + } + + if (ipPeriod() == 0) + m_videoParamCommon.intraPeriod = 1; + else + m_numBFrames = ipPeriod() - 1; + + m_keyPeriod = intraPeriod() * (m_videoParamAVC.idrInterval + 1); + + if (initQP() < minQP()) + initQP() = minQP(); + + if (initQP() > maxQP()) + initQP() = maxQP(); + + m_ppsQp = initQP(); + + if (m_numBFrames > (intraPeriod() + 1) / 2) + m_numBFrames = (intraPeriod() + 1) / 2; + + /* init m_maxFrameNum, max_poc */ + m_log2MaxFrameNum = + h264_get_log2_max_frame_num (m_keyPeriod); + assert (m_log2MaxFrameNum >= 4); + m_maxFrameNum = (1 << m_log2MaxFrameNum); + m_log2MaxPicOrderCnt = m_log2MaxFrameNum + 1; + m_maxPicOrderCnt = (1 << m_log2MaxPicOrderCnt); + + m_maxRefList1Count = m_numBFrames > 0;//m_maxRefList1Count <=1, because of currenent order mechanism + m_maxRefList0Count = numRefFrames(); + if (m_maxRefList0Count >= m_maxOutputBuffer -1) + m_maxRefList0Count = m_maxOutputBuffer -1; + + m_maxRefFrames = + m_maxRefList0Count + m_maxRefList1Count; + if (m_isSvcT) { + uint32_t refFrameNum = m_temporalLayerID->getMiniRefFrameNum(); + if (refFrameNum > m_maxOutputBuffer) { + ERROR("Reference frame number %d > output buffer %d", refFrameNum, m_maxOutputBuffer); + assert(false); + } + if (m_maxRefFrames < refFrameNum) + m_maxRefFrames = refFrameNum; + } + + assert((uint32_t)(1 << (m_temporalLayerNum - 1)) <= m_maxOutputBuffer); + CLIP(m_maxRefFrames, (uint32_t)(1 << (m_temporalLayerNum - 1)), m_maxOutputBuffer); + INFO("m_maxRefFrames: %d", m_maxRefFrames); + + resetGopStart(); +} + +YamiStatus VaapiEncoderH264::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + + if (ensureCodedBufferSize()) + *maxSize = m_maxCodedbufSize; + else + *maxSize = 0; + + return YAMI_SUCCESS; +} + +#ifdef __BUILD_GET_MV__ +YamiStatus VaapiEncoderH264::getMVBufferSize(uint32_t* Size) +{ + FUNC_ENTER(); + *Size = sizeof(VAMotionVectorIntel)*16*m_mbWidth*m_mbHeight; + return YAMI_SUCCESS; +} +#endif + +YamiStatus VaapiEncoderH264::start() +{ + FUNC_ENTER(); + resetParams(); + return VaapiEncoderBase::start(); +} + +void VaapiEncoderH264::flush() +{ + YamiStatus ret; + + FUNC_ENTER(); + + if (!m_reorderFrameList.empty()) { + changeLastBFrameToPFrame(); + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + + ret = encodeAllFrames(); + if (ret != YAMI_SUCCESS) { + ERROR("Not all frames are flushed."); + } + } + + resetGopStart(); + m_reorderFrameList.clear(); + referenceListFree(); + + VaapiEncoderBase::flush(); +} + +YamiStatus VaapiEncoderH264::stop() +{ + flush(); + return VaapiEncoderBase::stop(); +} + +YamiStatus VaapiEncoderH264::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + AutoLock locker(m_paramLock); + + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + switch (type) { + case VideoParamsTypeAVC: { + VideoParamsAVC* avc = (VideoParamsAVC*)videoEncParams; + if (avc->size == sizeof(VideoParamsAVC)) { + PARAMETER_ASSIGN(m_videoParamAVC, *avc); + status = YAMI_SUCCESS; + } + } + break; + case VideoConfigTypeAVCStreamFormat: { + VideoConfigAVCStreamFormat* format = (VideoConfigAVCStreamFormat*)videoEncParams; + if (format->size == sizeof(VideoConfigAVCStreamFormat)) { + m_streamFormat = format->streamFormat; + status = YAMI_SUCCESS; + } + } + break; + default: + status = VaapiEncoderBase::setParameters(type, videoEncParams); + break; + } + return status; +} + +YamiStatus VaapiEncoderH264::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + AutoLock locker(m_paramLock); + + FUNC_ENTER(); + if (!videoEncParams) + return status; + switch (type) { + case VideoParamsTypeAVC: { + VideoParamsAVC* avc = (VideoParamsAVC*)videoEncParams; + if (avc->size == sizeof(VideoParamsAVC)) { + PARAMETER_ASSIGN(*avc, m_videoParamAVC); + status = YAMI_SUCCESS; + } + } + break; + case VideoConfigTypeAVCStreamFormat: { + VideoConfigAVCStreamFormat* format = (VideoConfigAVCStreamFormat*)videoEncParams; + if (format->size == sizeof(VideoConfigAVCStreamFormat)) { + format->streamFormat = m_streamFormat; + status = YAMI_SUCCESS; + } + } + break; + default: + status = VaapiEncoderBase::getParameters(type, videoEncParams); + break; + } + + // TODO, update video resolution basing on hw requirement + status = VaapiEncoderBase::getParameters(type, videoEncParams); + + return status; +} + +void VaapiEncoderH264::changeLastBFrameToPFrame() +{ + PicturePtr lastPic = m_reorderFrameList.back(); + if (lastPic->m_type == VAAPI_PICTURE_B) { + lastPic->m_type = VAAPI_PICTURE_P; + m_reorderFrameList.pop_back(); + m_reorderFrameList.push_front(lastPic); + } +} + +YamiStatus VaapiEncoderH264::reorder(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + if (!surface) + return YAMI_INVALID_PARAM; + + PicturePtr picture(new VaapiEncPictureH264(m_context, surface, timeStamp)); + + bool isIdr = (m_frameIndex == 0 ||m_frameIndex >= m_keyPeriod || forceKeyFrame); + + if (isIdr) { + // If the last frame before IDR is B frame, set it to P frame. + if (m_reorderFrameList.size()) { + changeLastBFrameToPFrame(); + } + setIdrFrame (picture); + m_reorderFrameList.push_back(picture); + m_curFrameNum++; + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + } else if (m_frameIndex % intraPeriod() == 0) { + setIFrame (picture); + m_reorderFrameList.push_front(picture); + m_curFrameNum++; + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + }else if (m_frameIndex % (m_numBFrames + 1) != 0) { + setBFrame (picture); + m_reorderFrameList.push_back(picture); + } else { + setPFrame (picture); + m_reorderFrameList.push_front(picture); + m_curFrameNum++; + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + } + + picture->m_poc = m_frameIndex * 2; + picture->m_priorityId = m_videoParamAVC.priorityId; + if (m_isSvcT) + picture->m_temporalID = m_temporalLayerID->getTemporalLayer(m_frameIndex); + else + picture->m_temporalID = 0; + DEBUG("m_temporalID is %d", picture->m_temporalID); + m_frameIndex++; + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderH264::encodeAllFrames() +{ + FUNC_ENTER(); + YamiStatus ret; + + while (m_reorderState == VAAPI_ENC_REORD_DUMP_FRAMES) { + if (!m_maxCodedbufSize) + ensureCodedBufferSize(); + CodedBufferPtr codedBuffer = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize); + if (!codedBuffer) + return YAMI_OUT_MEMORY; + PicturePtr picture = m_reorderFrameList.front(); + m_reorderFrameList.pop_front(); + picture->m_codedBuffer = codedBuffer; + + if (m_reorderFrameList.empty()) + m_reorderState = VAAPI_ENC_REORD_WAIT_FRAMES; + + ret = encodePicture(picture); + if (ret != YAMI_SUCCESS) { + return ret; + } + codedBuffer->setFlag(ENCODE_BUFFERFLAG_ENDOFFRAME); + INFO("picture->m_type: 0x%x\n", picture->m_type); + if (picture->isIdr()) { + codedBuffer->setFlag(ENCODE_BUFFERFLAG_SYNCFRAME); + } + + if (!output(picture)) + return YAMI_INVALID_PARAM; + } + + INFO(); + return YAMI_SUCCESS; +} + +// calls immediately after reorder, +// it makes sure I frame are encoded immediately, so P frames can be pushed to the front of the m_reorderFrameList. +// it also makes sure input thread and output thread runs in parallel +YamiStatus VaapiEncoderH264::doEncode(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + FUNC_ENTER(); + YamiStatus ret; + ret = reorder(surface, timeStamp, forceKeyFrame); + if (ret != YAMI_SUCCESS) + return ret; + + ret = encodeAllFrames(); + if (ret != YAMI_SUCCESS) { + return ret; + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderH264::getCodecConfig(VideoEncOutputBuffer* outBuffer) +{ + if (!outBuffer) { + return YAMI_INVALID_PARAM; + } + + ASSERT((outBuffer->flag == OUTPUT_CODEC_DATA) || outBuffer->flag == OUTPUT_EVERYTHING); + AutoLock locker(m_paramLock); + if (!m_headers) + return YAMI_ENCODE_NO_REQUEST_DATA; + return m_headers->getCodecConfig(outBuffer); +} + +#if VA_CHECK_VERSION(0, 39, 4) +void VaapiEncoderH264::fill( + VAEncMiscParameterTemporalLayerStructure* layerParam) const +{ + LayerIDs ids; + m_temporalLayerID->getLayerIds(ids); + layerParam->number_of_layers = m_temporalLayerNum; + layerParam->periodicity = ids.size(); + + for (uint32_t i = 0; i < layerParam->periodicity; i++) + layerParam->layer_id[i] = ids[(i + 1) % layerParam->periodicity]; +} +#endif + +/* Generates additional control parameters */ +bool VaapiEncoderH264::ensureMiscParams(VaapiEncPicture* picture) +{ + VideoRateControl mode = rateControlMode(); + if (mode == RATE_CONTROL_CBR || mode == RATE_CONTROL_VBR) { +#if VA_CHECK_VERSION(0, 39, 4) + if (m_isSvcT) { + VAEncMiscParameterTemporalLayerStructure* layerParam = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeTemporalLayerStructure, + layerParam)) + return false; + if (layerParam) + fill(layerParam); + } +#endif + } + + if (!VaapiEncoderBase::ensureMiscParams(picture)) + return false; + + return true; +} + +/* Handle new GOP starts */ +void VaapiEncoderH264::resetGopStart () +{ + m_frameIndex = 0; + m_curFrameNum = 0; +} + +/* Marks the supplied picture as a B-frame */ +void VaapiEncoderH264::setBFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_B; + pic->m_frameNum = (m_curFrameNum % m_maxFrameNum); +} + +/* Marks the supplied picture as a P-frame */ +void VaapiEncoderH264::setPFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_P; + pic->m_frameNum = (m_curFrameNum % m_maxFrameNum); +} + +/* Marks the supplied picture as an I-frame */ +void VaapiEncoderH264::setIFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_I; + pic->m_frameNum = (m_curFrameNum % m_maxFrameNum); +} + +/* Marks the supplied picture as an IDR frame */ +void VaapiEncoderH264::setIdrFrame (const PicturePtr& pic) +{ + resetGopStart(); + pic->m_type = VAAPI_PICTURE_I; + pic->m_frameNum = 0; + pic->m_poc = 0; + m_idrNum++; +} + +bool VaapiEncoderH264:: +referenceListUpdate (const PicturePtr& picture, const SurfacePtr& surface) +{ + if (VAAPI_PICTURE_B == picture->m_type) { + return true; + } + if (picture->isIdr()) { + m_refList.clear(); + } else if (m_refList.size() >= m_maxRefFrames) { + m_refList.pop_back(); + } + ReferencePtr ref(new VaapiEncoderH264Ref(picture, surface)); + m_refList.push_front(ref); // descending order for short-term reference list + assert (m_refList.size() <= m_maxRefFrames); + return true; +} + +bool VaapiEncoderH264::pictureReferenceListSet ( + const PicturePtr& picture) +{ + uint32_t i; + + /* reset reflist0 and reflist1 every time */ + m_refList0.clear(); + m_refList1.clear(); + + if (picture->m_type == VAAPI_PICTURE_I) + return true; + + for (i = 0; i < m_refList.size(); i++) { + assert(picture->m_poc != m_refList[i]->m_poc); + if (picture->m_temporalID >= m_refList[i]->m_temporalId) { + m_refList[i]->m_diffPicNumMinus1 = + picture->m_frameNum - m_refList[i]->m_frameNum - 1; + if (picture->m_poc > m_refList[i]->m_poc) { + m_refList0.push_back(m_refList[i]);/* set forward reflist: descending order */ + } else + m_refList1.push_front(m_refList[i]);/* set backward reflist: ascending order */ + } + } + + if (m_refList0.size() > m_maxRefList0Count) + m_refList0.resize(m_maxRefList0Count); + if (m_refList1.size() > m_maxRefList1Count) + m_refList1.resize(m_maxRefList1Count); + + if (picture->m_type == VAAPI_PICTURE_P) + assert(m_refList1.empty()); + + DEBUG("pictureReferenceListSet, m_refList0_size is %d", + (int32_t)m_refList0.size()); + + assert (m_refList0.size() + m_refList1.size() <= m_maxRefFrames); + + return true; +} + +void VaapiEncoderH264::referenceListFree() +{ + m_refList.clear(); + m_refList0.clear(); + m_refList1.clear(); +} + +bool VaapiEncoderH264::fill(VAEncSequenceParameterBufferH264* seqParam) const +{ + seqParam->seq_parameter_set_id = 0; + seqParam->level_idc = m_levelIdc; + seqParam->intra_period = intraPeriod(); + seqParam->intra_idr_period = seqParam->intra_period; + seqParam->ip_period = 1 + m_numBFrames; + seqParam->bits_per_second = bitRate(); + + seqParam->max_num_ref_frames = m_maxRefFrames; + seqParam->picture_width_in_mbs = m_mbWidth; + seqParam->picture_height_in_mbs = m_mbHeight; + + /*sequence field values */ + seqParam->seq_fields.value = 0; + seqParam->seq_fields.bits.chroma_format_idc = 1; + seqParam->seq_fields.bits.frame_mbs_only_flag = 1; + assert (m_log2MaxFrameNum >= 4); + seqParam->seq_fields.bits.log2_max_frame_num_minus4 = + m_log2MaxFrameNum - 4; + /* picture order count */ + seqParam->seq_fields.bits.pic_order_cnt_type = 0; + assert (m_log2MaxPicOrderCnt >= 4); + seqParam->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = + m_log2MaxPicOrderCnt - 4; + + + /* not used if pic_order_cnt_type == 0 */ + if (seqParam->seq_fields.bits.pic_order_cnt_type == 1) { + seqParam->seq_fields.bits.delta_pic_order_always_zero_flag = TRUE; + } + + /* frame_cropping_flag */ + const int cropRight = (16 * m_mbWidth - width()); + const int cropBottom = (16 * m_mbHeight - height()); + if (cropRight || cropBottom) { + const int CHROMA_420 = 1; + const int CHROMA_422 = 2; + int chroma = seqParam->seq_fields.bits.chroma_format_idc; + static const uint32_t subWidthC = (chroma == CHROMA_420 || chroma == CHROMA_422) ? 2 : 1; + static const uint32_t subHeightC = chroma == CHROMA_420 ? 2 : 1; + const uint32_t cropUnitX = subWidthC; + const uint32_t cropUnitY = subHeightC * (2 - seqParam->seq_fields.bits.frame_mbs_only_flag); + + seqParam->frame_cropping_flag = 1; + seqParam->frame_crop_right_offset = cropRight / cropUnitX; + seqParam->frame_crop_bottom_offset = cropBottom / cropUnitY; + } + + /* VUI parameters are always set, at least for timing_info (framerate) */ + seqParam->vui_parameters_present_flag = TRUE; + if (seqParam->vui_parameters_present_flag) { + seqParam->vui_fields.bits.aspect_ratio_info_present_flag = FALSE; + seqParam->vui_fields.bits.bitstream_restriction_flag = FALSE; + seqParam->vui_fields.bits.timing_info_present_flag = TRUE; + if (seqParam->vui_fields.bits.timing_info_present_flag) { + seqParam->num_units_in_tick = frameRateDenom(); + seqParam->time_scale = frameRateNum() * 2; + } + } + return true; +} + +/* Fills in VA picture parameter buffer */ +bool VaapiEncoderH264::fill(VAEncPictureParameterBufferH264* picParam, const PicturePtr& picture, + const SurfacePtr& surface) const +{ + uint32_t i = 0; + + /* reference list, */ + picParam->CurrPic.picture_id = surface->getID(); + picParam->CurrPic.TopFieldOrderCnt = picture->m_poc; + + if (picture->m_type != VAAPI_PICTURE_I) { + for (i = 0; i < m_refList.size(); i++) { + picParam->ReferenceFrames[i].picture_id = m_refList[i]->m_pic->getID(); + picParam->ReferenceFrames[i].TopFieldOrderCnt = m_refList[i]->m_poc; + picParam->ReferenceFrames[i].flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE; + } + } + + for (; i < 16; ++i) { + picParam->ReferenceFrames[i].picture_id = VA_INVALID_ID; + } + picParam->coded_buf = picture->m_codedBuffer->getID(); + + picParam->pic_parameter_set_id = 0; + picParam->seq_parameter_set_id = 0; + picParam->last_picture = 0; /* means last encoding picture */ + picParam->frame_num = picture->m_frameNum; + picParam->pic_init_qp = m_ppsQp; + picParam->num_ref_idx_l0_active_minus1 = + (m_maxRefList0Count ? (m_maxRefList0Count - 1) : 0); + picParam->num_ref_idx_l1_active_minus1 = + (m_maxRefList1Count ? (m_maxRefList1Count - 1) : 0); + picParam->chroma_qp_index_offset = 0; + picParam->second_chroma_qp_index_offset = 0; + + /* set picture fields */ + picParam->pic_fields.bits.idr_pic_flag = picture->isIdr(); + picParam->pic_fields.bits.reference_pic_flag = picture->m_isReference + = (picture->m_type != VAAPI_PICTURE_B); + picParam->pic_fields.bits.entropy_coding_mode_flag = m_videoParamAVC.enableCabac; + picParam->pic_fields.bits.transform_8x8_mode_flag = m_videoParamAVC.enableDct8x8; + picParam->pic_fields.bits.deblocking_filter_control_present_flag = true; + + return TRUE; +} + +bool VaapiEncoderH264::ensureSequenceHeader(const PicturePtr& picture,const VAEncSequenceParameterBufferH264* const sequence) +{ + m_headers.reset(new VaapiEncStreamHeaderH264()); + if (m_isSvcT) + m_headers->setSEI(sequence, m_temporalLayerNum, m_svctFrameRate); + m_headers->setSPS(sequence, profile()); + return true; +} + +bool VaapiEncoderH264::ensurePictureHeader(const PicturePtr& picture, const VAEncPictureParameterBufferH264* const picParam) +{ + m_headers->addPPS(picParam); + m_headers->generateCodecConfig(m_streamFormat == AVC_STREAM_FORMAT_AVCC); + picture->m_headers = m_headers; + return true; +} + +bool VaapiEncoderH264::fillReferenceList(VAEncSliceParameterBufferH264* slice) const +{ + uint32_t i = 0; + for (i = 0; i < m_refList0.size(); i++) { + assert(m_refList0[i] && m_refList0[i]->m_pic && (m_refList0[i]->m_pic->getID() != VA_INVALID_ID)); + slice->RefPicList0[i].picture_id = m_refList0[i]->m_pic->getID(); + slice->RefPicList0[i].TopFieldOrderCnt= m_refList0[i]->m_poc; + slice->RefPicList0[i].flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE; + } + for (; i < N_ELEMENTS(slice->RefPicList0); i++) + slice->RefPicList0[i].picture_id = VA_INVALID_SURFACE; + + for (i = 0; i < m_refList1.size(); i++){ + assert(m_refList1[i] && m_refList1[i]->m_pic && (m_refList1[i]->m_pic->getID() != VA_INVALID_ID)); + slice->RefPicList1[i].picture_id = m_refList1[i]->m_pic->getID(); + slice->RefPicList1[i].TopFieldOrderCnt= m_refList1[i]->m_poc; + slice->RefPicList1[i].flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE; + } + for (; i < N_ELEMENTS(slice->RefPicList1); i++) + slice->RefPicList1[i].picture_id = VA_INVALID_SURFACE; + return true; +} + +bool VaapiEncoderH264::addPackedPrefixNalUnit(const PicturePtr& picture) const +{ + bool ret = true; + BitWriter bs; + bs.writeBits(H264_NAL_START_CODE, 32); + bit_writer_write_nal_header(&bs, picture->m_isReference + ? VAAPI_ENCODER_H264_NAL_REF_IDC_LOW + : VAAPI_ENCODER_H264_NAL_REF_IDC_NONE, + VAAPI_ENCODER_H264_NAL_PREFIX); + + bs.writeBits(1, 1); /* svc_extension_flag */ + bs.writeBits(picture->isIdr(), 1); + bs.writeBits(picture->m_priorityId, 6); + bs.writeBits(1, 1); /* no_inter_layer_pred_flag */ + bs.writeBits(0, 3); /* dependency_id */ + bs.writeBits(0, 4); /* quality_id */ + bs.writeBits(picture->m_temporalID, 3); + bs.writeBits(0, 1); /* use_ref_base_pic_flag */ + bs.writeBits(1, 1); /* discardable_flag */ + bs.writeBits(1, 1); /* output_flag */ + bs.writeBits(3, 2); /* reserved_three_2bits */ + + if (picture->m_isReference) { + bs.writeBits(0, 1); /* store_ref_base_pic_flag */ + bs.writeBits(0, 1); /* additional_prefix_nal_unit_extension_flag*/ + } + /* no more rbsp data */ + + bit_writer_write_trailing_bits(&bs); + + uint32_t codedBits = bs.getCodedBitsCount(); + uint8_t* codedData = bs.getBitWriterData(); + ASSERT(codedData && codedBits); + + if (!picture->addPackedHeader(VAEncPackedHeaderRawData, codedData, + codedBits)) { + ret = false; + } + + return ret; +} + +bool VaapiEncoderH264::addPackedSliceHeader( + const PicturePtr& picture, + const VAEncSliceParameterBufferH264* const sliceParam) const +{ + bool ret = true; + uint32_t i = 0; + BitWriter bs; + bs.writeBits(H264_NAL_START_CODE, 32); + + if (sliceParam->slice_type == H264_SLICE_TYPE_I) { + bit_writer_write_nal_header(&bs, VAAPI_ENCODER_H264_NAL_REF_IDC_HIGH, + picture->isIdr() + ? VAAPI_ENCODER_H264_NAL_IDR + : VAAPI_ENCODER_H264_NAL_NON_IDR); + } else if (sliceParam->slice_type == H264_SLICE_TYPE_P) { + bit_writer_write_nal_header(&bs, VAAPI_ENCODER_H264_NAL_REF_IDC_MEDIUM, + VAAPI_ENCODER_H264_NAL_NON_IDR); + } else { + assert(sliceParam->slice_type == H264_SLICE_TYPE_B); + bit_writer_write_nal_header( + &bs, picture->m_isReference ? VAAPI_ENCODER_H264_NAL_REF_IDC_LOW + : VAAPI_ENCODER_H264_NAL_REF_IDC_NONE, + VAAPI_ENCODER_H264_NAL_NON_IDR); + } + + bit_writer_put_ue(&bs, + sliceParam->macroblock_address); /* first_mb_in_slice*/ + bit_writer_put_ue(&bs, sliceParam->slice_type); /* slice_type */ + + bit_writer_put_ue( + &bs, sliceParam->pic_parameter_set_id); /* pic_parameter_set_id: 0 */ + bs.writeBits(m_picParam->frame_num, + m_seqParam->seq_fields.bits.log2_max_frame_num_minus4 + + 4); /* frame_num */ + + /* frame_mbs_only_flag == 1 */ + if (!m_seqParam->seq_fields.bits.frame_mbs_only_flag) { + ERROR("interlace unsupported"); + return false; + } + + if (m_picParam->pic_fields.bits.idr_pic_flag) + bit_writer_put_ue(&bs, sliceParam->idr_pic_id); /* idr_pic_id: 0 */ + + if (m_seqParam->seq_fields.bits.pic_order_cnt_type == 0) { + bs.writeBits( + m_picParam->CurrPic.TopFieldOrderCnt, + m_seqParam->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 + 4); + /* pic_order_present_flag == 0 */ + } else { + ERROR("POC type unsupported"); + return false; + } + + /* slice type */ + if (sliceParam->slice_type == H264_SLICE_TYPE_P) { + bs.writeBits(sliceParam->num_ref_idx_active_override_flag, + 1); /* num_ref_idx_active_override_flag: */ + + if (sliceParam->num_ref_idx_active_override_flag) + bit_writer_put_ue(&bs, sliceParam->num_ref_idx_l0_active_minus1); + + bool refPicListModificationFlagL0 = false; + /* ref_pic_list_reordering */ + for (i = 0; i < m_refList0.size(); i++) { + if (m_refList0[i]->m_diffPicNumMinus1) { + DEBUG("m_diffPicNumMinus1 is %d", + m_refList0[i]->m_diffPicNumMinus1); + refPicListModificationFlagL0 = true; + break; + } + } + + bs.writeBits(refPicListModificationFlagL0, + 1); /* ref_pic_list_reordering_flag_l0*/ + + if (refPicListModificationFlagL0) { + DEBUG("m_refList0_size is %d", (int32_t)m_refList0.size()); + for (i = 0; i < m_refList0.size(); i++) { + bit_writer_put_ue(&bs, 0); /* modification_of_pic_nums_idc: 0 */ + bit_writer_put_ue( + &bs, + m_refList0[i] + ->m_diffPicNumMinus1); /* abs_diff_pic_num_minus1 */ + } + bit_writer_put_ue(&bs, 3); /* modification_of_pic_nums_idc: 3 */ + } + } else if (sliceParam->slice_type == H264_SLICE_TYPE_B) { + bs.writeBits(sliceParam->direct_spatial_mv_pred_flag, + 1); /* direct_spatial_mv_pred: 1 */ + + bs.writeBits(sliceParam->num_ref_idx_active_override_flag, + 1); /* num_ref_idx_active_override_flag: */ + + if (sliceParam->num_ref_idx_active_override_flag) { + bit_writer_put_ue(&bs, sliceParam->num_ref_idx_l0_active_minus1); + bit_writer_put_ue(&bs, sliceParam->num_ref_idx_l1_active_minus1); + } + + /* ref_pic_list_reordering */ + bs.writeBits(0, 1); /* ref_pic_list_reordering_flag_l0: 0 */ + bs.writeBits(0, 1); /* ref_pic_list_reordering_flag_l1: 0 */ + } + + if ((m_picParam->pic_fields.bits.weighted_pred_flag + && sliceParam->slice_type == H264_SLICE_TYPE_P) + || ((m_picParam->pic_fields.bits.weighted_bipred_idc == 1) + && sliceParam->slice_type == H264_SLICE_TYPE_B)) { + /* FIXME: fill weight/offset table */ + ERROR("don't support weighted prediction"); + return false; + } + + /* dec_ref_pic_marking */ + if (m_picParam->pic_fields.bits.reference_pic_flag) { /* nal_ref_idc != 0 */ + if (m_picParam->pic_fields.bits.idr_pic_flag) { + bs.writeBits(0, 1); /* no_output_of_prior_pics_flag: 0 */ + bs.writeBits(0, 1); /* long_term_reference_flag: 0 */ + } else { + bs.writeBits(0, 1); /* adaptive_ref_pic_marking_mode_flag: 0 */ + } + } + + if (m_picParam->pic_fields.bits.entropy_coding_mode_flag + && (sliceParam->slice_type != H264_SLICE_TYPE_I)) + bit_writer_put_ue(&bs, + sliceParam->cabac_init_idc); /* cabac_init_idc: 0 */ + + bit_writer_put_se(&bs, sliceParam->slice_qp_delta); /* slice_qp_delta: 0 */ + + /* ignore for SP/SI */ + + if (m_picParam->pic_fields.bits.deblocking_filter_control_present_flag) { + bit_writer_put_ue( + &bs, + sliceParam + ->disable_deblocking_filter_idc); /* disable_deblocking_filter_idc: + 0 */ + + if (sliceParam->disable_deblocking_filter_idc != 1) { + bit_writer_put_se( + &bs, + sliceParam + ->slice_alpha_c0_offset_div2); /* slice_alpha_c0_offset_div2: + 2 */ + bit_writer_put_se( + &bs, + sliceParam + ->slice_beta_offset_div2); /* slice_beta_offset_div2: 2 */ + } + } + + if (m_picParam->pic_fields.bits.entropy_coding_mode_flag) { + bs.writeToBytesAligned(true); + } + + uint32_t codedBits = bs.getCodedBitsCount(); + uint8_t* codedData = bs.getBitWriterData(); + ASSERT(codedData && codedBits); + + if (!picture->addPackedHeader(VAEncPackedHeaderSlice, codedData, + codedBits)) { + ret = false; + } + + return ret; +} + +/* Adds slice headers to picture */ +bool VaapiEncoderH264::addSliceHeaders (const PicturePtr& picture) const +{ + VAEncSliceParameterBufferH264 *sliceParam; + uint32_t sliceOfMbs, sliceModMbs, curSliceMbs; + uint32_t mbSize; + uint32_t lastMbIndex; + + assert (picture); + + if (picture->m_type != VAAPI_PICTURE_I) { + /* have one reference frame at least */ + assert(m_refList0.size() > 0); + } + + mbSize = m_mbWidth * m_mbHeight; + + assert (m_numSlices && m_numSlices < mbSize); + sliceOfMbs = mbSize / m_numSlices; + sliceModMbs = mbSize % m_numSlices; + lastMbIndex = 0; + for (uint32_t i = 0; i < m_numSlices; ++i) { + curSliceMbs = sliceOfMbs; + if (sliceModMbs) { + ++curSliceMbs; + --sliceModMbs; + } + if (!picture->newSlice(sliceParam)) + return false; + + sliceParam->macroblock_address = lastMbIndex; + sliceParam->num_macroblocks = curSliceMbs; + sliceParam->macroblock_info = VA_INVALID_ID; + sliceParam->slice_type = h264_get_slice_type (picture->m_type); + assert (sliceParam->slice_type != -1); + sliceParam->idr_pic_id = m_idrNum; + sliceParam->pic_order_cnt_lsb = picture->m_poc % m_maxPicOrderCnt; + + sliceParam->num_ref_idx_active_override_flag = 1; + if (picture->m_type != VAAPI_PICTURE_I && m_refList0.size() > 0) + sliceParam->num_ref_idx_l0_active_minus1 = m_refList0.size() - 1; + if (picture->m_type == VAAPI_PICTURE_B && m_refList1.size() > 0) + sliceParam->num_ref_idx_l1_active_minus1 = m_refList1.size() - 1; + + fillReferenceList(sliceParam); + + sliceParam->slice_qp_delta = initQP() - m_ppsQp; + DEBUG("init qp is %d, pps qp is %d, maxQp is %d, minQp is %d", initQP(), + m_ppsQp, maxQP(), minQP()); + if(rateControlMode() == RATE_CONTROL_CQP){ + switch (picture->m_type) { + case VAAPI_PICTURE_B: + sliceParam->slice_qp_delta += m_videoParamCommon.rcParams.diffQPIB; + break; + case VAAPI_PICTURE_P: + sliceParam->slice_qp_delta += m_videoParamCommon.rcParams.diffQPIP; + break; + case VAAPI_PICTURE_I: + default: + break; + } + if((int32_t)initQP() + sliceParam->slice_qp_delta > (int32_t)maxQP()){ + sliceParam->slice_qp_delta = maxQP() - initQP(); + } + if((int32_t)initQP() + sliceParam->slice_qp_delta < (int32_t)minQP()){ + sliceParam->slice_qp_delta = (int32_t)minQP() - (int32_t)initQP(); + } + } + + DEBUG("slice_qp_delta is %d", sliceParam->slice_qp_delta); + + sliceParam->disable_deblocking_filter_idc = !m_videoParamAVC.enableDeblockFilter; + sliceParam->slice_alpha_c0_offset_div2 = m_videoParamAVC.deblockAlphaOffsetDiv2; + sliceParam->slice_beta_offset_div2 = m_videoParamAVC.deblockBetaOffsetDiv2; + /* set calculation for next slice */ + lastMbIndex += curSliceMbs; + + if (m_videoParamAVC.enablePrefixNalUnit + && !addPackedPrefixNalUnit(picture)) + return false; + if (!addPackedSliceHeader(picture, sliceParam)) + return false; + } + assert (lastMbIndex == mbSize); + return true; +} + +bool VaapiEncoderH264::ensureSequence(const PicturePtr& picture) +{ + if (!picture->editSequence(m_seqParam) || !fill(m_seqParam)) { + ERROR("failed to create sequence parameter buffer (SPS)"); + return false; + } + + if (picture->isIdr() && !ensureSequenceHeader(picture, m_seqParam)) { + ERROR ("failed to create packed sequence header buffer"); + return false; + } + return true; +} + +bool VaapiEncoderH264::ensurePicture (const PicturePtr& picture, const SurfacePtr& surface) +{ + if (!pictureReferenceListSet(picture)) { + ERROR ("reference list reorder failed"); + return false; + } + + if (!picture->editPicture(m_picParam) + || !fill(m_picParam, picture, surface)) { + ERROR("failed to create picture parameter buffer (PPS)"); + return false; + } + + if (picture->isIdr() && !ensurePictureHeader(picture, m_picParam)) { + ERROR ("set picture packed header failed"); + return false; + } + return true; +} + +bool VaapiEncoderH264::ensureSlices(const PicturePtr& picture) +{ + assert (picture); + + if (!addSliceHeaders (picture)) + return false; + return true; +} + +YamiStatus VaapiEncoderH264::encodePicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_FAIL; + + SurfacePtr reconstruct = createSurface(); + if (!reconstruct) + return ret; + { + AutoLock locker(m_paramLock); + +#ifdef __BUILD_GET_MV__ + uint32_t size; + void *buffer = NULL; + getMVBufferSize(&size); + if (!picture->editMVBuffer(buffer, &size)) + return ret; +#endif + if (!ensureSequence (picture)) + return ret; + if (!ensureMiscParams (picture.get())) + return ret; + if (!ensurePicture(picture, reconstruct)) + return ret; + if (!ensureSlices (picture)) + return ret; + } + if (!picture->encode()) + return ret; + + if (!referenceListUpdate (picture, reconstruct)) + return ret; + + return YAMI_SUCCESS; +} + +} diff --git a/encoder/vaapiencoder_h264.h b/encoder/vaapiencoder_h264.h new file mode 100644 index 0000000..0335162 --- /dev/null +++ b/encoder/vaapiencoder_h264.h @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_h264_h +#define vaapiencoder_h264_h + +#include "vaapiencoder_base.h" +#include "vaapi/vaapiptrs.h" +#include "common/lock.h" +#include +#include +#include +#include +#include + +namespace YamiMediaCodec{ +class VaapiEncPictureH264; +class VaapiEncoderH264Ref; +class VaapiEncStreamHeaderH264; + +class VaapiEncoderH264 : public VaapiEncoderBase { +public: + //shortcuts, It's intended to elimilate codec diffrence + //to make template for other codec implelmentation. + typedef SharedPtr PicturePtr; + typedef SharedPtr ReferencePtr; + typedef SharedPtr StreamHeaderPtr; + + VaapiEncoderH264(); + ~VaapiEncoderH264(); + virtual YamiStatus start(); + virtual void flush(); + virtual YamiStatus stop(); + + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); +#ifdef __BUILD_GET_MV__ + // get MV buffer size. + virtual YamiStatus getMVBufferSize(uint32_t* Size); +#endif + +protected: + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, bool forceKeyFrame); + virtual YamiStatus getCodecConfig(VideoEncOutputBuffer* outBuffer); + virtual bool ensureMiscParams(VaapiEncPicture*); + +private: + friend class FactoryTest; + friend class VaapiEncoderH264Test; + + //following code is a template for other encoder implementation + YamiStatus encodePicture(const PicturePtr&); + +#if VA_CHECK_VERSION(0, 39, 4) + void fill(VAEncMiscParameterTemporalLayerStructure*) const; +#endif + bool fill(VAEncSequenceParameterBufferH264*) const; + bool fill(VAEncPictureParameterBufferH264*, const PicturePtr&, const SurfacePtr&) const ; + bool ensureSequenceHeader(const PicturePtr&, const VAEncSequenceParameterBufferH264* const); + bool ensurePictureHeader(const PicturePtr&, const VAEncPictureParameterBufferH264* const ); + bool addSliceHeaders (const PicturePtr&) const; + bool ensureSequence(const PicturePtr&); + bool ensurePicture (const PicturePtr&, const SurfacePtr&); + bool ensureSlices(const PicturePtr&); + bool ensureCodedBufferSize(); + bool addPackedPrefixNalUnit(const PicturePtr&) const; + bool addPackedSliceHeader( + const PicturePtr& picture, + const VAEncSliceParameterBufferH264* const sliceParam) const; + + //reference list related + YamiStatus reorder(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame); + bool fillReferenceList(VAEncSliceParameterBufferH264* slice) const; + bool referenceListUpdate (const PicturePtr&, const SurfacePtr&); + bool pictureReferenceListSet (const PicturePtr&); + + void referenceListFree(); + //template end + + void resetGopStart(); + void setBFrame(const PicturePtr&); + void setPFrame(const PicturePtr&); + void setIFrame(const PicturePtr&); + void setIdrFrame(const PicturePtr&); + + void changeLastBFrameToPFrame(); + + YamiStatus encodeAllFrames(); + + void resetParams(); + void checkProfileLimitation(); + void checkSvcTempLimitaion(); + + VideoParamsAVC m_videoParamAVC; + + uint8_t m_levelIdc; + uint32_t m_numSlices; + uint32_t m_numBFrames; + uint32_t m_mbWidth; + uint32_t m_mbHeight; + bool m_isSvcT; + uint32_t m_temporalLayerNum; + TemporalLayerIDPtr m_temporalLayerID; + + /* re-ordering */ + std::list m_reorderFrameList; + VaapiEncReorderState m_reorderState; + AVCStreamFormat m_streamFormat; + uint32_t m_frameIndex; + uint32_t m_curFrameNum; + uint32_t m_keyPeriod; + uint32_t m_ppsQp; /*pic_init_qp_minus26 + 26*/ + + /* reference list */ + std::deque m_refList; + std::deque m_refList0; + std::deque m_refList1; + + uint32_t m_maxRefFrames; + /* max reflist count */ + uint32_t m_maxRefList0Count; + uint32_t m_maxRefList1Count; + + /* frame, poc */ + uint32_t m_maxFrameNum; + uint32_t m_log2MaxFrameNum; + uint32_t m_maxPicOrderCnt; + uint32_t m_log2MaxPicOrderCnt; + uint16_t m_idrNum; //used to set idr_pic_id, max value is 65535 as spec + + VAEncSequenceParameterBufferH264* m_seqParam; + VAEncPictureParameterBufferH264* m_picParam; + + StreamHeaderPtr m_headers; + Lock m_paramLock; // locker for parameters update, for example: m_sps/m_pps/m_maxCodedbufSize (width/height etc) + + /** + * VaapiEncoderFactory registration result. This encoder is registered in + * vaapiencoder_host.cpp + */ + static const bool s_registered; +}; +} +#endif /* vaapiencoder_h264_h */ diff --git a/encoder/vaapiencoder_h264_unittest.cpp b/encoder/vaapiencoder_h264_unittest.cpp new file mode 100644 index 0000000..7ade4f2 --- /dev/null +++ b/encoder/vaapiencoder_h264_unittest.cpp @@ -0,0 +1,64 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiencoder_h264.h" + +namespace YamiMediaCodec { + +class VaapiEncoderH264Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIENCODER_H264_TEST(name) \ + TEST_F(VaapiEncoderH264Test, name) + +VAAPIENCODER_H264_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_AVC); + mimeTypes.push_back(YAMI_MIME_H264); + doFactoryTest(mimeTypes); +} + +} diff --git a/encoder/vaapiencoder_hevc.cpp b/encoder/vaapiencoder_hevc.cpp new file mode 100644 index 0000000..022d23b --- /dev/null +++ b/encoder/vaapiencoder_hevc.cpp @@ -0,0 +1,1769 @@ +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_hevc.h" +#include +#include "codecparsers/bitWriter.h" +#include "common/scopedlogger.h" +#include "common/common_def.h" +#include "common/Functional.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapicodedbuffer.h" +#include "vaapiencpicture.h" +#include + +namespace YamiMediaCodec{ +//shortcuts +typedef VaapiEncoderHEVC::PicturePtr PicturePtr; +typedef VaapiEncoderHEVC::ReferencePtr ReferencePtr; +typedef VaapiEncoderHEVC::StreamHeaderPtr StreamHeaderPtr; + +using YamiParser::BitWriter; +using std::list; +using std::vector; +using std::deque; + +#define HEVC_NAL_START_CODE 0x000001 + +#define HEVC_SLICE_TYPE_I 2 +#define HEVC_SLICE_TYPE_P 1 +#define HEVC_SLICE_TYPE_B 0 + +#define VAAPI_ENCODER_HEVC_NAL_REF_IDC_NONE 0 +#define VAAPI_ENCODER_HEVC_NAL_REF_IDC_LOW 1 +#define VAAPI_ENCODER_HEVC_NAL_REF_IDC_MEDIUM 2 +#define VAAPI_ENCODER_HEVC_NAL_REF_IDC_HIGH 3 + +typedef enum +{ + TRAIL_N = 0, + TRAIL_R = 1, + TSA_N = 2, + TSA_R = 3 , + STSA_N = 4, + STSA_R = 5, + RADL_N = 6, + RADL_R = 7, + RASL_N = 8, + RASL_R = 9, + RSV_VCL_N10 = 10, + RSV_VCL_N11 = 11, + RSV_VCL_N12 = 12, + RSV_VCL_N13 = 13, + RSV_VCL_N14 = 14, + RSV_VCL_N15 = 15, + BLA_W_LP = 16, + BLA_W_RADL = 17, + BLA_N_LP = 18, + IDR_W_RADL = 19, + IDR_N_LP = 20, + CRA_NUT = 21, + RSV_IRAP_VCL22 = 22, + RSV_IRAP_VCL23 = 23, + RSV_VCL24 = 24, + RSV_VCL25 = 25, + RSV_VCL26 = 26, + RSV_VCL27 = 27, + RSV_VCL28 = 28, + RSV_VCL29 = 29, + RSV_VCL30 = 30, + RSV_VCL31 = 31, + VPS_NUT = 32, + SPS_NUT = 33, + PPS_NUT = 34, + AUD_NUT = 35, + EOS_NUT = 36, + EOB_NUT = 37, + FD_NUT = 38, + PREFIX_SEI_NUT = 39, + SUFFIX_SEI_NUT = 40 +}HevcNalUnitType; + +static uint8_t +hevc_get_slice_type (VaapiPictureType type) +{ + switch (type) { + case VAAPI_PICTURE_I: + DEBUG("HEVC_SLICE_TYPE_I \n"); + return HEVC_SLICE_TYPE_I; + case VAAPI_PICTURE_P: + DEBUG("HEVC_SLICE_TYPE_P \n"); + return HEVC_SLICE_TYPE_P; + case VAAPI_PICTURE_B: + DEBUG("HEVC_SLICE_TYPE_B \n"); + return HEVC_SLICE_TYPE_B; + default: + return -1; + } + return -1; +} + +static uint32_t log2 (uint32_t num) +{ + uint32_t ret = 0; + assert(num); + + uint32_t one = 1; + while (num > (one << ret)) + ++ret; + + return ret; +} + +static uint32_t +hevc_get_log2_max_frame_num (uint32_t num) +{ + uint32_t ret = 0; + + ret = log2(num); + + if (ret <= 4) + ret = 4; + else if (ret > 10) + ret = 10; + /* must be greater than 4 */ + return ret; +} + +static uint8_t hevc_get_profile_idc(VideoProfile profile) +{ + uint8_t idc; + switch (profile) { + case PROFILE_H265_MAIN: + idc = 1; + break; + case PROFILE_H265_MAIN10: + idc = 2; + break; + default: + assert(0); + } + return idc; + +} + +static BOOL +bit_writer_put_ue(BitWriter *bitwriter, uint32_t value) +{ + uint32_t size_in_bits = 0; + uint32_t tmp_value = ++value; + + while (tmp_value) { + ++size_in_bits; + tmp_value >>= 1; + } + if (size_in_bits > 1 + && !bitwriter->writeBits(0, size_in_bits - 1)) + return FALSE; + if (!bitwriter->writeBits(value, size_in_bits)) + return FALSE; + return TRUE; +} + +static BOOL +bit_writer_put_se(BitWriter *bitwriter, int32_t value) +{ + uint32_t new_val; + + if (value <= 0) + new_val = -(value<<1); + else + new_val = (value<<1) - 1; + + if (!bit_writer_put_ue(bitwriter, new_val)) + return FALSE; + return TRUE; +} + +static BOOL +bit_writer_write_nal_header( + BitWriter *bitwriter, + uint32_t nal_unit_type +) +{ + /* forbidden_zero_bit */ + bitwriter->writeBits(0, 1); + /* nal unit_type */ + bitwriter->writeBits(nal_unit_type, 6); + /* layer_id */ + bitwriter->writeBits(0, 6); + /* temporal_id_plus1*/ + bitwriter->writeBits(1, 3); + + return TRUE; +} + +static BOOL +bit_writer_write_trailing_bits(BitWriter *bitwriter) +{ + bitwriter->writeBits(1, 1); + bitwriter->writeToBytesAligned(); + return TRUE; +} + +static void profile_tier_level( + BitWriter *bitwriter, + BOOL profile_present_flag, + uint32_t max_num_sub_layers, + const VAEncSequenceParameterBufferHEVC* const seq +) +{ + uint32_t i; + bool general_profile_compatibility_flag[32] = {0}; + + unsigned char vps_general_level_idc = seq->general_level_idc * 3; + + if (profile_present_flag) { + /* general_profile_space */ + bitwriter->writeBits(0, 2); + /* general_tier_flag */ + bitwriter->writeBits(seq->general_tier_flag, 1); + /* general_profile_idc */ + bitwriter->writeBits(seq->general_profile_idc, 5); + + /* general_profile_compatibility_flag. Only the bit corresponding to profile_idc is set */ + general_profile_compatibility_flag[seq->general_profile_idc] = 1; + for (i = 0; i < N_ELEMENTS(general_profile_compatibility_flag); i++) { + bitwriter->writeBits(general_profile_compatibility_flag[i], 1); + } + + /* general_progressive_source_flag */ + bitwriter->writeBits(1, 1); + /* general_interlaced_source_flag */ + bitwriter->writeBits(0, 1); + /* general_non_packed_constraint_flag */ + bitwriter->writeBits(0, 1); + /* general_frame_only_constraint_flag */ + bitwriter->writeBits(1, 1); + + /* reserved zero 44bits */ + bitwriter->writeBits(0, 12); + bitwriter->writeBits(0, 16); + bitwriter->writeBits(0, 16); + } + + /* general_level_idc */ + bitwriter->writeBits(vps_general_level_idc, 8); + + if (max_num_sub_layers) { + /* TBD: can't support multi-layers now + */ + } +} + +void st_ref_pic_set(BitWriter *bs, int stRpsIdx, const ShortRFS& shortRFS) +{ + int i; + if (stRpsIdx) + bs->writeBits(shortRFS.inter_ref_pic_set_prediction_flag, 1); + + ASSERT(!shortRFS.inter_ref_pic_set_prediction_flag); + + bit_writer_put_ue(bs, shortRFS.num_negative_pics); + bit_writer_put_ue(bs, shortRFS.num_positive_pics); + + for (i = 0; i < shortRFS.num_negative_pics; i++) + { + bit_writer_put_ue(bs, shortRFS.delta_poc_s0_minus1[i]); + bs->writeBits(shortRFS.used_by_curr_pic_s0_flag[i], 1); + } + for (i = 0; i < shortRFS.num_positive_pics; i++) + { + bit_writer_put_ue(bs, shortRFS.delta_poc_s1_minus1[i]); + bs->writeBits(shortRFS.used_by_curr_pic_s1_flag[i], 1); + } + + return; +} + + +class VaapiEncStreamHeaderHEVC +{ + typedef std::vector Header; +public: + + VaapiEncStreamHeaderHEVC(); + VaapiEncStreamHeaderHEVC(VaapiEncoderHEVC* encoder) {m_encoder = encoder;}; + + void setVPS(const VAEncSequenceParameterBufferHEVC* const sequence) + { + ASSERT(m_vps.empty()); + BitWriter bs; + bit_writer_write_vps (&bs, sequence); + bsToHeader(m_vps, bs); + } + + void setSPS(const VAEncSequenceParameterBufferHEVC* const sequence) + { + ASSERT(m_vps.size() && m_sps.empty()); + BitWriter bs; + bit_writer_write_sps (&bs, sequence); + bsToHeader(m_sps, bs); + } + + void addPPS(const VAEncPictureParameterBufferHEVC* const picParam) + { + ASSERT(m_sps.size() && m_pps.empty()); + BitWriter bs; + bit_writer_write_pps (&bs, picParam); + bsToHeader(m_pps, bs); + } + + void generateCodecConfig() + { + std::vector headers; + + ASSERT(m_vps.size() && m_sps.size() && (m_sps.size() > 4)&& m_pps.size() && m_headers.empty()); + + headers.push_back(&m_vps); + headers.push_back(&m_sps); + headers.push_back(&m_pps); + uint8_t sync[] = {0, 0, 0, 1}; + for (size_t i = 0; i < headers.size(); i++) { + m_headers.insert(m_headers.end(), sync, sync + N_ELEMENTS(sync)); + appendHeaderWithEmulation(*headers[i]); + } + } + + YamiStatus getCodecConfig(VideoEncOutputBuffer* outBuffer) + { + ASSERT(outBuffer && (outBuffer->format == OUTPUT_CODEC_DATA || outBuffer->format == OUTPUT_EVERYTHING)); + if (outBuffer->bufferSize < m_headers.size()) + return YAMI_ENCODE_BUFFER_TOO_SMALL; + if (m_headers.empty()) + return YAMI_ENCODE_NO_REQUEST_DATA; + std::copy(m_headers.begin(), m_headers.end(), outBuffer->data); + outBuffer->dataSize = m_headers.size(); + outBuffer->flag |= ENCODE_BUFFERFLAG_CODECCONFIG; + return YAMI_SUCCESS; + } +private: + BOOL bit_writer_write_vps ( + BitWriter *bitwriter, + const VAEncSequenceParameterBufferHEVC* const seq + ) + { + BOOL vps_timing_info_present_flag = 0; + + bit_writer_write_nal_header(bitwriter, VPS_NUT); + + /* vps_video_parameter_set_id */ + bitwriter->writeBits(0, 4); + /* vps_base_layer_internal_flag */ + bitwriter->writeBits(1, 1); + /* vps_base_layer_available_flag */ + bitwriter->writeBits(1, 1); + /* vps_max_layers_minus1 */ + bitwriter->writeBits(0, 6); + /* vps_max_sub_layers_minus1 */ + bitwriter->writeBits(0, 3); + /* vps_temporal_id_nesting_flag */ + bitwriter->writeBits(1, 1); + + /* vps_reserved_0xffff_16bits */ + bitwriter->writeBits(0xffff, 16); + + profile_tier_level(bitwriter, 1, 0, seq); + + /* vps_sub_layer_ordering_info_present_flag */ + bitwriter->writeBits(0, 1); + + /*vps_max_dec_pic_buffering_minus1*/ + bit_writer_put_ue(bitwriter, 5); + + /*vps_max_num_reorder_pics*/ + bit_writer_put_ue(bitwriter, m_encoder->m_numBFrames); + + /*vps_max_latency_increase_plus1*/ + bit_writer_put_ue(bitwriter, 0); + + /* vps_max_layer_id */ + bitwriter->writeBits(0, 6); + + /* vps_num_layer_sets_minus1 */ + bit_writer_put_ue(bitwriter, 0); + + /* vps_timing_info_present_flag */ + bitwriter->writeBits(vps_timing_info_present_flag, 1); + + if (vps_timing_info_present_flag) { + /* TBD: add it later for BRC */ + } + + /* vps_extension_flag */ + bitwriter->writeBits(0, 1); + + /* rbsp_trailing_bits */ + bit_writer_write_trailing_bits(bitwriter); + + return TRUE; + } + + BOOL bit_writer_write_sps( + BitWriter *bitwriter, + const VAEncSequenceParameterBufferHEVC* const seq + ) + { + uint32_t i = 0; + + bit_writer_write_nal_header(bitwriter, SPS_NUT); + + /* sps_video_parameter_set_id */ + bitwriter->writeBits(0, 4); + /* sps_max_sub_layers_minus1 */ + bitwriter->writeBits(0, 3); + /* sps_temporal_id_nesting_flag */ + bitwriter->writeBits(1, 1); + + profile_tier_level(bitwriter, 1, 0, seq); + + /* seq_parameter_set_id */ + bit_writer_put_ue(bitwriter, 0); + /* chroma_format_idc: only support 4:2:0 for libva */ + bit_writer_put_ue(bitwriter, seq->seq_fields.bits.chroma_format_idc); + if (3 == seq->seq_fields.bits.chroma_format_idc) { + bitwriter->writeBits(seq->seq_fields.bits.separate_colour_plane_flag, 1); + } + /* pic_width_in_luma_samples */ + bit_writer_put_ue(bitwriter, seq->pic_width_in_luma_samples); + /* pic_height_in_luma_samples */ + bit_writer_put_ue(bitwriter, seq->pic_height_in_luma_samples); + + /* conformance_window_flag */ + bitwriter->writeBits(m_encoder->m_confWinFlag, 1); + + if (m_encoder->m_confWinFlag) { + bit_writer_put_ue(bitwriter, m_encoder->m_confWinLeftOffset); + bit_writer_put_ue(bitwriter, m_encoder->m_confWinRightOffset); + bit_writer_put_ue(bitwriter, m_encoder->m_confWinTopOffset); + bit_writer_put_ue(bitwriter, m_encoder->m_confWinBottomOffset); + } + + /* bit_depth_luma_minus8 */ + bit_writer_put_ue(bitwriter, seq->seq_fields.bits.bit_depth_luma_minus8); + /* bit_depth_chroma_minus8 */ + bit_writer_put_ue(bitwriter, seq->seq_fields.bits.bit_depth_chroma_minus8); + + /* log2_max_pic_order_cnt_lsb_minus4 */ + assert(m_encoder->m_log2MaxPicOrderCnt >= 4); + bit_writer_put_ue(bitwriter, m_encoder->m_log2MaxPicOrderCnt - 4); + + /* sps_sub_layer_ordering_info_present_flag */ + bitwriter->writeBits(0, 1); + + /* sps_max_dec_pic_buffering_minus1 */ + bit_writer_put_ue(bitwriter, 5); + /* sps_max_num_reorder_pics */ + bit_writer_put_ue(bitwriter, m_encoder->m_numBFrames); + /* sps_max_latency_increase_plus1 */ + bit_writer_put_ue(bitwriter, 0); + + bit_writer_put_ue(bitwriter, seq->log2_min_luma_coding_block_size_minus3); + bit_writer_put_ue(bitwriter, seq->log2_diff_max_min_luma_coding_block_size); + bit_writer_put_ue(bitwriter, seq->log2_min_transform_block_size_minus2); + bit_writer_put_ue(bitwriter, seq->log2_diff_max_min_transform_block_size); + bit_writer_put_ue(bitwriter, seq->max_transform_hierarchy_depth_inter); + bit_writer_put_ue(bitwriter, seq->max_transform_hierarchy_depth_intra); + + /* scaling_list_enabled_flag */ + bitwriter->writeBits(0, 1); + /* amp_enabled_flag */ + bitwriter->writeBits(seq->seq_fields.bits.amp_enabled_flag, 1); + /* sample_adaptive_offset_enabled_flag */ + bitwriter->writeBits(seq->seq_fields.bits.sample_adaptive_offset_enabled_flag, 1); + /* pcm_enabled_flag */ + bitwriter->writeBits(seq->seq_fields.bits.pcm_enabled_flag, 1); + + if (seq->seq_fields.bits.pcm_enabled_flag) { + /* pcm_sample_bit_depth_luma_minus1 */ + bitwriter->writeBits(seq->pcm_sample_bit_depth_luma_minus1, 4); + /* pcm_sample_bit_depth_luma_minus1 */ + bitwriter->writeBits(seq->pcm_sample_bit_depth_chroma_minus1, 4); + /* log2_min_pcm_luma_coding_block_size_minus3 */ + bit_writer_put_ue(bitwriter, seq->log2_min_pcm_luma_coding_block_size_minus3); + /* log2_diff_max_min_pcm_luma_coding_block_size */ + bit_writer_put_ue(bitwriter, seq->log2_max_pcm_luma_coding_block_size_minus3 - seq->log2_min_pcm_luma_coding_block_size_minus3); + /* pcm_loop_filter_disabled_flag */ + bitwriter->writeBits(seq->seq_fields.bits.pcm_loop_filter_disabled_flag, 1); + } + + bit_writer_put_ue(bitwriter, m_encoder->m_shortRFS.num_short_term_ref_pic_sets); + for (i = 0; i < m_encoder->m_shortRFS.num_short_term_ref_pic_sets; i++) + st_ref_pic_set(bitwriter, i, m_encoder->m_shortRFS); + + /* long_term_ref_pics_present_flag */ + bitwriter->writeBits(0, 1); + + /*sps_temporal_mvp_enabled_flag*/ + bitwriter->writeBits(0, 1); + + /* strong_intra_smoothing_enabled_flag */ + bitwriter->writeBits(seq->seq_fields.bits.strong_intra_smoothing_enabled_flag, 1); + + /* vui_parameters_present_flag */ + bitwriter->writeBits(seq->vui_parameters_present_flag, 1); + if (seq->vui_parameters_present_flag) { + /* aspect_ratio_info_present_flag */ + bitwriter->writeBits(seq->vui_fields.bits.aspect_ratio_info_present_flag, 1); + if (seq->vui_fields.bits.aspect_ratio_info_present_flag) { + bitwriter->writeBits(seq->aspect_ratio_idc, 8); + if (seq->aspect_ratio_idc == 0xFF) { + bitwriter->writeBits(seq->sar_width, 16); + bitwriter->writeBits(seq->sar_height, 16); + } + } + + /* overscan_info_present_flag */ + bitwriter->writeBits(0, 1); + /* video_signal_type_present_flag */ + bitwriter->writeBits(0, 1); + /* chroma_loc_info_present_flag */ + bitwriter->writeBits(0, 1); + /* neutral_chroma_indication_flag */ + bitwriter->writeBits(0, 1); + /* field_seq_flag */ + bitwriter->writeBits(0, 1); + /* frame_field_info_present_flag */ + bitwriter->writeBits(0, 1); + /* default_display_window_flag */ + bitwriter->writeBits(0, 1); + + /* vui_timing_info_present_flag */ + bitwriter->writeBits(seq->vui_fields.bits.vui_timing_info_present_flag, 1); + if (seq->vui_fields.bits.vui_timing_info_present_flag) { + bitwriter->writeBits(seq->vui_num_units_in_tick, 32); + bitwriter->writeBits(seq->vui_time_scale, 32); + /* vui_poc_proportional_to_timing_flag */ + bitwriter->writeBits(0, 1); + /* set hrd_parameters */ + BOOL vui_hrd_parameters_present_flag = (seq->bits_per_second > 0 ? TRUE : FALSE); + /* vui_hrd_parameters_present_flag */ + bitwriter->writeBits(vui_hrd_parameters_present_flag, 1); + if (vui_hrd_parameters_present_flag) { + /* nal_hrd_parameters_present_flag */ + bitwriter->writeBits(1, 1); + /* vcl_hrd_parameters_present_flag */ + bitwriter->writeBits(0, 1); + /* sub_pic_hrd_params_present_flag */ + bitwriter->writeBits(0, 1); + + bitwriter->writeBits(4, 4); /* bit_rate_scale */ + bitwriter->writeBits(6, 4); /* cpb_size_scale */ + + /* initial_cpb_removal_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + /* au_cpb_removal_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + /* dpb_output_delay_length_minus1 */ + bitwriter->writeBits(23, 5); + + for (i = 0; i < 1; ++i) { + /* fixed_pic_rate_general_flag[0] */ + bitwriter->writeBits(0, 1); + /* fixed_pic_rate_within_cvs_flag[0] */ + bitwriter->writeBits(0, 1); + /* low_delay_hrd_flag[0] */ + bitwriter->writeBits(1, 1); + + /* bit_rate_value_minus1[0] */ + bit_writer_put_ue(bitwriter, seq->bits_per_second/1024- 1); + /* cpb_size_value_minus1[0] */ + bit_writer_put_ue(bitwriter, seq->bits_per_second/(1024*8) - 1); + /* cbr_flag[0] */ + bitwriter->writeBits(1, 1); + } + } + } + + /* bitwriter_restriction_flag */ + bitwriter->writeBits(0, 1); + } + + /* sps_extension_present_flag */ + bitwriter->writeBits(0, 1); + + /* rbsp_trailing_bits */ + bit_writer_write_trailing_bits(bitwriter); + return TRUE; + } + + BOOL bit_writer_write_pps( + BitWriter *bitwriter, + const VAEncPictureParameterBufferHEVC* const pic + ) + { + uint32_t deblocking_filter_control_present_flag = 0; + uint32_t pps_slice_chroma_qp_offsets_present_flag = 1; + + bit_writer_write_nal_header(bitwriter, PPS_NUT); + + /* pps_pic_parameter_set_id */ + bit_writer_put_ue(bitwriter, 0); + /* pps_seq_parameter_set_id */ + bit_writer_put_ue(bitwriter, 0); + + /* dependent_slice_segments_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.dependent_slice_segments_enabled_flag, 1); + + /* output_flag_present_flag */ + bitwriter->writeBits(0, 1); + + /* num_extra_slice_header_bits */ + bitwriter->writeBits(0, 3); + + /* sign_data_hiding_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.sign_data_hiding_enabled_flag, 1); + + /* cabac_init_present_flag */ + bitwriter->writeBits(0, 1); + + bit_writer_put_ue(bitwriter, pic->num_ref_idx_l0_default_active_minus1); + bit_writer_put_ue(bitwriter, pic->num_ref_idx_l1_default_active_minus1); + + /* init_qp_minus26 */ + bit_writer_put_se(bitwriter, pic->pic_init_qp-26); + + /* constrained_intra_pred_flag */ + bitwriter->writeBits(pic->pic_fields.bits.constrained_intra_pred_flag, 1); + + /* transform_skip_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.transform_skip_enabled_flag, 1); + + /* cu_qp_delta_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.cu_qp_delta_enabled_flag, 1); + + if (pic->pic_fields.bits.cu_qp_delta_enabled_flag) { + /* diff_cu_qp_delta_depth */ + bit_writer_put_ue(bitwriter, pic->diff_cu_qp_delta_depth); + } + + /* pps_cb_qp_offset */ + bit_writer_put_se(bitwriter, pic->pps_cb_qp_offset); + + /* pps_cr_qp_offset */ + bit_writer_put_se(bitwriter, pic->pps_cr_qp_offset); + + /* pps_slice_chroma_qp_offsets_present_flag */ + bitwriter->writeBits(pps_slice_chroma_qp_offsets_present_flag, 1); + + /* weighted_pred_flag */ + bitwriter->writeBits(pic->pic_fields.bits.weighted_pred_flag, 1); + + /* weighted_bipred_flag */ + bitwriter->writeBits(pic->pic_fields.bits.weighted_bipred_flag, 1); + + /* transquant_bypass_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.transquant_bypass_enabled_flag, 1); + + /* tiles_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.tiles_enabled_flag, 1); + + /* entropy_coding_sync_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.entropy_coding_sync_enabled_flag, 1); + + if (pic->pic_fields.bits.tiles_enabled_flag) { + /* + * TBD: Add the tile division when tiles are enabled. + */ + assert(!pic->pic_fields.bits.tiles_enabled_flag); + } + + /* pps_loop_filter_across_slices_enabled_flag */ + bitwriter->writeBits(pic->pic_fields.bits.loop_filter_across_tiles_enabled_flag, 1); + + /* deblocking_filter_control_present_flag. 1 */ + bitwriter->writeBits(deblocking_filter_control_present_flag, 1); + if (deblocking_filter_control_present_flag) { + /* deblocking_filter_override_enabled_flag */ + bitwriter->writeBits(0, 1); + /* pps_deblocking_filter_disabled_flag */ + bitwriter->writeBits(0, 1); + } + + /* scaling_list_data_present_flag */ + bitwriter->writeBits(pic->pic_fields.bits.scaling_list_data_present_flag, 1); + + if (pic->pic_fields.bits.scaling_list_data_present_flag) { + /* + * TBD: Add the scaling list data for PPS + */ + assert(!pic->pic_fields.bits.scaling_list_data_present_flag); + } + + /* lists_modification_present_flag 0/1 ?*/ + bitwriter->writeBits(0, 1); + + /* log2_parallel_merge_level_minus2: 2 - 2 */ + bit_writer_put_ue(bitwriter, 0); + + /* slice_segment_header_extension_present_flag. Zero */ + bitwriter->writeBits(0, 1); + + /* pps_extension_flag */ + bitwriter->writeBits(0, 1); + + bit_writer_write_trailing_bits(bitwriter); + + return TRUE; + } + + + void bsToHeader(Header& param, BitWriter& bs) + { + uint64_t codedBits = bs.getCodedBitsCount(); + uint64_t codedBytes = codedBits / 8; + ASSERT(codedBytes && codedBits % 8 == 0); + + uint8_t* codedData = bs.getBitWriterData(); + ASSERT(codedData); + + param.insert(param.end(), codedData, codedData + codedBytes); + } + + void appendHeaderWithEmulation(Header& h) + { + Header::iterator s = h.begin(); + Header::iterator e; + uint8_t zeros[] = {0, 0}; + uint8_t emulation[] = {0, 0, 3}; + do { + e = std::search(s, h.end(), zeros, zeros + N_ELEMENTS(zeros)); + m_headers.insert(m_headers.end(), s, e); + if (e == h.end()) + break; + + s = e + N_ELEMENTS(zeros); + + /* only when bitstream contains 0x000000/0x000001/0x000002/0x000003 + need to insert emulation prevention byte 0x03 */ + if (*s <= 3) + m_headers.insert(m_headers.end(), emulation, emulation + N_ELEMENTS(emulation)); + else + m_headers.insert(m_headers.end(), zeros, zeros + N_ELEMENTS(zeros)); + } while (1); + } + + Header m_vps; + Header m_sps; + Header m_pps; + Header m_headers; + VaapiEncoderHEVC* m_encoder; +}; + +class VaapiEncPictureHEVC:public VaapiEncPicture +{ + friend class VaapiEncoderHEVC; + friend class VaapiEncoderHEVCRef; + typedef std::function Function; + +public: + virtual ~VaapiEncPictureHEVC() {} + + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer) + { + ASSERT(outBuffer); + VideoOutputFormat format = outBuffer->format; + //make a local copy of out Buffer; + VideoEncOutputBuffer out = *outBuffer; + out.flag = 0; + + std::vector functions; + if (format == OUTPUT_CODEC_DATA || ((format == OUTPUT_EVERYTHING) && isIdr())) + functions.push_back(std::bind(&VaapiEncStreamHeaderHEVC::getCodecConfig, m_headers,&out)); + if (format == OUTPUT_EVERYTHING || format == OUTPUT_FRAME_DATA) + functions.push_back(std::bind(getOutputHelper, this, &out)); + YamiStatus ret = getOutput(&out, functions); + if (ret == YAMI_SUCCESS) { + outBuffer->dataSize = out.data - outBuffer->data; + outBuffer->flag = out.flag; + } + return ret; + } + +private: + VaapiEncPictureHEVC(const ContextPtr& context, const SurfacePtr& surface, int64_t timeStamp): + VaapiEncPicture(context, surface, timeStamp), + m_frameNum(0), + m_poc(0) + { + } + + bool isIdr() const { + return m_type == VAAPI_PICTURE_I && !m_frameNum; + } + + //getOutput is a virutal function, we need this to help bind + static YamiStatus getOutputHelper(VaapiEncPictureHEVC* p, VideoEncOutputBuffer* out) + { + return p->VaapiEncPicture::getOutput(out); + } + + YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, std::vector& functions) + { + ASSERT(outBuffer); + + outBuffer->dataSize = 0; + + YamiStatus ret; + for (size_t i = 0; i < functions.size(); i++) { + ret = functions[i](); + if (ret != YAMI_SUCCESS) + return ret; + outBuffer->bufferSize -= outBuffer->dataSize; + outBuffer->data += outBuffer->dataSize; + } + return YAMI_SUCCESS; + } + + uint32_t m_frameNum; + uint32_t m_poc; + StreamHeaderPtr m_headers; +}; + +class VaapiEncoderHEVCRef +{ +public: + VaapiEncoderHEVCRef(const PicturePtr& picture, const SurfacePtr& surface): + m_frameNum(picture->m_frameNum), + m_poc(picture->m_poc), + m_pic(surface) + { + } + uint32_t m_frameNum; + uint32_t m_poc; + SurfacePtr m_pic; +}; + +VaapiEncoderHEVC::VaapiEncoderHEVC(): + m_numBFrames(0), + m_ctbSize(8), + m_cuSize(32), + m_minTbSize(4), + m_maxTbSize(32), + m_reorderState(VAAPI_ENC_REORD_WAIT_FRAMES), + m_keyPeriod(30) +{ + m_videoParamCommon.profile = VAProfileHEVCMain; + m_videoParamCommon.level = 51; + m_videoParamCommon.rcParams.initQP = 26; + m_videoParamCommon.rcParams.minQP = 1; + + memset(&m_videoParamAVC, 0, sizeof(m_videoParamAVC)); + m_videoParamAVC.idrInterval = 0; +} + +VaapiEncoderHEVC::~VaapiEncoderHEVC() +{ + FUNC_ENTER(); +} + +bool VaapiEncoderHEVC::ensureCodedBufferSize() +{ + AutoLock locker(m_paramLock); + + FUNC_ENTER(); + + if (m_maxCodedbufSize) + return true; + + m_maxCodedbufSize = m_AlignedWidth * m_AlignedHeight * 3 / 2 + 0x1000; + + DEBUG("m_maxCodedbufSize: %u", m_maxCodedbufSize); + + return true; +} + +void VaapiEncoderHEVC::resetParams () +{ + + m_levelIdc = level(); + if (10 == m_videoParamCommon.bitDepth) + m_videoParamCommon.profile = VAProfileHEVCMain10; + m_profileIdc = hevc_get_profile_idc(profile()); + + m_numSlices = 1; + + assert (width() && height()); + + /* libva driver requred pic_width_in_luma_samples 16 aligned, not ctb aligned */ + m_AlignedWidth = (width() + 15) / 16 * 16; + m_AlignedHeight = (height() + 15) / 16 * 16; + + m_cuWidth = (width() + m_cuSize -1) / m_cuSize; + m_cuHeight = (height() + m_cuSize-1) / m_cuSize; + + m_confWinLeftOffset = m_confWinTopOffset = 0; + + if (m_AlignedWidth != width() || m_AlignedHeight !=height()) { + m_confWinFlag = true; + m_confWinRightOffset = (m_AlignedWidth - width()) / 2; + m_confWinBottomOffset = (m_AlignedHeight -height()) / 2; + } else { + m_confWinFlag = false; + m_confWinRightOffset = 0; + m_confWinBottomOffset = 0; + } + + if (intraPeriod() == 0) { + ERROR("intra period must larger than 0"); + m_videoParamCommon.intraPeriod = 1; + } + + if (intraPeriod() <= ipPeriod()) { + WARNING("intra period is not larger than ip period"); + m_videoParamCommon.ipPeriod = intraPeriod() - 1; + } + + if (ipPeriod() == 0) + m_videoParamCommon.intraPeriod = 1; + else if (ipPeriod() >= 1) + m_numBFrames = ipPeriod() - 1; + + m_keyPeriod = intraPeriod() * (m_videoParamAVC.idrInterval + 1); + + if (minQP() > initQP() || + (rateControlMode()== RATE_CONTROL_CQP && minQP() < initQP())) + minQP() = initQP(); + + if (m_numBFrames > (intraPeriod() + 1) / 2) + m_numBFrames = (intraPeriod() + 1) / 2; + + DEBUG("resetParams, ensureCodedBufferSize"); + ensureCodedBufferSize(); + + /* init m_maxFrameNum, max_poc */ + m_log2MaxFrameNum = + hevc_get_log2_max_frame_num (m_keyPeriod); + assert (m_log2MaxFrameNum >= 4); + m_maxFrameNum = (1 << m_log2MaxFrameNum); + m_log2MaxPicOrderCnt = m_log2MaxFrameNum + 1; + m_maxPicOrderCnt = (1 << m_log2MaxPicOrderCnt); + + m_maxRefList1Count = m_numBFrames > 0;//m_maxRefList1Count <=1, because of currenent order mechanism + m_maxRefList0Count = numRefFrames(); + if (m_maxRefList0Count >= m_maxOutputBuffer -1) + m_maxRefList0Count = m_maxOutputBuffer -1; + + m_maxRefFrames = + m_maxRefList0Count + m_maxRefList1Count; + + assert(m_maxRefFrames <= m_maxOutputBuffer); + + INFO("m_maxRefFrames: %d", m_maxRefFrames); + + setShortRfs(); + + resetGopStart(); +} + +YamiStatus VaapiEncoderHEVC::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + + if (ensureCodedBufferSize()) + *maxSize = m_maxCodedbufSize; + else + *maxSize = 0; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderHEVC::start() +{ + FUNC_ENTER(); + resetParams(); + return VaapiEncoderBase::start(); +} + +void VaapiEncoderHEVC::flush() +{ + YamiStatus ret; + + FUNC_ENTER(); + + if (!m_reorderFrameList.empty()) { + changeLastBFrameToPFrame(); + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + + ret = encodeAllFrames(); + if (ret != YAMI_SUCCESS) { + ERROR("Not all frames are flushed."); + } + } + + resetGopStart(); + m_reorderFrameList.clear(); + referenceListFree(); + VaapiEncoderBase::flush(); +} + +YamiStatus VaapiEncoderHEVC::stop() +{ + flush(); + return VaapiEncoderBase::stop(); +} + +YamiStatus VaapiEncoderHEVC::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + AutoLock locker(m_paramLock); + + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + switch (type) { + case VideoParamsTypeAVC: { + VideoParamsAVC* avc = (VideoParamsAVC*)videoEncParams; + if (avc->size == sizeof(VideoParamsAVC)) { + PARAMETER_ASSIGN(m_videoParamAVC, *avc); + status = YAMI_SUCCESS; + } + } + break; + default: + status = VaapiEncoderBase::setParameters(type, videoEncParams); + break; + } + return status; +} + +YamiStatus VaapiEncoderHEVC::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + AutoLock locker(m_paramLock); + + FUNC_ENTER(); + if (!videoEncParams) + return status; + switch (type) { + case VideoParamsTypeAVC: { + VideoParamsAVC* avc = (VideoParamsAVC*)videoEncParams; + if (avc->size == sizeof(VideoParamsAVC)) { + PARAMETER_ASSIGN(*avc, m_videoParamAVC); + status = YAMI_SUCCESS; + } + } + break; + default: + status = VaapiEncoderBase::getParameters(type, videoEncParams); + break; + } + + return status; +} + +void VaapiEncoderHEVC::changeLastBFrameToPFrame() +{ + PicturePtr lastPic = m_reorderFrameList.back(); + if (lastPic->m_type == VAAPI_PICTURE_B) { + lastPic->m_type = VAAPI_PICTURE_P; + m_reorderFrameList.pop_back(); + m_reorderFrameList.push_front(lastPic); + } +} + +YamiStatus VaapiEncoderHEVC::reorder(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + if (!surface) + return YAMI_INVALID_PARAM; + + PicturePtr picture(new VaapiEncPictureHEVC(m_context, surface, timeStamp)); + + bool isIdr = (m_frameIndex == 0 ||m_frameIndex >= m_keyPeriod || forceKeyFrame); + + /* check key frames */ + if (isIdr || (m_frameIndex % intraPeriod() == 0)) { + if (isIdr && m_reorderFrameList.size()) { + changeLastBFrameToPFrame(); + } + + setIntraFrame (picture, isIdr); + m_reorderFrameList.push_back(picture); + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + } else if (m_frameIndex % (m_numBFrames + 1) != 0) { + setBFrame (picture); + m_reorderFrameList.push_back(picture); + } else { + setPFrame (picture); + m_reorderFrameList.push_front(picture); + m_reorderState = VAAPI_ENC_REORD_DUMP_FRAMES; + } + + DEBUG("m_frameIndex is %d\n", m_frameIndex); + picture->m_poc = m_frameIndex; + m_frameIndex++; + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderHEVC::encodeAllFrames() +{ + FUNC_ENTER(); + YamiStatus ret; + + while (m_reorderState == VAAPI_ENC_REORD_DUMP_FRAMES) { + if (!m_maxCodedbufSize) + ensureCodedBufferSize(); + ASSERT(m_maxCodedbufSize); + CodedBufferPtr codedBuffer = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize); + if (!codedBuffer) + return YAMI_OUT_MEMORY; + DEBUG("m_reorderFrameList size: %zu\n", m_reorderFrameList.size()); + PicturePtr picture = m_reorderFrameList.front(); + m_reorderFrameList.pop_front(); + picture->m_codedBuffer = codedBuffer; + + if (m_reorderFrameList.empty()) + m_reorderState = VAAPI_ENC_REORD_WAIT_FRAMES; + + ret = encodePicture(picture); + if (ret != YAMI_SUCCESS) { + return ret; + } + codedBuffer->setFlag(ENCODE_BUFFERFLAG_ENDOFFRAME); + INFO("picture->m_type: 0x%x\n", picture->m_type); + if (picture->isIdr()) { + codedBuffer->setFlag(ENCODE_BUFFERFLAG_SYNCFRAME); + } + + if (!output(picture)) + return YAMI_INVALID_PARAM; + } + + INFO(); + return YAMI_SUCCESS; +} + +// calls immediately after reorder, +// it makes sure I frame are encoded immediately, so P frames can be pushed to the front of the m_reorderFrameList. +// it also makes sure input thread and output thread runs in parallel +YamiStatus VaapiEncoderHEVC::doEncode(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + FUNC_ENTER(); + YamiStatus ret; + ret = reorder(surface, timeStamp, forceKeyFrame); + if (ret != YAMI_SUCCESS) + return ret; + + ret = encodeAllFrames(); + if (ret != YAMI_SUCCESS) { + return ret; + } + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderHEVC::getCodecConfig(VideoEncOutputBuffer* outBuffer) +{ + ASSERT(outBuffer && ((outBuffer->flag == OUTPUT_CODEC_DATA) || outBuffer->flag == OUTPUT_EVERYTHING)); + AutoLock locker(m_paramLock); + if (!m_headers) + return YAMI_ENCODE_NO_REQUEST_DATA; + return m_headers->getCodecConfig(outBuffer); +} + +/* Handle new GOP starts */ +void VaapiEncoderHEVC::resetGopStart () +{ + m_frameIndex = 0; +} + +/* Marks the supplied picture as a B-frame */ +void VaapiEncoderHEVC::setBFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_B; + pic->m_frameNum = (m_frameIndex % m_maxFrameNum); +} + +/* Marks the supplied picture as a P-frame */ +void VaapiEncoderHEVC::setPFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_P; + pic->m_frameNum = (m_frameIndex % m_maxFrameNum); +} + +/* Marks the supplied picture as an I-frame */ +void VaapiEncoderHEVC::setIFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_I; + pic->m_frameNum = (m_frameIndex % m_maxFrameNum); +} + +/* Marks the supplied picture as an IDR frame */ +void VaapiEncoderHEVC::setIdrFrame (const PicturePtr& pic) +{ + pic->m_type = VAAPI_PICTURE_I; + pic->m_frameNum = 0; + pic->m_poc = 0; +} + +/* Marks the supplied picture a a key-frame */ +void VaapiEncoderHEVC::setIntraFrame (const PicturePtr& picture,bool idIdr) +{ + if (idIdr) { + resetGopStart(); + setIdrFrame(picture); + } else + setIFrame(picture); +} + +bool VaapiEncoderHEVC:: +referenceListUpdate (const PicturePtr& picture, const SurfacePtr& surface) +{ + if (VAAPI_PICTURE_B == picture->m_type) { + return true; + } + + if (picture->isIdr()) { + m_refList.clear(); + } else if (m_refList.size() >= m_maxRefFrames) { + m_refList.pop_back(); + } + ReferencePtr ref(new VaapiEncoderHEVCRef(picture, surface)); + m_refList.push_front(ref); // recent first + assert (m_refList.size() <= m_maxRefFrames); + return true; +} + +bool VaapiEncoderHEVC::pictureReferenceListSet ( + const PicturePtr& picture) +{ + uint32_t i; + + /* reset reflist0 and reflist1 every time */ + m_refList0.clear(); + m_refList1.clear(); + + if (picture->m_type == VAAPI_PICTURE_I) + return true; + + for (i = 0; i < m_refList.size(); i++) { + assert(picture->m_poc != m_refList[i]->m_poc); + if (picture->m_poc > m_refList[i]->m_poc) { + /* set forward reflist: descending order */ + m_refList0.push_back(m_refList[i]); + } else { + /* set backward reflist: ascending order */ + m_refList1.push_front(m_refList[i]); + } + } + + if (m_refList0.size() > m_maxRefList0Count) + m_refList0.resize(m_maxRefList0Count); + if (m_refList1.size() > m_maxRefList1Count) + m_refList1.resize(m_maxRefList1Count); + + shortRfsUpdate(picture); + + assert (m_refList0.size() + m_refList1.size() <= m_maxRefFrames); + + return true; +} + +void VaapiEncoderHEVC::referenceListFree() +{ + m_refList.clear(); + m_refList0.clear(); + m_refList1.clear(); +} + +void VaapiEncoderHEVC::shortRfsUpdate(const PicturePtr& picture) +{ + int i; + + memset(&m_shortRFS, 0, sizeof(m_shortRFS)); + + m_shortRFS.num_short_term_ref_pic_sets = 0; + m_shortRFS.inter_ref_pic_set_prediction_flag = 0; + + if (intraPeriod() > 1 && m_refList0.size()) { + m_shortRFS.num_negative_pics = 1; + m_shortRFS.delta_poc_s0_minus1[0] = picture->m_poc - m_refList0[0]->m_poc - 1; + m_shortRFS.used_by_curr_pic_s0_flag[0] = 1; + if (m_numBFrames && m_refList1.size()) { + m_shortRFS.num_positive_pics = 1; + m_shortRFS.delta_poc_s1_minus1[0] = m_refList1[0]->m_poc - picture->m_poc - 1; + m_shortRFS.used_by_curr_pic_s1_flag[0] = 1; + + DEBUG("m_refList1_size is %zu\n", m_refList1.size()); + } + } + + for (i = 1; i < m_shortRFS.num_negative_pics; i++) + { + m_shortRFS.delta_poc_s0_minus1[i] = 0; + m_shortRFS.used_by_curr_pic_s0_flag[i] = 1; + } + + for (i = 1; i < m_shortRFS.num_positive_pics; i++) { + m_shortRFS.delta_poc_s1_minus1[i] = 0; + m_shortRFS.used_by_curr_pic_s1_flag[i] = 1; + } + +} + + +void VaapiEncoderHEVC::setShortRfs() +{ + int i; + + memset(&m_shortRFS, 0, sizeof(m_shortRFS)); + + if (intraPeriod() > 1) { + m_shortRFS.num_negative_pics = 1; + if (m_numBFrames ) + m_shortRFS.num_positive_pics = 1; + } + + m_shortRFS.num_short_term_ref_pic_sets = 0; + + m_shortRFS.inter_ref_pic_set_prediction_flag = 0; + + m_shortRFS.delta_poc_s0_minus1[0] = 0; + m_shortRFS.used_by_curr_pic_s0_flag[0] = 1; + + for (i = 1; i < m_shortRFS.num_negative_pics; i++) + { + m_shortRFS.delta_poc_s0_minus1[i] = 0; + m_shortRFS.used_by_curr_pic_s0_flag[i] = 1; + } + + for (i = 1; i < m_shortRFS.num_positive_pics; i++) { + m_shortRFS.delta_poc_s1_minus1[i] = 0; + m_shortRFS.used_by_curr_pic_s1_flag[i] = 1; + } + +} + +bool VaapiEncoderHEVC::fill(VAEncSequenceParameterBufferHEVC* seqParam) const +{ + + seqParam->general_profile_idc = m_profileIdc; + seqParam->general_level_idc = level(); + seqParam->general_tier_flag = 0; + seqParam->intra_period = intraPeriod(); + seqParam->intra_idr_period = seqParam->intra_period; + seqParam->ip_period = 1 + m_numBFrames; + seqParam->bits_per_second = bitRate(); + + seqParam->pic_width_in_luma_samples = m_AlignedWidth; + seqParam->pic_height_in_luma_samples = m_AlignedHeight; + + /*Only support yuv 4:2:0 format */ + seqParam->seq_fields.bits.chroma_format_idc = 1; + /* separate color plane_flag*/ + seqParam->seq_fields.bits.separate_colour_plane_flag = 0; + /* bit_depth_luma_minus8. Only 0 is supported for main profile */ + seqParam->seq_fields.bits.bit_depth_luma_minus8 = m_videoParamCommon.bitDepth - 8; + /* bit_depth_chroma_minus8. Only 0 is supported for main profile*/ + seqParam->seq_fields.bits.bit_depth_chroma_minus8 = m_videoParamCommon.bitDepth - 8; + + /* scaling_list_enabled_flag. Use the default value */ + seqParam->seq_fields.bits.scaling_list_enabled_flag = 0; + /* strong_intra_smoothing_enabled_flag. Not use the bi-linear interpolation */ + seqParam->seq_fields.bits.strong_intra_smoothing_enabled_flag = 0; + /* amp_enabled_flag(nLx2N or nRx2N). This is not supported */ + seqParam->seq_fields.bits.amp_enabled_flag = 1; + /* sample_adaptive_offset_enabled_flag. Unsupported */ + seqParam->seq_fields.bits.sample_adaptive_offset_enabled_flag = 0; + /* pcm_enabled_flag */ + seqParam->seq_fields.bits.pcm_enabled_flag = 0; + /* pcm_loop_filter_disabled_flag */ + seqParam->seq_fields.bits.pcm_loop_filter_disabled_flag = 1; + /* sps_temporal_mvp_enabled_flag. Enabled */ + seqParam->seq_fields.bits.sps_temporal_mvp_enabled_flag = 0; + + seqParam->log2_min_luma_coding_block_size_minus3 = log2(m_ctbSize) -3; + seqParam->log2_diff_max_min_luma_coding_block_size = log2(m_cuSize) - log2(m_ctbSize); + seqParam->log2_min_transform_block_size_minus2 = log2(m_minTbSize) - 2; + seqParam->log2_diff_max_min_transform_block_size = log2(m_maxTbSize) - log2(m_minTbSize); + + /* max_transform_hierarchy_depth_inter */ + seqParam->max_transform_hierarchy_depth_inter = 2; + + /* max_transform_hierarchy_depth_intra */ + seqParam->max_transform_hierarchy_depth_intra = 2; + + /* The PCM fields can be ignored as PCM is disabled */ + seqParam->pcm_sample_bit_depth_luma_minus1 = 7; + seqParam->pcm_sample_bit_depth_chroma_minus1 = 7; + seqParam->log2_min_pcm_luma_coding_block_size_minus3 = 0; + seqParam->log2_max_pcm_luma_coding_block_size_minus3 = 0; + + /* VUI parameters are always set for timing_info (framerate/bitrate) */ + seqParam->vui_parameters_present_flag = TRUE; + seqParam->vui_fields.bits.vui_timing_info_present_flag = TRUE; + seqParam->vui_num_units_in_tick = frameRateDenom(); + /* Fps of hevc is equal to vui_time_scale/vui_time_scale. It is differenet from h264 */ + seqParam->vui_time_scale = frameRateNum(); + + return true; +} + +/* Fills in VA picture parameter buffer */ +bool VaapiEncoderHEVC::fill(VAEncPictureParameterBufferHEVC* picParam, const PicturePtr& picture, + const SurfacePtr& surface) const +{ + uint32_t i = 0; + + picParam->decoded_curr_pic.picture_id = surface->getID(); + picParam->decoded_curr_pic.flags = VA_PICTURE_HEVC_RPS_LT_CURR; + picParam->decoded_curr_pic.pic_order_cnt = picture->m_poc; + + if (picture->m_type != VAAPI_PICTURE_I) { + for (i = 0; i < m_refList.size(); i++) { + picParam->reference_frames[i].picture_id = m_refList[i]->m_pic->getID(); + picParam->reference_frames[i].pic_order_cnt= m_refList[i]->m_poc; + } + } + + for (; i < N_ELEMENTS(picParam->reference_frames); ++i) { + picParam->reference_frames[i].picture_id = VA_INVALID_ID; + } + + picParam->coded_buf = picture->m_codedBuffer->getID(); + + /*collocated_ref_pic_index should be 0xff when element slice_temporal_mvp_enable_flag is 0 */ + picParam->collocated_ref_pic_index = 0xff; + + picParam->last_picture = 0; /* means last encoding picture */ + + picParam->pic_init_qp = initQP(); + + picParam->diff_cu_qp_delta_depth = 0; + + picParam->pps_cb_qp_offset = 0; + picParam->pps_cr_qp_offset = 0; + + /* currently multi-tile is disabled */ + picParam->num_tile_columns_minus1 = 0; + picParam->num_tile_rows_minus1 = 0; + + memset(picParam->column_width_minus1, 0, sizeof(picParam->column_width_minus1)); + memset(picParam->row_height_minus1, 0, sizeof(picParam->row_height_minus1)); + + picParam->log2_parallel_merge_level_minus2 = 0; + + /*no bit size limitation*/ + picParam->ctu_max_bitsize_allowed = 0; + + picParam->num_ref_idx_l0_default_active_minus1 = 0; + picParam->num_ref_idx_l1_default_active_minus1 = 0; + + picParam->slice_pic_parameter_set_id = 0; + picParam->nal_unit_type = PPS_NUT; + + picParam->pic_fields.value = 0; + picParam->pic_fields.bits.idr_pic_flag = picture->isIdr(); + /*FIXME: can't support picture type B1 and B2 now */ + picParam->pic_fields.bits.coding_type = picture->m_type; + picParam->pic_fields.bits.reference_pic_flag = (picture->m_type != VAAPI_PICTURE_B); + picParam->pic_fields.bits.dependent_slice_segments_enabled_flag = 0; + picParam->pic_fields.bits.sign_data_hiding_enabled_flag = 0; + picParam->pic_fields.bits.constrained_intra_pred_flag = 0; + picParam->pic_fields.bits.transform_skip_enabled_flag = 0; + /* cu_qp_delta_enabled_flag should be true to bitrate control */ + picParam->pic_fields.bits.cu_qp_delta_enabled_flag = 1; + picParam->pic_fields.bits.weighted_pred_flag = 0; + picParam->pic_fields.bits.weighted_bipred_flag = 0; + picParam->pic_fields.bits.transquant_bypass_enabled_flag = 0; + picParam->pic_fields.bits.tiles_enabled_flag = 0; + picParam->pic_fields.bits.entropy_coding_sync_enabled_flag = 0; + picParam->pic_fields.bits.loop_filter_across_tiles_enabled_flag = 0; + picParam->pic_fields.bits.pps_loop_filter_across_slices_enabled_flag = 0; + /* scaling_list_data_present_flag: use default scaling list data*/ + picParam->pic_fields.bits.scaling_list_data_present_flag = 0; + picParam->pic_fields.bits.screen_content_flag = 1; + picParam->pic_fields.bits.no_output_of_prior_pics_flag = 0; + + return TRUE; +} + +bool VaapiEncoderHEVC::ensureSequenceHeader(const PicturePtr& picture,const VAEncSequenceParameterBufferHEVC* const sequence) +{ + m_headers.reset(new VaapiEncStreamHeaderHEVC(this)); + m_headers->setVPS(sequence); + m_headers->setSPS(sequence); + return true; +} + +bool VaapiEncoderHEVC::ensurePictureHeader(const PicturePtr& picture, const VAEncPictureParameterBufferHEVC* const picParam) +{ + m_headers->addPPS(picParam); + m_headers->generateCodecConfig(); + picture->m_headers = m_headers; + return true; +} + +bool VaapiEncoderHEVC:: fillReferenceList(VAEncSliceParameterBufferHEVC* slice) const +{ + uint32_t i = 0; + for (i = 0; i < m_refList0.size(); i++) { + assert(m_refList0[i] && m_refList0[i]->m_pic && (m_refList0[i]->m_pic->getID() != VA_INVALID_ID)); + slice->ref_pic_list0[i].picture_id = m_refList0[i]->m_pic->getID(); + slice->ref_pic_list0[i].pic_order_cnt= m_refList0[i]->m_poc; + } + for (; i < N_ELEMENTS(slice->ref_pic_list0); i++) + slice->ref_pic_list0[i].picture_id = VA_INVALID_SURFACE; + + for (i = 0; i < m_refList1.size(); i++){ + assert(m_refList1[i] && m_refList1[i]->m_pic && (m_refList1[i]->m_pic->getID() != VA_INVALID_ID)); + slice->ref_pic_list1[i].picture_id = m_refList1[i]->m_pic->getID(); + slice->ref_pic_list1[i].pic_order_cnt= m_refList1[i]->m_poc; + } + for (; i < N_ELEMENTS(slice->ref_pic_list1); i++) + slice->ref_pic_list1[i].picture_id = VA_INVALID_SURFACE; + return true; +} + +bool VaapiEncoderHEVC::addPackedSliceHeader(const PicturePtr& picture, + const VAEncSliceParameterBufferHEVC* const sliceParam, + uint32_t sliceIndex) const +{ + bool ret = true; + BitWriter bs; + BOOL short_term_ref_pic_set_sps_flag = !!m_shortRFS.num_short_term_ref_pic_sets; + HevcNalUnitType nalUnitType = (picture->isIdr() ? IDR_W_RADL : TRAIL_R ); + bs.writeBits(HEVC_NAL_START_CODE, 32); + bit_writer_write_nal_header(&bs, nalUnitType); + + /* first_slice_segment_in_pic_flag */ + bs.writeBits(sliceIndex == 0, 1); + + /* no_output_of_prior_pics_flag */ + if (nalUnitType >= BLA_W_LP && nalUnitType <= RSV_IRAP_VCL23 ) + bs.writeBits(0, 1); + + /* slice_pic_parameter_set_id */ + bit_writer_put_ue(&bs, 0); + + if (sliceIndex) { + /* don't support dependent_slice_segments_enabled_flag right now*/ + ASSERT (!m_picParam->pic_fields.bits.dependent_slice_segments_enabled_flag && + !sliceParam->slice_fields.bits.dependent_slice_segment_flag); + + bs.writeBits(sliceParam->slice_segment_address, log2(sliceParam->num_ctu_in_slice)); + } + + if (!sliceParam->slice_fields.bits.dependent_slice_segment_flag) { + bit_writer_put_ue(&bs, sliceParam->slice_type); + + ASSERT(!m_seqParam->seq_fields.bits.separate_colour_plane_flag); + + if (nalUnitType != IDR_W_RADL && nalUnitType != IDR_N_LP) { + bs.writeBits(m_picParam->decoded_curr_pic.pic_order_cnt, m_log2MaxPicOrderCnt); + bs.writeBits(short_term_ref_pic_set_sps_flag, 1); + if (!short_term_ref_pic_set_sps_flag) + st_ref_pic_set(&bs, m_shortRFS.num_short_term_ref_pic_sets, m_shortRFS); + else if (m_shortRFS.num_short_term_ref_pic_sets > 1) + bs.writeBits(m_shortRFS.short_term_ref_pic_set_idx, log2(m_shortRFS.num_short_term_ref_pic_sets)); + /* long_term_ref_pics_present_flag is set to 0 */ + + if (sliceParam->slice_type != HEVC_SLICE_TYPE_I) { + bs.writeBits(sliceParam->slice_fields.bits.num_ref_idx_active_override_flag, 1); + if (sliceParam->slice_fields.bits.num_ref_idx_active_override_flag) { + bit_writer_put_ue(&bs, sliceParam->num_ref_idx_l0_active_minus1); + if (sliceParam->slice_type == HEVC_SLICE_TYPE_B ) + bit_writer_put_ue(&bs, sliceParam->num_ref_idx_l1_active_minus1); + } + /* pps lists_modification_present_flag is set to 0 */ + if (sliceParam->slice_type == HEVC_SLICE_TYPE_B) + bs.writeBits(sliceParam->slice_fields.bits.mvd_l1_zero_flag, 1); + if (sliceParam->slice_fields.bits.cabac_init_flag) + bs.writeBits(sliceParam->slice_fields.bits.cabac_init_flag, 1); + + /* slice_temporal_mvp_enabled_flag and weighted_pred_flag are set to 0*/ + ASSERT(!sliceParam->slice_fields.bits.slice_temporal_mvp_enabled_flag && + !m_picParam->pic_fields.bits.weighted_bipred_flag); + + ASSERT(sliceParam->max_num_merge_cand <= 5); + bit_writer_put_ue(&bs, 5 - sliceParam->max_num_merge_cand); + } + } + + bit_writer_put_ue(&bs, sliceParam->slice_qp_delta); + /* pps_slice_chroma_qp_offsets_present_flag is set to 1 */ + bit_writer_put_ue(&bs, sliceParam->slice_cb_qp_offset); + bit_writer_put_ue(&bs, sliceParam->slice_cr_qp_offset); + /* deblocking_filter_override_enabled_flag and + * pps_loop_filter_across_slices_enabled_flag are set to 0 */ + } + + bit_writer_write_trailing_bits(&bs); + + uint8_t* codedData = bs.getBitWriterData(); + ASSERT(codedData); + + if (!picture->addPackedHeader(VAEncPackedHeaderSlice, codedData, bs.getCodedBitsCount())) { + ret = false; + } + + return ret; +} + +/* Add slice headers to picture */ +bool VaapiEncoderHEVC::addSliceHeaders (const PicturePtr& picture) const +{ + VAEncSliceParameterBufferHEVC *sliceParam; + uint32_t sliceOfCtus, sliceModCtus, curSliceCtus; + uint32_t numCtus; + uint32_t lastCtuIndex; + + assert (picture); + + if (picture->m_type != VAAPI_PICTURE_I) { + /* have one reference frame at least */ + assert(m_refList0.size() > 0); + } + + numCtus= m_cuWidth * m_cuHeight; + + assert (m_numSlices && m_numSlices < numCtus); + sliceOfCtus = numCtus / m_numSlices; + sliceModCtus = numCtus % m_numSlices; + lastCtuIndex = 0; + for (uint32_t i = 0; i < m_numSlices; ++i) { + curSliceCtus = sliceOfCtus; + if (sliceModCtus) { + ++curSliceCtus; + --sliceModCtus; + } + if (!picture->newSlice(sliceParam)) + return false; + + sliceParam->slice_segment_address = lastCtuIndex; + sliceParam->num_ctu_in_slice = curSliceCtus; + sliceParam->slice_type = hevc_get_slice_type (picture->m_type); + assert (sliceParam->slice_type != -1); + sliceParam->slice_pic_parameter_set_id = 0; + sliceParam->slice_fields.bits.num_ref_idx_active_override_flag = 1; + if (picture->m_type != VAAPI_PICTURE_I && m_refList0.size() > 0) + sliceParam->num_ref_idx_l0_active_minus1 = m_refList0.size() - 1; + if (picture->m_type == VAAPI_PICTURE_B && m_refList1.size() > 0) + sliceParam->num_ref_idx_l1_active_minus1 = m_refList1.size() - 1; + + fillReferenceList(sliceParam); + + /* luma_log2_weight_denom should be the range: [0, 7] */ + sliceParam->luma_log2_weight_denom = 0; + /* max_num_merge_cand should be the range [1, 5 + NumExtraMergeCand] */ + sliceParam->max_num_merge_cand = 5; + + /* let slice_qp equal to init_qp*/ + sliceParam->slice_qp_delta = 0; + + /* slice_beta_offset_div2 and slice_tc_offset_div2 should be the range [-6, 6] */ + sliceParam->slice_beta_offset_div2 = 0; + sliceParam->slice_tc_offset_div2 = 0; + + /* set calculation for next slice */ + lastCtuIndex += curSliceCtus; + + sliceParam->slice_fields.bits.slice_deblocking_filter_disabled_flag = 0; + + sliceParam->slice_fields.bits.last_slice_of_pic_flag = (lastCtuIndex == numCtus); + + addPackedSliceHeader(picture, sliceParam, i); + } + assert (lastCtuIndex == numCtus); + + return true; +} + +bool VaapiEncoderHEVC::ensureSequence(const PicturePtr& picture) +{ +#ifndef __ENABLE_H265_ENC_ON_STUDIO_VA__ + //fill sps for every frame, + //or else, occasionally, m_seqParam will be modified by vaCreateBuffer() when vaCreateBuffer() + //is called to create m_picParam; + if (picture->m_type != VAAPI_PICTURE_I) { + return true; + } +#endif + if (!picture->editSequence(m_seqParam) || !fill(m_seqParam)) { + ERROR("failed to create sequence parameter buffer (SPS)"); + return false; + } + + if (!ensureSequenceHeader(picture, m_seqParam)) { + ERROR ("failed to create packed sequence header buffer"); + return false; + } + + return true; +} + +bool VaapiEncoderHEVC::ensurePicture (const PicturePtr& picture, const SurfacePtr& surface) +{ + if (!pictureReferenceListSet(picture)) { + ERROR ("reference list reorder failed"); + return false; + } + + if (!picture->editPicture(m_picParam) || !fill(m_picParam, picture, surface)) { + ERROR("failed to create picture parameter buffer (PPS)"); + return false; + } + + if (picture->isIdr() && !ensurePictureHeader (picture, m_picParam)) { + ERROR ("set picture packed header failed"); + return false; + } + + return true; +} + +bool VaapiEncoderHEVC::ensureSlices(const PicturePtr& picture) +{ + assert (picture); + + if (!addSliceHeaders (picture)) + return false; + return true; +} + +YamiStatus VaapiEncoderHEVC::encodePicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_FAIL; + + SurfacePtr reconstruct = createSurface(); + if (!reconstruct) + return ret; + { + AutoLock locker(m_paramLock); + + if (!ensureSequence (picture)) + return ret; + if (!ensureMiscParams (picture.get())) + return ret; + if (!ensurePicture(picture, reconstruct)) + return ret; + if (!ensureSlices (picture)) + return ret; + } + if (!picture->encode()) + return ret; + + if (!referenceListUpdate (picture, reconstruct)) + return ret; + + return YAMI_SUCCESS; +} + +} diff --git a/encoder/vaapiencoder_hevc.h b/encoder/vaapiencoder_hevc.h new file mode 100755 index 0000000..df3cf21 --- /dev/null +++ b/encoder/vaapiencoder_hevc.h @@ -0,0 +1,174 @@ + +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_hevc_h +#define vaapiencoder_hevc_h + +#include "vaapiencoder_base.h" +#include "vaapi/vaapiptrs.h" +#include "common/lock.h" +#include +#include +#include +#include +#include + +namespace YamiMediaCodec{ +class VaapiEncPictureHEVC; +class VaapiEncoderHEVCRef; +class VaapiEncStreamHeaderHEVC; + +typedef struct shortRFS +{ + unsigned char num_negative_pics; + unsigned char num_positive_pics; + unsigned char delta_poc_s0_minus1[8]; + unsigned char used_by_curr_pic_s0_flag[8]; + unsigned char delta_poc_s1_minus1[8]; + unsigned char used_by_curr_pic_s1_flag[8]; + unsigned char num_short_term_ref_pic_sets; + unsigned char short_term_ref_pic_set_idx; + unsigned int inter_ref_pic_set_prediction_flag; +}ShortRFS; + +class VaapiEncoderHEVC : public VaapiEncoderBase { + friend class VaapiEncStreamHeaderHEVC; +public: + //shortcuts, It's intended to elimilate codec diffrence + //to make template for other codec implelmentation. + typedef SharedPtr PicturePtr; + typedef SharedPtr ReferencePtr; + typedef SharedPtr StreamHeaderPtr; + + VaapiEncoderHEVC(); + ~VaapiEncoderHEVC(); + virtual YamiStatus start(); + virtual void flush(); + virtual YamiStatus stop(); + + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); +#ifdef __BUILD_GET_MV__ + // get MV buffer size. + virtual YamiStatus getMVBufferSize(uint32_t* Size); +#endif + +protected: + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, bool forceKeyFrame); + virtual YamiStatus getCodecConfig(VideoEncOutputBuffer* outBuffer); + +private: + friend class FactoryTest; + friend class VaapiEncoderHEVCTest; + + //following code is a template for other encoder implementation + YamiStatus encodePicture(const PicturePtr&); + bool fill(VAEncSequenceParameterBufferHEVC*) const; + bool fill(VAEncPictureParameterBufferHEVC*, const PicturePtr&, const SurfacePtr&) const ; + bool fillReferenceList(VAEncSliceParameterBufferHEVC* slice) const; + bool ensureSequenceHeader(const PicturePtr&, const VAEncSequenceParameterBufferHEVC* const); + bool ensurePictureHeader(const PicturePtr&, const VAEncPictureParameterBufferHEVC* const ); + bool addSliceHeaders (const PicturePtr&) const; + bool addPackedSliceHeader (const PicturePtr&, + const VAEncSliceParameterBufferHEVC* const sliceParam, + uint32_t sliceIndex) const; + bool ensureSequence(const PicturePtr&); + bool ensurePicture (const PicturePtr&, const SurfacePtr&); + bool ensureSlices(const PicturePtr&); + bool ensureCodedBufferSize(); + + //reference list related + YamiStatus reorder(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame); + bool referenceListUpdate (const PicturePtr&, const SurfacePtr&); + bool pictureReferenceListSet (const PicturePtr&); + + void referenceListFree(); + //template end + + void resetGopStart(); + void setBFrame(const PicturePtr&); + void setPFrame(const PicturePtr&); + void setIFrame(const PicturePtr&); + void setIdrFrame(const PicturePtr&); + void setIntraFrame(const PicturePtr&, bool idIdr); + void resetParams(); + void setShortRfs(); + void shortRfsUpdate(const PicturePtr&); + + void changeLastBFrameToPFrame(); + YamiStatus encodeAllFrames(); + + VideoParamsAVC m_videoParamAVC; + + uint8_t m_profileIdc; + uint8_t m_levelIdc; + uint32_t m_numSlices; + uint32_t m_numBFrames; + uint32_t m_ctbSize; + uint32_t m_cuSize; + uint32_t m_minTbSize; + uint32_t m_maxTbSize; + + uint32_t m_AlignedWidth; + uint32_t m_AlignedHeight; + uint32_t m_cuWidth; + uint32_t m_cuHeight; + + /* re-ordering */ + std::list m_reorderFrameList; + VaapiEncReorderState m_reorderState; + uint32_t m_frameIndex; + uint32_t m_keyPeriod; + + /* reference list */ + std::deque m_refList; + std::deque m_refList0; + std::deque m_refList1; + + uint32_t m_maxRefFrames; + /* max reflist count */ + uint32_t m_maxRefList0Count; + uint32_t m_maxRefList1Count; + + /* frame, poc */ + uint32_t m_maxFrameNum; + uint32_t m_log2MaxFrameNum; + uint32_t m_maxPicOrderCnt; + uint32_t m_log2MaxPicOrderCnt; + + bool m_confWinFlag; + uint32_t m_confWinLeftOffset; + uint32_t m_confWinRightOffset; + uint32_t m_confWinTopOffset; + uint32_t m_confWinBottomOffset; + + VAEncSequenceParameterBufferHEVC* m_seqParam; + VAEncPictureParameterBufferHEVC* m_picParam; + + ShortRFS m_shortRFS; + StreamHeaderPtr m_headers; + Lock m_paramLock; // locker for parameters update, for example: m_sps/m_pps/m_maxCodedbufSize (width/height etc) + + /** + * VaapiEncoderFactory registration result. This encoder is registered in + * vaapiencoder_host.cpp + */ + static const bool s_registered; +}; +} +#endif /* vaapiencoder_hevc_h */ diff --git a/encoder/vaapiencoder_hevc_unittest.cpp b/encoder/vaapiencoder_hevc_unittest.cpp new file mode 100644 index 0000000..515e9a8 --- /dev/null +++ b/encoder/vaapiencoder_hevc_unittest.cpp @@ -0,0 +1,64 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiencoder_hevc.h" + +namespace YamiMediaCodec { + +class VaapiEncoderHEVCTest + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIENCODER_HEVC_TEST(name) \ + TEST_F(VaapiEncoderHEVCTest, name) + +VAAPIENCODER_HEVC_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_HEVC); + mimeTypes.push_back(YAMI_MIME_H265); + doFactoryTest(mimeTypes); +} + +} diff --git a/encoder/vaapiencoder_host.cpp b/encoder/vaapiencoder_host.cpp new file mode 100644 index 0000000..fa052c0 --- /dev/null +++ b/encoder/vaapiencoder_host.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "VideoEncoderHost.h" +#include "vaapiencoder_factory.h" + +using namespace YamiMediaCodec; + +#if __BUILD_H264_ENCODER__ +#include "vaapiencoder_h264.h" +const bool VaapiEncoderH264::s_registered = + VaapiEncoderFactory::register_(YAMI_MIME_AVC) + && VaapiEncoderFactory::register_(YAMI_MIME_H264); +#endif + +#if __BUILD_H265_ENCODER__ +#include "vaapiencoder_hevc.h" +const bool VaapiEncoderHEVC::s_registered = + VaapiEncoderFactory::register_(YAMI_MIME_HEVC) + && VaapiEncoderFactory::register_(YAMI_MIME_H265); +#endif + +#if __BUILD_JPEG_ENCODER__ +#include "vaapiencoder_jpeg.h" +const bool VaapiEncoderJpeg::s_registered = + VaapiEncoderFactory::register_(YAMI_MIME_JPEG); +#endif + +#if __BUILD_VP8_ENCODER__ +#include "vaapiencoder_vp8.h" +const bool VaapiEncoderVP8::s_registered = + VaapiEncoderFactory::register_(YAMI_MIME_VP8); +#endif + +#if __BUILD_VP9_ENCODER__ +#include "vaapiencoder_vp9.h" +const bool VaapiEncoderVP9::s_registered + = VaapiEncoderFactory::register_(YAMI_MIME_VP9); +#endif + +IVideoEncoder* createVideoEncoder(const char* mimeType) { + if (!mimeType) { + ERROR("NULL mime type."); + return NULL; + } + + VaapiEncoderFactory::Type enc = VaapiEncoderFactory::create(mimeType); + + if (!enc) + ERROR("Failed to create encoder for mimeType: '%s'", mimeType); + else + INFO("Created encoder for mimeType: '%s'", mimeType); + + return enc; +} + +void releaseVideoEncoder(IVideoEncoder* p) { + delete p; +} + +std::vector getVideoEncoderMimeTypes() +{ + return VaapiEncoderFactory::keys(); +} diff --git a/encoder/vaapiencoder_host_unittest.cpp b/encoder/vaapiencoder_host_unittest.cpp new file mode 100644 index 0000000..5737f08 --- /dev/null +++ b/encoder/vaapiencoder_host_unittest.cpp @@ -0,0 +1,108 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/unittest.h" + +// primary header +#include "VideoEncoderHost.h" + +// system headers +#include +#include +#include + +namespace YamiMediaCodec { + +std::set& expectations() +{ + static std::set e; + +#if __BUILD_H264_ENCODER__ + e.insert(YAMI_MIME_H264); + e.insert(YAMI_MIME_AVC); +#endif + +#if __BUILD_H265_ENCODER__ + e.insert(YAMI_MIME_H265); + e.insert(YAMI_MIME_HEVC); +#endif + +#if __BUILD_VP8_ENCODER__ + e.insert(YAMI_MIME_VP8); +#endif + +#if __BUILD_VP9_ENCODER__ + e.insert(YAMI_MIME_VP9); +#endif + +#if __BUILD_JPEG_ENCODER__ + e.insert(YAMI_MIME_JPEG); +#endif + + return e; +} + +class VaapiEncoderHostTest + : public ::testing::TestWithParam +{ }; + +TEST_P(VaapiEncoderHostTest, createVideoEncoder) +{ + std::string mime = GetParam(); + IVideoEncoder *encoder = createVideoEncoder(mime.c_str()); + bool expect = expectations().count(mime) != 0; + + EXPECT_EQ(expect, (encoder != NULL)) + << "createVideoEncoder(" << mime << "): " + << "did not " << (expect ? "SUCCEED" : "FAIL") + << " as it should have."; + + releaseVideoEncoder(encoder); +} + +TEST_P(VaapiEncoderHostTest, getVideoEncoderMimeTypesContains) +{ + std::string mime = GetParam(); + std::vector avail = getVideoEncoderMimeTypes(); + + bool expect = expectations().count(mime) != 0; + bool actual = std::find(avail.begin(), avail.end(), mime) != avail.end(); + + EXPECT_EQ( expect, actual ); +} + +INSTANTIATE_TEST_CASE_P( + MimeType, VaapiEncoderHostTest, + ::testing::Values( + YAMI_MIME_H264, YAMI_MIME_AVC, YAMI_MIME_H265, YAMI_MIME_HEVC, + YAMI_MIME_MPEG2, YAMI_MIME_VC1, YAMI_MIME_VP8, YAMI_MIME_VP9, + YAMI_MIME_JPEG)); +} diff --git a/encoder/vaapiencoder_jpeg.cpp b/encoder/vaapiencoder_jpeg.cpp new file mode 100644 index 0000000..d1c1e29 --- /dev/null +++ b/encoder/vaapiencoder_jpeg.cpp @@ -0,0 +1,547 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_jpeg.h" +#include "codecparsers/jpegParser.h" +#include "common/Array.h" +#include "common/common_def.h" +#include "common/scopedlogger.h" +#include "vaapicodedbuffer.h" +#include "vaapiencpicture.h" +#include "common/log.h" +#include + +#define NUM_DC_RUN_SIZE_BITS 16 +#define NUM_AC_RUN_SIZE_BITS 16 +#define NUM_AC_CODE_WORDS_HUFFVAL 162 +#define NUM_DC_CODE_WORDS_HUFFVAL 12 + +using ::YamiParser::JPEG::FrameHeader; +using ::YamiParser::JPEG::ScanHeader; +using ::YamiParser::JPEG::QuantTable; +using ::YamiParser::JPEG::QuantTables; +using ::YamiParser::JPEG::HuffTable; +using ::YamiParser::JPEG::HuffTables; +using ::YamiParser::JPEG::Component; +using ::YamiParser::JPEG::Defaults; + +void generateFrameHdr(const FrameHeader::Shared& frameHdr, int picWidth, int picHeight) +{ + frameHdr->dataPrecision = 8; + frameHdr->imageWidth = picWidth; + frameHdr->imageHeight = picHeight; + + frameHdr->components.resize(3); + + for(int i = 0; i < 3; i++) { + frameHdr->components[i].reset(new Component); + + frameHdr->components[i]->id = i + 1; + frameHdr->components[i]->index = i; + + if(i == 0) { + frameHdr->components[i]->hSampleFactor = 2; + frameHdr->components[i]->vSampleFactor = 2; + frameHdr->components[i]->quantTableNumber = 0; + + } else { + //Analyzing the sampling factors for U/V, they are 1 for all formats except for Y8. + //So, it is okay to have the code below like this. For Y8, we wont reach this code. + frameHdr->components[i]->hSampleFactor = 1; + frameHdr->components[i]->vSampleFactor = 1; + frameHdr->components[i]->quantTableNumber = 1; + } + } +} + +void generateScanHdr(const ScanHeader::Shared& scanHdr) +{ + scanHdr->numComponents = 3; + + //Y Component + scanHdr->components[0].reset(new Component); + scanHdr->components[0]->id = 1; + scanHdr->components[0]->dcTableNumber = 0; + scanHdr->components[0]->acTableNumber = 0; + + //U Component + scanHdr->components[1].reset(new Component); + scanHdr->components[1]->id = 2; + scanHdr->components[1]->dcTableNumber = 1; + scanHdr->components[1]->acTableNumber = 1; + + //V Component + scanHdr->components[2].reset(new Component); + scanHdr->components[2]->id = 3; + scanHdr->components[2]->dcTableNumber = 1; + scanHdr->components[2]->acTableNumber = 1; +} + +static const size_t JPEG_HEADER_SIZE = 83 + (YamiParser::JPEG::DCTSIZE2 * 2) + + (NUM_DC_RUN_SIZE_BITS * 2) + (NUM_DC_CODE_WORDS_HUFFVAL * 2) + + (NUM_AC_RUN_SIZE_BITS * 2) + (NUM_AC_CODE_WORDS_HUFFVAL * 2); + +typedef std::array JPEGHeader; + +int buildJpegHeader(JPEGHeader& header, int picture_width, int picture_height, unsigned quality) +{ + using namespace ::YamiParser::JPEG; + + size_t idx(0); + + // Start Of Input + header[idx] = 0xFF; + header[++idx] = M_SOI; + + // Application Segment - JFIF standard 1.01 + header[++idx] = 0xFF; + header[++idx] = M_APP0; + header[++idx] = 0x00; + header[++idx] = 0x10; // Segment length:16 (2-byte) + header[++idx] = 0x4A; // J + header[++idx] = 0x46; // F + header[++idx] = 0x49; // I + header[++idx] = 0x46; // F + header[++idx] = 0x00; // 0 + header[++idx] = 0x01; // Major version + header[++idx] = 0x01; // Minor version + header[++idx] = 0x01; // Density units 0:no units, 1:pixels per inch, 2: pixels per cm + header[++idx] = 0x00; + header[++idx] = 0x48; // X density (2-byte) + header[++idx] = 0x00; + header[++idx] = 0x48; // Y density (2-byte) + header[++idx] = 0x00; // Thumbnail width + header[++idx] = 0x00; // Thumbnail height + + // Quantization Tables. + // + // Application is responsible for scaling and normalizing the quantization + // tables in the packed header. + + // Normalize quality factor + quality = (quality < 50) ? (5000/quality) : (200 - (quality * 2)); + + const QuantTables& quantTables = Defaults::instance().quantTables(); + for (size_t i(0); i < 2; ++i) { + const QuantTable::Shared& quantTable = quantTables[i]; + header[++idx] = 0xFF; + header[++idx] = M_DQT; + header[++idx] = 0x00; + header[++idx] = 0x03 + DCTSIZE2; // Segment length:67 (2-byte) + + // Only 8-bit (1 byte) precision is supported + // 0:8-bit precision, 1:16-bit precision + assert(quantTable->precision == 0); + + // Precision (4-bit high) = 0, Index (4-bit low) = i + header[++idx] = static_cast(i); + + for (size_t j(0); j < DCTSIZE2; ++j) { + unsigned scaled = (quantTable->values[j] * quality) / 100; + scaled = std::min(255u, std::max(1u, scaled)); + header[++idx] = static_cast(scaled); + } + } + + // Start of Frame - Baseline + FrameHeader::Shared frameHdr(new FrameHeader); + generateFrameHdr(frameHdr, picture_width, picture_height); + header[++idx] = 0xFF; + header[++idx] = M_SOF0; // Baseline + header[++idx] = 0x00; + header[++idx] = 0x11; // Segment length:17 (2-byte) + header[++idx] = static_cast(frameHdr->dataPrecision); + header[++idx] = static_cast((frameHdr->imageHeight >> 8) & 0xFF); + header[++idx] = static_cast(frameHdr->imageHeight & 0xFF); + header[++idx] = static_cast((frameHdr->imageWidth >> 8) & 0xFF); + header[++idx] = static_cast(frameHdr->imageWidth & 0xFF); + header[++idx] = 0x03; // Number of Components + for (size_t i(0); i < 3; ++i) { + const Component::Shared& component = frameHdr->components[i]; + header[++idx] = static_cast(component->id); + // Horizontal Sample Factor (4-bit high), Vertical Sample Factor (4-bit low) + header[++idx] = static_cast(component->hSampleFactor << 4) + | static_cast(component->vSampleFactor); + header[++idx] = static_cast(component->quantTableNumber); + } + + // Huffman Tables + const HuffTables& dcTables = Defaults::instance().dcHuffTables(); + const HuffTables& acTables = Defaults::instance().acHuffTables(); + for(size_t i(0); i < 2; ++i) { + // DC Table + const HuffTable::Shared& dcTable = dcTables[i]; + header[++idx] = 0xFF; + header[++idx] = M_DHT; + header[++idx] = 0x00; + header[++idx] = 0x1F; // Segment length:31 (2-byte) + + // Type (4-bit high) = 0:DC, Index (4-bit low) + header[++idx] = static_cast(i); + + for(size_t j(0); j < NUM_DC_RUN_SIZE_BITS; ++j) + header[++idx] = dcTable->codes[j]; + for(size_t j(0); j < NUM_DC_CODE_WORDS_HUFFVAL; ++j) + header[++idx] = dcTable->values[j]; + + // AC Table + const HuffTable::Shared& acTable = acTables[i]; + header[++idx] = 0xFF; + header[++idx] = M_DHT; + header[++idx] = 0x00; + header[++idx] = 0xB5; // Segment length:181 (2-byte) + + // Type (4-bit high) = 1:AC, Index (4-bit low) + header[++idx] = 0x10 | static_cast(i); + + for(size_t j(0); j < NUM_AC_RUN_SIZE_BITS; ++j) + header[++idx] = acTable->codes[j]; + for(size_t j(0); j < NUM_AC_CODE_WORDS_HUFFVAL; ++j) + header[++idx] = acTable->values[j]; + } + + // Start of Scan + ScanHeader::Shared scanHdr(new ScanHeader); + generateScanHdr(scanHdr); + header[++idx] = 0xFF; + header[++idx] = M_SOS; + header[++idx] = 0x00; + header[++idx] = 0x0C; // Segment Length:12 (2-byte) + header[++idx] = 0x03; // Number of components in scan + for (size_t i(0); i < 3; ++i) { + header[++idx] = static_cast(scanHdr->components[i]->id); + // DC Table Selector (4-bit high), AC Table Selector (4-bit low) + header[++idx] = static_cast(scanHdr->components[i]->dcTableNumber << 4) + | static_cast(scanHdr->components[i]->acTableNumber); + } + header[++idx] = 0x00; // 0 for Baseline + header[++idx] = 0x3F; // 63 for Baseline + header[++idx] = 0x00; // 0 for Baseline + + return ++idx << 3; +} + +namespace YamiMediaCodec { + +typedef VaapiEncoderJpeg::PicturePtr PicturePtr; + +class VaapiEncPictureJPEG:public VaapiEncPicture +{ +public: + VaapiEncPictureJPEG(const ContextPtr& context, const SurfacePtr& surface, int64_t timeStamp): + VaapiEncPicture(context, surface, timeStamp) + { + } + VAEncPictureParameterBufferJPEG picParam; + VAQMatrixBufferJPEG qMatrix; + VAEncSliceParameterBufferJPEG sliceParam; + VAHuffmanTableBufferJPEGBaseline huffTableParam; +}; + +VaapiEncoderJpeg::VaapiEncoderJpeg() +{ + m_videoParamCommon.profile = VAProfileJPEGBaseline; + m_entrypoint = VAEntrypointEncPicture; + m_videoParamQualityLevel.level = 50; +} + +YamiStatus VaapiEncoderJpeg::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + *maxSize = m_maxCodedbufSize; + return YAMI_SUCCESS; +} + +void VaapiEncoderJpeg::resetParams() +{ + m_maxCodedbufSize = (width()*height()*3/2) + JPEG_HEADER_SIZE; +} + +YamiStatus VaapiEncoderJpeg::start() +{ + FUNC_ENTER(); + resetParams(); + return VaapiEncoderBase::start(); +} + +void VaapiEncoderJpeg::flush() +{ + FUNC_ENTER(); + VaapiEncoderBase::flush(); +} + +YamiStatus VaapiEncoderJpeg::stop() +{ + flush(); + return VaapiEncoderBase::stop(); +} + +YamiStatus VaapiEncoderJpeg::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_SUCCESS; + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + + switch (type) { + + // override base class quality settings since it tries to map to a range + // that does not correspond to valid JPEG quality range. + case VideoParamsTypeQualityLevel: { + VideoParamsQualityLevel* videoQualityLevel = (VideoParamsQualityLevel*)videoEncParams; + if (videoQualityLevel->size == sizeof(VideoParamsQualityLevel)) { + if (videoQualityLevel->level != m_videoParamQualityLevel.level) { + PARAMETER_ASSIGN(m_videoParamQualityLevel, *videoQualityLevel); + m_videoParamQualityLevel.level = + std::min(100u, std::max(1u, m_videoParamQualityLevel.level)); + } + } else { + status = YAMI_INVALID_PARAM; + } + } + break; + default: + status = VaapiEncoderBase::setParameters(type, videoEncParams); + break; + } + return status; +} + +YamiStatus VaapiEncoderJpeg::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + + return VaapiEncoderBase::getParameters(type, videoEncParams); +} + +YamiStatus VaapiEncoderJpeg::doEncode(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + FUNC_ENTER(); + YamiStatus ret; + CodedBufferPtr codedBuffer = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize); + PicturePtr picture(new VaapiEncPictureJPEG(m_context, surface, timeStamp)); + picture->m_codedBuffer = codedBuffer; + ret = encodePicture(picture); + if (ret != YAMI_SUCCESS) + return ret; + INFO(); + if (!output(picture)) + return YAMI_INVALID_PARAM; + return YAMI_SUCCESS; +} + +bool VaapiEncoderJpeg::fill(VAEncPictureParameterBufferJPEG * picParam, const PicturePtr &picture, + const SurfacePtr &surface) const +{ + picParam->reconstructed_picture = surface->getID(); + picParam->picture_height = height(); + picParam->picture_width = width(); + picParam->coded_buf = picture->m_codedBuffer->getID(); + //Profile = Baseline + picParam->pic_flags.bits.profile = 0; + //Sequential encoding + picParam->pic_flags.bits.progressive = 0; + //Uses Huffman coding + picParam->pic_flags.bits.huffman = 1; + //Input format is interleaved (YUV) + picParam->pic_flags.bits.interleaved = 0; + //non-Differential Encoding + picParam->pic_flags.bits.differential = 0; + //only 8 bit sample depth is currently supported + picParam->sample_bit_depth = 8; + picParam->num_scan = 1; + // Supporting only upto 3 components maximum + picParam->num_components = 3; + picParam->quality = m_videoParamQualityLevel.level; + + DEBUG("picture encode quality = %d", picParam->quality); + + return TRUE; +} + +bool VaapiEncoderJpeg::fill(VAQMatrixBufferJPEG * qMatrix) const +{ + // Fill the raw, unscaled quant tables for VAAPI. The VAAPI driver is + // responsible for scaling the quantization tables based on picture + // parameter quality. + const QuantTable::Shared luminance = Defaults::instance().quantTables()[0]; + qMatrix->load_lum_quantiser_matrix = 1; + for (size_t i = 0; i < ::YamiParser::JPEG::DCTSIZE2; i++) { + qMatrix->lum_quantiser_matrix[i] = luminance->values[i]; + } + + const QuantTable::Shared chrominance = Defaults::instance().quantTables()[1]; + qMatrix->load_chroma_quantiser_matrix = 1; + for (size_t i = 0; i < ::YamiParser::JPEG::DCTSIZE2; i++) { + qMatrix->chroma_quantiser_matrix[i] = chrominance->values[i]; + } + + return true; +} + +bool VaapiEncoderJpeg::fill(VAEncSliceParameterBufferJPEG *sliceParam) const +{ + sliceParam->restart_interval = 0; + + sliceParam->num_components = 3; + + sliceParam->components[0].component_selector = 1; + sliceParam->components[0].dc_table_selector = 0; + sliceParam->components[0].ac_table_selector = 0; + + sliceParam->components[1].component_selector = 2; + sliceParam->components[1].dc_table_selector = 1; + sliceParam->components[1].ac_table_selector = 1; + + sliceParam->components[2].component_selector = 3; + sliceParam->components[2].dc_table_selector = 1; + sliceParam->components[2].ac_table_selector = 1; + return true; +} + +bool VaapiEncoderJpeg::fill(VAHuffmanTableBufferJPEGBaseline *huffTableParam) const +{ + const HuffTables& dcHuffTables = Defaults::instance().dcHuffTables(); + const HuffTables& acHuffTables = Defaults::instance().acHuffTables(); + + const size_t numTables = MIN(N_ELEMENTS(huffTableParam->huffman_table), + ::YamiParser::JPEG::NUM_HUFF_TBLS); + + for (size_t i(0); i < numTables; ++i) { + const HuffTable::Shared& dcTable = dcHuffTables[i]; + const HuffTable::Shared& acTable = acHuffTables[i]; + bool valid = bool(dcTable) && bool(acTable); + huffTableParam->load_huffman_table[i] = valid; + if (!valid) + continue; + + // Load DC Table + memcpy(huffTableParam->huffman_table[i].num_dc_codes, + &dcTable->codes[0], + sizeof(huffTableParam->huffman_table[i].num_dc_codes)); + memcpy(huffTableParam->huffman_table[i].dc_values, + &dcTable->values[0], + sizeof(huffTableParam->huffman_table[i].dc_values)); + + // Load AC Table + memcpy(huffTableParam->huffman_table[i].num_ac_codes, + &acTable->codes[0], + sizeof(huffTableParam->huffman_table[i].num_ac_codes)); + memcpy(huffTableParam->huffman_table[i].ac_values, + &acTable->values[0], + sizeof(huffTableParam->huffman_table[i].ac_values)); + + memset(huffTableParam->huffman_table[i].pad, + 0, sizeof(huffTableParam->huffman_table[i].pad)); + } + + return true; +} + +bool VaapiEncoderJpeg::ensurePicture (const PicturePtr& picture, const SurfacePtr& surface) +{ + VAEncPictureParameterBufferJPEG *picParam; + + if(!picture->editPicture(picParam) || !fill(picParam, picture, surface)) { + ERROR("failed to create picture parameter buffer"); + return false; + } + memcpy(&picture->picParam, picParam, sizeof(*picParam)); + return true; +} + +bool VaapiEncoderJpeg::ensureQMatrix (const PicturePtr& picture) +{ + VAQMatrixBufferJPEG *qMatrix; + + if(!picture->editQMatrix(qMatrix) || !fill(qMatrix)) { + ERROR("failed to create qMatrix"); + return false; + } + memcpy(&picture->qMatrix, qMatrix, sizeof(*qMatrix)); + return true; +} + +bool VaapiEncoderJpeg::ensureSlice (const PicturePtr& picture) +{ + VAEncSliceParameterBufferJPEG *sliceParam; + + if(!picture->newSlice(sliceParam) || !fill(sliceParam)) { + ERROR("failed to create slice parameter"); + return false; + } + memcpy(&picture->sliceParam, sliceParam, sizeof(*sliceParam)); + return true; +} + +bool VaapiEncoderJpeg::ensureHuffTable(const PicturePtr & picture) +{ + VAHuffmanTableBufferJPEGBaseline *huffTableParam; + + if(!picture->editHuffTable(huffTableParam) || !fill(huffTableParam)) { + ERROR("failed to create Huffman Table"); + return false; + } + memcpy(&picture->huffTableParam, huffTableParam, sizeof(*huffTableParam)); + return true; +} + +bool VaapiEncoderJpeg::addSliceHeaders (const PicturePtr& picture) const +{ + unsigned int length_in_bits; + JPEGHeader header; + DEBUG("header encode quality = %d", m_videoParamQualityLevel.level); + length_in_bits = buildJpegHeader(header, width(), height(), m_videoParamQualityLevel.level); + + if(!picture->addPackedHeader(VAEncPackedHeaderRawData, header.data(), length_in_bits)) + return false; + return true; +} + +YamiStatus VaapiEncoderJpeg::encodePicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_FAIL; + SurfacePtr reconstruct = createSurface(); + if (!reconstruct) + return ret; + + if (!ensurePicture(picture, reconstruct)) + return ret; + + if (!ensureQMatrix (picture)) + return ret; + + if (!ensureHuffTable(picture)) + return ret; + + if (!ensureSlice (picture)) + return ret; + + if (!addSliceHeaders (picture)) + return ret; + + if (!picture->encode()) + return ret; + return YAMI_SUCCESS; +} + +} diff --git a/encoder/vaapiencoder_jpeg.h b/encoder/vaapiencoder_jpeg.h new file mode 100644 index 0000000..3c606a7 --- /dev/null +++ b/encoder/vaapiencoder_jpeg.h @@ -0,0 +1,70 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_jpeg_h +#define vaapiencoder_jpeg_h + +#include "vaapiencoder_base.h" +#include "vaapi/vaapiptrs.h" +#include + +namespace YamiMediaCodec { +class VaapiEncPictureJPEG; + +class VaapiEncoderJpeg : public VaapiEncoderBase { +public: + typedef SharedPtr PicturePtr; + + VaapiEncoderJpeg(); + virtual ~VaapiEncoderJpeg() { } + virtual YamiStatus start(); + virtual void flush(); + virtual YamiStatus stop(); + + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR videoEncParams); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR videoEncParams); + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); + +protected: + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, bool forceKeyFrame); + virtual bool isBusy() { return false;}; + +private: + friend class FactoryTest; + friend class VaapiEncoderJpegTest; + + YamiStatus encodePicture(const PicturePtr&); + bool addSliceHeaders (const PicturePtr&) const; + bool fill(VAEncPictureParameterBufferJPEG * picParam, const PicturePtr &, const SurfacePtr &) const; + bool fill(VAQMatrixBufferJPEG * qMatrix) const; + bool fill(VAEncSliceParameterBufferJPEG *sliceParam) const; + bool fill(VAHuffmanTableBufferJPEGBaseline *huffTableParam) const; + + bool ensurePicture (const PicturePtr&, const SurfacePtr&); + bool ensureQMatrix (const PicturePtr&); + bool ensureSlice (const PicturePtr&); + bool ensureHuffTable (const PicturePtr&); + + void resetParams(); + + /** + * VaapiEncoderFactory registration result. This encoder is registered in + * vaapiencoder_host.cpp + */ + static const bool s_registered; +}; +} +#endif diff --git a/encoder/vaapiencoder_jpeg_unittest.cpp b/encoder/vaapiencoder_jpeg_unittest.cpp new file mode 100644 index 0000000..47c6bbc --- /dev/null +++ b/encoder/vaapiencoder_jpeg_unittest.cpp @@ -0,0 +1,379 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiencoder_jpeg.h" + +// library headers +#include "common/Array.h" +#include "common/utils.h" + +// system headers +#include +#include + +const static std::array g_SimpleSmallI420 = { + 0x37, 0x38, 0x39, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x38, 0x38, + 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x39, 0x39, 0x3b, 0x3b, + 0x3c, 0x3e, 0x3e, 0x40, 0x41, 0x42, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x44, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x40, 0x42, 0x43, 0x44, 0x45, + 0x3c, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x47, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x46, 0x47, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x45, 0x45, 0x46, 0x48, 0x48, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, + 0x46, 0x47, 0x49, 0x49, 0xe9, 0xda, 0xcb, 0xbd, 0xaf, 0xda, 0xcb, 0xbd, + 0xaf, 0xa1, 0xcb, 0xbd, 0xaf, 0xa0, 0x92, 0xbd, 0xae, 0xa0, 0x92, 0x83, + 0xaf, 0xa0, 0x92, 0x83, 0x74, 0x63, 0x73, 0x83, 0x92, 0xa2, 0x73, 0x83, + 0x92, 0xa2, 0xb1, 0x82, 0x92, 0xa1, 0xb1, 0xc1, 0x92, 0xa1, 0xb0, 0xc0, + 0xcf, 0xa0, 0xb0, 0xc0, 0xcf, 0xde +}; + +const static std::array g_SimpleSmallNV12 = { + 0x37, 0x38, 0x39, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x38, 0x38, + 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x39, 0x39, 0x3b, 0x3b, + 0x3c, 0x3e, 0x3e, 0x40, 0x41, 0x42, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x44, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x40, 0x42, 0x43, 0x44, 0x45, + 0x3c, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x47, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x46, 0x47, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x45, 0x45, 0x46, 0x48, 0x48, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, + 0x46, 0x47, 0x49, 0x49, 0xe9, 0x63, 0xda, 0x73, 0xcb, 0x83, 0xbd, 0x92, + 0xaf, 0xa2, 0xda, 0x73, 0xcb, 0x83, 0xbd, 0x92, 0xaf, 0xa2, 0xa1, 0xb1, + 0xcb, 0x82, 0xbd, 0x92, 0xaf, 0xa1, 0xa0, 0xb1, 0x92, 0xc1, 0xbd, 0x92, + 0xae, 0xa1, 0xa0, 0xb0, 0x92, 0xc0, 0x83, 0xcf, 0xaf, 0xa0, 0xa0, 0xb0, + 0x92, 0xc0, 0x83, 0xcf, 0x74, 0xde +}; + +const static std::array g_SimpleSmallYV12 = { + 0x37, 0x38, 0x39, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x38, 0x38, + 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x39, 0x39, 0x3b, 0x3b, + 0x3c, 0x3e, 0x3e, 0x40, 0x41, 0x42, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x44, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x40, 0x42, 0x43, 0x44, 0x45, + 0x3c, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x47, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x46, 0x47, 0x3f, 0x40, 0x41, 0x42, + 0x43, 0x45, 0x45, 0x46, 0x48, 0x48, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, + 0x46, 0x47, 0x49, 0x49, 0x5f, 0x6f, 0x7f, 0x8e, 0x9d, 0x6f, 0x7f, 0x8e, + 0x9e, 0xad, 0x7e, 0x8e, 0x9d, 0xad, 0xbd, 0x8e, 0x9e, 0xac, 0xbc, 0xcb, + 0x9c, 0xac, 0xbc, 0xcb, 0xda, 0xec, 0xdd, 0xce, 0xc0, 0xb2, 0xde, 0xcf, + 0xc1, 0xb2, 0xa4, 0xcf, 0xc0, 0xb2, 0xa3, 0x95, 0xc1, 0xb2, 0xa3, 0x95, + 0x86, 0xb2, 0xa3, 0x95, 0x87, 0x77 +}; + +const static std::array g_SimpleSmallUYVY = { + 0xec, 0x37, 0x5f, 0x38, 0xdd, 0x39, 0x6f, 0x39, 0xce, 0x3b, 0x7f, 0x3c, + 0xc0, 0x3d, 0x8e, 0x3e, 0xb2, 0x3f, 0x9d, 0x40, 0xe5, 0x38, 0x67, 0x38, + 0xd6, 0x39, 0x77, 0x3b, 0xc7, 0x3c, 0x86, 0x3d, 0xb9, 0x3e, 0x96, 0x3f, + 0xab, 0x40, 0xa6, 0x41, 0xde, 0x39, 0x6f, 0x39, 0xcf, 0x3b, 0x7f, 0x3b, + 0xc1, 0x3c, 0x8e, 0x3e, 0xb2, 0x3e, 0x9e, 0x40, 0xa4, 0x41, 0xad, 0x42, + 0xd6, 0x3a, 0x76, 0x3b, 0xc7, 0x3c, 0x86, 0x3d, 0xb9, 0x3e, 0x95, 0x3f, + 0xab, 0x40, 0xa5, 0x41, 0x9d, 0x42, 0xb5, 0x43, 0xcf, 0x3b, 0x7e, 0x3c, + 0xc0, 0x3d, 0x8e, 0x3e, 0xb2, 0x3f, 0x9d, 0x40, 0xa3, 0x41, 0xad, 0x42, + 0x95, 0x43, 0xbd, 0x44, 0xc7, 0x3c, 0x86, 0x3d, 0xb9, 0x3e, 0x95, 0x3f, + 0xab, 0x40, 0xa4, 0x40, 0x9c, 0x42, 0xb5, 0x43, 0x8e, 0x44, 0xc4, 0x45, + 0xc1, 0x3c, 0x8e, 0x3e, 0xb2, 0x3f, 0x9e, 0x40, 0xa3, 0x41, 0xac, 0x42, + 0x95, 0x43, 0xbc, 0x44, 0x86, 0x46, 0xcb, 0x47, 0xb9, 0x3e, 0x95, 0x3f, + 0xaa, 0x40, 0xa4, 0x41, 0x9c, 0x42, 0xb4, 0x43, 0x8e, 0x44, 0xc4, 0x46, + 0x7f, 0x46, 0xd2, 0x47, 0xb2, 0x3f, 0x9c, 0x40, 0xa3, 0x41, 0xac, 0x42, + 0x95, 0x43, 0xbc, 0x45, 0x87, 0x45, 0xcb, 0x46, 0x77, 0x48, 0xda, 0x48, + 0xab, 0x40, 0xa4, 0x41, 0x9c, 0x42, 0xb4, 0x43, 0x8e, 0x44, 0xc4, 0x46, + 0x7f, 0x46, 0xd3, 0x47, 0x70, 0x49, 0xe2, 0x49 +}; + +const static std::array g_SimpleSmallYUY2 = { + 0x37, 0xec, 0x38, 0x5f, 0x39, 0xdd, 0x39, 0x6f, 0x3b, 0xce, 0x3c, 0x7f, + 0x3d, 0xc0, 0x3e, 0x8e, 0x3f, 0xb2, 0x40, 0x9d, 0x38, 0xe5, 0x38, 0x67, + 0x39, 0xd6, 0x3b, 0x77, 0x3c, 0xc7, 0x3d, 0x86, 0x3e, 0xb9, 0x3f, 0x96, + 0x40, 0xab, 0x41, 0xa6, 0x39, 0xde, 0x39, 0x6f, 0x3b, 0xcf, 0x3b, 0x7f, + 0x3c, 0xc1, 0x3e, 0x8e, 0x3e, 0xb2, 0x40, 0x9e, 0x41, 0xa4, 0x42, 0xad, + 0x3a, 0xd6, 0x3b, 0x76, 0x3c, 0xc7, 0x3d, 0x86, 0x3e, 0xb9, 0x3f, 0x95, + 0x40, 0xab, 0x41, 0xa5, 0x42, 0x9d, 0x43, 0xb5, 0x3b, 0xcf, 0x3c, 0x7e, + 0x3d, 0xc0, 0x3e, 0x8e, 0x3f, 0xb2, 0x40, 0x9d, 0x41, 0xa3, 0x42, 0xad, + 0x43, 0x95, 0x44, 0xbd, 0x3c, 0xc7, 0x3d, 0x86, 0x3e, 0xb9, 0x3f, 0x95, + 0x40, 0xab, 0x40, 0xa4, 0x42, 0x9c, 0x43, 0xb5, 0x44, 0x8e, 0x45, 0xc4, + 0x3c, 0xc1, 0x3e, 0x8e, 0x3f, 0xb2, 0x40, 0x9e, 0x41, 0xa3, 0x42, 0xac, + 0x43, 0x95, 0x44, 0xbc, 0x46, 0x86, 0x47, 0xcb, 0x3e, 0xb9, 0x3f, 0x95, + 0x40, 0xaa, 0x41, 0xa4, 0x42, 0x9c, 0x43, 0xb4, 0x44, 0x8e, 0x46, 0xc4, + 0x46, 0x7f, 0x47, 0xd2, 0x3f, 0xb2, 0x40, 0x9c, 0x41, 0xa3, 0x42, 0xac, + 0x43, 0x95, 0x45, 0xbc, 0x45, 0x87, 0x46, 0xcb, 0x48, 0x77, 0x48, 0xda, + 0x40, 0xab, 0x41, 0xa4, 0x42, 0x9c, 0x43, 0xb4, 0x44, 0x8e, 0x46, 0xc4, + 0x46, 0x7f, 0x47, 0xd3, 0x49, 0x70, 0x49, 0xe2 +}; + +const static std::array g_SimpleSmallBGRX = { + 0xff, 0x1b, 0x00, 0xff, 0xf2, 0x19, 0x0d, 0xff, 0xe5, 0x17, 0x1a, 0xff, + 0xd5, 0x13, 0x27, 0xff, 0xc9, 0x12, 0x36, 0xff, 0xbc, 0x10, 0x43, 0xff, + 0xaf, 0x0d, 0x51, 0xff, 0xa2, 0x0b, 0x5f, 0xff, 0x95, 0x08, 0x6c, 0xff, + 0x96, 0x09, 0x6e, 0xff, 0xf2, 0x19, 0x0d, 0xff, 0xe4, 0x15, 0x19, 0xff, + 0xd5, 0x13, 0x27, 0xff, 0xc9, 0x13, 0x35, 0xff, 0xbc, 0x10, 0x43, 0xff, + 0xaf, 0x0d, 0x51, 0xff, 0xa2, 0x0b, 0x5f, 0xff, 0x95, 0x09, 0x6b, 0xff, + 0x88, 0x06, 0x79, 0xff, 0x89, 0x08, 0x7a, 0xff, 0xe5, 0x17, 0x1a, 0xff, + 0xd5, 0x13, 0x27, 0xff, 0xc9, 0x12, 0x36, 0xff, 0xbb, 0x0f, 0x42, 0xff, + 0xae, 0x0c, 0x4f, 0xff, 0xa2, 0x0b, 0x5f, 0xff, 0x94, 0x07, 0x6b, 0xff, + 0x88, 0x06, 0x79, 0xff, 0x7b, 0x04, 0x87, 0xff, 0x7c, 0x05, 0x88, 0xff, + 0xd6, 0x15, 0x27, 0xff, 0xc9, 0x13, 0x35, 0xff, 0xbc, 0x10, 0x43, 0xff, + 0xaf, 0x0d, 0x51, 0xff, 0xa2, 0x0c, 0x5d, 0xff, 0x93, 0x09, 0x6b, 0xff, + 0x86, 0x07, 0x79, 0xff, 0x79, 0x04, 0x87, 0xff, 0x6c, 0x02, 0x95, 0xff, + 0x6d, 0x03, 0x96, 0xff, 0xc9, 0x13, 0x35, 0xff, 0xbc, 0x10, 0x43, 0xff, + 0xaf, 0x0d, 0x51, 0xff, 0xa2, 0x0c, 0x5d, 0xff, 0x95, 0x09, 0x6b, 0xff, + 0x86, 0x07, 0x79, 0xff, 0x79, 0x04, 0x87, 0xff, 0x6c, 0x02, 0x95, 0xff, + 0x5f, 0x00, 0xa3, 0xff, 0x60, 0x00, 0xa4, 0xff, 0xbc, 0x10, 0x43, 0xff, + 0xad, 0x0f, 0x4f, 0xff, 0xa0, 0x0c, 0x5d, 0xff, 0x93, 0x09, 0x6b, 0xff, + 0x86, 0x08, 0x77, 0xff, 0x78, 0x04, 0x84, 0xff, 0x6c, 0x02, 0x93, 0xff, + 0x5d, 0x00, 0xa1, 0xff, 0x50, 0x00, 0xaf, 0xff, 0x51, 0x00, 0xb0, 0xff, + 0xae, 0x0c, 0x4f, 0xff, 0xa0, 0x0c, 0x5d, 0xff, 0x93, 0x09, 0x6b, 0xff, + 0x86, 0x08, 0x77, 0xff, 0x79, 0x05, 0x85, 0xff, 0x6c, 0x02, 0x93, 0xff, + 0x5f, 0x00, 0xa1, 0xff, 0x50, 0x00, 0xad, 0xff, 0x44, 0x00, 0xbc, 0xff, + 0x46, 0x00, 0xbe, 0xff, 0xa2, 0x0c, 0x5d, 0xff, 0x93, 0x0a, 0x69, 0xff, + 0x86, 0x08, 0x77, 0xff, 0x79, 0x05, 0x85, 0xff, 0x6c, 0x02, 0x93, 0xff, + 0x5d, 0x01, 0x9f, 0xff, 0x50, 0x00, 0xad, 0xff, 0x44, 0x00, 0xbc, 0xff, + 0x34, 0x00, 0xc8, 0xff, 0x35, 0x00, 0xc9, 0xff, 0x95, 0x0a, 0x69, 0xff, + 0x86, 0x08, 0x77, 0xff, 0x79, 0x05, 0x85, 0xff, 0x6c, 0x02, 0x93, 0xff, + 0x5f, 0x00, 0xa1, 0xff, 0x51, 0x00, 0xaf, 0xff, 0x43, 0x00, 0xbb, 0xff, + 0x34, 0x00, 0xc8, 0xff, 0x28, 0x00, 0xd7, 0xff, 0x28, 0x00, 0xd7, 0xff, + 0x96, 0x0b, 0x6a, 0xff, 0x87, 0x09, 0x78, 0xff, 0x7a, 0x06, 0x86, 0xff, + 0x6d, 0x04, 0x94, 0xff, 0x60, 0x01, 0xa2, 0xff, 0x53, 0x01, 0xb0, 0xff, + 0x44, 0x00, 0xbc, 0xff, 0x35, 0x00, 0xc9, 0xff, 0x2a, 0x00, 0xd8, 0xff, + 0x2a, 0x00, 0xd8, 0xff +}; + +const static std::array g_SimpleSmallRGBX = { + 0x00, 0x1b, 0xff, 0xff, 0x0d, 0x19, 0xf2, 0xff, 0x1a, 0x17, 0xe5, 0xff, + 0x27, 0x13, 0xd5, 0xff, 0x36, 0x12, 0xc9, 0xff, 0x43, 0x10, 0xbc, 0xff, + 0x51, 0x0d, 0xaf, 0xff, 0x5f, 0x0b, 0xa2, 0xff, 0x6c, 0x08, 0x95, 0xff, + 0x6e, 0x09, 0x96, 0xff, 0x0d, 0x19, 0xf2, 0xff, 0x19, 0x15, 0xe4, 0xff, + 0x27, 0x13, 0xd5, 0xff, 0x35, 0x13, 0xc9, 0xff, 0x43, 0x10, 0xbc, 0xff, + 0x51, 0x0d, 0xaf, 0xff, 0x5f, 0x0b, 0xa2, 0xff, 0x6b, 0x09, 0x95, 0xff, + 0x79, 0x06, 0x88, 0xff, 0x7a, 0x08, 0x89, 0xff, 0x1a, 0x17, 0xe5, 0xff, + 0x27, 0x13, 0xd5, 0xff, 0x36, 0x12, 0xc9, 0xff, 0x42, 0x0f, 0xbb, 0xff, + 0x4f, 0x0c, 0xae, 0xff, 0x5f, 0x0b, 0xa2, 0xff, 0x6b, 0x07, 0x94, 0xff, + 0x79, 0x06, 0x88, 0xff, 0x87, 0x04, 0x7b, 0xff, 0x88, 0x05, 0x7c, 0xff, + 0x27, 0x15, 0xd6, 0xff, 0x35, 0x13, 0xc9, 0xff, 0x43, 0x10, 0xbc, 0xff, + 0x51, 0x0d, 0xaf, 0xff, 0x5d, 0x0c, 0xa2, 0xff, 0x6b, 0x09, 0x93, 0xff, + 0x79, 0x07, 0x86, 0xff, 0x87, 0x04, 0x79, 0xff, 0x95, 0x02, 0x6c, 0xff, + 0x96, 0x03, 0x6d, 0xff, 0x35, 0x13, 0xc9, 0xff, 0x43, 0x10, 0xbc, 0xff, + 0x51, 0x0d, 0xaf, 0xff, 0x5d, 0x0c, 0xa2, 0xff, 0x6b, 0x09, 0x95, 0xff, + 0x79, 0x07, 0x86, 0xff, 0x87, 0x04, 0x79, 0xff, 0x95, 0x02, 0x6c, 0xff, + 0xa3, 0x00, 0x5f, 0xff, 0xa4, 0x00, 0x60, 0xff, 0x43, 0x10, 0xbc, 0xff, + 0x4f, 0x0f, 0xad, 0xff, 0x5d, 0x0c, 0xa0, 0xff, 0x6b, 0x09, 0x93, 0xff, + 0x77, 0x08, 0x86, 0xff, 0x84, 0x04, 0x78, 0xff, 0x93, 0x02, 0x6c, 0xff, + 0xa1, 0x00, 0x5d, 0xff, 0xaf, 0x00, 0x50, 0xff, 0xb0, 0x00, 0x51, 0xff, + 0x4f, 0x0c, 0xae, 0xff, 0x5d, 0x0c, 0xa0, 0xff, 0x6b, 0x09, 0x93, 0xff, + 0x77, 0x08, 0x86, 0xff, 0x85, 0x05, 0x79, 0xff, 0x93, 0x02, 0x6c, 0xff, + 0xa1, 0x00, 0x5f, 0xff, 0xad, 0x00, 0x50, 0xff, 0xbc, 0x00, 0x44, 0xff, + 0xbe, 0x00, 0x46, 0xff, 0x5d, 0x0c, 0xa2, 0xff, 0x69, 0x0a, 0x93, 0xff, + 0x77, 0x08, 0x86, 0xff, 0x85, 0x05, 0x79, 0xff, 0x93, 0x02, 0x6c, 0xff, + 0x9f, 0x01, 0x5d, 0xff, 0xad, 0x00, 0x50, 0xff, 0xbc, 0x00, 0x44, 0xff, + 0xc8, 0x00, 0x34, 0xff, 0xc9, 0x00, 0x35, 0xff, 0x69, 0x0a, 0x95, 0xff, + 0x77, 0x08, 0x86, 0xff, 0x85, 0x05, 0x79, 0xff, 0x93, 0x02, 0x6c, 0xff, + 0xa1, 0x00, 0x5f, 0xff, 0xaf, 0x00, 0x51, 0xff, 0xbb, 0x00, 0x43, 0xff, + 0xc8, 0x00, 0x34, 0xff, 0xd7, 0x00, 0x28, 0xff, 0xd7, 0x00, 0x28, 0xff, + 0x6a, 0x0b, 0x96, 0xff, 0x78, 0x09, 0x87, 0xff, 0x86, 0x06, 0x7a, 0xff, + 0x94, 0x04, 0x6d, 0xff, 0xa2, 0x01, 0x60, 0xff, 0xb0, 0x01, 0x53, 0xff, + 0xbc, 0x00, 0x44, 0xff, 0xc9, 0x00, 0x35, 0xff, 0xd8, 0x00, 0x2a, 0xff, + 0xd8, 0x00, 0x2a, 0xff +}; + +namespace YamiMediaCodec { + +class VaapiEncoderJpegTest + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIENCODER_JPEG_TEST(name) \ + TEST_F(VaapiEncoderJpegTest, name) + +VAAPIENCODER_JPEG_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_JPEG); + doFactoryTest(mimeTypes); +} + +VAAPIENCODER_JPEG_TEST(QualityParamSetGet) { + VaapiEncoderJpeg encoder; + VideoParamsQualityLevel quality = { + .size = sizeof(VideoParamsQualityLevel), .level = 0u}; + + // default quality level + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, 50u); + + // out of low range limit clamps to low range + quality.level = 0u; + EXPECT_EQ(YAMI_SUCCESS, + encoder.setParameters(VideoParamsTypeQualityLevel, &quality)); + quality.level = 0u; + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, 1u); + + // in valid range + for (uint32_t q(1u); q <= 100; ++q) { + quality.level = q; + EXPECT_EQ(YAMI_SUCCESS, + encoder.setParameters(VideoParamsTypeQualityLevel, &quality)); + quality.level = 0u; + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, q); + } + + // out of high range limit clamps to high range + for (uint32_t q(101u); q < 256; ++q) { + quality.level = q; + EXPECT_EQ(YAMI_SUCCESS, + encoder.setParameters(VideoParamsTypeQualityLevel, &quality)); + quality.level = 0u; + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, 100u); + } +} + +class SimpleDataTest + : public VaapiEncoderJpegTest + , public ::testing::WithParamInterface +{ +protected: + uint8_t* getData() const + { + const uint8_t* result(NULL); + switch (getFourcc()) { + case VA_FOURCC_NV12: + result = g_SimpleSmallNV12.data(); + break; + case VA_FOURCC_I420: + result = g_SimpleSmallI420.data(); + break; + case VA_FOURCC_YV12: + result = g_SimpleSmallYV12.data(); + break; + case VA_FOURCC_YUY2: + result = g_SimpleSmallYUY2.data(); + break; + case VA_FOURCC_UYVY: + result = g_SimpleSmallUYVY.data(); + break; + case VA_FOURCC_RGBX: + result = g_SimpleSmallRGBX.data(); + break; + case VA_FOURCC_BGRX: + result = g_SimpleSmallBGRX.data(); + break; + default: + ADD_FAILURE() << "Test data is undefined for " << GetParam(); + } + return const_cast(result); + } + + uint32_t getFourcc() const + { + const std::string param(GetParam()); + return VA_FOURCC(param[0], param[1], param[2], param[3]); + } +}; + +#define VAAPIENCODER_JPEG_TEST_SIMPLE_DATA(name) \ + TEST_P(SimpleDataTest, name) + +VAAPIENCODER_JPEG_TEST_SIMPLE_DATA(Encode) +{ + uint8_t* data = getData(); + uint32_t fourcc = getFourcc(); + + ASSERT_FALSE(HasFailure()); + + VaapiEncoderJpeg encoder; + VideoParamsQualityLevel quality = {.size = sizeof(VideoParamsQualityLevel)}; + VideoParamsCommon parameters = {.size = sizeof(VideoParamsCommon)}; + + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeCommon, ¶meters)); + parameters.resolution.width = 10; + parameters.resolution.height = 10; + EXPECT_EQ(YAMI_SUCCESS, + encoder.setParameters(VideoParamsTypeCommon, ¶meters)); + + // verify default jpeg quality level + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, 50u); + + ASSERT_EQ(YAMI_SUCCESS, encoder.start()); + + VideoFrameRawData frame = { }; + + ASSERT_TRUE(fillFrameRawData(&frame, fourcc, 10, 10, data)); + + ASSERT_EQ(YAMI_SUCCESS, encoder.encode(&frame)); + + uint32_t size; + encoder.getMaxOutSize(&size); + std::vector buffer(size, 0); + VideoEncOutputBuffer output; + output.data = const_cast(buffer.data()); + output.bufferSize = buffer.size(); + output.format = OUTPUT_EVERYTHING; + + EXPECT_EQ(YAMI_SUCCESS, encoder.getOutput(&output, false)); + + // Verify jpeg quality level did not get changed during encode + quality.level = 0u; + EXPECT_EQ(YAMI_SUCCESS, + encoder.getParameters(VideoParamsTypeQualityLevel, &quality)); + EXPECT_EQ(quality.level, 50u); +} + +INSTANTIATE_TEST_CASE_P( + VaapiEncoderJpegTest, SimpleDataTest, + ::testing::Values("NV12", "I420", "YUY2") + + // The following fourcc's cause the test program to abort + // (see https://github.com/01org/libyami/issues/439): + // + // "YV12", "UYVY", "RGBX", "BGRX", "BGRA", "RGBA" +); + +} diff --git a/encoder/vaapiencoder_vp8.cpp b/encoder/vaapiencoder_vp8.cpp new file mode 100755 index 0000000..450b78c --- /dev/null +++ b/encoder/vaapiencoder_vp8.cpp @@ -0,0 +1,530 @@ +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_vp8.h" +#include "common/scopedlogger.h" +#include "common/common_def.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapicodedbuffer.h" +#include "vaapiencpicture.h" +#include +#include + +namespace YamiMediaCodec{ + +//golden, alter, last +#define MAX_REFERECNE_FRAME 3 +#define VP8_DEFAULT_QP 40 + +class VaapiEncPictureVP8 : public VaapiEncPicture +{ +public: + VaapiEncPictureVP8(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiEncPicture(context, surface, timeStamp) + { + return; + } + + VAGenericID getCodedBufferID() + { + return m_codedBuffer->getID(); + } +}; + +struct RefFlags +{ + /* exactly same things in VAEncPictureParameterBufferVP8 */ + uint32_t refresh_golden_frame : 1; + uint32_t refresh_alternate_frame : 1; + uint32_t refresh_last : 1; + uint32_t copy_buffer_to_golden : 2; + uint32_t copy_buffer_to_alternate : 2; + uint32_t no_ref_last : 1; + uint32_t no_ref_gf : 1; + uint32_t no_ref_arf : 1; + + RefFlags() + { + memset(this, 0, sizeof(RefFlags)); + + } +}; + +class Vp8Encoder { +public: + virtual void getRefFlags(RefFlags&, uint8_t temporalLayer) = 0; + virtual void getLayerIds(LayerIDs& ids) const = 0; + virtual bool getErrorResilient() const = 0; + virtual bool getRefreshEntropyProbs() const = 0; + virtual uint8_t getTemporalLayer(uint32_t frameNum) const = 0; + virtual uint8_t getLayerNum() const = 0; + virtual void getLayerFrameRates(LayerFrameRates& frameRates) const = 0; + virtual void resetRefNum() = 0; + virtual ~Vp8Encoder() {} +}; + +class Vp8EncoderNormal : public Vp8Encoder { +public: + void getRefFlags(RefFlags&, uint8_t temporalLayer); + void getLayerIds(LayerIDs& ids) const { ASSERT(0 && "not suppose call this"); } + bool getErrorResilient() const { return false; } + bool getRefreshEntropyProbs() const { return false; } + uint8_t getTemporalLayer(uint32_t frameNum) const { return 0; } + uint8_t getLayerNum() const { return 1; } + void getLayerFrameRates(LayerFrameRates& frameRates) const { return; } + void resetRefNum() { return; } +}; + +void Vp8EncoderNormal::getRefFlags(RefFlags& refFlags, uint8_t temporalLayer) +{ + refFlags.refresh_last = 1; + refFlags.refresh_golden_frame = 0; + refFlags.copy_buffer_to_golden = 1; + refFlags.refresh_alternate_frame = 0; + refFlags.copy_buffer_to_alternate = 2; + +} +class Vp8EncoderSvct : public Vp8Encoder { +public: + Vp8EncoderSvct(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex) + : m_layerIndex(layerIndex % VP8_MAX_TEMPORAL_LAYER_NUM) + , m_goldenRefreshed(false) + { + m_layerIDs.reset(new Vp8LayerID(frameRate, layerIDs, m_layerIndex)); + } + void getRefFlags(RefFlags&, uint8_t temporalLayer); + void getLayerIds(LayerIDs& ids) const; + void getLayerFrameRates(LayerFrameRates& frameRates) const { return m_layerIDs->getLayerFrameRates(frameRates); } + + bool getErrorResilient() const { return true; } + bool getRefreshEntropyProbs() const { return false; } + uint8_t getTemporalLayer(uint32_t frameNum) const; + uint8_t getLayerNum() const { return m_layerIDs->getLayerNum(); } + void resetRefNum(); + +private: + uint8_t m_layerIndex; + bool m_goldenRefreshed; + TemporalLayerIDPtr m_layerIDs; +}; + +void Vp8EncoderSvct::resetRefNum() +{ + m_goldenRefreshed = false; +} + +uint8_t Vp8EncoderSvct::getTemporalLayer(uint32_t frameNum) const +{ + return m_layerIDs->getTemporalLayer(frameNum); +} + +void Vp8EncoderSvct::getLayerIds(LayerIDs& ids) const +{ + m_layerIDs->getLayerIds(ids); +} + +void Vp8EncoderSvct::getRefFlags(RefFlags& refFlags, uint8_t temporalLayer) +{ + refFlags.no_ref_arf = 1; + switch (temporalLayer) { + case 2: + if (!m_goldenRefreshed) + refFlags.no_ref_gf = 1; + refFlags.refresh_alternate_frame = 1; + //allow to drop the third layer's frames on terrible network condition, + //so the third layer's frames don't reference to each other. + break; + case 1: + if (!m_goldenRefreshed) + refFlags.no_ref_gf = 1; + refFlags.refresh_golden_frame = 1; + m_goldenRefreshed = true; + break; + case 0: + refFlags.refresh_last = 1; + refFlags.no_ref_gf = 1; + break; + default: + ERROR("temporal layer %d is out of the range[0, 2].", temporalLayer); + break; + } +} + +VaapiEncoderVP8::VaapiEncoderVP8(): + m_frameCount(0), + m_qIndex(VP8_DEFAULT_QP) +{ + m_videoParamCommon.profile = VAProfileVP8Version0_3; + m_videoParamCommon.rcParams.minQP = 9; + m_videoParamCommon.rcParams.maxQP = 127; + m_videoParamCommon.rcParams.initQP = VP8_DEFAULT_QP; +} + +VaapiEncoderVP8::~VaapiEncoderVP8() +{ +} + +YamiStatus VaapiEncoderVP8::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + *maxSize = m_maxCodedbufSize; + return YAMI_SUCCESS; +} + +//if the context is very complex and the quantization value is very small, +//the coded slice data will be very close to the limitation value width() * height() * 3 / 2. +//And the coded bitstream (slice_data + frame headers) will more than width() * height() * 3 / 2. +//so we add VP8_HEADER_MAX_SIZE to m_maxCodedbufSize to make sure it's not overflow. +#define VP8_HEADER_MAX_SIZE 0x4000 + +void VaapiEncoderVP8::resetParams() +{ + m_maxCodedbufSize = width() * height() * 3 / 2 + VP8_HEADER_MAX_SIZE; + if (ipPeriod() == 0) + m_videoParamCommon.intraPeriod = 1; + + VideoFrameRate frameRate; + frameRate.frameRateDenom = frameRateDenom(); + frameRate.frameRateNum = frameRateNum(); + uint8_t layerIndex = m_videoParamCommon.temporalLayers.numLayersMinus1; + if (layerIndex > 0) { +#ifndef __ENABLE_VP8_SVCT__ + assert(0 && "Please enable --enable-vp8svct during compilation!"); +#endif + m_encoder.reset(new Vp8EncoderSvct(frameRate, m_videoParamCommon.temporalLayerIDs, layerIndex)); + m_encoder->getLayerFrameRates(m_svctFrameRate); + assert((layerIndex + 1) == m_encoder->getLayerNum()); + } + else { + m_encoder.reset(new Vp8EncoderNormal()); + } +} + +YamiStatus VaapiEncoderVP8::start() +{ + FUNC_ENTER(); + resetParams(); + return VaapiEncoderBase::start(); +} + +void VaapiEncoderVP8::flush() +{ + FUNC_ENTER(); + m_frameCount = 0; + m_last.reset(); + m_golden.reset(); + m_alt.reset(); + VaapiEncoderBase::flush(); +} + +YamiStatus VaapiEncoderVP8::stop() +{ + flush(); + return VaapiEncoderBase::stop(); +} + +YamiStatus VaapiEncoderVP8::setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_SUCCESS; + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + + switch (type) { + default: + status = VaapiEncoderBase::setParameters(type, videoEncParams); + break; + } + return status; +} + +YamiStatus VaapiEncoderVP8::getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) +{ + FUNC_ENTER(); + if (!videoEncParams) + return YAMI_INVALID_PARAM; + + // TODO, update video resolution basing on hw requirement + return VaapiEncoderBase::getParameters(type, videoEncParams); +} + +YamiStatus VaapiEncoderVP8::doEncode(const SurfacePtr& surface, uint64_t timeStamp, bool forceKeyFrame) +{ + YamiStatus ret; + if (!surface) + return YAMI_INVALID_PARAM; + + PicturePtr picture(new VaapiEncPictureVP8(m_context, surface, timeStamp)); + + if (!(m_frameCount % keyFramePeriod()) || forceKeyFrame) + picture->m_type = VAAPI_PICTURE_I; + else + picture->m_type = VAAPI_PICTURE_P; + + picture->m_temporalID = m_encoder->getTemporalLayer(m_frameCount % keyFramePeriod()); + m_frameCount++; + + m_qIndex = (initQP() > minQP() && initQP() < maxQP()) ? initQP() : VP8_DEFAULT_QP; + + CodedBufferPtr codedBuffer = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize); + if (!codedBuffer) + return YAMI_OUT_MEMORY; + picture->m_codedBuffer = codedBuffer; + codedBuffer->setFlag(ENCODE_BUFFERFLAG_ENDOFFRAME); + INFO("picture->m_type: 0x%x\n", picture->m_type); + if (picture->m_type == VAAPI_PICTURE_I) { + codedBuffer->setFlag(ENCODE_BUFFERFLAG_SYNCFRAME); + } + ret = encodePicture(picture); + if (ret != YAMI_SUCCESS) { + return ret; + } + output(picture); + return YAMI_SUCCESS; +} + + +bool VaapiEncoderVP8::fill(VAEncSequenceParameterBufferVP8* seqParam) const +{ + seqParam->frame_width = width(); + seqParam->frame_height = height(); + seqParam->bits_per_second = bitRate(); + seqParam->intra_period = intraPeriod(); + seqParam->error_resilient = m_encoder->getErrorResilient(); + return true; +} + +void VaapiEncoderVP8::fill(VAEncPictureParameterBufferVP8* picParam, const RefFlags& refFlags) const +{ + picParam->pic_flags.bits.refresh_golden_frame = refFlags.refresh_golden_frame; + picParam->pic_flags.bits.refresh_alternate_frame = refFlags.refresh_alternate_frame; + picParam->pic_flags.bits.refresh_last = refFlags.refresh_last; + picParam->pic_flags.bits.copy_buffer_to_golden = refFlags.copy_buffer_to_golden; + picParam->pic_flags.bits.copy_buffer_to_alternate = refFlags.copy_buffer_to_alternate; + +#ifdef __ENABLE_VP8_SVCT__ + picParam->ref_flags.bits.no_ref_last = refFlags.no_ref_last; + picParam->ref_flags.bits.no_ref_gf = refFlags.no_ref_gf; + picParam->ref_flags.bits.no_ref_arf = refFlags.no_ref_arf; + if (!picParam->ref_flags.bits.no_ref_last) + picParam->ref_flags.bits.first_ref = 0x01; + if (!picParam->ref_flags.bits.no_ref_gf) + picParam->ref_flags.bits.second_ref = 0x02; +#endif +} + +/* Fills in VA picture parameter buffer */ +bool VaapiEncoderVP8::fill(VAEncPictureParameterBufferVP8* picParam, const PicturePtr& picture, + const SurfacePtr& surface, RefFlags& refFlags) const +{ + picParam->reconstructed_frame = surface->getID(); + picParam->ref_last_frame = VA_INVALID_SURFACE; + picParam->ref_gf_frame = VA_INVALID_SURFACE; + picParam->ref_arf_frame = VA_INVALID_SURFACE; + + if (picture->m_type == VAAPI_PICTURE_P) { + picParam->pic_flags.bits.frame_type = 1; + m_encoder->getRefFlags(refFlags, picture->m_temporalID); + if (!refFlags.no_ref_arf) + picParam->ref_arf_frame = m_alt->getID(); + if (!refFlags.no_ref_gf) + picParam->ref_gf_frame = m_golden->getID(); + if (!refFlags.no_ref_last) + picParam->ref_last_frame = m_last->getID(); + + fill(picParam, refFlags); + } + else { + m_encoder->resetRefNum(); + } + + picParam->coded_buf = picture->getCodedBufferID(); +#ifdef __ENABLE_VP8_SVCT__ + picParam->ref_flags.bits.temporal_id = picture->m_temporalID; +#endif + + picParam->pic_flags.bits.show_frame = 1; + /*TODO: multi partition*/ + picParam->pic_flags.bits.num_token_partitions = 0; + //REMOVE THIS + picParam->pic_flags.bits.refresh_entropy_probs = 0; + /*pic_flags end */ + for (int i = 0; i < 4; i++) { + picParam->loop_filter_level[i] = 19; + } + + picParam->clamp_qindex_low = minQP(); + picParam->clamp_qindex_high = maxQP(); + return TRUE; +} + +bool VaapiEncoderVP8::fill(VAQMatrixBufferVP8* qMatrix) const +{ + size_t i; + + for (i = 0; i < N_ELEMENTS(qMatrix->quantization_index); i++) { + qMatrix->quantization_index[i] = m_qIndex; + } + + for (i = 0; i < N_ELEMENTS(qMatrix->quantization_index_delta); i++) { + qMatrix->quantization_index_delta[i] = 0; + } + + return true; +} + + +bool VaapiEncoderVP8::ensureSequence(const PicturePtr& picture) +{ + if (picture->m_type != VAAPI_PICTURE_I) + return true; + + VAEncSequenceParameterBufferVP8* seqParam; + if (!picture->editSequence(seqParam) || !fill(seqParam)) { + ERROR("failed to create sequence parameter buffer (SPS)"); + return false; + } + return true; +} + +bool VaapiEncoderVP8::ensurePicture (const PicturePtr& picture, + const SurfacePtr& surface, + RefFlags& refFlags) +{ + VAEncPictureParameterBufferVP8 *picParam; + + if (!picture->editPicture(picParam) || !fill(picParam, picture, surface, refFlags)) { + ERROR("failed to create picture parameter buffer (PPS)"); + return false; + } + return true; +} + +bool VaapiEncoderVP8::ensureQMatrix (const PicturePtr& picture) +{ + VAQMatrixBufferVP8 *qMatrix; + + if (!picture->editQMatrix(qMatrix) || !fill(qMatrix)) { + ERROR("failed to create qMatrix"); + return false; + } + return true; +} + +/* Section 9.7 */ +const SurfacePtr& VaapiEncoderVP8::referenceUpdate( + const SurfacePtr& to, const SurfacePtr& from, + const SurfacePtr& recon, bool refresh, uint32_t copy) const +{ + if (refresh) + return recon; + switch (copy) { + case 0: + return to; + case 1: + return m_last; + case 2: + return from; + default: + ASSERT(0 && "invalid copy to flags"); + return to; + } + +} + +bool VaapiEncoderVP8::referenceListUpdate (const PicturePtr& pic, const SurfacePtr& recon, const RefFlags& refFlags) +{ + if (VAAPI_PICTURE_I == pic->m_type) { + m_last = recon; + m_golden = recon; + m_alt = recon; + } + else { + /* 9.7 and 9.8 */ + m_golden = referenceUpdate(m_golden, m_alt, recon, + refFlags.refresh_golden_frame, refFlags.copy_buffer_to_golden); + m_alt = referenceUpdate(m_alt, m_golden, recon, + refFlags.refresh_alternate_frame, refFlags.copy_buffer_to_alternate); + if (refFlags.refresh_last) + m_last = recon; + } + return true; +} +/* Generates additional control parameters */ +bool VaapiEncoderVP8::ensureMiscParams(VaapiEncPicture* picture) +{ + VideoRateControl mode = rateControlMode(); + if (mode == RATE_CONTROL_CBR || mode == RATE_CONTROL_VBR) { + if (m_videoParamCommon.temporalLayers.numLayersMinus1 > 0) { + VAEncMiscParameterTemporalLayerStructure* layerParam = NULL; + if (!picture->newMisc(VAEncMiscParameterTypeTemporalLayerStructure, + layerParam)) + return false; + + LayerIDs ids; + m_encoder->getLayerIds(ids); + if (layerParam) { + layerParam->number_of_layers = m_videoParamCommon.temporalLayers.numLayersMinus1 + 1; + layerParam->periodicity = ids.size(); + for (uint32_t i = 1; i < layerParam->periodicity; i++) + layerParam->layer_id[i - 1] = ids[i]; + layerParam->layer_id[layerParam->periodicity - 1] = ids[0]; + } + } + } + + if (!VaapiEncoderBase::ensureMiscParams(picture)) + return false; + + return true; +} + +YamiStatus VaapiEncoderVP8::encodePicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_FAIL; + SurfacePtr reconstruct = createSurface(); + if (!reconstruct) + return ret; + + if (!ensureSequence (picture)) + return ret; + + if (!ensureMiscParams (picture.get())) + return ret; + + RefFlags refFlags; + if (!ensurePicture(picture, reconstruct, refFlags)) + return ret; + + if (!ensureQMatrix(picture)) + return ret; + + if (!picture->encode()) + return ret; + + if (!referenceListUpdate(picture, reconstruct, refFlags)) + return ret; + + return YAMI_SUCCESS; +} + +} diff --git a/encoder/vaapiencoder_vp8.h b/encoder/vaapiencoder_vp8.h new file mode 100644 index 0000000..1337151 --- /dev/null +++ b/encoder/vaapiencoder_vp8.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_vp8_h +#define vaapiencoder_vp8_h + +#include "vaapiencoder_base.h" +#include "vaapi/vaapiptrs.h" +#include +#include + + +namespace YamiMediaCodec{ + +class VaapiEncPictureVP8; +class Vp8Encoder; +struct RefFlags; +class VaapiEncoderVP8 : public VaapiEncoderBase { +public: + //shortcuts, It's intended to elimilate codec diffrence + //to make template for other codec implelmentation. + typedef SharedPtr PicturePtr; + typedef SharedPtr Vp8EncoderPtr; + typedef SurfacePtr ReferencePtr; + + VaapiEncoderVP8(); + ~VaapiEncoderVP8(); + virtual YamiStatus start(); + virtual void flush(); + virtual YamiStatus stop(); + + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); + +protected: + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, bool forceKeyFrame = false); + virtual bool ensureMiscParams(VaapiEncPicture*); + +private: + friend class FactoryTest; + friend class VaapiEncoderVP8Test; + + YamiStatus encodePicture(const PicturePtr&); + bool fill(VAEncSequenceParameterBufferVP8*) const; + void fill(VAEncPictureParameterBufferVP8*, const RefFlags&) const; + bool fill(VAEncPictureParameterBufferVP8*, const PicturePtr&, const SurfacePtr&, RefFlags&) const; + bool fill(VAQMatrixBufferVP8* qMatrix) const; + bool ensureSequence(const PicturePtr&); + bool ensurePicture (const PicturePtr&, const SurfacePtr&, RefFlags&); + bool ensureQMatrix (const PicturePtr&); + const SurfacePtr& referenceUpdate(const SurfacePtr& to, const SurfacePtr& from, + const SurfacePtr& recon, bool refresh, uint32_t copy) const; + bool referenceListUpdate (const PicturePtr&, const SurfacePtr&, const RefFlags&); + + void resetParams(); + + int keyFramePeriod() { return m_videoParamCommon.intraPeriod ? m_videoParamCommon.intraPeriod : 1; } + + int m_frameCount; + + int m_maxCodedbufSize; + + int m_qIndex; + + SurfacePtr m_last; + SurfacePtr m_golden; + SurfacePtr m_alt; + Vp8EncoderPtr m_encoder; + + /** + * VaapiEncoderFactory registration result. This encoder is registered in + * vaapiencoder_host.cpp + */ + static const bool s_registered; +}; +} +#endif /* vaapiencoder_vp8_h */ diff --git a/encoder/vaapiencoder_vp8_unittest.cpp b/encoder/vaapiencoder_vp8_unittest.cpp new file mode 100755 index 0000000..a7c8ddb --- /dev/null +++ b/encoder/vaapiencoder_vp8_unittest.cpp @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiencoder_vp8.h" + +namespace YamiMediaCodec { + +class VaapiEncoderVP8Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIENCODER_VP8_TEST(name) \ + TEST_F(VaapiEncoderVP8Test, name) + +VAAPIENCODER_VP8_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_VP8); + doFactoryTest(mimeTypes); +} + +} diff --git a/encoder/vaapiencoder_vp9.cpp b/encoder/vaapiencoder_vp9.cpp new file mode 100644 index 0000000..88ffe95 --- /dev/null +++ b/encoder/vaapiencoder_vp9.cpp @@ -0,0 +1,401 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencoder_vp9.h" +#include "common/scopedlogger.h" +#include "common/common_def.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/vaapidisplay.h" +#include "vaapicodedbuffer.h" +#include "vaapiencpicture.h" +#include + +namespace YamiMediaCodec { + +// each frame can have at most 3 reference frames, golden, alt and last +enum maxSizeValues { + kMaxReferenceFrames = 8, + kMaxWidth = 4096, + kMaxHeight = kMaxWidth, + kMaxHeaderSize=kMaxWidth +}; + +enum VP9QPValues { kMinQPValue = 9, kDefaultQPValue = 60, kMaxQPValue = 127 }; + +enum VP9FrameType { kKeyFrame, kInterFrame }; + +enum VP9LevelValues { kDefaultSharpnessLevel, kDefaultFilterLevel = 10 }; + +class VaapiEncPictureVP9 : public VaapiEncPicture { +public: + VaapiEncPictureVP9(const ContextPtr& context, const SurfacePtr& surface, + int64_t timeStamp) + : VaapiEncPicture(context, surface, timeStamp) + { + return; + } + + VAGenericID getCodedBufferID() { return m_codedBuffer->getID(); } +}; + +VaapiEncoderVP9::VaapiEncoderVP9() + : m_frameCount(0) +{ + m_videoParamCommon.profile = VAProfileVP9Profile0; + m_videoParamCommon.rcParams.minQP = kMinQPValue; + m_videoParamCommon.rcParams.maxQP = kMaxQPValue; + m_videoParamCommon.rcParams.initQP = kDefaultQPValue; + + // add extra surfaces to operate due to kMaxReferenceFrames + // vaapi_encoder class will create 5 extra surfaces already + m_maxOutputBuffer = kMaxReferenceFrames; +} + +VaapiEncoderVP9::~VaapiEncoderVP9() {} + +YamiStatus VaapiEncoderVP9::getMaxOutSize(uint32_t* maxSize) +{ + FUNC_ENTER(); + *maxSize = m_maxCodedbufSize; + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderVP9::resetParams() +{ + + // intel driver cannot handle non 8-bit aligned resolutions, once + // fixed this can go away + if (width() != ALIGN8(width()) || height() != ALIGN8(height())) { + ERROR("Input resolution %dx%d is not 8-bit aligned", width(), height()); + return YAMI_INVALID_PARAM; + } + + m_maxCodedbufSize = width() * height() * 3 / 2; + + // adding extra padding. In particular small resolutions require more + // space depending on other quantization parameters during execution. The + // value below is a good compromise + m_maxCodedbufSize += kMaxHeaderSize; + + if (ipPeriod() == 0) + m_videoParamCommon.intraPeriod = 1; + + return YAMI_SUCCESS; +} + +YamiStatus VaapiEncoderVP9::start() +{ + YamiStatus status; + FUNC_ENTER(); + status = resetParams(); + if (status != YAMI_SUCCESS) + return status; + return VaapiEncoderBase::start(); +} + +void VaapiEncoderVP9::flush() +{ + FUNC_ENTER(); + m_frameCount = 0; + m_reference.clear(); + VaapiEncoderBase::flush(); +} + +YamiStatus VaapiEncoderVP9::stop() +{ + flush(); + return VaapiEncoderBase::stop(); +} + +YamiStatus VaapiEncoderVP9::setParameters(VideoParamConfigType type, + Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + if (!videoEncParams) + return YAMI_INVALID_PARAM; + switch (type) { + case VideoParamsTypeVP9: { + VideoParamsVP9* vp9Params = (VideoParamsVP9*)videoEncParams; + PARAMETER_ASSIGN(m_videoParamsVP9, *vp9Params); + status = YAMI_SUCCESS; + } break; + default: + status = VaapiEncoderBase::setParameters(type, videoEncParams); + break; + } + return status; +} + +YamiStatus VaapiEncoderVP9::getParameters(VideoParamConfigType type, + Yami_PTR videoEncParams) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + if (!videoEncParams) + return status; + switch (type) { + case VideoParamsTypeVP9: { + VideoParamsVP9* vp9Params = (VideoParamsVP9*)videoEncParams; + PARAMETER_ASSIGN(*vp9Params, m_videoParamsVP9); + status = YAMI_SUCCESS; + } break; + default: + status = VaapiEncoderBase::getParameters(type, videoEncParams); + break; + } + + return status; +} + +YamiStatus VaapiEncoderVP9::doEncode(const SurfacePtr& surface, + uint64_t timeStamp, bool forceKeyFrame) +{ + YamiStatus ret; + if (!surface) + return YAMI_INVALID_PARAM; + + PicturePtr picture(new VaapiEncPictureVP9(m_context, surface, timeStamp)); + + if (!(m_frameCount % keyFramePeriod()) || forceKeyFrame) + picture->m_type = VAAPI_PICTURE_I; + else + picture->m_type = VAAPI_PICTURE_P; + + m_frameCount++; + + CodedBufferPtr codedBuffer + = VaapiCodedBuffer::create(m_context, m_maxCodedbufSize); + if (!codedBuffer) + return YAMI_OUT_MEMORY; + picture->m_codedBuffer = codedBuffer; + codedBuffer->setFlag(ENCODE_BUFFERFLAG_ENDOFFRAME); + if (picture->m_type == VAAPI_PICTURE_I) { + codedBuffer->setFlag(ENCODE_BUFFERFLAG_SYNCFRAME); + } + + ret = encodePicture(picture); + if (ret != YAMI_SUCCESS) { + return ret; + } + output(picture); + return YAMI_SUCCESS; +} + +bool VaapiEncoderVP9::fill(VAEncSequenceParameterBufferVP9* seqParam) const +{ + seqParam->max_frame_width = kMaxWidth; + seqParam->max_frame_height = kMaxHeight; + + seqParam->bits_per_second = bitRate(); + seqParam->intra_period = intraPeriod(); + seqParam->kf_min_dist = 1; + seqParam->kf_max_dist = intraPeriod(); + + return true; +} + +// Fills in VA picture parameter buffer +bool VaapiEncoderVP9::fill(VAEncPictureParameterBufferVP9* picParam, + const PicturePtr& picture, + const SurfacePtr& surface) +{ + picParam->reconstructed_frame = surface->getID(); + picParam->coded_buf = picture->getCodedBufferID(); + + if (picture->m_type == VAAPI_PICTURE_I) { + for (uint32_t i = 0; i < kMaxReferenceFrames ; i++) + picParam->reference_frames[i] = VA_INVALID_SURFACE; + } + else { + + picParam->pic_flags.bits.frame_type = kInterFrame; + + ReferenceQueue::const_iterator it = m_reference.begin(); + + for (uint32_t i = 0; it != m_reference.end(); ++it, i++) { + picParam->reference_frames[i] = (*it)->getID(); + DEBUG("reference frame[%d] 0x%x", i, (*it)->getID()); + } + + picParam->pic_flags.bits.frame_context_idx = 0; + // last/golden/alt is used as reference frame. L0 forward + picParam->ref_flags.bits.ref_frame_ctrl_l0 = 0x7; + + // golden and alt are last KeyFrame + // last is last decoded frame + + if (getReferenceMode()) { + // intel driver updates a new slot with every new frame and keeps + // the reference frames in a circular buffer, the buffer is defined + // with 8 slots but it is up to the application to use as many as + // desired. This scheme implements the use of 3 slots for + // last/gold/alt refs + + m_currentReferenceIndex = (m_currentReferenceIndex + 1) % 3; + + // set to refresh next slot with current reconstructed surface + picParam->refresh_frame_flags = 1 << m_currentReferenceIndex; + // assign the references on only 3 slots + picParam->ref_flags.bits.ref_arf_idx = m_currentReferenceIndex; + picParam->ref_flags.bits.ref_gf_idx = m_currentReferenceIndex + 1; + picParam->ref_flags.bits.ref_last_idx = m_currentReferenceIndex - 1; + + if (m_currentReferenceIndex == 0) { + picParam->ref_flags.bits.ref_last_idx + = m_currentReferenceIndex + 2; + } + else if (m_currentReferenceIndex == 2) { + picParam->ref_flags.bits.ref_gf_idx + = m_currentReferenceIndex - 2; + } + } + else { + picParam->refresh_frame_flags = 0x01; // refresh last frame + picParam->ref_flags.bits.ref_last_idx = 0; + picParam->ref_flags.bits.ref_gf_idx = 1; + picParam->ref_flags.bits.ref_arf_idx = 2; + } + } + + picParam->frame_width_src = width(); + picParam->frame_height_src = height(); + picParam->frame_width_dst = width(); + picParam->frame_height_dst = height(); + + picParam->pic_flags.bits.show_frame = 1; + + picParam->luma_ac_qindex = (initQP() >= minQP() && initQP() <= maxQP()) ? initQP() : kDefaultQPValue; + + picParam->luma_dc_qindex_delta = 1; + picParam->chroma_ac_qindex_delta = 1; + picParam->chroma_dc_qindex_delta = 1; + + picParam->filter_level = kDefaultFilterLevel; + picParam->sharpness_level = kDefaultSharpnessLevel; + + return true; +} + +bool VaapiEncoderVP9::fill( + VAEncMiscParameterTypeVP9PerSegmantParam* segParam) const +{ + return true; +} + +bool VaapiEncoderVP9::ensureSequence(const PicturePtr& picture) +{ + if (picture->m_type != VAAPI_PICTURE_I) + return true; + + VAEncSequenceParameterBufferVP9* seqParam; + if (!picture->editSequence(seqParam) || !fill(seqParam)) { + ERROR("failed to create sequence parameter buffer (SPS)"); + return false; + } + return true; +} + +bool VaapiEncoderVP9::ensurePicture(const PicturePtr& picture, + const SurfacePtr& surface) +{ + VAEncPictureParameterBufferVP9* picParam; + + if (!picture->editPicture(picParam) || !fill(picParam, picture, surface)) { + ERROR("failed to create picture parameter buffer (PPS)"); + return false; + } + return true; +} + +bool VaapiEncoderVP9::ensureQMatrix(const PicturePtr& picture) +{ + VAEncMiscParameterTypeVP9PerSegmantParam* segmentParam; + + if (picture->m_type != VAAPI_PICTURE_I) + return true; + + if (!picture->editQMatrix(segmentParam) || !fill(segmentParam)) { + ERROR("failed to create qMatrix"); + return false; + } + return true; +} + +bool VaapiEncoderVP9::referenceListUpdate(const PicturePtr& pic, + const SurfacePtr& recon) +{ + + if (pic->m_type == VAAPI_PICTURE_I) { + m_reference.clear(); + m_reference.insert(m_reference.end(), kMaxReferenceFrames, recon); + if (getReferenceMode()) + m_currentReferenceIndex = 0; + } + else { + if (getReferenceMode()) { + ReferenceQueue::iterator it + = m_reference.begin() + m_currentReferenceIndex; + + (*it) = recon; + +#if __ENABLE_DEBUG__ + for (it = m_reference.begin(); it != m_reference.end(); ++it) + DEBUG("Update ref frames 0x%x", (*it)->getID()); +#endif + } + else { + m_reference.pop_front(); + m_reference.push_front(recon); + } + } + + return true; +} + +YamiStatus VaapiEncoderVP9::encodePicture(const PicturePtr& picture) +{ + YamiStatus ret = YAMI_FAIL; + SurfacePtr reconstruct = createSurface(); + if (!reconstruct) + return ret; + + if (!ensureSequence(picture)) + return ret; + + if (!ensureQMatrix(picture)) + return ret; + + if (!ensureMiscParams(picture.get())) + return ret; + + if (!ensurePicture(picture, reconstruct)) + return ret; + + if (!picture->encode()) + return ret; + + if (!referenceListUpdate(picture, reconstruct)) + return ret; + + return YAMI_SUCCESS; +} + +} diff --git a/encoder/vaapiencoder_vp9.h b/encoder/vaapiencoder_vp9.h new file mode 100644 index 0000000..b458d8b --- /dev/null +++ b/encoder/vaapiencoder_vp9.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencoder_vp9_h +#define vaapiencoder_vp9_h + +#include "vaapiencoder_base.h" +#include "vaapi/vaapiptrs.h" +#include +#include + +#include "VideoEncoderDefs.h" + +namespace YamiMediaCodec { + +class VaapiEncPictureVP9; +class VaapiEncoderVP9 : public VaapiEncoderBase { +public: + typedef SharedPtr PicturePtr; + typedef SurfacePtr ReferencePtr; + + VaapiEncoderVP9(); + ~VaapiEncoderVP9(); + virtual YamiStatus start(); + virtual void flush(); + virtual YamiStatus stop(); + + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR); + virtual YamiStatus getMaxOutSize(uint32_t* maxSize); + +protected: + virtual YamiStatus doEncode(const SurfacePtr&, uint64_t timeStamp, + bool forceKeyFrame = false); + +private: + friend class FactoryTest; + friend class VaapiEncoderVP9Test; + + YamiStatus encodePicture(const PicturePtr&); + bool fill(VAEncSequenceParameterBufferVP9*) const; + bool fill(VAEncPictureParameterBufferVP9*, const PicturePtr&, + const SurfacePtr&); + bool fill(VAEncMiscParameterTypeVP9PerSegmantParam* segParam) const; + bool ensureSequence(const PicturePtr&); + bool ensurePicture(const PicturePtr&, const SurfacePtr&); + bool ensureQMatrix(const PicturePtr&); + bool referenceListUpdate(const PicturePtr&, const SurfacePtr&); + + YamiStatus resetParams(); + + int keyFramePeriod() + { + return m_videoParamCommon.intraPeriod ? m_videoParamCommon.intraPeriod + : 1; + } + + inline uint32_t getReferenceMode() { return m_videoParamsVP9.referenceMode; } + + VideoParamsVP9 m_videoParamsVP9; + int m_frameCount; + int m_currentReferenceIndex; + + int m_maxCodedbufSize; + + typedef std::deque ReferenceQueue; + std::deque m_reference; + + /** + * VaapiEncoderFactory registration result. This encoder is registered in + * vaapiencoder_host.cpp + */ + static const bool s_registered; +}; +} // namespace YamiMediaCodec +#endif // vaapiencoder_vp9_h diff --git a/encoder/vaapiencoder_vp9_unittest.cpp b/encoder/vaapiencoder_vp9_unittest.cpp new file mode 100755 index 0000000..bbc21c2 --- /dev/null +++ b/encoder/vaapiencoder_vp9_unittest.cpp @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapiencoder_vp9.h" + +namespace YamiMediaCodec { + +class VaapiEncoderVP9Test + : public FactoryTest +{ +protected: + /* invoked by gtest before the test */ + virtual void SetUp() { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() { + return; + } +}; + +#define VAAPIENCODER_VP9_TEST(name) \ + TEST_F(VaapiEncoderVP9Test, name) + +VAAPIENCODER_VP9_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_MIME_VP9); + doFactoryTest(mimeTypes); +} + +} diff --git a/encoder/vaapiencpicture.cpp b/encoder/vaapiencpicture.cpp new file mode 100644 index 0000000..c5e4587 --- /dev/null +++ b/encoder/vaapiencpicture.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapiencpicture.h" +#include "vaapicodedbuffer.h" + +#include "common/log.h" +#ifdef __BUILD_GET_MV__ +#include +#endif + +namespace YamiMediaCodec{ +VaapiEncPicture::VaapiEncPicture(const ContextPtr& context, + const SurfacePtr & surface, + int64_t timeStamp) +: VaapiPicture(context, surface, timeStamp) +, m_temporalID(0) +{ +} + +bool VaapiEncPicture::encode() +{ + return render(); +} + +bool VaapiEncPicture::doRender() +{ + RENDER_OBJECT(m_sequence); + RENDER_OBJECT(m_packedHeaders); + RENDER_OBJECT(m_miscParams); + RENDER_OBJECT(m_picture); + RENDER_OBJECT(m_qMatrix); + RENDER_OBJECT(m_huffTable); + RENDER_OBJECT(m_slices); +#ifdef __BUILD_GET_MV__ + RENDER_OBJECT(m_FEIBuffer); +#endif + return true; +} + +bool VaapiEncPicture:: +addPackedHeader(VAEncPackedHeaderType packedHeaderType, const void *header, + uint32_t headerBitSize) +{ + VAEncPackedHeaderParameterBuffer *packedHeader; + BufObjectPtr param = + createBufferObject(VAEncPackedHeaderParameterBufferType, + packedHeader); + BufObjectPtr data = + createBufferObject(VAEncPackedHeaderDataBufferType, + (headerBitSize + 7) / 8, header, NULL); + bool ret = addObject(m_packedHeaders, param, data); + if (ret && packedHeader) { + packedHeader->type = packedHeaderType; + packedHeader->bit_length = headerBitSize; + packedHeader->has_emulation_bytes = 0; + return true; + } + return false; +} + +YamiStatus VaapiEncPicture::getOutput(VideoEncOutputBuffer* outBuffer) +{ + ASSERT(outBuffer); + uint32_t size = m_codedBuffer->size(); + if (size > outBuffer->bufferSize) { + outBuffer->dataSize = 0; + return YAMI_ENCODE_BUFFER_TOO_SMALL; + } + if (size > 0) { + m_codedBuffer->copyInto(outBuffer->data); + outBuffer->flag |= m_codedBuffer->getFlags(); + } + outBuffer->dataSize = size; + return YAMI_SUCCESS; +} + +#ifdef __BUILD_GET_MV__ +bool VaapiEncPicture::editMVBuffer(void*& buffer, uint32_t *size) +{ + VABufferID bufID; + VAEncMiscParameterFEIFrameControlH264Intel fei_pic_param; + VAEncMiscParameterFEIFrameControlH264Intel *misc_fei_pic_control_param; + + if (!m_MVBuffer) { + m_MVBuffer = createBufferObject(VAEncFEIMVBufferTypeIntel, *size, NULL, (void**)&buffer); + bufID = m_MVBuffer->getID(); + fei_pic_param.mv_data = bufID; + fei_pic_param.function = VA_ENC_FUNCTION_ENC_PAK_INTEL; + fei_pic_param.num_mv_predictors = 1; + + if (!newMisc(VAEncMiscParameterTypeFEIFrameControlIntel, misc_fei_pic_control_param)) + return false; + *misc_fei_pic_control_param = fei_pic_param; + } else { + buffer = m_MVBuffer->map(); + *size = m_MVBuffer->getSize(); + } + return true; +} + +#endif + +} diff --git a/encoder/vaapiencpicture.h b/encoder/vaapiencpicture.h new file mode 100755 index 0000000..0eabf8c --- /dev/null +++ b/encoder/vaapiencpicture.h @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiencpicture_h +#define vaapiencpicture_h + +#include "VideoEncoderDefs.h" + +#include "vaapi/vaapipicture.h" + + +namespace YamiMediaCodec{ +class VaapiEncPicture:public VaapiPicture { + public: + VaapiEncPicture(const ContextPtr& context, + const SurfacePtr & surface, int64_t timeStamp); + virtual ~VaapiEncPicture() { } + + template < class T > + bool editSequence(T * &seqParam); + + template < class T > + bool editPicture(T * &picParam); + + template < class T > + bool editQMatrix(T * &qMatrix); + + template < class T > + bool editHuffTable(T * &huffTable); + + template < class T > + bool newSlice(T * &sliceParam); + + + template < class T > + bool newMisc(VAEncMiscParameterType, T * &miscParam); + + bool addPackedHeader(VAEncPackedHeaderType, const void *header, + uint32_t headerBitSize); + + bool encode(); + + // give subclass a chance to convert codec buffer to they wanted format. + // vp8 hybrid driver may need entropy code the coded buffer + // h264 encoder may need convert annexb to avcC + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer); + +#ifdef __BUILD_GET_MV__ + virtual bool editMVBuffer(void*& buffer, uint32_t *size); +#endif + + CodedBufferPtr m_codedBuffer; + uint8_t m_temporalID; + + private: + bool doRender(); + + template < class T > + BufObjectPtr createMiscObject(VAEncMiscParameterType, T * &bufPtr); + + BufObjectPtr m_sequence; + BufObjectPtr m_picture; + BufObjectPtr m_qMatrix; + BufObjectPtr m_huffTable; +#ifdef __BUILD_GET_MV__ + BufObjectPtr m_MVBuffer; + BufObjectPtr m_FEIBuffer; +#endif + std::vector < BufObjectPtr > m_miscParams; + std::vector < BufObjectPtr > m_slices; + std::vector < std::pair >m_packedHeaders; +}; + +template < class T > bool VaapiEncPicture::editSequence(T * &seqParam) +{ + return editObject(m_sequence, VAEncSequenceParameterBufferType, + seqParam); +} + +template < class T > bool VaapiEncPicture::editPicture(T * &picParam) +{ + return editObject(m_picture, VAEncPictureParameterBufferType, + picParam); +} + +template < class T > bool VaapiEncPicture::editQMatrix(T * &qMatrix) +{ + return editObject(m_qMatrix, VAQMatrixBufferType, qMatrix); +} + +template < class T > bool VaapiEncPicture::editHuffTable(T * &huffTable) +{ + return editObject(m_huffTable, VAHuffmanTableBufferType, huffTable); +} + +template < class T > bool VaapiEncPicture::newSlice(T * &sliceParam) +{ + BufObjectPtr slice = + createBufferObject(VAEncSliceParameterBufferType, sliceParam); + return (sliceParam != NULL) && addObject(m_slices, slice); +} + +template < class T > +BufObjectPtr VaapiEncPicture:: +createMiscObject(VAEncMiscParameterType miscType, T * &bufPtr) +{ + VAEncMiscParameterBuffer *misc; + int size = sizeof(VAEncMiscParameterBuffer) + sizeof(T); + BufObjectPtr obj = + createBufferObject(VAEncMiscParameterBufferType, size, NULL, + (void **) &misc); + if (obj) { + misc->type = miscType; + bufPtr = (T *) (misc->data); + memset(bufPtr, 0, sizeof(T)); + } + return obj; +} + +template < class T > +bool VaapiEncPicture::newMisc(VAEncMiscParameterType miscType, + T * &miscParam) +{ + BufObjectPtr misc = createMiscObject(miscType, miscParam); + return addObject(m_miscParams, misc); +} +} +#endif //vaapiencpicture_h diff --git a/encoder/vaapilayerid.cpp b/encoder/vaapilayerid.cpp new file mode 100644 index 0000000..f589992 --- /dev/null +++ b/encoder/vaapilayerid.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "vaapilayerid.h" +#include "common/log.h" + +namespace YamiMediaCodec { + +const uint8_t Vp8LayerID::m_vp8TempIds[VP8_MAX_TEMPORAL_LAYER_NUM][VP8_MIN_TEMPORAL_GOP] + = { { 0, 0, 0, 0 }, + { 0, 1, 0, 1 }, + { 0, 2, 1, 2 } }; + +const uint8_t AvcLayerID::m_avcTempIds[H264_MAX_TEMPORAL_LAYER_NUM][H264_MIN_TEMPORAL_GOP] + = { { 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 1, 0, 1, 0, 1, 0, 1 }, + { 0, 2, 1, 2, 0, 2, 1, 2 }, + { 0, 3, 2, 3, 1, 3, 2, 3 } }; + +TemporalLayerID::TemporalLayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, const uint8_t* defaultIDs, uint8_t defaultIDsLen) +{ + m_miniRefFrameNum = 0; + if (layerIDs.numIDs) { + m_idPeriod = layerIDs.numIDs; + for (uint32_t i = 0; i < layerIDs.numIDs; i++) + m_ids.push_back(layerIDs.ids[i]); + } + else { //use the default temporal IDs + assert(defaultIDs && defaultIDsLen > 0); + m_idPeriod = defaultIDsLen; + for (uint32_t i = 0; i < m_idPeriod; i++) + m_ids.push_back(defaultIDs[i]); + } + + calculateFramerate(frameRate); +} + +void TemporalLayerID::getLayerIds(LayerIDs& ids) const +{ + ids = m_ids; +} + +uint8_t TemporalLayerID::getTemporalLayer(uint32_t frameNumInGOP) const +{ + return m_ids[frameNumInGOP % m_idPeriod]; +} + +void TemporalLayerID::getLayerFrameRates(LayerFrameRates& frameRates) const +{ + frameRates = m_frameRates; + return; +} + +void TemporalLayerID::calculateFramerate(const VideoFrameRate& frameRate) +{ + uint8_t numberOfLayerIDs[TEMPORAL_LAYERIDS_LENGTH_MAX]; + LayerIDs tempIDs = m_ids; + uint8_t i; + + std::sort(tempIDs.begin(), tempIDs.end()); + memset(numberOfLayerIDs, 0, sizeof(numberOfLayerIDs)); + for (i = 0; i < tempIDs.size(); i++) { + numberOfLayerIDs[tempIDs[i]]++; + } + m_layerLen = tempIDs[i - 1] + 1; + assert(m_layerLen < TEMPORAL_LAYERIDS_LENGTH_MAX); + + VideoFrameRate frameRateTemp; + uint32_t denom = m_ids.size(); + uint32_t num = 0; + assert(frameRate.frameRateNum && frameRate.frameRateDenom); + frameRateTemp.frameRateDenom = frameRate.frameRateDenom * denom; + for (i = 0; i < m_layerLen; i++) { + num += numberOfLayerIDs[i]; + frameRateTemp.frameRateNum = num * frameRate.frameRateNum; + m_frameRates.push_back(frameRateTemp); + } + + return; +} + +uint8_t TemporalLayerID::getMiniRefFrameNum() const +{ + return m_miniRefFrameNum; +} + +void TemporalLayerID::checkLayerIDs(uint8_t maxLayerLength) const +{ + LayerIDs tempIDs = m_ids; + const uint8_t LAYERID0 = 0; + assert(LAYERID0 == tempIDs[0]); + if (m_idPeriod > TEMPORAL_LAYERIDS_LENGTH_MAX) { + ERROR("m_idPeriod(%d) should be in (0, %d]", m_idPeriod, TEMPORAL_LAYERIDS_LENGTH_MAX); + assert(false); + } + //check if the layerID is complete + std::sort(tempIDs.begin(), tempIDs.end()); + for (uint8_t i = 1; i < m_idPeriod; i++) { + if (tempIDs[i] - tempIDs[i - 1] > 1) { + ERROR("layer IDs illegal, no layer: %d.\n", (tempIDs[i - 1] + tempIDs[i]) / 2); + assert(false); + } + } + if ((m_layerLen > maxLayerLength) || (m_layerLen < 2)) { + ERROR("m_layerLen(%d) should be in [2, %d]", m_layerLen, maxLayerLength); + assert(false); + } + return; +} + +Vp8LayerID::Vp8LayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex) + : TemporalLayerID(frameRate, layerIDs, m_vp8TempIds[layerIndex], VP8_MIN_TEMPORAL_GOP) +{ + checkLayerIDs(VP8_MAX_TEMPORAL_LAYER_NUM); +} + +AvcLayerID::AvcLayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex) + : TemporalLayerID(frameRate, layerIDs, m_avcTempIds[layerIndex], H264_MIN_TEMPORAL_GOP) +{ + checkLayerIDs(H264_MAX_TEMPORAL_LAYER_NUM); + calculateMiniRefNum(); +} + +void AvcLayerID::calculateMiniRefNum() +{ + uint8_t max = 0; + const uint8_t LAYER0 = 0; + //The current frame of layer0 should be in the refList + uint8_t refFrameNum = 1; + for (uint8_t i = 0; i < m_idPeriod; i++) { + if (LAYER0 == m_ids[i]) { + if (max < refFrameNum) + max = refFrameNum; + //The current frame of layer0 should be in the refList + refFrameNum = 1; + } + else { + refFrameNum++; + } + } + m_miniRefFrameNum = max > refFrameNum ? max : refFrameNum; +} +} diff --git a/encoder/vaapilayerid.h b/encoder/vaapilayerid.h new file mode 100755 index 0000000..8286400 --- /dev/null +++ b/encoder/vaapilayerid.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2014-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapilayerid_h +#define vaapilayerid_h + +#include +#include "VideoEncoderDefs.h" + +namespace YamiMediaCodec { + +#define VP8_MAX_TEMPORAL_LAYER_NUM 3 +#define VP8_MIN_TEMPORAL_GOP 4 +#define H264_MIN_TEMPORAL_GOP 8 +#define H264_MAX_TEMPORAL_LAYER_NUM 4 + +class TemporalLayerID; + +typedef std::vector LayerIDs; +typedef std::vector LayerFrameRates; +typedef SharedPtr TemporalLayerIDPtr; + +class TemporalLayerID { +public: + TemporalLayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, const uint8_t* defaultIDs, uint8_t defaultIDsLen); + virtual void getLayerIds(LayerIDs& ids) const; + virtual uint8_t getTemporalLayer(uint32_t frameNum) const; + virtual void getLayerFrameRates(LayerFrameRates& frameRates) const; + virtual uint8_t getLayerNum() const { return m_layerLen; } + virtual uint8_t getMiniRefFrameNum() const; + + void checkLayerIDs(uint8_t maxLayerLength = 0) const; + virtual ~TemporalLayerID() {} + +private: + void calculateFramerate(const VideoFrameRate& frameRate); + +protected: + uint8_t m_layerLen; + LayerIDs m_ids; + LayerFrameRates m_frameRates; + uint8_t m_idPeriod; + uint8_t m_miniRefFrameNum; +}; + +class Vp8LayerID : public TemporalLayerID { +public: + Vp8LayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex); + +public: + static const uint8_t m_vp8TempIds[VP8_MAX_TEMPORAL_LAYER_NUM][VP8_MIN_TEMPORAL_GOP]; +}; + +class AvcLayerID : public TemporalLayerID { +public: + AvcLayerID(const VideoFrameRate& frameRate, const VideoTemporalLayerIDs& layerIDs, uint8_t layerIndex); + +private: + void calculateMiniRefNum(); + +public: + static const uint8_t m_avcTempIds[H264_MAX_TEMPORAL_LAYER_NUM][H264_MIN_TEMPORAL_GOP]; +}; +} + +#endif diff --git a/gtestsrc/Makefile.am b/gtestsrc/Makefile.am new file mode 100644 index 0000000..b81519e --- /dev/null +++ b/gtestsrc/Makefile.am @@ -0,0 +1,24 @@ +AUTOMAKE_OPTIONS = subdir-objects + +# libgtest +noinst_LTLIBRARIES = libgtest.la + +libgtest_la_SOURCES = \ + gtest/src/gtest-all.cc \ + gtest/src/gtest_main.cc \ + $(NULL) + +libgtest_la_CXXFLAGS = \ + -I$(top_srcdir)/gtestsrc/gtest \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(AM_CXXFLAGS) \ + $(NULL) + +EXTRA_DIST = \ + gtest/docs \ + gtest/include \ + gtest/src/*.cc \ + gtest/src/*.h \ + gtest/README.md \ + gtest/LICENSE \ + $(NULL) diff --git a/gtestsrc/gtest/LICENSE b/gtestsrc/gtest/LICENSE new file mode 100644 index 0000000..1941a11 --- /dev/null +++ b/gtestsrc/gtest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/gtestsrc/gtest/README.md b/gtestsrc/gtest/README.md new file mode 100644 index 0000000..edd4408 --- /dev/null +++ b/gtestsrc/gtest/README.md @@ -0,0 +1,280 @@ + +### Generic Build Instructions ### + +#### Setup #### + +To build Google Test and your tests that use it, you need to tell your +build system where to find its headers and source files. The exact +way to do it depends on which build system you use, and is usually +straightforward. + +#### Build #### + +Suppose you put Google Test in directory `${GTEST_DIR}`. To build it, +create a library build target (or a project as called by Visual Studio +and Xcode) to compile + + ${GTEST_DIR}/src/gtest-all.cc + +with `${GTEST_DIR}/include` in the system header search path and `${GTEST_DIR}` +in the normal header search path. Assuming a Linux-like system and gcc, +something like the following will do: + + g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ + -pthread -c ${GTEST_DIR}/src/gtest-all.cc + ar -rv libgtest.a gtest-all.o + +(We need `-pthread` as Google Test uses threads.) + +Next, you should compile your test source file with +`${GTEST_DIR}/include` in the system header search path, and link it +with gtest and any other necessary libraries: + + g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ + -o your_test + +As an example, the make/ directory contains a Makefile that you can +use to build Google Test on systems where GNU make is available +(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google +Test's own tests. Instead, it just builds the Google Test library and +a sample test. You can use it as a starting point for your own build +script. + +If the default settings are correct for your environment, the +following commands should succeed: + + cd ${GTEST_DIR}/make + make + ./sample1_unittest + +If you see errors, try to tweak the contents of `make/Makefile` to make +them go away. There are instructions in `make/Makefile` on how to do +it. + +### Using CMake ### + +Google Test comes with a CMake build script ( +[CMakeLists.txt](CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for +cross-platform.). If you don't have CMake installed already, you can +download it for free from . + +CMake works by generating native makefiles or build projects that can +be used in the compiler environment of your choice. The typical +workflow starts with: + + mkdir mybuild # Create a directory to hold the build output. + cd mybuild + cmake ${GTEST_DIR} # Generate native build scripts. + +If you want to build Google Test's samples, you should replace the +last command with + + cmake -Dgtest_build_samples=ON ${GTEST_DIR} + +If you are on a \*nix system, you should now see a Makefile in the +current directory. Just type 'make' to build gtest. + +If you use Windows and have Visual Studio installed, a `gtest.sln` file +and several `.vcproj` files will be created. You can then build them +using Visual Studio. + +On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated. + +### Legacy Build Scripts ### + +Before settling on CMake, we have been providing hand-maintained build +projects/scripts for Visual Studio, Xcode, and Autotools. While we +continue to provide them for convenience, they are not actively +maintained any more. We highly recommend that you follow the +instructions in the previous two sections to integrate Google Test +with your existing build system. + +If you still need to use the legacy build scripts, here's how: + +The msvc\ folder contains two solutions with Visual C++ projects. +Open the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you +are ready to build Google Test the same way you build any Visual +Studio project. Files that have names ending with -md use DLL +versions of Microsoft runtime libraries (the /MD or the /MDd compiler +option). Files without that suffix use static versions of the runtime +libraries (the /MT or the /MTd option). Please note that one must use +the same option to compile both gtest and the test code. If you use +Visual Studio 2005 or above, we recommend the -md version as /MD is +the default for new projects in these versions of Visual Studio. + +On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using +Xcode. Build the "gtest" target. The universal binary framework will +end up in your selected build directory (selected in the Xcode +"Preferences..." -> "Building" pane and defaults to xcode/build). +Alternatively, at the command line, enter: + + xcodebuild + +This will build the "Release" configuration of gtest.framework in your +default build location. See the "xcodebuild" man page for more +information about building different configurations and building in +different locations. + +If you wish to use the Google Test Xcode project with Xcode 4.x and +above, you need to either: + + * update the SDK configuration options in xcode/Config/General.xconfig. + Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If + you choose this route you lose the ability to target earlier versions + of MacOS X. + * Install an SDK for an earlier version. This doesn't appear to be + supported by Apple, but has been reported to work + (http://stackoverflow.com/questions/5378518). + +### Tweaking Google Test ### + +Google Test can be used in diverse environments. The default +configuration may not work (or may not work well) out of the box in +some environments. However, you can easily tweak Google Test by +defining control macros on the compiler command line. Generally, +these macros are named like `GTEST_XYZ` and you define them to either 1 +or 0 to enable or disable a certain feature. + +We list the most frequently used macros below. For a complete list, +see file [include/gtest/internal/gtest-port.h](include/gtest/internal/gtest-port.h). + +### Choosing a TR1 Tuple Library ### + +Some Google Test features require the C++ Technical Report 1 (TR1) +tuple library, which is not yet available with all compilers. The +good news is that Google Test implements a subset of TR1 tuple that's +enough for its own need, and will automatically use this when the +compiler doesn't provide TR1 tuple. + +Usually you don't need to care about which tuple library Google Test +uses. However, if your project already uses TR1 tuple, you need to +tell Google Test to use the same TR1 tuple library the rest of your +project uses, or the two tuple implementations will clash. To do +that, add + + -DGTEST_USE_OWN_TR1_TUPLE=0 + +to the compiler flags while compiling Google Test and your tests. If +you want to force Google Test to use its own tuple library, just add + + -DGTEST_USE_OWN_TR1_TUPLE=1 + +to the compiler flags instead. + +If you don't want Google Test to use tuple at all, add + + -DGTEST_HAS_TR1_TUPLE=0 + +and all features using tuple will be disabled. + +### Multi-threaded Tests ### + +Google Test is thread-safe where the pthread library is available. +After `#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE` +macro to see whether this is the case (yes if the macro is `#defined` to +1, no if it's undefined.). + +If Google Test doesn't correctly detect whether pthread is available +in your environment, you can force it with + + -DGTEST_HAS_PTHREAD=1 + +or + + -DGTEST_HAS_PTHREAD=0 + +When Google Test uses pthread, you may need to add flags to your +compiler and/or linker to select the pthread library, or you'll get +link errors. If you use the CMake script or the deprecated Autotools +script, this is taken care of for you. If you use your own build +script, you'll need to read your compiler and linker's manual to +figure out what flags to add. + +### As a Shared Library (DLL) ### + +Google Test is compact, so most users can build and link it as a +static library for the simplicity. You can choose to use Google Test +as a shared library (known as a DLL on Windows) if you prefer. + +To compile *gtest* as a shared library, add + + -DGTEST_CREATE_SHARED_LIBRARY=1 + +to the compiler flags. You'll also need to tell the linker to produce +a shared library instead - consult your linker's manual for how to do +it. + +To compile your *tests* that use the gtest shared library, add + + -DGTEST_LINKED_AS_SHARED_LIBRARY=1 + +to the compiler flags. + +Note: while the above steps aren't technically necessary today when +using some compilers (e.g. GCC), they may become necessary in the +future, if we decide to improve the speed of loading the library (see + for details). Therefore you are +recommended to always add the above flags when using Google Test as a +shared library. Otherwise a future release of Google Test may break +your build script. + +### Avoiding Macro Name Clashes ### + +In C++, macros don't obey namespaces. Therefore two libraries that +both define a macro of the same name will clash if you `#include` both +definitions. In case a Google Test macro clashes with another +library, you can force Google Test to rename its macro to avoid the +conflict. + +Specifically, if both Google Test and some other code define macro +FOO, you can add + + -DGTEST_DONT_DEFINE_FOO=1 + +to the compiler flags to tell Google Test to change the macro's name +from `FOO` to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, +or `TEST`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll +need to write + + GTEST_TEST(SomeTest, DoesThis) { ... } + +instead of + + TEST(SomeTest, DoesThis) { ... } + +in order to define a test. + +## Developing Google Test ## + +This section discusses how to make your own changes to Google Test. + +### Testing Google Test Itself ### + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test's own tests. +For that you can use CMake: + + mkdir mybuild + cd mybuild + cmake -Dgtest_build_tests=ON ${GTEST_DIR} + +Make sure you have Python installed, as some of Google Test's tests +are written in Python. If the cmake command complains about not being +able to find Python (`Could NOT find PythonInterp (missing: +PYTHON_EXECUTABLE)`), try telling it explicitly where your Python +executable can be found: + + cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} + +Next, you can build Google Test and all of its own tests. On \*nix, +this is usually done by 'make'. To run the tests, do + + make test + +All tests should pass. + +Normally you don't need to worry about regenerating the source files, +unless you need to modify them. In that case, you should modify the +corresponding .pump files instead and run the pump.py Python script to +regenerate them. You can find pump.py in the [scripts/](scripts/) directory. +Read the [Pump manual](docs/PumpManual.md) for how to use it. diff --git a/gtestsrc/gtest/docs/AdvancedGuide.md b/gtestsrc/gtest/docs/AdvancedGuide.md new file mode 100644 index 0000000..d85cb23 --- /dev/null +++ b/gtestsrc/gtest/docs/AdvancedGuide.md @@ -0,0 +1,2182 @@ + + +Now that you have read [Primer](Primer.md) and learned how to write tests +using Google Test, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex +failure messages, propagate fatal failures, reuse and speed up your +test fixtures, and use various flags with your tests. + +# More Assertions # + +This section covers some less frequently used, but still significant, +assertions. + +## Explicit Success and Failure ## + +These three assertions do not actually test a value or expression. Instead, +they generate a success or failure directly. Like the macros that actually +perform a test, you may stream a custom failure message into the them. + +| `SUCCEED();` | +|:-------------| + +Generates a success. This does NOT make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +Note: `SUCCEED()` is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED()` messages to Google Test's +output in the future. + +| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | +|:-----------|:-----------------|:------------------------------------------------------| + +`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal +failure. These are useful when control flow, rather than a Boolean expression, +deteremines the test's success or failure. For example, you might want to write +something like: + +``` +switch(expression) { + case 1: ... some checks ... + case 2: ... some other checks + ... + default: FAIL() << "We shouldn't get here."; +} +``` + +Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. + +_Availability_: Linux, Windows, Mac. + +## Exception Assertions ## + +These are for verifying that a piece of code throws (or does not +throw) an exception of the given type: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | +| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | +| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | + +Examples: + +``` +ASSERT_THROW(Foo(5), bar_exception); + +EXPECT_NO_THROW({ + int n = 5; + Bar(&n); +}); +``` + +_Availability_: Linux, Windows, Mac; since version 1.1.0. + +## Predicate Assertions for Better Error Messages ## + +Even though Google Test has a rich set of assertions, they can never be +complete, as it's impossible (nor a good idea) to anticipate all the scenarios +a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` +to check a complex expression, for lack of a better macro. This has the problem +of not showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +Google Test gives you three different options to solve this problem: + +### Using an Existing Boolean Function ### + +If you already have a function or a functor that returns `bool` (or a type +that can be implicitly converted to `bool`), you can use it in a _predicate +assertion_ to get the function arguments printed for free: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | +| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | +| ... | ... | ... | + +In the above, _predn_ is an _n_-ary predicate function or functor, where +_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds +if the predicate returns `true` when applied to the given arguments, and fails +otherwise. When the assertion fails, it prints the value of each argument. In +either case, the arguments are evaluated exactly once. + +Here's an example. Given + +``` +// Returns true iff m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +const int a = 3; +const int b = 4; +const int c = 10; +``` + +the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the +assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message + +
+!MutuallyPrime(b, c) is false, where
+b is 4
+c is 10
+
+ +**Notes:** + + 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. + 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. + +_Availability_: Linux, Windows, Mac + +### Using a Function That Returns an AssertionResult ### + +While `EXPECT_PRED*()` and friends are handy for a quick job, the +syntax is not satisfactory: you have to use different macros for +different arities, and it feels more like Lisp than C++. The +`::testing::AssertionResult` class solves this problem. + +An `AssertionResult` object represents the result of an assertion +(whether it's a success or a failure, and an associated message). You +can create an `AssertionResult` using one of these factory +functions: + +``` +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the +`AssertionResult` object. + +To provide more readable messages in Boolean assertions +(e.g. `EXPECT_TRUE()`), write a predicate function that returns +`AssertionResult` instead of `bool`. For example, if you define +`IsEven()` as: + +``` +::testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return ::testing::AssertionSuccess(); + else + return ::testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +``` +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +
+Value of: IsEven(Fib(4))
+Actual: false (*3 is odd*)
+Expected: true
+
+ +instead of a more opaque + +
+Value of: IsEven(Fib(4))
+Actual: false
+Expected: true
+
+ +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` +as well, and are fine with making the predicate slower in the success +case, you can supply a success message: + +``` +::testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return ::testing::AssertionSuccess() << n << " is even"; + else + return ::testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +
+Value of: IsEven(Fib(6))
+Actual: true (8 is even)
+Expected: false
+
+ +_Availability_: Linux, Windows, Mac; since version 1.4.1. + +### Using a Predicate-Formatter ### + +If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and +`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your +predicate do not support streaming to `ostream`, you can instead use the +following _predicate-formatter assertions_ to _fully_ customize how the +message is formatted: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | +| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | +| `...` | `...` | `...` | + +The difference between this and the previous two groups of macros is that instead of +a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ +(_pred\_formatn_), which is a function or functor with the signature: + +`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` + +where _val1_, _val2_, ..., and _valn_ are the values of the predicate +arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., and +`Tn` can be either value types or reference types. For example, if an +argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, +whichever is appropriate. + +A predicate-formatter returns a `::testing::AssertionResult` object to indicate +whether the assertion has succeeded or not. The only way to create such an +object is to call one of these factory functions: + +As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: + +``` +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) + return ::testing::AssertionSuccess(); + + return ::testing::AssertionFailure() + << m_expr << " and " << n_expr << " (" << m << " and " << n + << ") are not mutually prime, " << "as they have a common divisor " + << SmallestPrimeCommonDivisor(m, n); +} +``` + +With this predicate-formatter, we can use + +``` +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); +``` + +to generate the message + +
+b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
+
+ +As you may have realized, many of the assertions we introduced earlier are +special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are +indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. + +_Availability_: Linux, Windows, Mac. + + +## Floating-Point Comparison ## + +Comparing floating-point numbers is tricky. Due to round-off errors, it is +very unlikely that two floating-points will match exactly. Therefore, +`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points +can have a wide value range, no single fixed error bound works. It's better to +compare by a fixed relative error bound, except for values close to 0 due to +the loss of precision there. + +In general, for floating-point comparison to make sense, the user needs to +carefully choose the error bound. If they don't want or care to, comparing in +terms of Units in the Last Place (ULPs) is a good default, and Google Test +provides assertions to do this. Full details about ULPs are quite long; if you +want to learn more, see +[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). + +### Floating-Point Macros ### + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | +| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | + +By "almost equal", we mean the two values are within 4 ULP's from each +other. + +The following assertions allow you to choose the acceptable error bound: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | + +_Availability_: Linux, Windows, Mac. + +### Floating-Point Predicate-Format Functions ### + +Some floating-point operations are useful, but not that often used. In order +to avoid an explosion of new macros, we provide them as predicate-format +functions that can be used in predicate assertion macros (e.g. +`EXPECT_PRED_FORMAT2`, etc). + +``` +EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); +``` + +Verifies that _val1_ is less than, or almost equal to, _val2_. You can +replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. + +_Availability_: Linux, Windows, Mac. + +## Windows HRESULT assertions ## + +These assertions test for `HRESULT` success or failure. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | +| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | + +The generated output contains the human-readable error message +associated with the `HRESULT` code returned by _expression_. + +You might use them like this: + +``` +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +_Availability_: Windows. + +## Type Assertions ## + +You can call the function +``` +::testing::StaticAssertTypeEq(); +``` +to assert that types `T1` and `T2` are the same. The function does +nothing if the assertion is satisfied. If the types are different, +the function call will fail to compile, and the compiler error message +will likely (depending on the compiler) show you the actual values of +`T1` and `T2`. This is mainly useful inside template code. + +_Caveat:_ When used inside a member function of a class template or a +function template, `StaticAssertTypeEq()` is effective _only if_ +the function is instantiated. For example, given: +``` +template class Foo { + public: + void Bar() { ::testing::StaticAssertTypeEq(); } +}; +``` +the code: +``` +void Test1() { Foo foo; } +``` +will _not_ generate a compiler error, as `Foo::Bar()` is never +actually instantiated. Instead, you need: +``` +void Test2() { Foo foo; foo.Bar(); } +``` +to cause a compiler error. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +## Assertion Placement ## + +You can use assertions in any C++ function. In particular, it doesn't +have to be a method of the test fixture class. The one constraint is +that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) +can only be used in void-returning functions. This is a consequence of +Google Test not using exceptions. By placing it in a non-void function +you'll get a confusing compile error like +`"error: void value not ignored as it ought to be"`. + +If you need to use assertions in a function that returns non-void, one option +is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use +assertions that generate non-fatal failures, such as `ADD_FAILURE*` and +`EXPECT_*`. + +_Note_: Constructors and destructors are not considered void-returning +functions, according to the C++ language specification, and so you may not use +fatal assertions in them. You'll get a compilation error if you try. A simple +workaround is to transfer the entire body of the constructor or destructor to a +private void-returning method. However, you should be aware that a fatal +assertion failure in a constructor does not terminate the current test, as your +intuition might suggest; it merely returns from the constructor early, possibly +leaving your object in a partially-constructed state. Likewise, a fatal +assertion failure in a destructor may leave your object in a +partially-destructed state. Use assertions carefully in these situations! + +# Teaching Google Test How to Print Your Values # + +When a test assertion such as `EXPECT_EQ` fails, Google Test prints the +argument values to help you debug. It does this using a +user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other +types, it prints the raw bytes in the value and hopes that you the +user can figure it out. + +As mentioned earlier, the printer is _extensible_. That means +you can teach it to do a better job at printing your particular type +than to dump the bytes. To do that, define `<<` for your type: + +``` +#include + +namespace foo { + +class Bar { ... }; // We want Google Test to be able to print instances of this. + +// It's important that the << operator is defined in the SAME +// namespace that defines Bar. C++'s look-up rules rely on that. +::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +Sometimes, this might not be an option: your team may consider it bad +style to have a `<<` operator for `Bar`, or `Bar` may already have a +`<<` operator that doesn't do what you want (and you cannot change +it). If so, you can instead define a `PrintTo()` function like this: + +``` +#include + +namespace foo { + +class Bar { ... }; + +// It's important that PrintTo() is defined in the SAME +// namespace that defines Bar. C++'s look-up rules rely on that. +void PrintTo(const Bar& bar, ::std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +If you have defined both `<<` and `PrintTo()`, the latter will be used +when Google Test is concerned. This allows you to customize how the value +appears in Google Test's output without affecting code that relies on the +behavior of its `<<` operator. + +If you want to print a value `x` using Google Test's value printer +yourself, just call `::testing::PrintToString(`_x_`)`, which +returns an `std::string`: + +``` +vector > bar_ints = GetBarIntVector(); + +EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) + << "bar_ints = " << ::testing::PrintToString(bar_ints); +``` + +# Death Tests # + +In many applications, there are assertions that can cause application failure +if a condition is not met. These sanity checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test +that such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +_death tests_. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the exception +and avoid the crash. If you want to verify exceptions thrown by your code, +see [Exception Assertions](#exception-assertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). + +## How to Write a Death Test ## + +Google Test has the following macros to support death tests: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | +| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | +| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | + +where _statement_ is a statement that is expected to cause the process to +die, _predicate_ is a function or function object that evaluates an integer +exit status, and _regex_ is a regular expression that the stderr output of +_statement_ is expected to match. Note that _statement_ can be _any valid +statement_ (including _compound statement_) and doesn't have to be an +expression. + +As usual, the `ASSERT` variants abort the current test function, while the +`EXPECT` variants do not. + +**Note:** We use the word "crash" here to mean that the process +terminates with a _non-zero_ exit status code. There are two +possibilities: either the process has called `exit()` or `_exit()` +with a non-zero value, or it may be killed by a signal. + +This means that if _statement_ terminates the process with a 0 exit +code, it is _not_ considered a crash by `EXPECT_DEATH`. Use +`EXPECT_EXIT` instead if this is the case, or if you want to restrict +the exit code more precisely. + +A predicate here must accept an `int` and return a `bool`. The death test +succeeds only if the predicate returns `true`. Google Test defines a few +predicates that handle the most common cases: + +``` +::testing::ExitedWithCode(exit_code) +``` + +This expression is `true` if the program exited normally with the given exit +code. + +``` +::testing::KilledBySignal(signal_number) // Not available on Windows. +``` + +This expression is `true` if the program was killed by the given signal. + +The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate +that verifies the process' exit code is non-zero. + +Note that a death test only cares about three things: + + 1. does _statement_ abort or exit the process? + 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And + 1. does the stderr output match _regex_? + +In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. + +To write a death test, simply use one of the above macros inside your test +function. For example, + +``` +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); +} +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); +} +TEST(MyDeathTest, KillMyself) { + EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); +} +``` + +verifies that: + + * calling `Foo(5)` causes the process to die with the given error message, + * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and + * calling `KillMyself()` kills the process with signal `SIGKILL`. + +The test function body may contain other assertions and statements as well, if +necessary. + +_Important:_ We strongly recommend you to follow the convention of naming your +test case (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The `Death Tests And Threads` section below +explains why. + +If a test fixture class is shared by normal tests and death tests, you +can use typedef to introduce an alias for the fixture class and avoid +duplicating its code: +``` +class FooTest : public ::testing::Test { ... }; + +typedef FooTest FooDeathTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. + +## Regular Expression Syntax ## + +On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the +[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). + +On Windows, Google Test uses its own simple regular expression +implementation. It lacks many features you can find in POSIX extended +regular expressions. For example, we don't support union (`"x|y"`), +grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count +(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a +literal character, period (`.`), or a single `\\` escape sequence; `x` +and `y` denote regular expressions.): + +| `c` | matches any literal character `c` | +|:----|:----------------------------------| +| `\\d` | matches any decimal digit | +| `\\D` | matches any character that's not a decimal digit | +| `\\f` | matches `\f` | +| `\\n` | matches `\n` | +| `\\r` | matches `\r` | +| `\\s` | matches any ASCII whitespace, including `\n` | +| `\\S` | matches any character that's not a whitespace | +| `\\t` | matches `\t` | +| `\\v` | matches `\v` | +| `\\w` | matches any letter, `_`, or decimal digit | +| `\\W` | matches any character that `\\w` doesn't match | +| `\\c` | matches any literal character `c`, which must be a punctuation | +| `\\.` | matches the `.` character | +| `.` | matches any single character except `\n` | +| `A?` | matches 0 or 1 occurrences of `A` | +| `A*` | matches 0 or many occurrences of `A` | +| `A+` | matches 1 or many occurrences of `A` | +| `^` | matches the beginning of a string (not that of each line) | +| `$` | matches the end of a string (not that of each line) | +| `xy` | matches `x` followed by `y` | + +To help you determine which capability is available on your system, +Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX +extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses +the simple version. If you want your death tests to work in both +cases, you can either `#if` on these macros or use the more limited +syntax only. + +## How It Works ## + +Under the hood, `ASSERT_EXIT()` spawns a new process and executes the +death test statement in that process. The details of of how precisely +that happens depend on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the +command-line flag `--gtest_death_test_style`). + + * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: + * If the variable's value is `"fast"`, the death test statement is immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. + * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to +fail. Currently, the flag's default value is `"fast"`. However, we reserve the +right to change it in the future. Therefore, your tests should not depend on +this. + +In either case, the parent process waits for the child process to complete, and checks that + + 1. the child's exit status satisfies the predicate, and + 1. the child's stderr matches the regular expression. + +If the death test statement runs to completion without dying, the child +process will nonetheless terminate, and the assertion fails. + +## Death Tests And Threads ## + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +Google Test has three features intended to raise awareness of threading issues. + + 1. A warning is emitted if multiple threads are running when a death test is encountered. + 1. Test cases with a name ending in "DeathTest" are run before all other tests. + 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +## Death Test Styles ## + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. +We suggest using the faster, default "fast" style unless your test has specific +problems with it. + +You can choose a particular style of death tests by setting the flag +programmatically: + +``` +::testing::FLAGS_gtest_death_test_style = "threadsafe"; +``` + +You can do this in `main()` to set the style for all death tests in the +binary, or in individual tests. Recall that flags are saved before running each +test and restored afterwards, so you need not do that yourself. For example: + +``` +TEST(MyDeathTest, TestOne) { + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::FLAGS_gtest_death_test_style = "fast"; + return RUN_ALL_TESTS(); +} +``` + +## Caveats ## + +The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. +If it leaves the current function via a `return` statement or by throwing an exception, +the death test is considered to have failed. Some Google Test macros may return +from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. + +Since _statement_ runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will _not_ be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + + 1. try not to free memory in a death test; + 1. free the memory again in the parent process; or + 1. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test +assertions on the same line; otherwise, compilation will fail with an unobvious +error message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +# Using Assertions in Sub-routines # + +## Adding Traces to Assertions ## + +If a test sub-routine is called from several places, when an assertion +inside it fails, it can be hard to tell which invocation of the +sub-routine the failure is from. You can alleviate this problem using +extra logging or custom failure messages, but that usually clutters up +your tests. A better solution is to use the `SCOPED_TRACE` macro: + +| `SCOPED_TRACE(`_message_`);` | +|:-----------------------------| + +where _message_ can be anything streamable to `std::ostream`. This +macro will cause the current file name, line number, and the given +message to be added in every failure message. The effect will be +undone when the control leaves the current lexical scope. + +For example, + +``` +10: void Sub1(int n) { +11: EXPECT_EQ(1, Bar(n)); +12: EXPECT_EQ(2, Bar(n + 1)); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +``` +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 + Trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation +of `Sub1()` the two failures come from respectively. (You could add an +extra message to each assertion in `Sub1()` to indicate the value of +`n`, but that's tedious.) + +Some tips on using `SCOPED_TRACE`: + + 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. + 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. + 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. + 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. + 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! + +_Availability:_ Linux, Windows, Mac. + +## Propagating Fatal Failures ## + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the _current function_, not the entire test. For +example, the following test will segfault: +``` +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); + // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + // The actual behavior: the function goes on after Subroutine() returns. + int* p = NULL; + *p = 3; // Segfault! +} +``` + +Since we don't use exceptions, it is technically impossible to +implement the intended behavior here. To alleviate this, Google Test +provides two solutions. You could use either the +`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +### Asserting on Subroutines ### + +As shown above, if your test calls a subroutine that has an `ASSERT_*` +failure in it, the test will continue after the subroutine +returns. This may not be what you want. + +Often people want fatal failures to propagate like exceptions. For +that Google Test offers the following macros: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | + +Only failures in the thread that executes the assertion are checked to +determine the result of this type of assertions. If _statement_ +creates new threads, failures in these threads are ignored. + +Examples: + +``` +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +_Availability:_ Linux, Windows, Mac. Assertions from multiple threads +are currently not supported. + +### Checking for Failures in the Current Test ### + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This +allows functions to catch fatal failures in a sub-routine and return +early. + +``` +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown +exception, is: + +``` +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) + return; + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +``` +if (::testing::Test::HasFatalFailure()) + return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test +has at least one non-fatal failure, and `HasFailure()` returns `true` +if the current test has at least one failure of either kind. + +_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and +`HasFailure()` are available since version 1.4.0. + +# Logging Additional Information # + +In your test code, you can call `RecordProperty("key", value)` to log +additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output +if you specify one. For example, the test + +``` +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +``` +... + +... +``` + +_Note_: + * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. + * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). + * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. + +_Availability_: Linux, Windows, Mac. + +# Sharing Resources Between Tests in the Same Test Case # + + + +Google Test creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in them sharing a +single resource copy. So, in addition to per-test set-up/tear-down, Google Test +also supports per-test-case set-up/tear-down. To use it: + + 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. + 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. + +That's it! Google Test automatically calls `SetUpTestCase()` before running the +_first test_ in the `FooTest` test case (i.e. before creating the first +`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ +in it (i.e. after deleting the last `FooTest` object). In between, the tests +can use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the +state of any shared resource, or, if they do modify the state, they must +restore the state to its original value before passing control to the next +test. + +Here's an example of per-test-case set-up and tear-down: +``` +class FooTest : public ::testing::Test { + protected: + // Per-test-case set-up. + // Called before the first test in this test case. + // Can be omitted if not needed. + static void SetUpTestCase() { + shared_resource_ = new ...; + } + + // Per-test-case tear-down. + // Called after the last test in this test case. + // Can be omitted if not needed. + static void TearDownTestCase() { + delete shared_resource_; + shared_resource_ = NULL; + } + + // You can define per-test set-up and tear-down logic as usual. + virtual void SetUp() { ... } + virtual void TearDown() { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = NULL; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource here ... +} +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource here ... +} +``` + +_Availability:_ Linux, Windows, Mac. + +# Global Set-Up and Tear-Down # + +Just as you can do set-up and tear-down at the test level and the test case +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +``` +class Environment { + public: + virtual ~Environment() {} + // Override this to define how to set up the environment. + virtual void SetUp() {} + // Override this to define how to tear down the environment. + virtual void TearDown() {} +}; +``` + +Then, you register an instance of your environment class with Google Test by +calling the `::testing::AddGlobalTestEnvironment()` function: + +``` +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of +the environment object, then runs the tests if there was no fatal failures, and +finally calls `TearDown()` of the environment object. + +It's OK to register multiple environment objects. In this case, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that Google Test takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is +called, probably in `main()`. If you use `gtest_main`, you need to call +this before `main()` starts for it to take effect. One way to do this is to +define a global variable like this: + +``` +::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you +register multiple environments from different translation units and the +environments have dependencies among them (remember that the compiler doesn't +guarantee the order in which global variables from different translation units +are initialized). + +_Availability:_ Linux, Windows, Mac. + + +# Value Parameterized Tests # + +_Value-parameterized tests_ allow you to test your code with different +parameters without writing multiple copies of the same test. + +Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. + +``` +TEST(MyCodeTest, TestFoo) { + // A code to test foo(). +} +``` + +Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. + +``` +void TestFooHelper(bool flag_value) { + flag = flag_value; + // A code to test foo(). +} + +TEST(MyCodeTest, TestFoo) { + TestFooHelper(false); + TestFooHelper(true); +} +``` + +But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? + +Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. + +Here are some other situations when value-parameterized tests come handy: + + * You want to test different implementations of an OO interface. + * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! + +## How to Write Value-Parameterized Tests ## + +To write value-parameterized tests, first you should define a fixture +class. It must be derived from both `::testing::Test` and +`::testing::WithParamInterface` (the latter is a pure interface), +where `T` is the type of your parameter values. For convenience, you +can just derive the fixture class from `::testing::TestWithParam`, +which itself is derived from both `::testing::Test` and +`::testing::WithParamInterface`. `T` can be any copyable type. If +it's a raw pointer, you are responsible for managing the lifespan of +the pointed values. + +``` +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public ::testing::Test { + ... +}; +class BarTest : public BaseTest, + public ::testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using +this fixture as you want. The `_P` suffix is for "parameterized" or +"pattern", whichever you prefer to think. + +``` +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test +case with any set of parameters you want. Google Test defines a number of +functions for generating test parameters. They return what we call +(surprise!) _parameter generators_. Here is a summary of them, +which are all in the `testing` namespace: + +| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +|:----------------------------|:------------------------------------------------------------------------------------------------------------------| +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | + +For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). + +The following statement will instantiate tests from the `FooTest` test case +each with parameter values `"meeny"`, `"miny"`, and `"moe"`. + +``` +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + ::testing::Values("meeny", "miny", "moe")); +``` + +To distinguish different instances of the pattern (yes, you can +instantiate it more than once), the first argument to +`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual +test case name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these +names: + + * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` + * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` + * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` + * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` + * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` + * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). + +This statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"`: + +``` +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, + ::testing::ValuesIn(pets)); +``` + +The tests from the instantiation above will have these names: + + * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` + * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` + * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` + * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ +tests in the given test case, whether their definitions come before or +_after_ the `INSTANTIATE_TEST_CASE_P` statement. + +You can see +[these](../samples/sample7_unittest.cc) +[files](../samples/sample8_unittest.cc) for more examples. + +_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. + +## Creating Value-Parameterized Abstract Tests ## + +In the above, we define and instantiate `FooTest` in the same source +file. Sometimes you may want to define value-parameterized tests in a +library and let other people instantiate them later. This pattern is +known as abstract tests. As an example of its application, when you +are designing an interface you can write a standard suite of abstract +tests (perhaps using a factory function as the test parameter) that +all implementations of the interface are expected to pass. When +someone implements the interface, he can instantiate your suite to get +all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + + 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. + 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. + +Once they are defined, you can instantiate them by including +`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking +with `foo_param_test.cc`. You can instantiate the same abstract test +case multiple times, possibly in different source files. + +# Typed Tests # + +Suppose you have multiple implementations of the same interface and +want to make sure that all of them satisfy some common requirements. +Or, you may have defined several types that are supposed to conform to +the same "concept" and you want to verify it. In both cases, you want +the same test logic repeated for different types. + +While you can write one `TEST` or `TEST_F` for each type you want to +test (and you may even factor the test logic into a function template +that you invoke from the `TEST`), it's tedious and doesn't scale: +if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ +`TEST`s. + +_Typed tests_ allow you to repeat the same test logic over a list of +types. You only need to write the test logic once, although you must +know the type list when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized +by a type. Remember to derive it from `::testing::Test`: + +``` +template +class FooTest : public ::testing::Test { + public: + ... + typedef std::list List; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test case, which will be +repeated for each type in the list: + +``` +typedef ::testing::Types MyTypes; +TYPED_TEST_CASE(FooTest, MyTypes); +``` + +The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse +correctly. Otherwise the compiler will think that each comma in the +type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test +for this test case. You can repeat this as many times as you want: + +``` +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see `samples/sample6_unittest.cc` for a complete example. + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; +since version 1.1.0. + +# Type-Parameterized Tests # + +_Type-parameterized tests_ are like typed tests, except that they +don't require you to know the list of types ahead of time. Instead, +you can define the test logic first and instantiate it with different +type lists later. You can even instantiate it more than once in the +same program. + +If you are designing an interface or concept, you can define a suite +of type-parameterized tests to verify properties that any valid +implementation of the interface/concept should have. Then, the author +of each implementation can just instantiate the test suite with his +type to verify that it conforms to the requirements, without having to +write similar tests repeatedly. Here's an example: + +First, define a fixture class template, as we did with typed tests: + +``` +template +class FooTest : public ::testing::Test { + ... +}; +``` + +Next, declare that you will define a type-parameterized test case: + +``` +TYPED_TEST_CASE_P(FooTest); +``` + +The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You +can repeat this as many times as you want: + +``` +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. +The first argument of the macro is the test case name; the rest are +the names of the tests in this test case: + +``` +REGISTER_TYPED_TEST_CASE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you +want. If you put the above code in a header file, you can `#include` +it in multiple C++ source files and instantiate it multiple times. + +``` +typedef ::testing::Types MyTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument +to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be +added to the actual test case name. Remember to pick unique prefixes +for different instances. + +In the special case where the type list contains only one type, you +can write that type directly without `::testing::Types<...>`, like this: + +``` +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); +``` + +You can see `samples/sample6_unittest.cc` for a complete example. + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; +since version 1.1.0. + +# Testing Private Code # + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, per the +_black-box testing principle_, most of the time you should test your code +through its public interfaces. + +If you still find yourself needing to test internal implementation code, +consider if there's a better design that wouldn't require you to do so. If you +absolutely have to test non-public interface code though, you can. There are +two cases to consider: + + * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and + * Private or protected class members + +## Static Functions ## + +Both static functions and definitions/declarations in an unnamed namespace are +only visible within the same translation unit. To test them, you can `#include` +the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` +files is not a good way to reuse code - you should not do this in production +code!) + +However, a better approach is to move the private code into the +`foo::internal` namespace, where `foo` is the namespace your project normally +uses, and put the private declarations in a `*-internal.h` file. Your +production `.cc` files and your tests are allowed to include this internal +header, but your clients are not. This way, you can fully test your internal +implementation without leaking it to your clients. + +## Private Class Members ## + +Private class members are only accessible from within the class or by friends. +To access a class' private members, you can declare your test fixture as a +friend to the class and define accessors in your fixture. Tests using the +fixture can then access the private members of your production class via the +accessors in the fixture. Note that even though your fixture is a friend to +your production class, your tests are not automatically friends to it, as they +are technically defined in sub-classes of the fixture. + +Another way to test private members is to refactor them into an implementation +class, which is then declared in a `*-internal.h` file. Your clients aren't +allowed to include this header but your tests can. Such is called the Pimpl +(Private Implementation) idiom. + +Or, you can declare an individual test as a friend of your class by adding this +line in the class body: + +``` +FRIEND_TEST(TestCaseName, TestName); +``` + +For example, +``` +// foo.h +#include "gtest/gtest_prod.h" + +// Defines FRIEND_TEST. +class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + int Bar(void* x); +}; + +// foo_test.cc +... +TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(0, foo.Bar(NULL)); + // Uses Foo's private member Bar(). +} +``` + +Pay special attention when your class is defined in a namespace, as you should +define your test fixtures and tests in the same namespace if you want them to +be friends of your class. For example, if the code to be tested looks like: + +``` +namespace my_namespace { + +class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... + definition of the class Foo + ... +}; + +} // namespace my_namespace +``` + +Your test code should be something like: + +``` +namespace my_namespace { +class FooTest : public ::testing::Test { + protected: + ... +}; + +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +} // namespace my_namespace +``` + +# Catching Failures # + +If you are building a testing utility on top of Google Test, you'll +want to test your utility. What framework would you use to test it? +Google Test, of course. + +The challenge is to verify that your testing utility reports failures +correctly. In frameworks that report a failure by throwing an +exception, you could catch the exception and assert on it. But Google +Test doesn't use exceptions, so how do we test that a piece of code +generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. After +`#include`ing this header, you can use + +| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | +|:--------------------------------------------------| + +to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure +whose message contains the given _substring_, or use + +| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | +|:-----------------------------------------------------| + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +For technical reasons, there are some caveats: + + 1. You cannot stream a failure message to either macro. + 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. + 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. + +_Note:_ Google Test is designed with threads in mind. Once the +synchronization primitives in `"gtest/internal/gtest-port.h"` have +been implemented, Google Test will become thread-safe, meaning that +you can then use assertions in multiple threads concurrently. Before +that, however, Google Test only supports single-threaded usage. Once +thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` +will capture failures in the current thread only. If _statement_ +creates new threads, failures in these threads will be ignored. If +you want to capture failures from all threads instead, you should use +the following macros: + +| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | +|:-----------------------------------------------------------------| +| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | + +# Getting the Current Test's Name # + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The `::testing::TestInfo` +class has this information: + +``` +namespace testing { + +class TestInfo { + public: + // Returns the test case name and the test name, respectively. + // + // Do NOT delete or free the return value - it's managed by the + // TestInfo class. + const char* test_case_name() const; + const char* name() const; +}; + +} // namespace testing +``` + + +> To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the `UnitTest` singleton object: + +``` +// Gets information about the currently running test. +// Do NOT delete the returned object - it's managed by the UnitTest class. +const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); +printf("We are in test %s of test case %s.\n", + test_info->name(), test_info->test_case_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test case name in `TestCaseSetUp()`, +`TestCaseTearDown()` (where you know the test case name implicitly), or +functions called from them. + +_Availability:_ Linux, Windows, Mac. + +# Extending Google Test by Handling Test Events # + +Google Test provides an event listener API to let you receive +notifications about the progress of a test program and test +failures. The events you can listen to include the start and end of +the test program, a test case, or a test method, among others. You may +use this API to augment or replace the standard console output, +replace the XML output, or provide a completely different form of +output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +_Availability:_ Linux, Windows, Mac; since v1.4.0. + +## Defining Event Listeners ## + +To define a event listener, you subclass either +[testing::TestEventListener](../include/gtest/gtest.h#L991) +or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). +The former is an (abstract) interface, where each pure virtual method
+can be overridden to handle a test event
(For example, when a test +starts, the `OnTestStart()` method will be called.). The latter provides +an empty implementation of all methods in the interface, such that a +subclass only needs to override the methods it cares about. + +When an event is fired, its context is passed to the handler function +as an argument. The following argument types are used: + * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, + * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, + * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and + * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. + +An event handler function can examine the argument it receives to find +out interesting information about the event and the test program's +state. Here's an example: + +``` + class MinimalistPrinter : public ::testing::EmptyTestEventListener { + // Called before a test starts. + virtual void OnTestStart(const ::testing::TestInfo& test_info) { + printf("*** Test %s.%s starting.\n", + test_info.test_case_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCEED() invocation. + virtual void OnTestPartResult( + const ::testing::TestPartResult& test_part_result) { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + virtual void OnTestEnd(const ::testing::TestInfo& test_info) { + printf("*** Test %s.%s ending.\n", + test_info.test_case_name(), test_info.name()); + } + }; +``` + +## Using Event Listeners ## + +To use the event listener you have defined, add an instance of it to +the Google Test event listener list (represented by class +[TestEventListeners](../include/gtest/gtest.h#L1064) +- note the "s" at the end of the name) in your +`main()` function, before calling `RUN_ALL_TESTS()`: +``` +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + ::testing::TestEventListeners& listeners = + ::testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. Google Test takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in +effect, so its output will mingle with the output from your minimalist +printer. To suppress the default printer, just release it from the +event listener list and delete it. You can do so by adding one line: +``` + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your +tests. For more details, you can read this +[sample](../samples/sample9_unittest.cc). + +You may append more than one listener to the list. When an `On*Start()` +or `OnTestPartResult()` event is fired, the listeners will receive it in +the order they appear in the list (since new listeners are added to +the end of the list, the default text printer and the default XML +generator will receive the event first). An `On*End()` event will be +received by the listeners in the _reverse_ order. This allows output by +listeners added later to be framed by output from listeners added +earlier. + +## Generating Failures in Listeners ## + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, +`FAIL()`, etc) when processing an event. There are some restrictions: + + 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). + 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. + +When you add listeners to the listener list, you should put listeners +that handle `OnTestPartResult()` _before_ listeners that can generate +failures. This ensures that failures generated by the latter are +attributed to the right test by the former. + +We have a sample of failure-raising listener +[here](../samples/sample10_unittest.cc). + +# Running Test Programs: Advanced Options # + +Google Test test programs are ordinary executables. Once built, you can run +them directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test +program with the `--help` flag. You can also use `-h`, `-?`, or `/?` +for short. This feature is added in version 1.3.0. + +If an option is specified both by an environment variable and by a +flag, the latter takes precedence. Most of the options can also be +set/read in code: to access the value of command line flag +`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is +to set the value of a flag before calling `::testing::InitGoogleTest()` +to change the default value of the flag: +``` +int main(int argc, char** argv) { + // Disables elapsed time by default. + ::testing::GTEST_FLAG(print_time) = false; + + // This allows the user to override the flag on the command line. + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} +``` + +## Selecting Tests ## + +This section shows various options for choosing which tests to run. + +### Listing Test Names ### + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: +``` +TestCase1. + TestName1 + TestName2 +TestCase2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +_Availability:_ Linux, Windows, Mac. + +### Running a Subset of the Tests ### + +By default, a Google Test program runs all tests the user has defined. +Sometimes, you want to run only a subset of the tests (e.g. for debugging or +quickly verifying a change). If you set the `GTEST_FILTER` environment variable +or the `--gtest_filter` flag to a filter string, Google Test will only run the +tests whose full names (in the form of `TestCaseName.TestName`) match the +filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the positive patterns) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the negative patterns). A test matches the +filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + + * `./foo_test` Has no flag, and thus runs all its tests. + * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. + * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. + * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. + * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. + * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. + +_Availability:_ Linux, Windows, Mac. + +### Temporarily Disabling Tests ### + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test case, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test case name. + +For example, the following tests won't be run by Google Test, even though they +will still be compiled: + +``` +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public ::testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +_Note:_ This feature should only be used for temporary pain-relief. You still +have to fix the disabled tests at a later date. As a reminder, Google Test will +print a banner warning you if a test program contains any disabled tests. + +_Tip:_ You can easily count the number of disabled tests you have +using `grep`. This number can be used as a metric for improving your +test quality. + +_Availability:_ Linux, Windows, Mac. + +### Temporarily Enabling Disabled Tests ### + +To include [disabled tests](#temporarily-disabling-tests) in test +execution, just invoke the test program with the +`--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other +than `0`. You can combine this with the +[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select +which disabled tests to run. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +## Repeating the Tests ## + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods +in a program many times. Hopefully, a flaky test will eventually fail and give +you a chance to debug. Here's how to use it: + +| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | +|:---------------------------------|:--------------------------------------------------------| +| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | +| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | +| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | + +If your test program contains global set-up/tear-down code registered +using `AddGlobalTestEnvironment()`, it will be repeated in each +iteration as well, as the flakiness may be in it. You can also specify +the repeat count by setting the `GTEST_REPEAT` environment variable. + +_Availability:_ Linux, Windows, Mac. + +## Shuffling the Tests ## + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random +order. This helps to reveal bad dependencies between tests. + +By default, Google Test uses a random seed calculated from the current +time. Therefore you'll get a different order every time. The console +output includes the random seed value, such that you can reproduce an +order-related test failure later. To specify the random seed +explicitly, use the `--gtest_random_seed=SEED` flag (or set the +`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer +between 0 and 99999. The seed value 0 is special: it tells Google Test +to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, Google Test will pick a +different random seed and re-shuffle the tests in each iteration. + +_Availability:_ Linux, Windows, Mac; since v1.4.0. + +## Controlling Test Output ## + +This section teaches how to tweak the way test results are reported. + +### Colored Terminal Output ### + +Google Test can use colors in its terminal output to make it easier to spot +the separation between tests, and whether tests passed. + +You can set the GTEST\_COLOR environment variable or set the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let Google Test decide. When the value is `auto`, Google +Test will use colors if and only if the output goes to a terminal and (on +non-Windows platforms) the `TERM` environment variable is set to `xterm` or +`xterm-color`. + +_Availability:_ Linux, Windows, Mac. + +### Suppressing the Elapsed Time ### + +By default, Google Test prints the time it takes to run each test. To +suppress that, run the test program with the `--gtest_print_time=0` +command line flag. Setting the `GTEST_PRINT_TIME` environment +variable to `0` has the same effect. + +_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, +the default behavior is that the elapsed time is **not** printed.) + +### Generating an XML Report ### + +Google Test can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can +help you identify slow tests. + +To generate the XML report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will +create the file at the given location. You can also just use the string +`"xml"`, in which case the output can be found in the `test_detail.xml` file in +the current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), Google Test will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), Google Test will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report uses the format described here. It is based on the +`junitreport` Ant task and can be parsed by popular continuous build +systems like [Hudson](https://hudson.dev.java.net/). Since that format +was originally intended for Java, a little interpretation is required +to make it apply to Google Test tests, as shown here: + +``` + + + + + + + + + +``` + + * The root `` element corresponds to the entire test program. + * `` elements correspond to Google Test test cases. + * `` elements correspond to Google Test test functions. + +For instance, the following program + +``` +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +``` + + + + + + + + + + + + + + + +``` + +Things to note: + + * The `tests` attribute of a `` or `` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. + * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. + * Each `` element corresponds to a single failed Google Test assertion. + * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. + +_Availability:_ Linux, Windows, Mac. + +## Controlling How Failures Are Reported ## + +### Turning Assertion Failures into Break-Points ### + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. Google Test's _break-on-failure_ mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0` . Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +_Availability:_ Linux, Windows, Mac. + +### Disabling Catching Test-Thrown Exceptions ### + +Google Test can be used either with or without exceptions enabled. If +a test throws a C++ exception or (on Windows) a structured exception +(SEH), by default Google Test catches it, reports it as a test +failure, and continues with the next test method. This maximizes the +coverage of a test run. Also, on Windows an uncaught exception will +cause a pop-up window, so catching the exceptions allows you to run +the tests automatically. + +When debugging the test failures, however, you may instead want the +exceptions to be handled by the debugger, such that you can examine +the call stack when an exception is thrown. To achieve that, set the +`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the +`--gtest_catch_exceptions=0` flag when running the tests. + +**Availability**: Linux, Windows, Mac. + +### Letting Another Testing Framework Drive ### + +If you work on a project that has already been using another testing +framework and is not ready to completely switch to Google Test yet, +you can get much of Google Test's benefit by using its assertions in +your existing tests. Just change your `main()` function to look +like: + +``` +#include "gtest/gtest.h" + +int main(int argc, char** argv) { + ::testing::GTEST_FLAG(throw_on_failure) = true; + // Important: Google Test must be initialized. + ::testing::InitGoogleTest(&argc, argv); + + ... whatever your existing testing framework requires ... +} +``` + +With that, you can use Google Test assertions in addition to the +native assertions your testing framework provides, for example: + +``` +void TestFooDoesBar() { + Foo foo; + EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. + CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. +} +``` + +If a Google Test assertion fails, it will print an error message and +throw an exception, which will be treated as a failure by your host +testing framework. If you compile your code with exceptions disabled, +a failed Google Test assertion will instead exit your program with a +non-zero code, which will also signal a test failure to your test +runner. + +If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in +your `main()`, you can alternatively enable this feature by specifying +the `--gtest_throw_on_failure` flag on the command-line or setting the +`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. + +Death tests are _not_ supported when other test framework is used to organize tests. + +_Availability:_ Linux, Windows, Mac; since v1.3.0. + +## Distributing Test Functions to Multiple Machines ## + +If you have more than one machine you can use to run a test program, +you might want to run the test functions in parallel and get the +result faster. We call this technique _sharding_, where each machine +is called a _shard_. + +Google Test is compatible with test sharding. To take advantage of +this feature, your test runner (not part of Google Test) needs to do +the following: + + 1. Allocate a number of machines (shards) to run the tests. + 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. + 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. + 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. + 1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without Google Test and +thus don't understand this protocol. In order for your test runner to +figure out which test supports sharding, it can set the environment +variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a +test program supports sharding, it will create this file to +acknowledge the fact (the actual contents of the file are not +important at this time; although we may stick some useful information +in it in the future.); otherwise it will not create it. + +Here's an example to make it clear. Suppose you have a test program +`foo_test` that contains the following 5 test functions: +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` +and you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and +set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. +Then you would run the same `foo_test` on each machine. + +Google Test reserves the right to change how the work is distributed +across the shards, but here's one possible scenario: + + * Machine #0 runs `A.V` and `B.X`. + * Machine #1 runs `A.W` and `B.Y`. + * Machine #2 runs `B.Z`. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +# Fusing Google Test Source Files # + +Google Test's implementation consists of ~30 files (excluding its own +tests). Sometimes you may want them to be packaged up in two files (a +`.h` and a `.cc`) instead, such that you can easily copy them to a new +machine and start hacking there. For this we provide an experimental +Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). +Assuming you have Python 2.4 or above installed on your machine, just +go to that directory and run +``` +python fuse_gtest_files.py OUTPUT_DIR +``` + +and you should see an `OUTPUT_DIR` directory being created with files +`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain +everything you need to use Google Test. Just copy them to anywhere +you want and you are ready to write tests. You can use the +[scripts/test/Makefile](../scripts/test/Makefile) +file as an example on how to compile your tests against them. + +# Where to Go from Here # + +Congratulations! You've now learned more advanced Google Test tools and are +ready to tackle more complex testing tasks. If you want to dive even deeper, you +can read the [Frequently-Asked Questions](FAQ.md). diff --git a/gtestsrc/gtest/docs/DevGuide.md b/gtestsrc/gtest/docs/DevGuide.md new file mode 100644 index 0000000..06467a3 --- /dev/null +++ b/gtestsrc/gtest/docs/DevGuide.md @@ -0,0 +1,126 @@ + + +If you are interested in understanding the internals of Google Test, +building from source, or contributing ideas or modifications to the +project, then this document is for you. + +# Introduction # + +First, let's give you some background of the project. + +## Licensing ## + +All Google Test source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php). + +## The Google Test Community ## + +The Google Test community exists primarily through the [discussion group](http://groups.google.com/group/googletestframework) and the GitHub repository. +You are definitely encouraged to contribute to the +discussion and you can also help us to keep the effectiveness of the +group high by following and promoting the guidelines listed here. + +### Please Be Friendly ### + +Showing courtesy and respect to others is a vital part of the Google +culture, and we strongly encourage everyone participating in Google +Test development to join us in accepting nothing less. Of course, +being courteous is not the same as failing to constructively disagree +with each other, but it does mean that we should be respectful of each +other when enumerating the 42 technical reasons that a particular +proposal may not be the best choice. There's never a reason to be +antagonistic or dismissive toward anyone who is sincerely trying to +contribute to a discussion. + +Sure, C++ testing is serious business and all that, but it's also +a lot of fun. Let's keep it that way. Let's strive to be one of the +friendliest communities in all of open source. + +As always, discuss Google Test in the official GoogleTest discussion group. +You don't have to actually submit code in order to sign up. Your participation +itself is a valuable contribution. + +# Working with the Code # + +If you want to get your hands dirty with the code inside Google Test, +this is the section for you. + +## Compiling from Source ## + +Once you check out the code, you can find instructions on how to +compile it in the [README](../README.md) file. + +## Testing ## + +A testing framework is of no good if itself is not thoroughly tested. +Tests should be written for any new code, and changes should be +verified to not break existing tests before they are submitted for +review. To perform the tests, follow the instructions in +[README](../README.md) and verify that there are no failures. + +# Contributing Code # + +We are excited that Google Test is now open source, and hope to get +great patches from the community. Before you fire up your favorite IDE +and begin hammering away at that new feature, though, please take the +time to read this section and understand the process. While it seems +rigorous, we want to keep a high standard of quality in the code +base. + +## Contributor License Agreements ## + +You must sign a Contributor License Agreement (CLA) before we can +accept any code. The CLA protects you and us. + + * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). + * If you work for a company that wants to allow you to contribute your work to Google Test, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. + +## Coding Style ## + +To keep the source consistent, readable, diffable and easy to merge, +we use a fairly rigid coding style, as defined by the [google-styleguide](http://code.google.com/p/google-styleguide/) project. All patches will be expected +to conform to the style outlined [here](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). + +## Updating Generated Code ## + +Some of Google Test's source files are generated by the Pump tool (a +Python script). If you need to update such files, please modify the +source (`foo.h.pump`) and re-generate the C++ file using Pump. You +can read the PumpManual for details. + +## Submitting Patches ## + +Please do submit code. Here's what you need to do: + + 1. A submission should be a set of changes that addresses one issue in the [issue tracker](https://github.com/google/googletest/issues). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one. + 1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches. + 1. Ensure that your code adheres to the [Google Test source code style](#Coding_Style.md). + 1. Ensure that there are unit tests for your code. + 1. Sign a Contributor License Agreement. + 1. Create a Pull Request in the usual way. + +## Google Test Committers ## + +The current members of the Google Test engineering team are the only +committers at present. In the great tradition of eating one's own +dogfood, we will be requiring each new Google Test engineering team +member to earn the right to become a committer by following the +procedures in this document, writing consistently great code, and +demonstrating repeatedly that he or she truly gets the zen of Google +Test. + +# Release Process # + +We follow a typical release process: + + 1. A release branch named `release-X.Y` is created. + 1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable. + 1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch. + 1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time). + 1. Go back to step 1 to create another release branch and so on. + +--- + +This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project. Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/). diff --git a/gtestsrc/gtest/docs/Documentation.md b/gtestsrc/gtest/docs/Documentation.md new file mode 100644 index 0000000..8ca1aac --- /dev/null +++ b/gtestsrc/gtest/docs/Documentation.md @@ -0,0 +1,14 @@ +This page lists all documentation wiki pages for Google Test **(the SVN trunk version)** +-- **if you use a released version of Google Test, please read the +documentation for that specific version instead.** + + * [Primer](Primer.md) -- start here if you are new to Google Test. + * [Samples](Samples.md) -- learn from examples. + * [AdvancedGuide](AdvancedGuide.md) -- learn more about Google Test. + * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. + * [Frequently-Asked Questions](FAQ.md) -- check here before asking a question on the mailing list. + +To contribute code to Google Test, read: + + * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. + * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files. \ No newline at end of file diff --git a/gtestsrc/gtest/docs/FAQ.md b/gtestsrc/gtest/docs/FAQ.md new file mode 100644 index 0000000..5fd6cb7 --- /dev/null +++ b/gtestsrc/gtest/docs/FAQ.md @@ -0,0 +1,1087 @@ + + +If you cannot find the answer to your question here, and you have read +[Primer](Primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to +googletestframework@googlegroups.com. + +## Why should I use Google Test instead of my favorite C++ testing framework? ## + +First, let us say clearly that we don't want to get into the debate of +which C++ testing framework is **the best**. There exist many fine +frameworks for writing C++ tests, and we have tremendous respect for +the developers and users of them. We don't think there is (or will +be) a single best framework - you have to pick the right tool for the +particular task you are tackling. + +We created Google Test because we couldn't find the right combination +of features and conveniences in an existing framework to satisfy _our_ +needs. The following is a list of things that _we_ like about Google +Test. We don't claim them to be unique to Google Test - rather, the +combination of them makes Google Test the choice for us. We hope this +list can help you decide whether it is for you too. + + * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. + * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. + * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`. It doesn't require a new set of macros or special functions. + * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. + * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. + * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. + * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. + * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. + * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](AdvancedGuide.md#global-set-up-and-tear-down) and tests parameterized by [values](AdvancedGuide.md#value-parameterized-tests) or [types](docs/AdvancedGuide.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: + * expand your testing vocabulary by defining [custom predicates](AdvancedGuide.md#predicate-assertions-for-better-error-messages), + * teach Google Test how to [print your types](AdvancedGuide.md#teaching-google-test-how-to-print-your-values), + * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](AdvancedGuide.md#catching-failures), and + * reflect on the test cases or change the test output format by intercepting the [test events](AdvancedGuide.md#extending-google-test-by-handling-test-events). + +## I'm getting warnings when compiling Google Test. Would you fix them? ## + +We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. + +Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: + + * You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. + * You may be compiling on a different platform as we do. + * Your project may be using different compiler flags as we do. + +It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. + +If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. + +## Why should not test case names and test names contain underscore? ## + +Underscore (`_`) is special, as C++ reserves the following to be used by +the compiler and the standard library: + + 1. any identifier that starts with an `_` followed by an upper-case letter, and + 1. any identifier that containers two consecutive underscores (i.e. `__`) _anywhere_ in its name. + +User code is _prohibited_ from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestCaseName, TestName)` generates a class named +`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` +contains `_`? + + 1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. + 1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. + 1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid. + 1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid. + +So clearly `TestCaseName` and `TestName` cannot start or end with `_` +(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't +followed by an upper-case letter. But that's getting complicated. So +for simplicity we just say that it cannot start with `_`.). + +It may seem fine for `TestCaseName` and `TestName` to contain `_` in the +middle. However, consider this: +``` cpp +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Files_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestCaseName` +and `TestName`. The rule is more constraining than necessary, but it's +simple and easy to remember. It also gives Google Test some wiggle +room in case its implementation needs to change in the future. + +If you violate the rule, there may not be immediately consequences, +but your test may (just may) break with a new compiler (or a new +version of the compiler you are using) or with a new version of Google +Test. Therefore it's best to follow the rule. + +## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ## + +In the early days, we said that you could install +compiled Google Test libraries on `*`nix systems using `make install`. +Then every user of your machine can write tests without +recompiling Google Test. + +This seemed like a good idea, but it has a +got-cha: every user needs to compile his tests using the _same_ compiler +flags used to compile the installed Google Test libraries; otherwise +he may run into undefined behaviors (i.e. the tests can behave +strangely and may even crash for no obvious reasons). + +Why? Because C++ has this thing called the One-Definition Rule: if +two C++ source files contain different definitions of the same +class/function/variable, and you link them together, you violate the +rule. The linker may or may not catch the error (in many cases it's +not required by the C++ standard to catch the violation). If it +doesn't, you get strange run-time behaviors that are unexpected and +hard to debug. + +If you compile Google Test and your test code using different compiler +flags, they may see different definitions of the same +class/function/variable (e.g. due to the use of `#if` in Google Test). +Therefore, for your sanity, we recommend to avoid installing pre-compiled +Google Test libraries. Instead, each project should compile +Google Test itself such that it can be sure that the same flags are +used for both Google Test and the tests. + +## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ## + +(Answered by Trevor Robinson) + +Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or +`msvc\gtest.sln`. Go through the migration wizard to migrate the +solution and project files to Visual Studio 2008. Select +`Configuration Manager...` from the `Build` menu. Select `` from +the `Active solution platform` dropdown. Select `x64` from the new +platform dropdown, leave `Copy settings from` set to `Win32` and +`Create new project platforms` checked, then click `OK`. You now have +`Win32` and `x64` platform configurations, selectable from the +`Standard` toolbar, which allow you to toggle between building 32-bit or +64-bit binaries (or both at once using Batch Build). + +In order to prevent build output files from overwriting one another, +you'll need to change the `Intermediate Directory` settings for the +newly created platform configuration across all the projects. To do +this, multi-select (e.g. using shift-click) all projects (but not the +solution) in the `Solution Explorer`. Right-click one of them and +select `Properties`. In the left pane, select `Configuration Properties`, +and from the `Configuration` dropdown, select `All Configurations`. +Make sure the selected platform is `x64`. For the +`Intermediate Directory` setting, change the value from +`$(PlatformName)\$(ConfigurationName)` to +`$(OutDir)\$(ProjectName)`. Click `OK` and then build the +solution. When the build is complete, the 64-bit binaries will be in +the `msvc\x64\Debug` directory. + +## Can I use Google Test on MinGW? ## + +We haven't tested this ourselves, but Per Abrahamsen reported that he +was able to compile and install Google Test successfully when using +MinGW from Cygwin. You'll need to configure it with: + +`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"` + +You should be able to replace the `-mno-cygwin` option with direct links +to the real MinGW binaries, but we haven't tried that. + +Caveats: + + * There are many warnings when compiling. + * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW. + +We also have reports on successful cross compilation of Google Test +MinGW binaries on Linux using +[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) +on the WxWidgets site. + +Please contact `googletestframework@googlegroups.com` if you are +interested in improving the support for MinGW. + +## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ## + +Due to some peculiarity of C++, it requires some non-trivial template +meta programming tricks to support using `NULL` as an argument of the +`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where +it's most needed (otherwise we make the implementation of Google Test +harder to maintain and more error-prone than necessary). + +The `EXPECT_EQ()` macro takes the _expected_ value as its first +argument and the _actual_ value as the second. It's reasonable that +someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this +indeed was requested several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the +assertion fails, you already know that `ptr` must be `NULL`, so it +doesn't add any information to print ptr in this case. That means +`EXPECT_TRUE(ptr != NULL)` works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll +have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, +we don't have a convention on the order of the two arguments for +`EXPECT_NE`. This means using the template meta programming tricks +twice in the implementation, making it even harder to understand and +maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) library, we are +encouraging people to use the unified `EXPECT_THAT(value, matcher)` +syntax more often in tests. One significant advantage of the matcher +approach is that matchers can be easily combined to form new matchers, +while the `EXPECT_NE`, etc, macros cannot be easily +combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## Does Google Test support running tests in parallel? ## + +Test runners tend to be tightly coupled with the build/test +environment, and Google Test doesn't try to solve the problem of +running tests in parallel. Instead, we tried to make Google Test work +nicely with test runners. For example, Google Test's XML report +contains the time spent on each test, and its `gtest_list_tests` and +`gtest_filter` flags can be used for splitting the execution of test +methods into multiple processes. These functionalities can help the +test runner run the tests in parallel. + +## Why don't Google Test run the tests in different threads to speed things up? ## + +It's difficult to write thread-safe code. Most tests are not written +with thread-safety in mind, and thus may not work correctly in a +multi-threaded setting. + +If you think about it, it's already hard to make your code work when +you know what other threads are doing. It's much harder, and +sometimes even impossible, to make your code work when you don't know +what other threads are doing (remember that test methods can be added, +deleted, or modified after your test was written). If you want to run +the tests in parallel, you'd better run them in different processes. + +## Why aren't Google Test assertions implemented using exceptions? ## + +Our original motivation was to be able to use Google Test in projects +that disable exceptions. Later we realized some additional benefits +of this approach: + + 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. + 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. + 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: +``` cpp +try { ... ASSERT_TRUE(...) ... } +catch (...) { ... } +``` +The above code will pass even if the `ASSERT_TRUE` throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. + +The downside of not using exceptions is that `ASSERT_*` (implemented +using `return`) will only abort the current function, not the current +`TEST`. + +## Why do we use two different macros for tests with and without fixtures? ## + +Unfortunately, C++'s macro system doesn't allow us to use the same +macro for both cases. One possibility is to provide only one macro +for tests with fixtures, and require the user to define an empty +fixture sometimes: + +``` cpp +class FooTest : public ::testing::Test {}; + +TEST_F(FooTest, DoesThis) { ... } +``` +or +``` cpp +typedef ::testing::Test FooTest; + +TEST_F(FooTest, DoesThat) { ... } +``` + +Yet, many people think this is one line too many. :-) Our goal was to +make it really easy to write tests, so we tried to make simple tests +trivial to create. That means using a separate macro for such tests. + +We think neither approach is ideal, yet either of them is reasonable. +In the end, it probably doesn't matter much either way. + +## Why don't we use structs as test fixtures? ## + +We like to use structs only when representing passive data. This +distinction between structs and classes is good for documenting the +intent of the code's author. Since test fixtures have logic like +`SetUp()` and `TearDown()`, they are better defined as classes. + +## Why are death tests implemented as assertions instead of using a test runner? ## + +Our goal was to make death tests as convenient for a user as C++ +possibly allows. In particular: + + * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. + * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. + * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: +``` cpp + if (FooCondition()) { + ASSERT_DEATH(Bar(), "blah"); + } else { + ASSERT_EQ(5, Bar()); + } +``` +If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. + * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, +``` cpp + const int count = GetCount(); // Only known at run time. + for (int i = 1; i <= count; i++) { + ASSERT_DEATH({ + double* buffer = new double[i]; + ... initializes buffer ... + Foo(buffer, i) + }, "blah blah"); + } +``` +The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. + +Another interesting thing about `ASSERT_DEATH` is that it calls `fork()` +to create a child process to run the death test. This is lightening +fast, as `fork()` uses copy-on-write pages and incurs almost zero +overhead, and the child process starts from the user-supplied +statement directly, skipping all global and local initialization and +any code leading to the given statement. If you launch the child +process from scratch, it can take seconds just to load everything and +start running if the test links to many libraries dynamically. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## + +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their +respective sub-processes, but not in the parent process. You can think of them +as running in a parallel universe, more or less. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ## + +If your class has a static data member: + +``` cpp +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +You also need to define it _outside_ of the class body in `foo.cc`: + +``` cpp +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc) +will generate an "undefined reference" linker error. + +## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ## + +Google Test doesn't yet have good support for this kind of tests, or +data-driven tests in general. We hope to be able to make improvements in this +area soon. + +## Can I derive a test fixture from another? ## + +Yes. + +Each test fixture has a corresponding and same named test case. This means only +one test case can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test cases don't leak +important system resources like fonts and brushes. + +In Google Test, you share a fixture among test cases by putting the shared +logic in a base test fixture, then deriving from that base a separate fixture +for each test case that wants to use this common logic. You then use `TEST_F()` +to write tests using each derived fixture. + +Typically, your code looks like this: + +``` cpp +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + virtual void SetUp() { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + virtual void TearDown() { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +Google Test has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5](../samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? ## + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions. + +## My death test hangs (or seg-faults). How do I fix it? ## + +In Google Test, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work. +Please make sure you have read this. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads +outside of `EXPECT_DEATH()`. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death +test style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there is no race conditions or dead locks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ## + +The first thing to remember is that Google Test does not reuse the +same test fixture object across multiple tests. For each `TEST_F`, +Google Test will create a fresh test fixture object, _immediately_ +call `SetUp()`, run the test body, call `TearDown()`, and then +_immediately_ delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have +the choice between using the test fixture constructor/destructor or +`SetUp()/TearDown()`. The former is usually preferred, as it has the +following benefits: + + * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct. + * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment. + +You may still want to use `SetUp()/TearDown()` in the following rare cases: + * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. + * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. + * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`. + +## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## + +If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is +overloaded or a template, the compiler will have trouble figuring out which +overloaded version it should use. `ASSERT_PRED_FORMAT*` and +`EXPECT_PRED_FORMAT*` don't have this problem. + +If you see this error, you might want to switch to +`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure +message. If, however, that is not an option, you can resolve the problem by +explicitly telling the compiler which version to pick. + +For example, suppose you have + +``` cpp +bool IsPositive(int n) { + return n > 0; +} +bool IsPositive(double x) { + return x > 0; +} +``` + +you will get a compiler error if you write + +``` cpp +EXPECT_PRED1(IsPositive, 5); +``` + +However, this will work: + +``` cpp +EXPECT_PRED1(*static_cast*(IsPositive), 5); +``` + +(The stuff inside the angled brackets for the `static_cast` operator is the +type of the function pointer for the `int`-version of `IsPositive()`.) + +As another example, when you have a template function + +``` cpp +template +bool IsNegative(T x) { + return x < 0; +} +``` + +you can use it in a predicate assertion like this: + +``` cpp +ASSERT_PRED1(IsNegative**, -5); +``` + +Things are more interesting if your template has more than one parameters. The +following won't compile: + +``` cpp +ASSERT_PRED2(*GreaterThan*, 5, 0); +``` + + +as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, +which is one more than expected. The workaround is to wrap the predicate +function in parentheses: + +``` cpp +ASSERT_PRED2(*(GreaterThan)*, 5, 0); +``` + + +## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ## + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +``` cpp +return RUN_ALL_TESTS(); +``` + +they write + +``` cpp +RUN_ALL_TESTS(); +``` + +This is wrong and dangerous. A test runner needs to see the return value of +`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` +function ignores it, your test will be considered successful even if it has a +Google Test assertion failure. Very bad. + +To help the users avoid this dangerous bug, the implementation of +`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is +ignored. If you see this warning, the fix is simple: just make sure its value +is used as the return value of `main()`. + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ## + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +``` cpp +ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This section in the user's guide explains +it. + +## My set-up function is not called. Why? ## + +C++ is case-sensitive. It should be spelled as `SetUp()`. Did you +spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and +wonder why it's never called. + +## How do I jump to the line of a failure in Emacs directly? ## + +Google Test's failure message format is understood by Emacs and many other +IDEs, like acme and XCode. If a Google Test message is in a compilation buffer +in Emacs, then it's clickable. You can now hit `enter` on a message to jump to +the corresponding source code, or use `C-x `` to jump to the next failure. + +## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## + +You don't have to. Instead of + +``` cpp +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: +``` cpp +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## The Google Test output is buried in a whole bunch of log messages. What do I do? ## + +The Google Test output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the Google Test +output, making it hard to read. However, there is an easy solution to this +problem. + +Since most log messages go to stderr, we decided to let Google Test output go +to stdout. This way, you can easily separate the two using redirection. For +example: +``` +./my_test > googletest_output.txt +``` + +## Why should I prefer test fixtures over global variables? ## + +There are several good reasons: + 1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. + 1. Global variables pollute the global namespace. + 1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. + +## How do I test private class members without writing FRIEND\_TEST()s? ## + +You should try to write testable code, which means classes should be easily +tested from their public interface. One way to achieve this is the Pimpl idiom: +you move all private members of a class into a helper class, and make all +members of the helper class public. + +You have several other options that don't require using `FRIEND_TEST`: + * Write the tests as members of the fixture class: +``` cpp +class Foo { + friend class FooTest; + ... +}; + +class FooTest : public ::testing::Test { + protected: + ... + void Test1() {...} // This accesses private members of class Foo. + void Test2() {...} // So does this one. +}; + +TEST_F(FooTest, Test1) { + Test1(); +} + +TEST_F(FooTest, Test2) { + Test2(); +} +``` + * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: +``` cpp +class Foo { + friend class FooTest; + ... +}; + +class FooTest : public ::testing::Test { + protected: + ... + T1 get_private_member1(Foo* obj) { + return obj->private_member1_; + } +}; + +TEST_F(FooTest, Test1) { + ... + get_private_member1(x) + ... +} +``` + * If the methods are declared **protected**, you can change their access level in a test-only subclass: +``` cpp +class YourClass { + ... + protected: // protected access for testability. + int DoSomethingReturningInt(); + ... +}; + +// in the your_class_test.cc file: +class TestableYourClass : public YourClass { + ... + public: using YourClass::DoSomethingReturningInt; // changes access rights + ... +}; + +TEST_F(YourClassTest, DoSomethingTest) { + TestableYourClass obj; + assertEquals(expected_value, obj.DoSomethingReturningInt()); +} +``` + +## How do I test private class static members without writing FRIEND\_TEST()s? ## + +We find private static methods clutter the header file. They are +implementation details and ideally should be kept out of a .h. So often I make +them free functions instead. + +Instead of: +``` cpp +// foo.h +class Foo { + ... + private: + static bool Func(int n); +}; + +// foo.cc +bool Foo::Func(int n) { ... } + +// foo_test.cc +EXPECT_TRUE(Foo::Func(12345)); +``` + +You probably should better write: +``` cpp +// foo.h +class Foo { + ... +}; + +// foo.cc +namespace internal { + bool Func(int n) { ... } +} + +// foo_test.cc +namespace internal { + bool Func(int n); +} + +EXPECT_TRUE(internal::Func(12345)); +``` + +## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## + +No. You can use a feature called [value-parameterized tests](AdvancedGuide.md#Value_Parameterized_Tests) which +lets you repeat your tests with different parameters, without defining it more than once. + +## How do I test a file that defines main()? ## + +To test a `foo.cc` file, you need to compile and link it into your unit test +program. However, when the file contains a definition for the `main()` +function, it will clash with the `main()` of your unit test, and will result in +a build error. + +The right solution is to split it into three files: + 1. `foo.h` which contains the declarations, + 1. `foo.cc` which contains the definitions except `main()`, and + 1. `foo_main.cc` which contains nothing but the definition of `main()`. + +Then `foo.cc` can be easily tested. + +If you are adding tests to an existing file and don't want an intrusive change +like this, there is a hack: just include the entire `foo.cc` file in your unit +test. For example: +``` cpp +// File foo_unittest.cc + +// The headers section +... + +// Renames main() in foo.cc to make room for the unit test main() +#define main FooMain + +#include "a/b/foo.cc" + +// The tests start here. +... +``` + + +However, please remember this is a hack and should only be used as the last +resort. + +## What can the statement argument in ASSERT\_DEATH() be? ## + +`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used +wherever `_statement_` is valid. So basically `_statement_` can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + * a simple function call (often the case), + * a complex expression, or + * a compound statement. + +Some examples are shown here: + +``` cpp +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used any where in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors");} +``` + +`googletest_unittest.cc` contains more examples if you are interested. + +## What syntax does the regular expression in ASSERT\_DEATH use? ## + +On POSIX systems, Google Test uses the POSIX Extended regular +expression syntax +(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). +On Windows, it uses a limited variant of regular expression +syntax. For more details, see the +[regular expression syntax](AdvancedGuide.md#Regular_Expression_Syntax). + +## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## + +Google Test needs to be able to create objects of your test fixture class, so +it must have a default constructor. Normally the compiler will define one for +you. However, there are cases where you have to define your own: + * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty. + * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does ASSERT\_DEATH complain about previous threads that were already joined? ## + +With the Linux pthread library, there is no turning back once you cross the +line from single thread to multiple threads. The first time you create a +thread, a manager thread is created in addition, so you get 3, not 2, threads. +Later when the thread you create joins the main thread, the thread count +decrements by 1, but the manager thread will never be killed, so you still have +2 threads, which means you cannot safely run a death test. + +The new NPTL thread library doesn't suffer from this problem, as it doesn't +create a manager thread. However, if you don't control which machine your test +runs on, you shouldn't depend on this. + +## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ## + +Google Test does not interleave tests from different test cases. That is, it +runs all tests in one test case first, and then runs all tests in the next test +case, and so on. Google Test does this because it needs to set up a test case +before the first test in it is run, and tear it down afterwords. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +``` cpp +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test cases, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ## + +You don't have to, but if you like, you may split up the test case into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +``` cpp +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef FooTest FooDeathTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ## + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the _same_ name space. + +## How do I suppress the memory leak messages on Windows? ## + +Since the statically initialized Google Test singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ## + +You may get a number of the following linker error or warnings if you +attempt to link your test project with the Google Test library when +your project and the are not built using the same compiler settings. + + * LNK2005: symbol already defined in object + * LNK4217: locally defined symbol 'symbol' imported in function 'function' + * LNK4049: locally defined symbol 'symbol' imported + +The Google Test project (gtest.vcproj) has the Runtime Library option +set to /MT (use multi-threaded static libraries, /MTd for debug). If +your project uses something else, for example /MD (use multi-threaded +DLLs, /MDd for debug), you need to change the setting in the Google +Test project to match your project's. + +To update this setting open the project properties in the Visual +Studio IDE then select the branch Configuration Properties | C/C++ | +Code Generation and change the option "Runtime Library". You may also try +using gtest-md.vcproj instead of gtest.vcproj. + +## I put my tests in a library and Google Test doesn't run them. What's happening? ## +Have you read a +[warning](Primer.md#important-note-for-visual-c-users) on +the Google Test Primer page? + +## I want to use Google Test with Visual Studio but don't know where to start. ## +Many people are in your position and one of the posted his solution to +our mailing list. + +## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ## +Google Test uses parts of the standard C++ library that SunStudio does not support. +Our users reported success using alternative implementations. Try running the build after runing this commad: + +`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'` + +## How can my code detect if it is running in a test? ## + +If you write code that sniffs whether it's running in a test and does +different things accordingly, you are leaking test-only logic into +production code and there is no easy way to ensure that the test-only +code paths aren't run by mistake in production. Such cleverness also +leads to +[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug). +Therefore we strongly advise against the practice, and Google Test doesn't +provide a way to do it. + +In general, the recommended way to cause the code to behave +differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html). +You can inject different functionality from the test and from the +production code. Since your production code doesn't link in the +for-test logic at all, there is no danger in accidentally running it. + +However, if you _really_, _really_, _really_ have no choice, and if +you follow the rule of ending your test program names with `_test`, +you can use the _horrible_ hack of sniffing your executable name +(`argv[0]` in `main()`) to know whether the code is under test. + +## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ## + +In C++, macros don't obey namespaces. Therefore two libraries that +both define a macro of the same name will clash if you `#include` both +definitions. In case a Google Test macro clashes with another +library, you can force Google Test to rename its macro to avoid the +conflict. + +Specifically, if both Google Test and some other code define macro +`FOO`, you can add +``` + -DGTEST_DONT_DEFINE_FOO=1 +``` +to the compiler flags to tell Google Test to change the macro's name +from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write +``` cpp + GTEST_TEST(SomeTest, DoesThis) { ... } +``` +instead of +``` cpp + TEST(SomeTest, DoesThis) { ... } +``` +in order to define a test. + +Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. + + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ## + +Yes. + +The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). + +``` cpp +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo +``` + +However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. + +``` cpp +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo +``` + +## How do I build Google Testing Framework with Xcode 4? ## + +If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like +"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this. + +## My question is not covered in your FAQ! ## + +If you cannot find the answer to your question in this FAQ, there are +some other resources you can use: + + 1. read other [wiki pages](../docs), + 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework), + 1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.). + +Please note that creating an issue in the +[issue tracker](https://github.com/google/googletest/issues) is _not_ +a good way to get your answer, as it is monitored infrequently by a +very small number of people. + +When asking a question, it's helpful to provide as much of the +following information as possible (people cannot help you if there's +not enough information in your question): + + * the version (or the commit hash if you check out from Git directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), + * your operating system, + * the name and version of your compiler, + * the complete command line flags you give to your compiler, + * the complete compiler error messages (if the question is about compilation), + * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/gtestsrc/gtest/docs/Primer.md b/gtestsrc/gtest/docs/Primer.md new file mode 100644 index 0000000..474c1d2 --- /dev/null +++ b/gtestsrc/gtest/docs/Primer.md @@ -0,0 +1,502 @@ + + +# Introduction: Why Google C++ Testing Framework? # + +_Google C++ Testing Framework_ helps you write better C++ tests. + +No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, +Google Test can help you. + +So what makes a good test, and how does Google C++ Testing Framework fit in? We believe: + 1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging. + 1. Tests should be well _organized_ and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. + 1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.) + 1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. + 1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. + 1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. + +Since Google C++ Testing Framework is based on the popular xUnit +architecture, you'll feel right at home if you've used JUnit or PyUnit before. +If not, it will take you about 10 minutes to learn the basics and get started. +So let's go! + +_Note:_ We sometimes refer to Google C++ Testing Framework informally +as _Google Test_. + +# Setting up a New Test Project # + +To write a test program using Google Test, you need to compile Google +Test into a library and link your test with it. We provide build +files for some popular build systems: `msvc/` for Visual Studio, +`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland +C++ Builder, and the autotools script (deprecated) and +`CMakeLists.txt` for CMake (recommended) in the Google Test root +directory. If your build system is not on this list, you can take a +look at `make/Makefile` to learn how Google Test should be compiled +(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT` +and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT` +is the Google Test root directory). + +Once you are able to compile the Google Test library, you should +create a project or build target for your test program. Make sure you +have `GTEST_ROOT/include` in the header search path so that the +compiler can find `"gtest/gtest.h"` when compiling your test. Set up +your test project to link with the Google Test library (for example, +in Visual Studio, this is done by adding a dependency on +`gtest.vcproj`). + +If you still have questions, take a look at how Google Test's own +tests are built and use them as examples. + +# Basic Concepts # + +When using Google Test, you start by writing _assertions_, which are statements +that check whether a condition is true. An assertion's result can be _success_, +_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts +the current function; otherwise the program continues normally. + +_Tests_ use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it _fails_; otherwise it _succeeds_. + +A _test case_ contains one or many tests. You should group your tests into test +cases that reflect the structure of the tested code. When multiple tests in a +test case need to share common objects and subroutines, you can put them into a +_test fixture_ class. + +A _test program_ can contain multiple test cases. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test cases. + +# Assertions # + +Google Test assertions are macros that resemble function calls. You test a +class or function by making assertions about its behavior. When an assertion +fails, Google Test prints the assertion's source file and line number location, +along with a failure message. You may also supply a custom failure message +which will be appended to Google Test's message. + +The assertions come in pairs that test the same thing but have different +effects on the current function. `ASSERT_*` versions generate fatal failures +when they fail, and **abort the current function**. `EXPECT_*` versions generate +nonfatal failures, which don't abort the current function. Usually `EXPECT_*` +are preferred, as they allow more than one failures to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when +the assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so +keep this in mind if you get a heap checker error in addition to assertion +errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator, or a sequence of such operators. An example: +``` +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +## Basic Assertions ## + +These assertions do basic true/false condition testing. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_TRUE(`_condition_`)`; | `EXPECT_TRUE(`_condition_`)`; | _condition_ is true | +| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`; | _condition_ is false | + +Remember, when they fail, `ASSERT_*` yields a fatal failure and +returns from the current function, while `EXPECT_*` yields a nonfatal +failure, allowing the function to continue running. In either case, an +assertion failure means its containing test fails. + +_Availability_: Linux, Windows, Mac. + +## Binary Comparison ## + +This section describes assertions that compare two values. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ | +|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ | +|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ | +|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ | +|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ | +|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ | + +In the event of a failure, Google Test prints both _val1_ and _val2_. + +Value arguments must be comparable by the assertion's comparison +operator or you'll get a compiler error. We used to require the +arguments to support the `<<` operator for streaming to an `ostream`, +but it's no longer necessary since v1.6.0 (if `<<` is supported, it +will be called to print the arguments when the assertion fails; +otherwise Google Test will attempt to print them in the best way it +can. For more details and how to customize the printing of the +arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).). + +These assertions can work with a user-defined type, but only if you define the +corresponding comparison operator (e.g. `==`, `<`, etc). If the corresponding +operator is defined, prefer using the `ASSERT_*()` macros because they will +print out not only the result of the comparison, but the two operands as well. + +Arguments are always evaluated exactly once. Therefore, it's OK for the +arguments to have side effects. However, as with any ordinary C/C++ function, +the arguments' evaluation order is undefined (i.e. the compiler is free to +choose any order) and your code should not depend on any particular argument +evaluation order. + +`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it +tests if they are in the same memory location, not if they have the same value. +Therefore, if you want to compare C strings (e.g. `const char*`) by value, use +`ASSERT_STREQ()` , which will be described later on. In particular, to assert +that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to +compare two `string` objects, you should use `ASSERT_EQ`. + +Macros in this section work with both narrow and wide string objects (`string` +and `wstring`). + +_Availability_: Linux, Windows, Mac. + +_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as +`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. +Now `*_EQ` treats both parameters in the same way. + +## String Comparison ## + +The assertions in this group compare two **C strings**. If you want to compare +two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_STREQ(`_str1_`, `_str2_`);` | `EXPECT_STREQ(`_str1_`, `_str_2`);` | the two C strings have the same content | +| `ASSERT_STRNE(`_str1_`, `_str2_`);` | `EXPECT_STRNE(`_str1_`, `_str2_`);` | the two C strings have different content | +| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case | +| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case | + +Note that "CASE" in an assertion name means that case is ignored. + +`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a +comparison of two wide strings fails, their values will be printed as UTF-8 +narrow strings. + +A `NULL` pointer and an empty string are considered _different_. + +_Availability_: Linux, Windows, Mac. + +See also: For more string comparison tricks (substring, prefix, suffix, and +regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md). + +# Simple Tests # + +To create a test: + 1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value. + 1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values. + 1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. + +``` +TEST(test_case_name, test_name) { + ... test body ... +} +``` + + +`TEST()` arguments go from general to specific. The _first_ argument is the +name of the test case, and the _second_ argument is the test's name within the +test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its +individual name. Tests from different test cases can have the same individual +name. + +For example, let's take a simple integer function: +``` +int Factorial(int n); // Returns the factorial of n +``` + +A test case for this function might look like: +``` +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(1, Factorial(0)); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(1, Factorial(1)); + EXPECT_EQ(2, Factorial(2)); + EXPECT_EQ(6, Factorial(3)); + EXPECT_EQ(40320, Factorial(8)); +} +``` + +Google Test groups the test results by test cases, so logically-related tests +should be in the same test case; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +case `FactorialTest`. + +_Availability_: Linux, Windows, Mac. + +# Test Fixtures: Using the Same Data Configuration for Multiple Tests # + +If you find yourself writing two or more tests that operate on similar data, +you can use a _test fixture_. It allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture, just: + 1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes. + 1. Inside the class, declare any objects you plan to use. + 1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you. + 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). + 1. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: +``` +TEST_F(test_case_name, test_name) { + ... test body ... +} +``` + +Like `TEST()`, the first argument is the test case name, but for `TEST_F()` +this must be the name of the test fixture class. You've probably guessed: `_F` +is for fixture. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, Google Test will: + 1. Create a _fresh_ test fixture at runtime + 1. Immediately initialize it via `SetUp()` , + 1. Run the test + 1. Clean up by calling `TearDown()` + 1. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which +has the following interface: +``` +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. +``` +class QueueTest : public ::testing::Test { + protected: + virtual void SetUp() { + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // virtual void TearDown() {} + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, `TearDown()` is not needed since we don't have to clean up after +each test, other than what's already done by the destructor. + +Now we'll write tests using `TEST_F()` and this fixture. +``` +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(0, q0_.size()); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(NULL, n); + + n = q1_.Dequeue(); + ASSERT_TRUE(n != NULL); + EXPECT_EQ(1, *n); + EXPECT_EQ(0, q1_.size()); + delete n; + + n = q2_.Dequeue(); + ASSERT_TRUE(n != NULL); + EXPECT_EQ(2, *n); + EXPECT_EQ(1, q2_.size()); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors +after the assertion failure, and use `ASSERT_*` when continuing after failure +doesn't make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later, +which would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + 1. Google Test constructs a `QueueTest` object (let's call it `t1` ). + 1. `t1.SetUp()` initializes `t1` . + 1. The first test ( `IsEmptyInitially` ) runs on `t1` . + 1. `t1.TearDown()` cleans up after the test finishes. + 1. `t1` is destructed. + 1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test. + +_Availability_: Linux, Windows, Mac. + +_Note_: Google Test automatically saves all _Google Test_ flags when a test +object is constructed, and restores them when it is destructed. + +# Invoking the Tests # + +`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + 1. Saves the state of all Google Test flags. + 1. Creates a test fixture object for the first test. + 1. Initializes it via `SetUp()`. + 1. Runs the test on the fixture object. + 1. Cleans up the fixture via `TearDown()`. + 1. Deletes the fixture. + 1. Restores the state of all Google Test flags. + 1. Repeats the above steps for the next test, until all tests have run. + +In addition, if the text fixture's constructor generates a fatal failure in +step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, +if step 3 generates a fatal failure, step 4 will be skipped. + +_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc` +will give you a compiler error. The rationale for this design is that the +automated testing service determines whether a test has passed based on its +exit code, not on its stdout/stderr output; thus your `main()` function must +return the value of `RUN_ALL_TESTS()`. + +Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once +conflicts with some advanced Google Test features (e.g. thread-safe death +tests) and thus is not supported. + +_Availability_: Linux, Windows, Mac. + +# Writing the main() Function # + +You can start from this boilerplate: +``` +#include "this/package/foo.h" +#include "gtest/gtest.h" + +namespace { + +// The fixture for testing class Foo. +class FooTest : public ::testing::Test { + protected: + // You can remove any or all of the following functions if its body + // is empty. + + FooTest() { + // You can do set-up work for each test here. + } + + virtual ~FooTest() { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + virtual void SetUp() { + // Code here will be called immediately after the constructor (right + // before each test). + } + + virtual void TearDown() { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Objects declared here can be used by all tests in the test case for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const string input_filepath = "this/package/testdata/myinputfile.dat"; + const string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `::testing::InitGoogleTest()` function parses the command line for Google +Test flags, and removes all recognized flags. This allows the user to control a +test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md). +You must call this function before calling `RUN_ALL_TESTS()`, or the flags +won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go. + +## Important note for Visual C++ users ## +If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function: +``` +__declspec(dllexport) int PullInMyLibrary() { return 0; } +``` +If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function: +``` +int PullInMyLibrary(); +static int dummy = PullInMyLibrary(); +``` +This will keep your tests referenced and will make them register themselves at startup. + +In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable. + +There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries! + +# Where to Go from Here # + +Congratulations! You've learned the Google Test basics. You can start writing +and running Google Test tests, read some [samples](Samples.md), or continue with +[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features. + +# Known Limitations # + +Google Test is designed to be thread-safe. The implementation is +thread-safe on systems where the `pthreads` library is available. It +is currently _unsafe_ to use Google Test assertions from two threads +concurrently on other systems (e.g. Windows). In most tests this is +not an issue as usually the assertions are done in the main thread. If +you want to help, you can volunteer to implement the necessary +synchronization primitives in `gtest-port.h` for your platform. diff --git a/gtestsrc/gtest/docs/PumpManual.md b/gtestsrc/gtest/docs/PumpManual.md new file mode 100644 index 0000000..8184f15 --- /dev/null +++ b/gtestsrc/gtest/docs/PumpManual.md @@ -0,0 +1,177 @@ + + +Pump is Useful for Meta Programming. + +# The Problem # + +Template and macro libraries often need to define many classes, +functions, or macros that vary only (or almost only) in the number of +arguments they take. It's a lot of repetitive, mechanical, and +error-prone work. + +Variadic templates and variadic macros can alleviate the problem. +However, while both are being considered by the C++ committee, neither +is in the standard yet or widely supported by compilers. Thus they +are often not a good choice, especially when your code needs to be +portable. And their capabilities are still limited. + +As a result, authors of such libraries often have to write scripts to +generate their implementation. However, our experience is that it's +tedious to write such scripts, which tend to reflect the structure of +the generated code poorly and are often hard to read and edit. For +example, a small change needed in the generated code may require some +non-intuitive, non-trivial changes in the script. This is especially +painful when experimenting with the code. + +# Our Solution # + +Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta +Programming, or Practical Utility for Meta Programming, whichever you +prefer) is a simple meta-programming tool for C++. The idea is that a +programmer writes a `foo.pump` file which contains C++ code plus meta +code that manipulates the C++ code. The meta code can handle +iterations over a range, nested iterations, local meta variable +definitions, simple arithmetic, and conditional expressions. You can +view it as a small Domain-Specific Language. The meta language is +designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, +for example) and concise, making Pump code intuitive and easy to +maintain. + +## Highlights ## + + * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. + * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. + * The format is human-readable and more concise than XML. + * The format works relatively well with Emacs' C++ mode. + +## Examples ## + +The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): + +``` +$var n = 3 $$ Defines a meta variable n. +$range i 0..n $$ Declares the range of meta iterator i (inclusive). +$for i [[ + $$ Meta loop. +// Foo$i does blah for $i-ary predicates. +$range j 1..i +template +class Foo$i { +$if i == 0 [[ + blah a; +]] $elif i <= 2 [[ + blah b; +]] $else [[ + blah c; +]] +}; + +]] +``` + +will be translated by the Pump compiler to: + +``` +// Foo0 does blah for 0-ary predicates. +template +class Foo0 { + blah a; +}; + +// Foo1 does blah for 1-ary predicates. +template +class Foo1 { + blah b; +}; + +// Foo2 does blah for 2-ary predicates. +template +class Foo2 { + blah b; +}; + +// Foo3 does blah for 3-ary predicates. +template +class Foo3 { + blah c; +}; +``` + +In another example, + +``` +$range i 1..n +Func($for i + [[a$i]]); +$$ The text between i and [[ is the separator between iterations. +``` + +will generate one of the following lines (without the comments), depending on the value of `n`: + +``` +Func(); // If n is 0. +Func(a1); // If n is 1. +Func(a1 + a2); // If n is 2. +Func(a1 + a2 + a3); // If n is 3. +// And so on... +``` + +## Constructs ## + +We support the following meta programming constructs: + +| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | +|:----------------|:-----------------------------------------------------------------------------------------------| +| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | +| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | +| `$($)` | Generates a single `$` character. | +| `$id` | Value of the named constant or iteration variable. | +| `$(exp)` | Value of the expression. | +| `$if exp [[ code ]] else_branch` | Conditional. | +| `[[ code ]]` | Meta lexical block. | +| `cpp_code` | Raw C++ code. | +| `$$ comment` | Meta comment. | + +**Note:** To give the user some freedom in formatting the Pump source +code, Pump ignores a new-line character if it's right after `$for foo` +or next to `[[` or `]]`. Without this rule you'll often be forced to write +very long lines to get the desired output. Therefore sometimes you may +need to insert an extra new-line in such places for a new-line to show +up in your output. + +## Grammar ## + +``` +code ::= atomic_code* +atomic_code ::= $var id = exp + | $var id = [[ code ]] + | $range id exp..exp + | $for id sep [[ code ]] + | $($) + | $id + | $(exp) + | $if exp [[ code ]] else_branch + | [[ code ]] + | cpp_code +sep ::= cpp_code | empty_string +else_branch ::= $else [[ code ]] + | $elif exp [[ code ]] else_branch + | empty_string +exp ::= simple_expression_in_Python_syntax +``` + +## Code ## + +You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still +very unpolished and lacks automated tests, although it has been +successfully used many times. If you find a chance to use it in your +project, please let us know what you think! We also welcome help on +improving Pump. + +## Real Examples ## + +You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. + +## Tips ## + + * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. + * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. diff --git a/gtestsrc/gtest/docs/Samples.md b/gtestsrc/gtest/docs/Samples.md new file mode 100644 index 0000000..f21d200 --- /dev/null +++ b/gtestsrc/gtest/docs/Samples.md @@ -0,0 +1,14 @@ +If you're like us, you'd like to look at some Google Test sample code. The +[samples folder](../samples) has a number of well-commented samples showing how to use a +variety of Google Test features. + + * [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions. + * [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions. + * [Sample #3](../samples/sample3_unittest.cc) uses a test fixture. + * [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test. + * [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it. + * [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests. + * [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests. + * [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests. + * [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results. + * [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker. diff --git a/gtestsrc/gtest/docs/XcodeGuide.md b/gtestsrc/gtest/docs/XcodeGuide.md new file mode 100644 index 0000000..1294d6c --- /dev/null +++ b/gtestsrc/gtest/docs/XcodeGuide.md @@ -0,0 +1,93 @@ + + +This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. + +# Quick Start # + +Here is the quick guide for using Google Test in your Xcode project. + + 1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only` + 1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework. + 1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests" + 1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests" + 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" + 1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. + 1. Build and Go + +The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. + +# Get the Source # + +Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command: + +``` +svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only +``` + +Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. + +To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory. + +The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`). + +Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory. + +``` +[Computer:svn] user$ svn propget svn:externals trunk +externals/src/googletest http://googletest.googlecode.com/svn/trunk +``` + +# Add the Framework to Your Project # + +The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. + + * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. + * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). + +# Make a Test Target # + +To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. + +Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. + + * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. + * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. + +# Set Up the Executable Run Environment # + +Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. + +If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: + +``` +[Session started at 2008-08-15 06:23:57 -0600.] + dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest + Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest + Reason: image not found +``` + +To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. + +# Build and Go # + +Now, when you click "Build and Go", the test will be executed. Dumping out something like this: + +``` +[Session started at 2008-08-06 06:36:13 -0600.] +[==========] Running 2 tests from 1 test case. +[----------] Global test environment set-up. +[----------] 2 tests from WidgetInitializerTest +[ RUN ] WidgetInitializerTest.TestConstructor +[ OK ] WidgetInitializerTest.TestConstructor +[ RUN ] WidgetInitializerTest.TestConversion +[ OK ] WidgetInitializerTest.TestConversion +[----------] Global test environment tear-down +[==========] 2 tests from 1 test case ran. +[ PASSED ] 2 tests. + +The Debugger has exited with status 0. +``` + +# Summary # + +Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. \ No newline at end of file diff --git a/gtestsrc/gtest/include/gtest/gtest-death-test.h b/gtestsrc/gtest/include/gtest/gtest-death-test.h new file mode 100644 index 0000000..957a69c --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-death-test.h @@ -0,0 +1,294 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for death tests. It is +// #included by gtest.h so a user doesn't need to include this +// directly. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ + +#include "gtest/internal/gtest-death-test-internal.h" + +namespace testing { + +// This flag controls the style of death tests. Valid values are "threadsafe", +// meaning that the death test child process will re-execute the test binary +// from the start, running only a single death test, or "fast", +// meaning that the child process will execute the test logic immediately +// after forking. +GTEST_DECLARE_string_(death_test_style); + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +GTEST_API_ bool InDeathTestChild(); + +} // namespace internal + +// The following macros are useful for writing death tests. + +// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is +// executed: +// +// 1. It generates a warning if there is more than one active +// thread. This is because it's safe to fork() or clone() only +// when there is a single thread. +// +// 2. The parent process clone()s a sub-process and runs the death +// test in it; the sub-process exits with code 0 at the end of the +// death test, if it hasn't exited already. +// +// 3. The parent process waits for the sub-process to terminate. +// +// 4. The parent process checks the exit code and error message of +// the sub-process. +// +// Examples: +// +// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); +// for (int i = 0; i < 5; i++) { +// EXPECT_DEATH(server.ProcessRequest(i), +// "Invalid request .* in ProcessRequest()") +// << "Failed to die on request " << i; +// } +// +// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); +// +// bool KilledBySIGHUP(int exit_code) { +// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; +// } +// +// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); +// +// On the regular expressions used in death tests: +// +// On POSIX-compliant systems (*nix), we use the library, +// which uses the POSIX extended regex syntax. +// +// On other platforms (e.g. Windows), we only support a simple regex +// syntax implemented as part of Google Test. This limited +// implementation should be enough most of the time when writing +// death tests; though it lacks many features you can find in PCRE +// or POSIX extended regex syntax. For example, we don't support +// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and +// repetition count ("x{5,7}"), among others. +// +// Below is the syntax that we do support. We chose it to be a +// subset of both PCRE and POSIX extended regex, so it's easy to +// learn wherever you come from. In the following: 'A' denotes a +// literal character, period (.), or a single \\ escape sequence; +// 'x' and 'y' denote regular expressions; 'm' and 'n' are for +// natural numbers. +// +// c matches any literal character c +// \\d matches any decimal digit +// \\D matches any character that's not a decimal digit +// \\f matches \f +// \\n matches \n +// \\r matches \r +// \\s matches any ASCII whitespace, including \n +// \\S matches any character that's not a whitespace +// \\t matches \t +// \\v matches \v +// \\w matches any letter, _, or decimal digit +// \\W matches any character that \\w doesn't match +// \\c matches any literal character c, which must be a punctuation +// . matches any single character except \n +// A? matches 0 or 1 occurrences of A +// A* matches 0 or many occurrences of A +// A+ matches 1 or many occurrences of A +// ^ matches the beginning of a string (not that of each line) +// $ matches the end of a string (not that of each line) +// xy matches x followed by y +// +// If you accidentally use PCRE or POSIX extended regex features +// not implemented by us, you will get a run-time failure. In that +// case, please try to rewrite your regular expression within the +// above syntax. +// +// This implementation is *not* meant to be as highly tuned or robust +// as a compiled regex library, but should perform well enough for a +// death test, which already incurs significant overhead by launching +// a child process. +// +// Known caveats: +// +// A "threadsafe" style death test obtains the path to the test +// program from argv[0] and re-executes it in the sub-process. For +// simplicity, the current implementation doesn't search the PATH +// when launching the sub-process. This means that the user must +// invoke the test program via a path that contains at least one +// path separator (e.g. path/to/foo_test and +// /absolute/path/to/bar_test are fine, but foo_test is not). This +// is rarely a problem as people usually don't put the test binary +// directory in PATH. +// +// TODO(wan@google.com): make thread-safe death tests search the PATH. + +// Asserts that a given statement causes the program to exit, with an +// integer exit status that satisfies predicate, and emitting error output +// that matches regex. +# define ASSERT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) + +// Like ASSERT_EXIT, but continues on to successive tests in the +// test case, if any: +# define EXPECT_EXIT(statement, predicate, regex) \ + GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) + +// Asserts that a given statement causes the program to exit, either by +// explicitly exiting with a nonzero exit code or being killed by a +// signal, and emitting error output that matches regex. +# define ASSERT_DEATH(statement, regex) \ + ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Like ASSERT_DEATH, but continues on to successive tests in the +// test case, if any: +# define EXPECT_DEATH(statement, regex) \ + EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) + +// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: + +// Tests that an exit code describes a normal exit with a given exit code. +class GTEST_API_ ExitedWithCode { + public: + explicit ExitedWithCode(int exit_code); + bool operator()(int exit_status) const; + private: + // No implementation - assignment is unsupported. + void operator=(const ExitedWithCode& other); + + const int exit_code_; +}; + +# if !GTEST_OS_WINDOWS +// Tests that an exit code describes an exit due to termination by a +// given signal. +class GTEST_API_ KilledBySignal { + public: + explicit KilledBySignal(int signum); + bool operator()(int exit_status) const; + private: + const int signum_; +}; +# endif // !GTEST_OS_WINDOWS + +// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. +// The death testing framework causes this to have interesting semantics, +// since the sideeffects of the call are only visible in opt mode, and not +// in debug mode. +// +// In practice, this can be used to test functions that utilize the +// LOG(DFATAL) macro using the following style: +// +// int DieInDebugOr12(int* sideeffect) { +// if (sideeffect) { +// *sideeffect = 12; +// } +// LOG(DFATAL) << "death"; +// return 12; +// } +// +// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { +// int sideeffect = 0; +// // Only asserts in dbg. +// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); +// +// #ifdef NDEBUG +// // opt-mode has sideeffect visible. +// EXPECT_EQ(12, sideeffect); +// #else +// // dbg-mode no visible sideeffect. +// EXPECT_EQ(0, sideeffect); +// #endif +// } +// +// This will assert that DieInDebugReturn12InOpt() crashes in debug +// mode, usually due to a DCHECK or LOG(DFATAL), but returns the +// appropriate fallback value (12 in this case) in opt mode. If you +// need to test that a function has appropriate side-effects in opt +// mode, include assertions against the side-effects. A general +// pattern for this is: +// +// EXPECT_DEBUG_DEATH({ +// // Side-effects here will have an effect after this statement in +// // opt mode, but none in debug mode. +// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); +// }, "death"); +// +# ifdef NDEBUG + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + GTEST_EXECUTE_STATEMENT_(statement, regex) + +# else + +# define EXPECT_DEBUG_DEATH(statement, regex) \ + EXPECT_DEATH(statement, regex) + +# define ASSERT_DEBUG_DEATH(statement, regex) \ + ASSERT_DEATH(statement, regex) + +# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // GTEST_HAS_DEATH_TEST + +// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and +// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if +// death tests are supported; otherwise they just issue a warning. This is +// useful when you are combining death test assertions with normal test +// assertions in one test. +#if GTEST_HAS_DEATH_TEST +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + EXPECT_DEATH(statement, regex) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + ASSERT_DEATH(statement, regex) +#else +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) +#endif + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-message.h b/gtestsrc/gtest/include/gtest/gtest-message.h new file mode 100644 index 0000000..fe879bc --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-message.h @@ -0,0 +1,250 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the Message class. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! + +#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ +#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ + +#include + +#include "gtest/internal/gtest-port.h" + +// Ensures that there is at least one operator<< in the global namespace. +// See Message& operator<<(...) below for why. +void operator<<(const testing::internal::Secret&, int); + +namespace testing { + +// The Message class works like an ostream repeater. +// +// Typical usage: +// +// 1. You stream a bunch of values to a Message object. +// It will remember the text in a stringstream. +// 2. Then you stream the Message object to an ostream. +// This causes the text in the Message to be streamed +// to the ostream. +// +// For example; +// +// testing::Message foo; +// foo << 1 << " != " << 2; +// std::cout << foo; +// +// will print "1 != 2". +// +// Message is not intended to be inherited from. In particular, its +// destructor is not virtual. +// +// Note that stringstream behaves differently in gcc and in MSVC. You +// can stream a NULL char pointer to it in the former, but not in the +// latter (it causes an access violation if you do). The Message +// class hides this difference by treating a NULL char pointer as +// "(null)". +class GTEST_API_ Message { + private: + // The type of basic IO manipulators (endl, ends, and flush) for + // narrow streams. + typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); + + public: + // Constructs an empty Message. + Message(); + + // Copy constructor. + Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT + *ss_ << msg.GetString(); + } + + // Constructs a Message from a C-string. + explicit Message(const char* str) : ss_(new ::std::stringstream) { + *ss_ << str; + } + +#if GTEST_OS_SYMBIAN + // Streams a value (either a pointer or not) to this object. + template + inline Message& operator <<(const T& value) { + StreamHelper(typename internal::is_pointer::type(), value); + return *this; + } +#else + // Streams a non-pointer value to this object. + template + inline Message& operator <<(const T& val) { + // Some libraries overload << for STL containers. These + // overloads are defined in the global namespace instead of ::std. + // + // C++'s symbol lookup rule (i.e. Koenig lookup) says that these + // overloads are visible in either the std namespace or the global + // namespace, but not other namespaces, including the testing + // namespace which Google Test's Message class is in. + // + // To allow STL containers (and other types that has a << operator + // defined in the global namespace) to be used in Google Test + // assertions, testing::Message must access the custom << operator + // from the global namespace. With this using declaration, + // overloads of << defined in the global namespace and those + // visible via Koenig lookup are both exposed in this function. + using ::operator <<; + *ss_ << val; + return *this; + } + + // Streams a pointer value to this object. + // + // This function is an overload of the previous one. When you + // stream a pointer to a Message, this definition will be used as it + // is more specialized. (The C++ Standard, section + // [temp.func.order].) If you stream a non-pointer, then the + // previous definition will be used. + // + // The reason for this overload is that streaming a NULL pointer to + // ostream is undefined behavior. Depending on the compiler, you + // may get "0", "(nil)", "(null)", or an access violation. To + // ensure consistent result across compilers, we always treat NULL + // as "(null)". + template + inline Message& operator <<(T* const& pointer) { // NOLINT + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + return *this; + } +#endif // GTEST_OS_SYMBIAN + + // Since the basic IO manipulators are overloaded for both narrow + // and wide streams, we have to provide this specialized definition + // of operator <<, even though its body is the same as the + // templatized version above. Without this definition, streaming + // endl or other basic IO manipulators to Message will confuse the + // compiler. + Message& operator <<(BasicNarrowIoManip val) { + *ss_ << val; + return *this; + } + + // Instead of 1/0, we want to see true/false for bool values. + Message& operator <<(bool b) { + return *this << (b ? "true" : "false"); + } + + // These two overloads allow streaming a wide C string to a Message + // using the UTF-8 encoding. + Message& operator <<(const wchar_t* wide_c_str); + Message& operator <<(wchar_t* wide_c_str); + +#if GTEST_HAS_STD_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::std::wstring& wstr); +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING + // Converts the given wide string to a narrow string using the UTF-8 + // encoding, and streams the result to this Message object. + Message& operator <<(const ::wstring& wstr); +#endif // GTEST_HAS_GLOBAL_WSTRING + + // Gets the text streamed to this object so far as an std::string. + // Each '\0' character in the buffer is replaced with "\\0". + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + std::string GetString() const; + + private: + +#if GTEST_OS_SYMBIAN + // These are needed as the Nokia Symbian Compiler cannot decide between + // const T& and const T* in a function template. The Nokia compiler _can_ + // decide between class template specializations for T and T*, so a + // tr1::type_traits-like is_pointer works, and we can overload on that. + template + inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { + if (pointer == NULL) { + *ss_ << "(null)"; + } else { + *ss_ << pointer; + } + } + template + inline void StreamHelper(internal::false_type /*is_pointer*/, + const T& value) { + // See the comments in Message& operator <<(const T&) above for why + // we need this using statement. + using ::operator <<; + *ss_ << value; + } +#endif // GTEST_OS_SYMBIAN + + // We'll hold the text streamed to this object here. + const internal::scoped_ptr< ::std::stringstream> ss_; + + // We declare (but don't implement) this to prevent the compiler + // from implementing the assignment operator. + void operator=(const Message&); +}; + +// Streams a Message to an ostream. +inline std::ostream& operator <<(std::ostream& os, const Message& sb) { + return os << sb.GetString(); +} + +namespace internal { + +// Converts a streamable value to an std::string. A NULL pointer is +// converted to "(null)". When the input value is a ::string, +// ::std::string, ::wstring, or ::std::wstring object, each NUL +// character in it is replaced with "\\0". +template +std::string StreamableToString(const T& streamable) { + return (Message() << streamable).GetString(); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-param-test.h b/gtestsrc/gtest/include/gtest/gtest-param-test.h new file mode 100644 index 0000000..038f9ba --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-param-test.h @@ -0,0 +1,1444 @@ +// This file was GENERATED by command: +// pump.py gtest-param-test.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// Macros and functions for implementing parameterized tests +// in Google C++ Testing Framework (Google Test) +// +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ + + +// Value-parameterized tests allow you to test your code with different +// parameters without writing multiple copies of the same test. +// +// Here is how you use value-parameterized tests: + +#if 0 + +// To write value-parameterized tests, first you should define a fixture +// class. It is usually derived from testing::TestWithParam (see below for +// another inheritance scheme that's sometimes useful in more complicated +// class hierarchies), where the type of your parameter values. +// TestWithParam is itself derived from testing::Test. T can be any +// copyable type. If it's a raw pointer, you are responsible for managing the +// lifespan of the pointed values. + +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual class fixture members here. +}; + +// Then, use the TEST_P macro to define as many parameterized tests +// for this fixture as you want. The _P suffix is for "parameterized" +// or "pattern", whichever you prefer to think. + +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} + +// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// case with any set of parameters you want. Google Test defines a number +// of functions for generating test parameters. They return what we call +// (surprise!) parameter generators. Here is a summary of them, which +// are all in the testing namespace: +// +// +// Range(begin, end [, step]) - Yields values {begin, begin+step, +// begin+step+step, ...}. The values do not +// include end. step defaults to 1. +// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. +// ValuesIn(container) - Yields values from a C-style array, an STL +// ValuesIn(begin,end) container, or an iterator range [begin, end). +// Bool() - Yields sequence {false, true}. +// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product +// for the math savvy) of the values generated +// by the N generators. +// +// For more details, see comments at the definitions of these functions below +// in this file. +// +// The following statement will instantiate tests from the FooTest test case +// each with parameter values "meeny", "miny", and "moe". + +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); + +// To distinguish different instances of the pattern, (yes, you +// can instantiate it more then once) the first argument to the +// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the +// actual test case name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: +// +// * InstantiationName/FooTest.DoesBlah/0 for "meeny" +// * InstantiationName/FooTest.DoesBlah/1 for "miny" +// * InstantiationName/FooTest.DoesBlah/2 for "moe" +// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" +// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" +// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" +// +// You can use these names in --gtest_filter. +// +// This statement will instantiate all tests from FooTest again, each +// with parameter values "cat" and "dog": + +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); + +// The tests from the instantiation above will have these names: +// +// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" +// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" +// +// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests +// in the given test case, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_CASE_P statement. +// +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. +// +// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc +// for more examples. +// +// In the future, we plan to publish the API for defining new parameter +// generators. But for now this interface remains part of the internal +// implementation and is subject to change. +// +// +// A parameterized test fixture must be derived from testing::Test and from +// testing::WithParamInterface, where T is the type of the parameter +// values. Inheriting from TestWithParam satisfies that requirement because +// TestWithParam inherits from both Test and WithParamInterface. In more +// complicated hierarchies, however, it is occasionally useful to inherit +// separately from Test and WithParamInterface. For example: + +class BaseTest : public ::testing::Test { + // You can inherit all the usual members for a non-parameterized test + // fixture here. +}; + +class DerivedTest : public BaseTest, public ::testing::WithParamInterface { + // The usual test fixture members go here too. +}; + +TEST_F(BaseTest, HasFoo) { + // This is an ordinary non-parameterized test. +} + +TEST_P(DerivedTest, DoesBlah) { + // GetParam works just the same here as if you inherit from TestWithParam. + EXPECT_TRUE(foo.Blah(GetParam())); +} + +#endif // 0 + +#include "gtest/internal/gtest-port.h" + +#if !GTEST_OS_SYMBIAN +# include +#endif + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Functions producing parameter generators. +// +// Google Test uses these generators to produce parameters for value- +// parameterized tests. When a parameterized test case is instantiated +// with a particular generator, Google Test creates and runs tests +// for each element in the sequence produced by the generator. +// +// In the following sample, tests from test case FooTest are instantiated +// each three times with parameter values 3, 5, and 8: +// +// class FooTest : public TestWithParam { ... }; +// +// TEST_P(FooTest, TestThis) { +// } +// TEST_P(FooTest, TestThat) { +// } +// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// + +// Range() returns generators providing sequences of values in a range. +// +// Synopsis: +// Range(start, end) +// - returns a generator producing a sequence of values {start, start+1, +// start+2, ..., }. +// Range(start, end, step) +// - returns a generator producing a sequence of values {start, start+step, +// start+step+step, ..., }. +// Notes: +// * The generated sequences never include end. For example, Range(1, 5) +// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) +// returns a generator producing {1, 3, 5, 7}. +// * start and end must have the same type. That type may be any integral or +// floating-point type or a user defined type satisfying these conditions: +// * It must be assignable (have operator=() defined). +// * It must have operator+() (operator+(int-compatible type) for +// two-operand version). +// * It must have operator<() defined. +// Elements in the resulting sequences will also have that type. +// * Condition start < end must be satisfied in order for resulting sequences +// to contain any elements. +// +template +internal::ParamGenerator Range(T start, T end, IncrementT step) { + return internal::ParamGenerator( + new internal::RangeGenerator(start, end, step)); +} + +template +internal::ParamGenerator Range(T start, T end) { + return Range(start, end, 1); +} + +// ValuesIn() function allows generation of tests with parameters coming from +// a container. +// +// Synopsis: +// ValuesIn(const T (&array)[N]) +// - returns a generator producing sequences with elements from +// a C-style array. +// ValuesIn(const Container& container) +// - returns a generator producing sequences with elements from +// an STL-style container. +// ValuesIn(Iterator begin, Iterator end) +// - returns a generator producing sequences with elements from +// a range [begin, end) defined by a pair of STL-style iterators. These +// iterators can also be plain C pointers. +// +// Please note that ValuesIn copies the values from the containers +// passed in and keeps them to generate tests in RUN_ALL_TESTS(). +// +// Examples: +// +// This instantiates tests from test case StringTest +// each with C-string values of "foo", "bar", and "baz": +// +// const char* strings[] = {"foo", "bar", "baz"}; +// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); +// +// This instantiates tests from test case StlStringTest +// each with STL strings with values "a" and "b": +// +// ::std::vector< ::std::string> GetParameterStrings() { +// ::std::vector< ::std::string> v; +// v.push_back("a"); +// v.push_back("b"); +// return v; +// } +// +// INSTANTIATE_TEST_CASE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); +// +// +// This will also instantiate tests from CharTest +// each with parameter values 'a' and 'b': +// +// ::std::list GetParameterChars() { +// ::std::list list; +// list.push_back('a'); +// list.push_back('b'); +// return list; +// } +// ::std::list l = GetParameterChars(); +// INSTANTIATE_TEST_CASE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); +// +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits + ::value_type ParamType; + return internal::ParamGenerator( + new internal::ValuesInIteratorRangeGenerator(begin, end)); +} + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]) { + return ValuesIn(array, array + N); +} + +template +internal::ParamGenerator ValuesIn( + const Container& container) { + return ValuesIn(container.begin(), container.end()); +} + +// Values() allows generating tests from explicitly specified list of +// parameters. +// +// Synopsis: +// Values(T v1, T v2, ..., T vN) +// - returns a generator producing sequences with elements v1, v2, ..., vN. +// +// For example, this instantiates tests from test case BarTest each +// with values "one", "two", and "three": +// +// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// +// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// The exact type of values will depend on the type of parameter in BazTest. +// +// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// +// Currently, Values() supports from 1 to 50 parameters. +// +template +internal::ValueArray1 Values(T1 v1) { + return internal::ValueArray1(v1); +} + +template +internal::ValueArray2 Values(T1 v1, T2 v2) { + return internal::ValueArray2(v1, v2); +} + +template +internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { + return internal::ValueArray3(v1, v2, v3); +} + +template +internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { + return internal::ValueArray4(v1, v2, v3, v4); +} + +template +internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5) { + return internal::ValueArray5(v1, v2, v3, v4, v5); +} + +template +internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6) { + return internal::ValueArray6(v1, v2, v3, v4, v5, v6); +} + +template +internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7) { + return internal::ValueArray7(v1, v2, v3, v4, v5, + v6, v7); +} + +template +internal::ValueArray8 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { + return internal::ValueArray8(v1, v2, v3, v4, + v5, v6, v7, v8); +} + +template +internal::ValueArray9 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { + return internal::ValueArray9(v1, v2, v3, + v4, v5, v6, v7, v8, v9); +} + +template +internal::ValueArray10 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { + return internal::ValueArray10(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10); +} + +template +internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) { + return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); +} + +template +internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) { + return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); +} + +template +internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) { + return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); +} + +template +internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { + return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14); +} + +template +internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { + return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15); +} + +template +internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16) { + return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16); +} + +template +internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17) { + return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17); +} + +template +internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18) { + return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18); +} + +template +internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { + return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); +} + +template +internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { + return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); +} + +template +internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { + return internal::ValueArray21(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); +} + +template +internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22) { + return internal::ValueArray22(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22); +} + +template +internal::ValueArray23 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23) { + return internal::ValueArray23(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23); +} + +template +internal::ValueArray24 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24) { + return internal::ValueArray24(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24); +} + +template +internal::ValueArray25 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { + return internal::ValueArray25(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25); +} + +template +internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) { + return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); +} + +template +internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) { + return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); +} + +template +internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) { + return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28); +} + +template +internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) { + return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29); +} + +template +internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { + return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30); +} + +template +internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { + return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31); +} + +template +internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32) { + return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32); +} + +template +internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33) { + return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); +} + +template +internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34) { + return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); +} + +template +internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { + return internal::ValueArray35(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); +} + +template +internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { + return internal::ValueArray36(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36); +} + +template +internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, + T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37) { + return internal::ValueArray37(v1, v2, v3, + v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37); +} + +template +internal::ValueArray38 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38) { + return internal::ValueArray38(v1, v2, + v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, + v33, v34, v35, v36, v37, v38); +} + +template +internal::ValueArray39 Values(T1 v1, T2 v2, + T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, + T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, + T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, + T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, + T37 v37, T38 v38, T39 v39) { + return internal::ValueArray39(v1, + v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, + v32, v33, v34, v35, v36, v37, v38, v39); +} + +template +internal::ValueArray40 Values(T1 v1, + T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, + T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, + T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { + return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, + v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); +} + +template +internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { + return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, + v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); +} + +template +internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) { + return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, + v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, + v42); +} + +template +internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) { + return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, + v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, + v41, v42, v43); +} + +template +internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) { + return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, + v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, + v40, v41, v42, v43, v44); +} + +template +internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { + return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, + v39, v40, v41, v42, v43, v44, v45); +} + +template +internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { + return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46); +} + +template +internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { + return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, + v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, + v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); +} + +template +internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, + T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, + T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, + T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, + T48 v48) { + return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, + v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); +} + +template +internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, + T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, + T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48, T49 v49) { + return internal::ValueArray49(v1, v2, v3, v4, v5, v6, + v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, + v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, + v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); +} + +template +internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, + T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, + T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, + T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, + T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { + return internal::ValueArray50(v1, v2, v3, v4, + v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, + v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, + v48, v49, v50); +} + +// Bool() allows generating tests with parameters in a set of (false, true). +// +// Synopsis: +// Bool() +// - returns a generator producing sequences with elements {false, true}. +// +// It is useful when testing code that depends on Boolean flags. Combinations +// of multiple flags can be tested when several Bool()'s are combined using +// Combine() function. +// +// In the following example all tests in the test case FlagDependentTest +// will be instantiated twice with parameters false and true. +// +// class FlagDependentTest : public testing::TestWithParam { +// virtual void SetUp() { +// external_flag = GetParam(); +// } +// } +// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// +inline internal::ParamGenerator Bool() { + return Values(false, true); +} + +# if GTEST_HAS_COMBINE +// Combine() allows the user to combine two or more sequences to produce +// values of a Cartesian product of those sequences' elements. +// +// Synopsis: +// Combine(gen1, gen2, ..., genN) +// - returns a generator producing sequences with elements coming from +// the Cartesian product of elements from the sequences generated by +// gen1, gen2, ..., genN. The sequence elements will have a type of +// tuple where T1, T2, ..., TN are the types +// of elements from sequences produces by gen1, gen2, ..., genN. +// +// Combine can have up to 10 arguments. This number is currently limited +// by the maximum number of elements in the tuple implementation used by Google +// Test. +// +// Example: +// +// This will instantiate tests in test case AnimalTest each one with +// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), +// tuple("dog", BLACK), and tuple("dog", WHITE): +// +// enum Color { BLACK, GRAY, WHITE }; +// class AnimalTest +// : public testing::TestWithParam > {...}; +// +// TEST_P(AnimalTest, AnimalLooksNice) {...} +// +// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); +// +// This will instantiate tests in FlagDependentTest with all variations of two +// Boolean flags: +// +// class FlagDependentTest +// : public testing::TestWithParam > { +// virtual void SetUp() { +// // Assigns external_flag_1 and external_flag_2 values from the tuple. +// tie(external_flag_1, external_flag_2) = GetParam(); +// } +// }; +// +// TEST_P(FlagDependentTest, TestFeature1) { +// // Test your code using external_flag_1 and external_flag_2 here. +// } +// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); +// +template +internal::CartesianProductHolder2 Combine( + const Generator1& g1, const Generator2& g2) { + return internal::CartesianProductHolder2( + g1, g2); +} + +template +internal::CartesianProductHolder3 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3) { + return internal::CartesianProductHolder3( + g1, g2, g3); +} + +template +internal::CartesianProductHolder4 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4) { + return internal::CartesianProductHolder4( + g1, g2, g3, g4); +} + +template +internal::CartesianProductHolder5 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5) { + return internal::CartesianProductHolder5( + g1, g2, g3, g4, g5); +} + +template +internal::CartesianProductHolder6 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6) { + return internal::CartesianProductHolder6( + g1, g2, g3, g4, g5, g6); +} + +template +internal::CartesianProductHolder7 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7) { + return internal::CartesianProductHolder7( + g1, g2, g3, g4, g5, g6, g7); +} + +template +internal::CartesianProductHolder8 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8) { + return internal::CartesianProductHolder8( + g1, g2, g3, g4, g5, g6, g7, g8); +} + +template +internal::CartesianProductHolder9 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9) { + return internal::CartesianProductHolder9( + g1, g2, g3, g4, g5, g6, g7, g8, g9); +} + +template +internal::CartesianProductHolder10 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, + const Generator4& g4, const Generator5& g5, const Generator6& g6, + const Generator7& g7, const Generator8& g8, const Generator9& g9, + const Generator10& g10) { + return internal::CartesianProductHolder10( + g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); +} +# endif // GTEST_HAS_COMBINE + + + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(\ + test_case_name, test_name)>()); \ + return 0; \ + } \ + static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user +// to specify a function or functor that generates custom test name suffixes +// based on the test parameters. The function should accept one argument of +// type testing::TestParamInfo, and return std::string. +// +// testing::PrintToStringParamName is a builtin test suffix generator that +// returns the value of testing::PrintToString(GetParam()). It does not work +// for std::string or C strings. +// +// Note: test names must be non-empty, unique, and may only contain ASCII +// alphanumeric characters or underscore. + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ + ::testing::internal::ParamGenerator \ + gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ + ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo& info) { \ + return ::testing::internal::GetParamNameGen \ + (__VA_ARGS__)(info); \ + } \ + int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + >est_##prefix##test_case_name##_EvalGenerateName_, \ + __FILE__, __LINE__) + +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-param-test.h.pump b/gtestsrc/gtest/include/gtest/gtest-param-test.h.pump new file mode 100644 index 0000000..3078d6d --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-param-test.h.pump @@ -0,0 +1,510 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of Values arguments we want to support. +$var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// Macros and functions for implementing parameterized tests +// in Google C++ Testing Framework (Google Test) +// +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ + + +// Value-parameterized tests allow you to test your code with different +// parameters without writing multiple copies of the same test. +// +// Here is how you use value-parameterized tests: + +#if 0 + +// To write value-parameterized tests, first you should define a fixture +// class. It is usually derived from testing::TestWithParam (see below for +// another inheritance scheme that's sometimes useful in more complicated +// class hierarchies), where the type of your parameter values. +// TestWithParam is itself derived from testing::Test. T can be any +// copyable type. If it's a raw pointer, you are responsible for managing the +// lifespan of the pointed values. + +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual class fixture members here. +}; + +// Then, use the TEST_P macro to define as many parameterized tests +// for this fixture as you want. The _P suffix is for "parameterized" +// or "pattern", whichever you prefer to think. + +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} + +// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// case with any set of parameters you want. Google Test defines a number +// of functions for generating test parameters. They return what we call +// (surprise!) parameter generators. Here is a summary of them, which +// are all in the testing namespace: +// +// +// Range(begin, end [, step]) - Yields values {begin, begin+step, +// begin+step+step, ...}. The values do not +// include end. step defaults to 1. +// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. +// ValuesIn(container) - Yields values from a C-style array, an STL +// ValuesIn(begin,end) container, or an iterator range [begin, end). +// Bool() - Yields sequence {false, true}. +// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product +// for the math savvy) of the values generated +// by the N generators. +// +// For more details, see comments at the definitions of these functions below +// in this file. +// +// The following statement will instantiate tests from the FooTest test case +// each with parameter values "meeny", "miny", and "moe". + +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); + +// To distinguish different instances of the pattern, (yes, you +// can instantiate it more then once) the first argument to the +// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the +// actual test case name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: +// +// * InstantiationName/FooTest.DoesBlah/0 for "meeny" +// * InstantiationName/FooTest.DoesBlah/1 for "miny" +// * InstantiationName/FooTest.DoesBlah/2 for "moe" +// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" +// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" +// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" +// +// You can use these names in --gtest_filter. +// +// This statement will instantiate all tests from FooTest again, each +// with parameter values "cat" and "dog": + +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); + +// The tests from the instantiation above will have these names: +// +// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" +// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" +// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" +// +// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests +// in the given test case, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_CASE_P statement. +// +// Please also note that generator expressions (including parameters to the +// generators) are evaluated in InitGoogleTest(), after main() has started. +// This allows the user on one hand, to adjust generator parameters in order +// to dynamically determine a set of tests to run and on the other hand, +// give the user a chance to inspect the generated tests with Google Test +// reflection API before RUN_ALL_TESTS() is executed. +// +// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc +// for more examples. +// +// In the future, we plan to publish the API for defining new parameter +// generators. But for now this interface remains part of the internal +// implementation and is subject to change. +// +// +// A parameterized test fixture must be derived from testing::Test and from +// testing::WithParamInterface, where T is the type of the parameter +// values. Inheriting from TestWithParam satisfies that requirement because +// TestWithParam inherits from both Test and WithParamInterface. In more +// complicated hierarchies, however, it is occasionally useful to inherit +// separately from Test and WithParamInterface. For example: + +class BaseTest : public ::testing::Test { + // You can inherit all the usual members for a non-parameterized test + // fixture here. +}; + +class DerivedTest : public BaseTest, public ::testing::WithParamInterface { + // The usual test fixture members go here too. +}; + +TEST_F(BaseTest, HasFoo) { + // This is an ordinary non-parameterized test. +} + +TEST_P(DerivedTest, DoesBlah) { + // GetParam works just the same here as if you inherit from TestWithParam. + EXPECT_TRUE(foo.Blah(GetParam())); +} + +#endif // 0 + +#include "gtest/internal/gtest-port.h" + +#if !GTEST_OS_SYMBIAN +# include +#endif + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util-generated.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Functions producing parameter generators. +// +// Google Test uses these generators to produce parameters for value- +// parameterized tests. When a parameterized test case is instantiated +// with a particular generator, Google Test creates and runs tests +// for each element in the sequence produced by the generator. +// +// In the following sample, tests from test case FooTest are instantiated +// each three times with parameter values 3, 5, and 8: +// +// class FooTest : public TestWithParam { ... }; +// +// TEST_P(FooTest, TestThis) { +// } +// TEST_P(FooTest, TestThat) { +// } +// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// + +// Range() returns generators providing sequences of values in a range. +// +// Synopsis: +// Range(start, end) +// - returns a generator producing a sequence of values {start, start+1, +// start+2, ..., }. +// Range(start, end, step) +// - returns a generator producing a sequence of values {start, start+step, +// start+step+step, ..., }. +// Notes: +// * The generated sequences never include end. For example, Range(1, 5) +// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) +// returns a generator producing {1, 3, 5, 7}. +// * start and end must have the same type. That type may be any integral or +// floating-point type or a user defined type satisfying these conditions: +// * It must be assignable (have operator=() defined). +// * It must have operator+() (operator+(int-compatible type) for +// two-operand version). +// * It must have operator<() defined. +// Elements in the resulting sequences will also have that type. +// * Condition start < end must be satisfied in order for resulting sequences +// to contain any elements. +// +template +internal::ParamGenerator Range(T start, T end, IncrementT step) { + return internal::ParamGenerator( + new internal::RangeGenerator(start, end, step)); +} + +template +internal::ParamGenerator Range(T start, T end) { + return Range(start, end, 1); +} + +// ValuesIn() function allows generation of tests with parameters coming from +// a container. +// +// Synopsis: +// ValuesIn(const T (&array)[N]) +// - returns a generator producing sequences with elements from +// a C-style array. +// ValuesIn(const Container& container) +// - returns a generator producing sequences with elements from +// an STL-style container. +// ValuesIn(Iterator begin, Iterator end) +// - returns a generator producing sequences with elements from +// a range [begin, end) defined by a pair of STL-style iterators. These +// iterators can also be plain C pointers. +// +// Please note that ValuesIn copies the values from the containers +// passed in and keeps them to generate tests in RUN_ALL_TESTS(). +// +// Examples: +// +// This instantiates tests from test case StringTest +// each with C-string values of "foo", "bar", and "baz": +// +// const char* strings[] = {"foo", "bar", "baz"}; +// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); +// +// This instantiates tests from test case StlStringTest +// each with STL strings with values "a" and "b": +// +// ::std::vector< ::std::string> GetParameterStrings() { +// ::std::vector< ::std::string> v; +// v.push_back("a"); +// v.push_back("b"); +// return v; +// } +// +// INSTANTIATE_TEST_CASE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); +// +// +// This will also instantiate tests from CharTest +// each with parameter values 'a' and 'b': +// +// ::std::list GetParameterChars() { +// ::std::list list; +// list.push_back('a'); +// list.push_back('b'); +// return list; +// } +// ::std::list l = GetParameterChars(); +// INSTANTIATE_TEST_CASE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); +// +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits + ::value_type ParamType; + return internal::ParamGenerator( + new internal::ValuesInIteratorRangeGenerator(begin, end)); +} + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]) { + return ValuesIn(array, array + N); +} + +template +internal::ParamGenerator ValuesIn( + const Container& container) { + return ValuesIn(container.begin(), container.end()); +} + +// Values() allows generating tests from explicitly specified list of +// parameters. +// +// Synopsis: +// Values(T v1, T v2, ..., T vN) +// - returns a generator producing sequences with elements v1, v2, ..., vN. +// +// For example, this instantiates tests from test case BarTest each +// with values "one", "two", and "three": +// +// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// +// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// The exact type of values will depend on the type of parameter in BazTest. +// +// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// +// Currently, Values() supports from 1 to $n parameters. +// +$range i 1..n +$for i [[ +$range j 1..i + +template <$for j, [[typename T$j]]> +internal::ValueArray$i<$for j, [[T$j]]> Values($for j, [[T$j v$j]]) { + return internal::ValueArray$i<$for j, [[T$j]]>($for j, [[v$j]]); +} + +]] + +// Bool() allows generating tests with parameters in a set of (false, true). +// +// Synopsis: +// Bool() +// - returns a generator producing sequences with elements {false, true}. +// +// It is useful when testing code that depends on Boolean flags. Combinations +// of multiple flags can be tested when several Bool()'s are combined using +// Combine() function. +// +// In the following example all tests in the test case FlagDependentTest +// will be instantiated twice with parameters false and true. +// +// class FlagDependentTest : public testing::TestWithParam { +// virtual void SetUp() { +// external_flag = GetParam(); +// } +// } +// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// +inline internal::ParamGenerator Bool() { + return Values(false, true); +} + +# if GTEST_HAS_COMBINE +// Combine() allows the user to combine two or more sequences to produce +// values of a Cartesian product of those sequences' elements. +// +// Synopsis: +// Combine(gen1, gen2, ..., genN) +// - returns a generator producing sequences with elements coming from +// the Cartesian product of elements from the sequences generated by +// gen1, gen2, ..., genN. The sequence elements will have a type of +// tuple where T1, T2, ..., TN are the types +// of elements from sequences produces by gen1, gen2, ..., genN. +// +// Combine can have up to $maxtuple arguments. This number is currently limited +// by the maximum number of elements in the tuple implementation used by Google +// Test. +// +// Example: +// +// This will instantiate tests in test case AnimalTest each one with +// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), +// tuple("dog", BLACK), and tuple("dog", WHITE): +// +// enum Color { BLACK, GRAY, WHITE }; +// class AnimalTest +// : public testing::TestWithParam > {...}; +// +// TEST_P(AnimalTest, AnimalLooksNice) {...} +// +// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); +// +// This will instantiate tests in FlagDependentTest with all variations of two +// Boolean flags: +// +// class FlagDependentTest +// : public testing::TestWithParam > { +// virtual void SetUp() { +// // Assigns external_flag_1 and external_flag_2 values from the tuple. +// tie(external_flag_1, external_flag_2) = GetParam(); +// } +// }; +// +// TEST_P(FlagDependentTest, TestFeature1) { +// // Test your code using external_flag_1 and external_flag_2 here. +// } +// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); +// +$range i 2..maxtuple +$for i [[ +$range j 1..i + +template <$for j, [[typename Generator$j]]> +internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine( + $for j, [[const Generator$j& g$j]]) { + return internal::CartesianProductHolder$i<$for j, [[Generator$j]]>( + $for j, [[g$j]]); +} + +]] +# endif // GTEST_HAS_COMBINE + + + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestPattern(\ + #test_case_name, \ + #test_name, \ + new ::testing::internal::TestMetaFactory< \ + GTEST_TEST_CLASS_NAME_(\ + test_case_name, test_name)>()); \ + return 0; \ + } \ + static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user +// to specify a function or functor that generates custom test name suffixes +// based on the test parameters. The function should accept one argument of +// type testing::TestParamInfo, and return std::string. +// +// testing::PrintToStringParamName is a builtin test suffix generator that +// returns the value of testing::PrintToString(GetParam()). +// +// Note: test names must be non-empty, unique, and may only contain ASCII +// alphanumeric characters or underscore. Because PrintToString adds quotes +// to std::string and C strings, it won't work for these types. + +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ + ::testing::internal::ParamGenerator \ + gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ + ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo& info) { \ + return ::testing::internal::GetParamNameGen \ + (__VA_ARGS__)(info); \ + } \ + int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ + GetTestCasePatternHolder(\ + #test_case_name, \ + ::testing::internal::CodeLocation(\ + __FILE__, __LINE__))->AddTestCaseInstantiation(\ + #prefix, \ + >est_##prefix##test_case_name##_EvalGenerator_, \ + >est_##prefix##test_case_name##_EvalGenerateName_, \ + __FILE__, __LINE__) + +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-printers.h b/gtestsrc/gtest/include/gtest/gtest-printers.h new file mode 100644 index 0000000..8a33164 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-printers.h @@ -0,0 +1,993 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// A user can teach this function how to print a class type T by +// defining either operator<<() or PrintTo() in the namespace that +// defines T. More specifically, the FIRST defined function in the +// following list will be used (assuming T is defined in namespace +// foo): +// +// 1. foo::PrintTo(const T&, ostream*) +// 2. operator<<(ostream&, const T&) defined in either foo or the +// global namespace. +// +// If none of the above is defined, it will print the debug string of +// the value if it is a protocol buffer, or print the raw bytes in the +// value otherwise. +// +// To aid debugging: when T is a reference type, the address of the +// value is also printed; when T is a (const) char pointer, both the +// pointer value and the NUL-terminated string it points to are +// printed. +// +// We also provide some convenient wrappers: +// +// // Prints a value to a string. For a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// std::string ::testing::PrintToString(const T& value); +// +// // Prints a value tersely: for a reference type, the referenced +// // value (but not the address) is printed; for a (const or not) char +// // pointer, the NUL-terminated string (but not the pointer) is +// // printed. +// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); +// +// // Prints value using the type inferred by the compiler. The difference +// // from UniversalTersePrint() is that this function prints both the +// // pointer and the NUL-terminated string for a (const or not) char pointer. +// void ::testing::internal::UniversalPrint(const T& value, ostream*); +// +// // Prints the fields of a tuple tersely to a string vector, one +// // element for each field. Tuple support must be enabled in +// // gtest-port.h. +// std::vector UniversalTersePrintTupleFieldsToStrings( +// const Tuple& value); +// +// Known limitation: +// +// The print primitives print the elements of an STL-style container +// using the compiler-inferred type of *iter where iter is a +// const_iterator of the container. When const_iterator is an input +// iterator but not a forward iterator, this inferred type may not +// match value_type, and the print output may be incorrect. In +// practice, this is rarely a problem as for most containers +// const_iterator is a forward iterator. We'll fix this if there's an +// actual need for it. Note that this fix cannot rely on value_type +// being defined as many user-defined container types don't have +// value_type. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ + +#include // NOLINT +#include +#include +#include +#include +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-internal.h" + +#if GTEST_HAS_STD_TUPLE_ +# include +#endif + +namespace testing { + +// Definitions in the 'internal' and 'internal2' name spaces are +// subject to change without notice. DO NOT USE THEM IN USER CODE! +namespace internal2 { + +// Prints the given number of bytes in the given object to the given +// ostream. +GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, + size_t count, + ::std::ostream* os); + +// For selecting which printer to use when a given type has neither << +// nor PrintTo(). +enum TypeKind { + kProtobuf, // a protobuf type + kConvertibleToInteger, // a type implicitly convertible to BiggestInt + // (e.g. a named or unnamed enum type) + kOtherType // anything else +}; + +// TypeWithoutFormatter::PrintValue(value, os) is called +// by the universal printer to print a value of type T when neither +// operator<< nor PrintTo() is defined for T, where kTypeKind is the +// "kind" of T as defined by enum TypeKind. +template +class TypeWithoutFormatter { + public: + // This default version is called when kTypeKind is kOtherType. + static void PrintValue(const T& value, ::std::ostream* os) { + PrintBytesInObjectTo(reinterpret_cast(&value), + sizeof(value), os); + } +}; + +// We print a protobuf using its ShortDebugString() when the string +// doesn't exceed this many characters; otherwise we print it using +// DebugString() for better readability. +const size_t kProtobufOneLinerMaxLength = 50; + +template +class TypeWithoutFormatter { + public: + static void PrintValue(const T& value, ::std::ostream* os) { + const ::testing::internal::string short_str = value.ShortDebugString(); + const ::testing::internal::string pretty_str = + short_str.length() <= kProtobufOneLinerMaxLength ? + short_str : ("\n" + value.DebugString()); + *os << ("<" + pretty_str + ">"); + } +}; + +template +class TypeWithoutFormatter { + public: + // Since T has no << operator or PrintTo() but can be implicitly + // converted to BiggestInt, we print it as a BiggestInt. + // + // Most likely T is an enum type (either named or unnamed), in which + // case printing it as an integer is the desired behavior. In case + // T is not an enum, printing it as an integer is the best we can do + // given that it has no user-defined printer. + static void PrintValue(const T& value, ::std::ostream* os) { + const internal::BiggestInt kBigInt = value; + *os << kBigInt; + } +}; + +// Prints the given value to the given ostream. If the value is a +// protocol message, its debug string is printed; if it's an enum or +// of a type implicitly convertible to BiggestInt, it's printed as an +// integer; otherwise the bytes in the value are printed. This is +// what UniversalPrinter::Print() does when it knows nothing about +// type T and T has neither << operator nor PrintTo(). +// +// A user can override this behavior for a class type Foo by defining +// a << operator in the namespace where Foo is defined. +// +// We put this operator in namespace 'internal2' instead of 'internal' +// to simplify the implementation, as much code in 'internal' needs to +// use << in STL, which would conflict with our own << were it defined +// in 'internal'. +// +// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If +// we define it to take an std::ostream instead, we'll get an +// "ambiguous overloads" compiler error when trying to print a type +// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether +// operator<<(std::ostream&, const T&) or +// operator<<(std::basic_stream, const Foo&) is more +// specific. +template +::std::basic_ostream& operator<<( + ::std::basic_ostream& os, const T& x) { + TypeWithoutFormatter::value ? kProtobuf : + internal::ImplicitlyConvertible::value ? + kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); + return os; +} + +} // namespace internal2 +} // namespace testing + +// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up +// magic needed for implementing UniversalPrinter won't work. +namespace testing_internal { + +// Used to print a value that is not an STL-style container when the +// user doesn't define PrintTo() for it. +template +void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { + // With the following statement, during unqualified name lookup, + // testing::internal2::operator<< appears as if it was declared in + // the nearest enclosing namespace that contains both + // ::testing_internal and ::testing::internal2, i.e. the global + // namespace. For more details, refer to the C++ Standard section + // 7.3.4-1 [namespace.udir]. This allows us to fall back onto + // testing::internal2::operator<< in case T doesn't come with a << + // operator. + // + // We cannot write 'using ::testing::internal2::operator<<;', which + // gcc 3.3 fails to compile due to a compiler bug. + using namespace ::testing::internal2; // NOLINT + + // Assuming T is defined in namespace foo, in the next statement, + // the compiler will consider all of: + // + // 1. foo::operator<< (thanks to Koenig look-up), + // 2. ::operator<< (as the current namespace is enclosed in ::), + // 3. testing::internal2::operator<< (thanks to the using statement above). + // + // The operator<< whose type matches T best will be picked. + // + // We deliberately allow #2 to be a candidate, as sometimes it's + // impossible to define #1 (e.g. when foo is ::std, defining + // anything in it is undefined behavior unless you are a compiler + // vendor.). + *os << value; +} + +} // namespace testing_internal + +namespace testing { +namespace internal { + +// FormatForComparison::Format(value) formats a +// value of type ToPrint that is an operand of a comparison assertion +// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in +// the comparison, and is used to help determine the best way to +// format the value. In particular, when the value is a C string +// (char pointer) and the other operand is an STL string object, we +// want to format the C string as a string, since we know it is +// compared by value with the string object. If the value is a char +// pointer but the other operand is not an STL string object, we don't +// know whether the pointer is supposed to point to a NUL-terminated +// string, and thus want to print it as a pointer to be safe. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// The default case. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint& value) { + return ::testing::PrintToString(value); + } +}; + +// Array. +template +class FormatForComparison { + public: + static ::std::string Format(const ToPrint* value) { + return FormatForComparison::Format(value); + } +}; + +// By default, print C string as pointers to be safe, as we don't know +// whether they actually point to a NUL-terminated string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ + template \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(static_cast(value)); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); +GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ + +// If a C string is compared with an STL string object, we know it's meant +// to point to a NUL-terminated string, and thus can print it as a string. + +#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ + template <> \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ + } + +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); + +#if GTEST_HAS_GLOBAL_STRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string); +#endif + +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring); +#endif + +#if GTEST_HAS_STD_WSTRING +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); +GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); +#endif + +#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ + +// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) +// operand to be used in a failure message. The type (but not value) +// of the other operand may affect the format. This allows us to +// print a char* as a raw pointer when it is compared against another +// char* or void*, and print it as a C string when it is compared +// against an std::string object, for example. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +std::string FormatForComparisonFailureMessage( + const T1& value, const T2& /* other_operand */) { + return FormatForComparison::Format(value); +} + +// UniversalPrinter::Print(value, ostream_ptr) prints the given +// value to the given ostream. The caller must ensure that +// 'ostream_ptr' is not NULL, or the behavior is undefined. +// +// We define UniversalPrinter as a class template (as opposed to a +// function template), as we need to partially specialize it for +// reference types, which cannot be done with function templates. +template +class UniversalPrinter; + +template +void UniversalPrint(const T& value, ::std::ostream* os); + +// Used to print an STL-style container when the user doesn't define +// a PrintTo() for it. +template +void DefaultPrintTo(IsContainer /* dummy */, + false_type /* is not a pointer */, + const C& container, ::std::ostream* os) { + const size_t kMaxCount = 32; // The maximum number of elements to print. + *os << '{'; + size_t count = 0; + for (typename C::const_iterator it = container.begin(); + it != container.end(); ++it, ++count) { + if (count > 0) { + *os << ','; + if (count == kMaxCount) { // Enough has been printed. + *os << " ..."; + break; + } + } + *os << ' '; + // We cannot call PrintTo(*it, os) here as PrintTo() doesn't + // handle *it being a native array. + internal::UniversalPrint(*it, os); + } + + if (count > 0) { + *os << ' '; + } + *os << '}'; +} + +// Used to print a pointer that is neither a char pointer nor a member +// pointer, when the user doesn't define PrintTo() for it. (A member +// variable pointer or member function pointer doesn't really point to +// a location in the address space. Their representation is +// implementation-defined. Therefore they will be printed as raw +// bytes.) +template +void DefaultPrintTo(IsNotContainer /* dummy */, + true_type /* is a pointer */, + T* p, ::std::ostream* os) { + if (p == NULL) { + *os << "NULL"; + } else { + // C++ doesn't allow casting from a function pointer to any object + // pointer. + // + // IsTrue() silences warnings: "Condition is always true", + // "unreachable code". + if (IsTrue(ImplicitlyConvertible::value)) { + // T is not a function type. We just call << to print p, + // relying on ADL to pick up user-defined << for their pointer + // types, if any. + *os << p; + } else { + // T is a function type, so '*os << p' doesn't do what we want + // (it just prints p as bool). We want to print p as a const + // void*. However, we cannot cast it to const void* directly, + // even using reinterpret_cast, as earlier versions of gcc + // (e.g. 3.4.5) cannot compile the cast when p is a function + // pointer. Casting to UInt64 first solves the problem. + *os << reinterpret_cast( + reinterpret_cast(p)); + } + } +} + +// Used to print a non-container, non-pointer value when the user +// doesn't define PrintTo() for it. +template +void DefaultPrintTo(IsNotContainer /* dummy */, + false_type /* is not a pointer */, + const T& value, ::std::ostream* os) { + ::testing_internal::DefaultPrintNonContainerTo(value, os); +} + +// Prints the given value using the << operator if it has one; +// otherwise prints the bytes in it. This is what +// UniversalPrinter::Print() does when PrintTo() is not specialized +// or overloaded for type T. +// +// A user can override this behavior for a class type Foo by defining +// an overload of PrintTo() in the namespace where Foo is defined. We +// give the user this option as sometimes defining a << operator for +// Foo is not desirable (e.g. the coding style may prevent doing it, +// or there is already a << operator but it doesn't do what the user +// wants). +template +void PrintTo(const T& value, ::std::ostream* os) { + // DefaultPrintTo() is overloaded. The type of its first two + // arguments determine which version will be picked. If T is an + // STL-style container, the version for container will be called; if + // T is a pointer, the pointer version will be called; otherwise the + // generic version will be called. + // + // Note that we check for container types here, prior to we check + // for protocol message types in our operator<<. The rationale is: + // + // For protocol messages, we want to give people a chance to + // override Google Mock's format by defining a PrintTo() or + // operator<<. For STL containers, other formats can be + // incompatible with Google Mock's format for the container + // elements; therefore we check for container types here to ensure + // that our format is used. + // + // The second argument of DefaultPrintTo() is needed to bypass a bug + // in Symbian's C++ compiler that prevents it from picking the right + // overload between: + // + // PrintTo(const T& x, ...); + // PrintTo(T* x, ...); + DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); +} + +// The following list of PrintTo() overloads tells +// UniversalPrinter::Print() how to print standard types (built-in +// types, strings, plain arrays, and pointers). + +// Overloads for various char types. +GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); +GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); +inline void PrintTo(char c, ::std::ostream* os) { + // When printing a plain char, we always treat it as unsigned. This + // way, the output won't be affected by whether the compiler thinks + // char is signed or not. + PrintTo(static_cast(c), os); +} + +// Overloads for other simple built-in types. +inline void PrintTo(bool x, ::std::ostream* os) { + *os << (x ? "true" : "false"); +} + +// Overload for wchar_t type. +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its decimal code (except for L'\0'). +// The L'\0' char is printed as "L'\\0'". The decimal code is printed +// as signed integer when wchar_t is implemented by the compiler +// as a signed type and is printed as an unsigned integer when wchar_t +// is implemented as an unsigned type. +GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); + +// Overloads for C strings. +GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); +inline void PrintTo(char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// signed/unsigned char is often used for representing binary data, so +// we print pointers to it as void* to be safe. +inline void PrintTo(const signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(signed char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(const unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +inline void PrintTo(unsigned char* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} + +// MSVC can be configured to define wchar_t as a typedef of unsigned +// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native +// type. When wchar_t is a typedef, defining an overload for const +// wchar_t* would cause unsigned short* be printed as a wide string, +// possibly causing invalid memory accesses. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Overloads for wide C strings +GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); +inline void PrintTo(wchar_t* s, ::std::ostream* os) { + PrintTo(ImplicitCast_(s), os); +} +#endif + +// Overload for C arrays. Multi-dimensional arrays are printed +// properly. + +// Prints the given number of elements in an array, without printing +// the curly braces. +template +void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { + UniversalPrint(a[0], os); + for (size_t i = 1; i != count; i++) { + *os << ", "; + UniversalPrint(a[i], os); + } +} + +// Overloads for ::string and ::std::string. +#if GTEST_HAS_GLOBAL_STRING +GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); +inline void PrintTo(const ::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); +inline void PrintTo(const ::std::string& s, ::std::ostream* os) { + PrintStringTo(s, os); +} + +// Overloads for ::wstring and ::std::wstring. +#if GTEST_HAS_GLOBAL_WSTRING +GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); +inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { + PrintWideStringTo(s, os); +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ +// Helper function for printing a tuple. T must be instantiated with +// a tuple type. +template +void PrintTupleTo(const T& t, ::std::ostream* os); +#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_TR1_TUPLE +// Overload for ::std::tr1::tuple. Needed for printing function arguments, +// which are packed as tuples. + +// Overloaded PrintTo() for tuples of various arities. We support +// tuples of up-to 10 fields. The following implementation works +// regardless of whether tr1::tuple is implemented using the +// non-standard variadic template feature or not. + +inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo(const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} + +template +void PrintTo( + const ::std::tr1::tuple& t, + ::std::ostream* os) { + PrintTupleTo(t, os); +} +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ +template +void PrintTo(const ::std::tuple& t, ::std::ostream* os) { + PrintTupleTo(t, os); +} +#endif // GTEST_HAS_STD_TUPLE_ + +// Overload for std::pair. +template +void PrintTo(const ::std::pair& value, ::std::ostream* os) { + *os << '('; + // We cannot use UniversalPrint(value.first, os) here, as T1 may be + // a reference type. The same for printing value.second. + UniversalPrinter::Print(value.first, os); + *os << ", "; + UniversalPrinter::Print(value.second, os); + *os << ')'; +} + +// Implements printing a non-reference type T by letting the compiler +// pick the right overload of PrintTo() for T. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) + + // Note: we deliberately don't call this PrintTo(), as that name + // conflicts with ::testing::internal::PrintTo in the body of the + // function. + static void Print(const T& value, ::std::ostream* os) { + // By default, ::testing::internal::PrintTo() is used for printing + // the value. + // + // Thanks to Koenig look-up, if T is a class and has its own + // PrintTo() function defined in its namespace, that function will + // be visible here. Since it is more specific than the generic ones + // in ::testing::internal, it will be picked by the compiler in the + // following statement - exactly what we want. + PrintTo(value, os); + } + + GTEST_DISABLE_MSC_WARNINGS_POP_() +}; + +// UniversalPrintArray(begin, len, os) prints an array of 'len' +// elements, starting at address 'begin'. +template +void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { + if (len == 0) { + *os << "{}"; + } else { + *os << "{ "; + const size_t kThreshold = 18; + const size_t kChunkSize = 8; + // If the array has more than kThreshold elements, we'll have to + // omit some details by printing only the first and the last + // kChunkSize elements. + // TODO(wan@google.com): let the user control the threshold using a flag. + if (len <= kThreshold) { + PrintRawArrayTo(begin, len, os); + } else { + PrintRawArrayTo(begin, kChunkSize, os); + *os << ", ..., "; + PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); + } + *os << " }"; + } +} +// This overload prints a (const) char array compactly. +GTEST_API_ void UniversalPrintArray( + const char* begin, size_t len, ::std::ostream* os); + +// This overload prints a (const) wchar_t array compactly. +GTEST_API_ void UniversalPrintArray( + const wchar_t* begin, size_t len, ::std::ostream* os); + +// Implements printing an array type T[N]. +template +class UniversalPrinter { + public: + // Prints the given array, omitting some elements when there are too + // many. + static void Print(const T (&a)[N], ::std::ostream* os) { + UniversalPrintArray(a, N, os); + } +}; + +// Implements printing a reference type T&. +template +class UniversalPrinter { + public: + // MSVC warns about adding const to a function type, so we want to + // disable the warning. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) + + static void Print(const T& value, ::std::ostream* os) { + // Prints the address of the value. We use reinterpret_cast here + // as static_cast doesn't compile when T is a function type. + *os << "@" << reinterpret_cast(&value) << " "; + + // Then prints the value itself. + UniversalPrint(value, os); + } + + GTEST_DISABLE_MSC_WARNINGS_POP_() +}; + +// Prints a value tersely: for a reference type, the referenced value +// (but not the address) is printed; for a (const) char pointer, the +// NUL-terminated string (but not the pointer) is printed. + +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T& value, ::std::ostream* os) { + UniversalPrint(value, os); + } +}; +template +class UniversalTersePrinter { + public: + static void Print(const T (&value)[N], ::std::ostream* os) { + UniversalPrinter::Print(value, os); + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(const char* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(string(str), os); + } + } +}; +template <> +class UniversalTersePrinter { + public: + static void Print(char* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +#if GTEST_HAS_STD_WSTRING +template <> +class UniversalTersePrinter { + public: + static void Print(const wchar_t* str, ::std::ostream* os) { + if (str == NULL) { + *os << "NULL"; + } else { + UniversalPrint(::std::wstring(str), os); + } + } +}; +#endif + +template <> +class UniversalTersePrinter { + public: + static void Print(wchar_t* str, ::std::ostream* os) { + UniversalTersePrinter::Print(str, os); + } +}; + +template +void UniversalTersePrint(const T& value, ::std::ostream* os) { + UniversalTersePrinter::Print(value, os); +} + +// Prints a value using the type inferred by the compiler. The +// difference between this and UniversalTersePrint() is that for a +// (const) char pointer, this prints both the pointer and the +// NUL-terminated string. +template +void UniversalPrint(const T& value, ::std::ostream* os) { + // A workarond for the bug in VC++ 7.1 that prevents us from instantiating + // UniversalPrinter with T directly. + typedef T T1; + UniversalPrinter::Print(value, os); +} + +typedef ::std::vector Strings; + +// TuplePolicy must provide: +// - tuple_size +// size of tuple TupleT. +// - get(const TupleT& t) +// static function extracting element I of tuple TupleT. +// - tuple_element::type +// type of element I of tuple TupleT. +template +struct TuplePolicy; + +#if GTEST_HAS_TR1_TUPLE +template +struct TuplePolicy { + typedef TupleT Tuple; + static const size_t tuple_size = ::std::tr1::tuple_size::value; + + template + struct tuple_element : ::std::tr1::tuple_element {}; + + template + static typename AddReference< + const typename ::std::tr1::tuple_element::type>::type get( + const Tuple& tuple) { + return ::std::tr1::get(tuple); + } +}; +template +const size_t TuplePolicy::tuple_size; +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ +template +struct TuplePolicy< ::std::tuple > { + typedef ::std::tuple Tuple; + static const size_t tuple_size = ::std::tuple_size::value; + + template + struct tuple_element : ::std::tuple_element {}; + + template + static const typename ::std::tuple_element::type& get( + const Tuple& tuple) { + return ::std::get(tuple); + } +}; +template +const size_t TuplePolicy< ::std::tuple >::tuple_size; +#endif // GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ +// This helper template allows PrintTo() for tuples and +// UniversalTersePrintTupleFieldsToStrings() to be defined by +// induction on the number of tuple fields. The idea is that +// TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N +// fields in tuple t, and can be defined in terms of +// TuplePrefixPrinter. +// +// The inductive case. +template +struct TuplePrefixPrinter { + // Prints the first N fields of a tuple. + template + static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { + TuplePrefixPrinter::PrintPrefixTo(t, os); + GTEST_INTENTIONAL_CONST_COND_PUSH_() + if (N > 1) { + GTEST_INTENTIONAL_CONST_COND_POP_() + *os << ", "; + } + UniversalPrinter< + typename TuplePolicy::template tuple_element::type> + ::Print(TuplePolicy::template get(t), os); + } + + // Tersely prints the first N fields of a tuple to a string vector, + // one element for each field. + template + static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { + TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); + ::std::stringstream ss; + UniversalTersePrint(TuplePolicy::template get(t), &ss); + strings->push_back(ss.str()); + } +}; + +// Base case. +template <> +struct TuplePrefixPrinter<0> { + template + static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} + + template + static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} +}; + +// Helper function for printing a tuple. +// Tuple must be either std::tr1::tuple or std::tuple type. +template +void PrintTupleTo(const Tuple& t, ::std::ostream* os) { + *os << "("; + TuplePrefixPrinter::tuple_size>::PrintPrefixTo(t, os); + *os << ")"; +} + +// Prints the fields of a tuple tersely to a string vector, one +// element for each field. See the comment before +// UniversalTersePrint() for how we define "tersely". +template +Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { + Strings result; + TuplePrefixPrinter::tuple_size>:: + TersePrintPrefixToStrings(value, &result); + return result; +} +#endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ + +} // namespace internal + +template +::std::string PrintToString(const T& value) { + ::std::stringstream ss; + internal::UniversalTersePrinter::Print(value, &ss); + return ss.str(); +} + +} // namespace testing + +// Include any custom printer added by the local installation. +// We must include this header at the end to make sure it can use the +// declarations from this file. +#include "gtest/internal/custom/gtest-printers.h" + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-spi.h b/gtestsrc/gtest/include/gtest/gtest-spi.h new file mode 100644 index 0000000..f63fa9a --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-spi.h @@ -0,0 +1,232 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Utilities for testing Google Test itself and code that uses Google Test +// (e.g. frameworks built on top of Google Test). + +#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ +#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ + +#include "gtest/gtest.h" + +namespace testing { + +// This helper class can be used to mock out Google Test failure reporting +// so that we can test Google Test or code that builds on Google Test. +// +// An object of this class appends a TestPartResult object to the +// TestPartResultArray object given in the constructor whenever a Google Test +// failure is reported. It can either intercept only failures that are +// generated in the same thread that created this object or it can intercept +// all generated failures. The scope of this mock object can be controlled with +// the second argument to the two arguments constructor. +class GTEST_API_ ScopedFakeTestPartResultReporter + : public TestPartResultReporterInterface { + public: + // The two possible mocking modes of this object. + enum InterceptMode { + INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. + INTERCEPT_ALL_THREADS // Intercepts all failures. + }; + + // The c'tor sets this object as the test part result reporter used + // by Google Test. The 'result' parameter specifies where to report the + // results. This reporter will only catch failures generated in the current + // thread. DEPRECATED + explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); + + // Same as above, but you can choose the interception scope of this object. + ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, + TestPartResultArray* result); + + // The d'tor restores the previous test part result reporter. + virtual ~ScopedFakeTestPartResultReporter(); + + // Appends the TestPartResult object to the TestPartResultArray + // received in the constructor. + // + // This method is from the TestPartResultReporterInterface + // interface. + virtual void ReportTestPartResult(const TestPartResult& result); + private: + void Init(); + + const InterceptMode intercept_mode_; + TestPartResultReporterInterface* old_reporter_; + TestPartResultArray* const result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); +}; + +namespace internal { + +// A helper class for implementing EXPECT_FATAL_FAILURE() and +// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +class GTEST_API_ SingleFailureChecker { + public: + // The constructor remembers the arguments. + SingleFailureChecker(const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr); + ~SingleFailureChecker(); + private: + const TestPartResultArray* const results_; + const TestPartResult::Type type_; + const string substr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); +}; + +} // namespace internal + +} // namespace testing + +// A set of macros for testing Google Test assertions or code that's expected +// to generate Google Test fatal failures. It verifies that the given +// statement will cause exactly one fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_FATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - 'statement' cannot reference local non-static variables or +// non-static members of the current object. +// - 'statement' cannot return a value. +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. The AcceptsMacroThatExpandsToUnprotectedComma test in +// gtest_unittest.cc will fail to compile if we do that. +#define EXPECT_FATAL_FAILURE(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper {\ + public:\ + static void Execute() { statement; }\ + };\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ALL_THREADS, >est_failures);\ + GTestExpectFatalFailureHelper::Execute();\ + }\ + } while (::testing::internal::AlwaysFalse()) + +// A macro for testing Google Test assertions or code that's expected to +// generate Google Test non-fatal failures. It asserts that the given +// statement will cause exactly one non-fatal Google Test failure with 'substr' +// being part of the failure message. +// +// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only +// affects and considers failures generated in the current thread and +// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. +// +// 'statement' is allowed to reference local variables and members of +// the current object. +// +// The verification of the assertion is done correctly even when the statement +// throws an exception or aborts the current function. +// +// Known restrictions: +// - You cannot stream a failure message to this macro. +// +// Note that even though the implementations of the following two +// macros are much alike, we cannot refactor them to use a common +// helper macro, due to some peculiarity in how the preprocessor +// works. If we do that, the code won't compile when the user gives +// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that +// expands to code containing an unprotected comma. The +// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc +// catches that. +// +// For the same reason, we have to write +// if (::testing::internal::AlwaysTrue()) { statement; } +// instead of +// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) +// to avoid an MSVC warning on unreachable code. +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do {\ + ::testing::TestPartResultArray gtest_failures;\ + ::testing::internal::SingleFailureChecker gtest_checker(\ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr));\ + {\ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ + >est_failures);\ + if (::testing::internal::AlwaysTrue()) { statement; }\ + }\ + } while (::testing::internal::AlwaysFalse()) + +#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-test-part.h b/gtestsrc/gtest/include/gtest/gtest-test-part.h new file mode 100644 index 0000000..77eb844 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-test-part.h @@ -0,0 +1,179 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ + +#include +#include +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" + +namespace testing { + +// A copyable object representing the result of a test part (i.e. an +// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). +// +// Don't inherit from TestPartResult as its destructor is not virtual. +class GTEST_API_ TestPartResult { + public: + // The possible outcomes of a test part (i.e. an assertion or an + // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). + enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure // Failed and the test should be terminated. + }; + + // C'tor. TestPartResult does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestPartResult object. + TestPartResult(Type a_type, + const char* a_file_name, + int a_line_number, + const char* a_message) + : type_(a_type), + file_name_(a_file_name == NULL ? "" : a_file_name), + line_number_(a_line_number), + summary_(ExtractSummary(a_message)), + message_(a_message) { + } + + // Gets the outcome of the test part. + Type type() const { return type_; } + + // Gets the name of the source file where the test part took place, or + // NULL if it's unknown. + const char* file_name() const { + return file_name_.empty() ? NULL : file_name_.c_str(); + } + + // Gets the line in the source file where the test part took place, + // or -1 if it's unknown. + int line_number() const { return line_number_; } + + // Gets the summary of the failure message. + const char* summary() const { return summary_.c_str(); } + + // Gets the message associated with the test part. + const char* message() const { return message_.c_str(); } + + // Returns true iff the test part passed. + bool passed() const { return type_ == kSuccess; } + + // Returns true iff the test part failed. + bool failed() const { return type_ != kSuccess; } + + // Returns true iff the test part non-fatally failed. + bool nonfatally_failed() const { return type_ == kNonFatalFailure; } + + // Returns true iff the test part fatally failed. + bool fatally_failed() const { return type_ == kFatalFailure; } + + private: + Type type_; + + // Gets the summary of the failure message by omitting the stack + // trace in it. + static std::string ExtractSummary(const char* message); + + // The name of the source file where the test part took place, or + // "" if the source file is unknown. + std::string file_name_; + // The line in the source file where the test part took place, or -1 + // if the line number is unknown. + int line_number_; + std::string summary_; // The test failure summary. + std::string message_; // The test failure message. +}; + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result); + +// An array of TestPartResult objects. +// +// Don't inherit from TestPartResultArray as its destructor is not +// virtual. +class GTEST_API_ TestPartResultArray { + public: + TestPartResultArray() {} + + // Appends the given TestPartResult to the array. + void Append(const TestPartResult& result); + + // Returns the TestPartResult at the given index (0-based). + const TestPartResult& GetTestPartResult(int index) const; + + // Returns the number of TestPartResult objects in the array. + int size() const; + + private: + std::vector array_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); +}; + +// This interface knows how to report a test part result. +class TestPartResultReporterInterface { + public: + virtual ~TestPartResultReporterInterface() {} + + virtual void ReportTestPartResult(const TestPartResult& result) = 0; +}; + +namespace internal { + +// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a +// statement generates new fatal failures. To do so it registers itself as the +// current test part result reporter. Besides checking if fatal failures were +// reported, it only delegates the reporting to the former result reporter. +// The original result reporter is restored in the destructor. +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +class GTEST_API_ HasNewFatalFailureHelper + : public TestPartResultReporterInterface { + public: + HasNewFatalFailureHelper(); + virtual ~HasNewFatalFailureHelper(); + virtual void ReportTestPartResult(const TestPartResult& result); + bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: + bool has_new_fatal_failure_; + TestPartResultReporterInterface* original_reporter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); +}; + +} // namespace internal + +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest-typed-test.h b/gtestsrc/gtest/include/gtest/gtest-typed-test.h new file mode 100644 index 0000000..5f69d56 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest-typed-test.h @@ -0,0 +1,263 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ + +// This header implements typed tests and type-parameterized tests. + +// Typed (aka type-driven) tests repeat the same test for types in a +// list. You must know which types you want to test with when writing +// typed tests. Here's how you do it: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + public: + ... + typedef std::list List; + static T shared_; + T value_; +}; + +// Next, associate a list of types with the test case, which will be +// repeated for each type in the list. The typedef is necessary for +// the macro to parse correctly. +typedef testing::Types MyTypes; +TYPED_TEST_CASE(FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// TYPED_TEST_CASE(FooTest, int); + +// Then, use TYPED_TEST() instead of TEST_F() to define as many typed +// tests for this test case as you want. +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + // Since we are inside a derived class template, C++ requires use to + // visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the TestFixture:: + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the "typename + // TestFixture::" prefix. + typename TestFixture::List values; + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } + +#endif // 0 + +// Type-parameterized tests are abstract test patterns parameterized +// by a type. Compared with typed tests, type-parameterized tests +// allow you to define the test pattern without knowing what the type +// parameters are. The defined pattern can be instantiated with +// different types any number of times, in any number of translation +// units. +// +// If you are designing an interface or concept, you can define a +// suite of type-parameterized tests to verify properties that any +// valid implementation of the interface/concept should have. Then, +// each implementation can easily instantiate the test suite to verify +// that it conforms to the requirements, without having to write +// similar tests repeatedly. Here's an example: + +#if 0 + +// First, define a fixture class template. It should be parameterized +// by a type. Remember to derive it from testing::Test. +template +class FooTest : public testing::Test { + ... +}; + +// Next, declare that you will define a type-parameterized test case +// (the _P suffix is for "parameterized" or "pattern", whichever you +// prefer): +TYPED_TEST_CASE_P(FooTest); + +// Then, use TYPED_TEST_P() to define as many type-parameterized tests +// for this type-parameterized test case as you want. +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } + +// Now the tricky part: you need to register all test patterns before +// you can instantiate them. The first argument of the macro is the +// test case name; the rest are the names of the tests in this test +// case. +REGISTER_TYPED_TEST_CASE_P(FooTest, + DoesBlah, HasPropertyA); + +// Finally, you are free to instantiate the pattern with the types you +// want. If you put the above code in a header file, you can #include +// it in multiple C++ source files and instantiate it multiple times. +// +// To distinguish different instances of the pattern, the first +// argument to the INSTANTIATE_* macro is a prefix that will be added +// to the actual test case name. Remember to pick unique prefixes for +// different instances. +typedef testing::Types MyTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); + +// If the type list contains only one type, you can write that type +// directly without Types<...>: +// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); + +#endif // 0 + +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/gtest-type-util.h" + +// Implements typed tests. + +#if GTEST_HAS_TYPED_TEST + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the typedef for the type parameters of the +// given test case. +# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define TYPED_TEST_CASE(CaseName, Types) \ + typedef ::testing::internal::TypeList< Types >::type \ + GTEST_TYPE_PARAMS_(CaseName) + +# define TYPED_TEST(CaseName, TestName) \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ + : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, \ + ::testing::internal::TemplateSel< \ + GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ + GTEST_TYPE_PARAMS_(CaseName)>::Register(\ + "", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + #CaseName, #TestName, 0); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() + +#endif // GTEST_HAS_TYPED_TEST + +// Implements type-parameterized tests. + +#if GTEST_HAS_TYPED_TEST_P + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the namespace name that the type-parameterized tests for +// the given type-parameterized test case are defined in. The exact +// name of the namespace is subject to change without notice. +# define GTEST_CASE_NAMESPACE_(TestCaseName) \ + gtest_case_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Expands to the name of the variable used to remember the names of +// the defined tests in the given test case. +# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ + gtest_typed_test_case_p_state_##TestCaseName##_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. +// +// Expands to the name of the variable used to remember the names of +// the registered tests in the given test case. +# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ + gtest_registered_test_names_##TestCaseName##_ + +// The variables defined in the type-parameterized test macros are +// static as typically these macros are used in a .h file that can be +// #included in multiple translation units linked together. +# define TYPED_TEST_CASE_P(CaseName) \ + static ::testing::internal::TypedTestCasePState \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) + +# define TYPED_TEST_P(CaseName, TestName) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + template \ + class TestName : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ + __FILE__, __LINE__, #CaseName, #TestName); \ + } \ + template \ + void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() + +# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ + } \ + static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ + __FILE__, __LINE__, #__VA_ARGS__) + +// The 'Types' template argument below must have spaces around it +// since some compilers may choke on '>>' when passing a template +// instance (e.g. Types) +# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ + bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestCase::type>::Register(\ + #Prefix, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_CASE_P_STATE_(CaseName), \ + #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) + +#endif // GTEST_HAS_TYPED_TEST_P + +#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest.h b/gtestsrc/gtest/include/gtest/gtest.h new file mode 100644 index 0000000..f846c5b --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest.h @@ -0,0 +1,2236 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the public API for Google Test. It should be +// included by any test program that uses Google Test. +// +// IMPORTANT NOTE: Due to limitation of the C++ language, we have to +// leave some internal implementation details in this header file. +// They are clearly marked by comments like this: +// +// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +// +// Such code is NOT meant to be used by a user directly, and is subject +// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user +// program! +// +// Acknowledgment: Google Test borrowed the idea of automatic test +// registration from Barthelemy Dagenais' (barthelemy@prologique.com) +// easyUnit framework. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +#define GTEST_INCLUDE_GTEST_GTEST_H_ + +#include +#include +#include + +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" +#include "gtest/gtest-death-test.h" +#include "gtest/gtest-message.h" +#include "gtest/gtest-param-test.h" +#include "gtest/gtest-printers.h" +#include "gtest/gtest_prod.h" +#include "gtest/gtest-test-part.h" +#include "gtest/gtest-typed-test.h" + +// Depending on the platform, different string classes are available. +// On Linux, in addition to ::std::string, Google also makes use of +// class ::string, which has the same interface as ::std::string, but +// has a different implementation. +// +// You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that +// ::string is available AND is a distinct type to ::std::string, or +// define it to 0 to indicate otherwise. +// +// If ::std::string and ::string are the same class on your platform +// due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0. +// +// If you do not define GTEST_HAS_GLOBAL_STRING, it is defined +// heuristically. + +namespace testing { + +// Declares the flags. + +// This flag temporary enables the disabled tests. +GTEST_DECLARE_bool_(also_run_disabled_tests); + +// This flag brings the debugger on an assertion failure. +GTEST_DECLARE_bool_(break_on_failure); + +// This flag controls whether Google Test catches all test-thrown exceptions +// and logs them as failures. +GTEST_DECLARE_bool_(catch_exceptions); + +// This flag enables using colors in terminal output. Available values are +// "yes" to enable colors, "no" (disable colors), or "auto" (the default) +// to let Google Test decide. +GTEST_DECLARE_string_(color); + +// This flag sets up the filter to select by name using a glob pattern +// the tests to run. If the filter is not given all tests are executed. +GTEST_DECLARE_string_(filter); + +// This flag causes the Google Test to list tests. None of the tests listed +// are actually run if the flag is provided. +GTEST_DECLARE_bool_(list_tests); + +// This flag controls whether Google Test emits a detailed XML report to a file +// in addition to its normal textual output. +GTEST_DECLARE_string_(output); + +// This flags control whether Google Test prints the elapsed time for each +// test. +GTEST_DECLARE_bool_(print_time); + +// This flag specifies the random number seed. +GTEST_DECLARE_int32_(random_seed); + +// This flag sets how many times the tests are repeated. The default value +// is 1. If the value is -1 the tests are repeating forever. +GTEST_DECLARE_int32_(repeat); + +// This flag controls whether Google Test includes Google Test internal +// stack frames in failure stack traces. +GTEST_DECLARE_bool_(show_internal_stack_frames); + +// When this flag is specified, tests' order is randomized on every iteration. +GTEST_DECLARE_bool_(shuffle); + +// This flag specifies the maximum number of stack frames to be +// printed in a failure message. +GTEST_DECLARE_int32_(stack_trace_depth); + +// When this flag is specified, a failed assertion will throw an +// exception if exceptions are enabled, or exit the program with a +// non-zero code otherwise. +GTEST_DECLARE_bool_(throw_on_failure); + +// When this flag is set with a "host:port" string, on supported +// platforms test results are streamed to the specified port on +// the specified host machine. +GTEST_DECLARE_string_(stream_result_to); + +// The upper limit for valid stack trace depths. +const int kMaxStackTraceDepth = 100; + +namespace internal { + +class AssertHelper; +class DefaultGlobalTestPartResultReporter; +class ExecDeathTest; +class NoExecDeathTest; +class FinalSuccessChecker; +class GTestFlagSaver; +class StreamingListenerTest; +class TestResultAccessor; +class TestEventListenersAccessor; +class TestEventRepeater; +class UnitTestRecordPropertyTestHelper; +class WindowsDeathTest; +class UnitTestImpl* GetUnitTestImpl(); +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message); + +} // namespace internal + +// The friend relationship of some of these classes is cyclic. +// If we don't forward declare them the compiler might confuse the classes +// in friendship clauses with same named classes on the scope. +class Test; +class TestCase; +class TestInfo; +class UnitTest; + +// A class for indicating whether an assertion was successful. When +// the assertion wasn't successful, the AssertionResult object +// remembers a non-empty message that describes how it failed. +// +// To create an instance of this class, use one of the factory functions +// (AssertionSuccess() and AssertionFailure()). +// +// This class is useful for two purposes: +// 1. Defining predicate functions to be used with Boolean test assertions +// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts +// 2. Defining predicate-format functions to be +// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). +// +// For example, if you define IsEven predicate: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) +// will print the message +// +// Value of: IsEven(Fib(5)) +// Actual: false (5 is odd) +// Expected: true +// +// instead of a more opaque +// +// Value of: IsEven(Fib(5)) +// Actual: false +// Expected: true +// +// in case IsEven is a simple Boolean predicate. +// +// If you expect your predicate to be reused and want to support informative +// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up +// about half as often as positive ones in our tests), supply messages for +// both success and failure cases: +// +// testing::AssertionResult IsEven(int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess() << n << " is even"; +// else +// return testing::AssertionFailure() << n << " is odd"; +// } +// +// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print +// +// Value of: IsEven(Fib(6)) +// Actual: true (8 is even) +// Expected: false +// +// NB: Predicates that support negative Boolean assertions have reduced +// performance in positive ones so be careful not to use them in tests +// that have lots (tens of thousands) of positive Boolean assertions. +// +// To use this class with EXPECT_PRED_FORMAT assertions such as: +// +// // Verifies that Foo() returns an even number. +// EXPECT_PRED_FORMAT1(IsEven, Foo()); +// +// you need to define: +// +// testing::AssertionResult IsEven(const char* expr, int n) { +// if ((n % 2) == 0) +// return testing::AssertionSuccess(); +// else +// return testing::AssertionFailure() +// << "Expected: " << expr << " is even\n Actual: it's " << n; +// } +// +// If Foo() returns 5, you will see the following message: +// +// Expected: Foo() is even +// Actual: it's 5 +// +class GTEST_API_ AssertionResult { + public: + // Copy constructor. + // Used in EXPECT_TRUE/FALSE(assertion_result). + AssertionResult(const AssertionResult& other); + + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) + + // Used in the EXPECT_TRUE/FALSE(bool_expression). + // + // T must be contextually convertible to bool. + // + // The second parameter prevents this overload from being considered if + // the argument is implicitly convertible to AssertionResult. In that case + // we want AssertionResult's copy constructor to be used. + template + explicit AssertionResult( + const T& success, + typename internal::EnableIf< + !internal::ImplicitlyConvertible::value>::type* + /*enabler*/ = NULL) + : success_(success) {} + + GTEST_DISABLE_MSC_WARNINGS_POP_() + + // Assignment operator. + AssertionResult& operator=(AssertionResult other) { + swap(other); + return *this; + } + + // Returns true iff the assertion succeeded. + operator bool() const { return success_; } // NOLINT + + // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. + AssertionResult operator!() const; + + // Returns the text streamed into this AssertionResult. Test assertions + // use it when they fail (i.e., the predicate's outcome doesn't match the + // assertion's expectation). When nothing has been streamed into the + // object, returns an empty string. + const char* message() const { + return message_.get() != NULL ? message_->c_str() : ""; + } + // TODO(vladl@google.com): Remove this after making sure no clients use it. + // Deprecated; please use message() instead. + const char* failure_message() const { return message(); } + + // Streams a custom failure message into this object. + template AssertionResult& operator<<(const T& value) { + AppendMessage(Message() << value); + return *this; + } + + // Allows streaming basic output manipulators such as endl or flush into + // this object. + AssertionResult& operator<<( + ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { + AppendMessage(Message() << basic_manipulator); + return *this; + } + + private: + // Appends the contents of message to message_. + void AppendMessage(const Message& a_message) { + if (message_.get() == NULL) + message_.reset(new ::std::string); + message_->append(a_message.GetString().c_str()); + } + + // Swap the contents of this AssertionResult with other. + void swap(AssertionResult& other); + + // Stores result of the assertion predicate. + bool success_; + // Stores the message describing the condition in case the expectation + // construct is not satisfied with the predicate's outcome. + // Referenced via a pointer to avoid taking too much stack frame space + // with test assertions. + internal::scoped_ptr< ::std::string> message_; +}; + +// Makes a successful assertion result. +GTEST_API_ AssertionResult AssertionSuccess(); + +// Makes a failed assertion result. +GTEST_API_ AssertionResult AssertionFailure(); + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << msg. +GTEST_API_ AssertionResult AssertionFailure(const Message& msg); + +// The abstract class that all tests inherit from. +// +// In Google Test, a unit test program contains one or many TestCases, and +// each TestCase contains one or many Tests. +// +// When you define a test using the TEST macro, you don't need to +// explicitly derive from Test - the TEST macro automatically does +// this for you. +// +// The only time you derive from Test is when defining a test fixture +// to be used a TEST_F. For example: +// +// class FooTest : public testing::Test { +// protected: +// void SetUp() override { ... } +// void TearDown() override { ... } +// ... +// }; +// +// TEST_F(FooTest, Bar) { ... } +// TEST_F(FooTest, Baz) { ... } +// +// Test is not copyable. +class GTEST_API_ Test { + public: + friend class TestInfo; + + // Defines types for pointers to functions that set up and tear down + // a test case. + typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; + typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; + + // The d'tor is virtual as we intend to inherit from Test. + virtual ~Test(); + + // Sets up the stuff shared by all tests in this test case. + // + // Google Test will call Foo::SetUpTestCase() before running the first + // test in test case Foo. Hence a sub-class can define its own + // SetUpTestCase() method to shadow the one defined in the super + // class. + static void SetUpTestCase() {} + + // Tears down the stuff shared by all tests in this test case. + // + // Google Test will call Foo::TearDownTestCase() after running the last + // test in test case Foo. Hence a sub-class can define its own + // TearDownTestCase() method to shadow the one defined in the super + // class. + static void TearDownTestCase() {} + + // Returns true iff the current test has a fatal failure. + static bool HasFatalFailure(); + + // Returns true iff the current test has a non-fatal failure. + static bool HasNonfatalFailure(); + + // Returns true iff the current test has a (either fatal or + // non-fatal) failure. + static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } + + // Logs a property for the current test, test case, or for the entire + // invocation of the test program when used outside of the context of a + // test case. Only the last value for a given key is remembered. These + // are public static so they can be called from utility functions that are + // not members of the test fixture. Calls to RecordProperty made during + // lifespan of the test (from the moment its constructor starts to the + // moment its destructor finishes) will be output in XML as attributes of + // the element. Properties recorded from fixture's + // SetUpTestCase or TearDownTestCase are logged as attributes of the + // corresponding element. Calls to RecordProperty made in the + // global context (before or after invocation of RUN_ALL_TESTS and from + // SetUp/TearDown method of Environment objects registered with Google + // Test) will be output as attributes of the element. + static void RecordProperty(const std::string& key, const std::string& value); + static void RecordProperty(const std::string& key, int value); + + protected: + // Creates a Test object. + Test(); + + // Sets up the test fixture. + virtual void SetUp(); + + // Tears down the test fixture. + virtual void TearDown(); + + private: + // Returns true iff the current test has the same fixture class as + // the first test in the current test case. + static bool HasSameFixtureClass(); + + // Runs the test after the test fixture has been set up. + // + // A sub-class must implement this to define the test logic. + // + // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. + // Instead, use the TEST or TEST_F macro. + virtual void TestBody() = 0; + + // Sets up, executes, and tears down the test. + void Run(); + + // Deletes self. We deliberately pick an unusual name for this + // internal method to avoid clashing with names used in user TESTs. + void DeleteSelf_() { delete this; } + + const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; + + // Often a user misspells SetUp() as Setup() and spends a long time + // wondering why it is never called by Google Test. The declaration of + // the following method is solely for catching such an error at + // compile time: + // + // - The return type is deliberately chosen to be not void, so it + // will be a conflict if void Setup() is declared in the user's + // test fixture. + // + // - This method is private, so it will be another compiler error + // if the method is called from the user's test fixture. + // + // DO NOT OVERRIDE THIS FUNCTION. + // + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } + + // We disallow copying Tests. + GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); +}; + +typedef internal::TimeInMillis TimeInMillis; + +// A copyable object representing a user specified test property which can be +// output as a key/value string pair. +// +// Don't inherit from TestProperty as its destructor is not virtual. +class TestProperty { + public: + // C'tor. TestProperty does NOT have a default constructor. + // Always use this constructor (with parameters) to create a + // TestProperty object. + TestProperty(const std::string& a_key, const std::string& a_value) : + key_(a_key), value_(a_value) { + } + + // Gets the user supplied key. + const char* key() const { + return key_.c_str(); + } + + // Gets the user supplied value. + const char* value() const { + return value_.c_str(); + } + + // Sets a new value, overriding the one supplied in the constructor. + void SetValue(const std::string& new_value) { + value_ = new_value; + } + + private: + // The key supplied by the user. + std::string key_; + // The value supplied by the user. + std::string value_; +}; + +// The result of a single Test. This includes a list of +// TestPartResults, a list of TestProperties, a count of how many +// death tests there are in the Test, and how much time it took to run +// the Test. +// +// TestResult is not copyable. +class GTEST_API_ TestResult { + public: + // Creates an empty TestResult. + TestResult(); + + // D'tor. Do not inherit from TestResult. + ~TestResult(); + + // Gets the number of all test parts. This is the sum of the number + // of successful test parts and the number of failed test parts. + int total_part_count() const; + + // Returns the number of the test properties. + int test_property_count() const; + + // Returns true iff the test passed (i.e. no test part failed). + bool Passed() const { return !Failed(); } + + // Returns true iff the test failed. + bool Failed() const; + + // Returns true iff the test fatally failed. + bool HasFatalFailure() const; + + // Returns true iff the test has a non-fatal failure. + bool HasNonfatalFailure() const; + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test part result among all the results. i can range + // from 0 to test_property_count() - 1. If i is not in that range, aborts + // the program. + const TestPartResult& GetTestPartResult(int i) const; + + // Returns the i-th test property. i can range from 0 to + // test_property_count() - 1. If i is not in that range, aborts the + // program. + const TestProperty& GetTestProperty(int i) const; + + private: + friend class TestInfo; + friend class TestCase; + friend class UnitTest; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::ExecDeathTest; + friend class internal::TestResultAccessor; + friend class internal::UnitTestImpl; + friend class internal::WindowsDeathTest; + + // Gets the vector of TestPartResults. + const std::vector& test_part_results() const { + return test_part_results_; + } + + // Gets the vector of TestProperties. + const std::vector& test_properties() const { + return test_properties_; + } + + // Sets the elapsed time. + void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } + + // Adds a test property to the list. The property is validated and may add + // a non-fatal failure if invalid (e.g., if it conflicts with reserved + // key names). If a property is already recorded for the same key, the + // value will be updated, rather than storing multiple values for the same + // key. xml_element specifies the element for which the property is being + // recorded and is used for validation. + void RecordProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a failure if the key is a reserved attribute of Google Test + // testcase tags. Returns true if the property is valid. + // TODO(russr): Validate attribute names are legal and human readable. + static bool ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property); + + // Adds a test part result to the list. + void AddTestPartResult(const TestPartResult& test_part_result); + + // Returns the death test count. + int death_test_count() const { return death_test_count_; } + + // Increments the death test count, returning the new count. + int increment_death_test_count() { return ++death_test_count_; } + + // Clears the test part results. + void ClearTestPartResults(); + + // Clears the object. + void Clear(); + + // Protects mutable state of the property vector and of owned + // properties, whose values may be updated. + internal::Mutex test_properites_mutex_; + + // The vector of TestPartResults + std::vector test_part_results_; + // The vector of TestProperties + std::vector test_properties_; + // Running count of death tests. + int death_test_count_; + // The elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + + // We disallow copying TestResult. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); +}; // class TestResult + +// A TestInfo object stores the following information about a test: +// +// Test case name +// Test name +// Whether the test should be run +// A function pointer that creates the test object when invoked +// Test result +// +// The constructor of TestInfo registers itself with the UnitTest +// singleton such that the RUN_ALL_TESTS() macro knows which tests to +// run. +class GTEST_API_ TestInfo { + public: + // Destructs a TestInfo object. This function is not virtual, so + // don't inherit from TestInfo. + ~TestInfo(); + + // Returns the test case name. + const char* test_case_name() const { return test_case_name_.c_str(); } + + // Returns the test name. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a typed + // or a type-parameterized test. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns the text representation of the value parameter, or NULL if this + // is not a value-parameterized test. + const char* value_param() const { + if (value_param_.get() != NULL) + return value_param_->c_str(); + return NULL; + } + + // Returns the file name where this test is defined. + const char* file() const { return location_.file.c_str(); } + + // Returns the line where this test is defined. + int line() const { return location_.line; } + + // Returns true if this test should run, that is if the test is not + // disabled (or it is disabled but the also_run_disabled_tests flag has + // been specified) and its full name matches the user-specified filter. + // + // Google Test allows the user to filter the tests by their full names. + // The full name of a test Bar in test case Foo is defined as + // "Foo.Bar". Only the tests that match the filter will run. + // + // A filter is a colon-separated list of glob (not regex) patterns, + // optionally followed by a '-' and a colon-separated list of + // negative patterns (tests to exclude). A test is run if it + // matches one of the positive patterns and does not match any of + // the negative patterns. + // + // For example, *A*:Foo.* is a filter that matches any string that + // contains the character 'A' or starts with "Foo.". + bool should_run() const { return should_run_; } + + // Returns true iff this test will appear in the XML report. + bool is_reportable() const { + // For now, the XML report includes all tests matching the filter. + // In the future, we may trim tests that are excluded because of + // sharding. + return matches_filter_; + } + + // Returns the result of the test. + const TestResult* result() const { return &result_; } + + private: +#if GTEST_HAS_DEATH_TEST + friend class internal::DefaultDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + friend class Test; + friend class TestCase; + friend class internal::UnitTestImpl; + friend class internal::StreamingListenerTest; + friend TestInfo* internal::MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + internal::CodeLocation code_location, + internal::TypeId fixture_class_id, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + internal::TestFactoryBase* factory); + + // Constructs a TestInfo object. The newly constructed instance assumes + // ownership of the factory object. + TestInfo(const std::string& test_case_name, + const std::string& name, + const char* a_type_param, // NULL if not a type-parameterized test + const char* a_value_param, // NULL if not a value-parameterized test + internal::CodeLocation a_code_location, + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory); + + // Increments the number of death tests encountered in this test so + // far. + int increment_death_test_count() { + return result_.increment_death_test_count(); + } + + // Creates the test object, runs it, records its result, and then + // deletes it. + void Run(); + + static void ClearTestResult(TestInfo* test_info) { + test_info->result_.Clear(); + } + + // These fields are immutable properties of the test. + const std::string test_case_name_; // Test case name + const std::string name_; // Test name + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // Text representation of the value parameter, or NULL if this is not a + // value-parameterized test. + const internal::scoped_ptr value_param_; + internal::CodeLocation location_; + const internal::TypeId fixture_class_id_; // ID of the test fixture class + bool should_run_; // True iff this test should run + bool is_disabled_; // True iff this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. + internal::TestFactoryBase* const factory_; // The factory that creates + // the test object + + // This field is mutable and needs to be reset before running the + // test for the second time. + TestResult result_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); +}; + +// A test case, which consists of a vector of TestInfos. +// +// TestCase is not copyable. +class GTEST_API_ TestCase { + public: + // Creates a TestCase with the given name. + // + // TestCase does NOT have a default constructor. Always use this + // constructor to create a TestCase object. + // + // Arguments: + // + // name: name of the test case + // a_type_param: the name of the test's type parameter, or NULL if + // this is not a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase(const char* name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Destructor of TestCase. + virtual ~TestCase(); + + // Gets the name of the TestCase. + const char* name() const { return name_.c_str(); } + + // Returns the name of the parameter type, or NULL if this is not a + // type-parameterized test case. + const char* type_param() const { + if (type_param_.get() != NULL) + return type_param_->c_str(); + return NULL; + } + + // Returns true if any test in this test case should run. + bool should_run() const { return should_run_; } + + // Gets the number of successful tests in this test case. + int successful_test_count() const; + + // Gets the number of failed tests in this test case. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests in this test case. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Get the number of tests in this test case that should run. + int test_to_run_count() const; + + // Gets the number of all tests in this test case. + int total_test_count() const; + + // Returns true iff the test case passed. + bool Passed() const { return !Failed(); } + + // Returns true iff the test case failed. + bool Failed() const { return failed_test_count() > 0; } + + // Returns the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + const TestInfo* GetTestInfo(int i) const; + + // Returns the TestResult that holds test properties recorded during + // execution of SetUpTestCase and TearDownTestCase. + const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } + + private: + friend class Test; + friend class internal::UnitTestImpl; + + // Gets the (mutable) vector of TestInfos in this TestCase. + std::vector& test_info_list() { return test_info_list_; } + + // Gets the (immutable) vector of TestInfos in this TestCase. + const std::vector& test_info_list() const { + return test_info_list_; + } + + // Returns the i-th test among all the tests. i can range from 0 to + // total_test_count() - 1. If i is not in that range, returns NULL. + TestInfo* GetMutableTestInfo(int i); + + // Sets the should_run member. + void set_should_run(bool should) { should_run_ = should; } + + // Adds a TestInfo to this test case. Will delete the TestInfo upon + // destruction of the TestCase object. + void AddTestInfo(TestInfo * test_info); + + // Clears the results of all tests in this test case. + void ClearResult(); + + // Clears the results of all tests in the given test case. + static void ClearTestCaseResult(TestCase* test_case) { + test_case->ClearResult(); + } + + // Runs every test in this TestCase. + void Run(); + + // Runs SetUpTestCase() for this TestCase. This wrapper is needed + // for catching exceptions thrown from SetUpTestCase(). + void RunSetUpTestCase() { (*set_up_tc_)(); } + + // Runs TearDownTestCase() for this TestCase. This wrapper is + // needed for catching exceptions thrown from TearDownTestCase(). + void RunTearDownTestCase() { (*tear_down_tc_)(); } + + // Returns true iff test passed. + static bool TestPassed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Passed(); + } + + // Returns true iff test failed. + static bool TestFailed(const TestInfo* test_info) { + return test_info->should_run() && test_info->result()->Failed(); + } + + // Returns true iff the test is disabled and will be reported in the XML + // report. + static bool TestReportableDisabled(const TestInfo* test_info) { + return test_info->is_reportable() && test_info->is_disabled_; + } + + // Returns true iff test is disabled. + static bool TestDisabled(const TestInfo* test_info) { + return test_info->is_disabled_; + } + + // Returns true iff this test will appear in the XML report. + static bool TestReportable(const TestInfo* test_info) { + return test_info->is_reportable(); + } + + // Returns true if the given test should run. + static bool ShouldRunTest(const TestInfo* test_info) { + return test_info->should_run(); + } + + // Shuffles the tests in this test case. + void ShuffleTests(internal::Random* random); + + // Restores the test order to before the first shuffle. + void UnshuffleTests(); + + // Name of the test case. + std::string name_; + // Name of the parameter type, or NULL if this is not a typed or a + // type-parameterized test. + const internal::scoped_ptr type_param_; + // The vector of TestInfos in their original order. It owns the + // elements in the vector. + std::vector test_info_list_; + // Provides a level of indirection for the test list to allow easy + // shuffling and restoring the test order. The i-th element in this + // vector is the index of the i-th test in the shuffled test list. + std::vector test_indices_; + // Pointer to the function that sets up the test case. + Test::SetUpTestCaseFunc set_up_tc_; + // Pointer to the function that tears down the test case. + Test::TearDownTestCaseFunc tear_down_tc_; + // True iff any test in this test case should run. + bool should_run_; + // Elapsed time, in milliseconds. + TimeInMillis elapsed_time_; + // Holds test properties recorded during execution of SetUpTestCase and + // TearDownTestCase. + TestResult ad_hoc_test_result_; + + // We disallow copying TestCases. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); +}; + +// An Environment object is capable of setting up and tearing down an +// environment. You should subclass this to define your own +// environment(s). +// +// An Environment object does the set-up and tear-down in virtual +// methods SetUp() and TearDown() instead of the constructor and the +// destructor, as: +// +// 1. You cannot safely throw from a destructor. This is a problem +// as in some cases Google Test is used where exceptions are enabled, and +// we may want to implement ASSERT_* using exceptions where they are +// available. +// 2. You cannot use ASSERT_* directly in a constructor or +// destructor. +class Environment { + public: + // The d'tor is virtual as we need to subclass Environment. + virtual ~Environment() {} + + // Override this to define how to set up the environment. + virtual void SetUp() {} + + // Override this to define how to tear down the environment. + virtual void TearDown() {} + private: + // If you see an error about overriding the following function or + // about it being private, you have mis-spelled SetUp() as Setup(). + struct Setup_should_be_spelled_SetUp {}; + virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } +}; + +// The interface for tracing execution of tests. The methods are organized in +// the order the corresponding events are fired. +class TestEventListener { + public: + virtual ~TestEventListener() {} + + // Fired before any test activity starts. + virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; + + // Fired before each iteration of tests starts. There may be more than + // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration + // index, starting from 0. + virtual void OnTestIterationStart(const UnitTest& unit_test, + int iteration) = 0; + + // Fired before environment set-up for each iteration of tests starts. + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; + + // Fired after environment set-up for each iteration of tests ends. + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; + + // Fired before the test case starts. + virtual void OnTestCaseStart(const TestCase& test_case) = 0; + + // Fired before the test starts. + virtual void OnTestStart(const TestInfo& test_info) = 0; + + // Fired after a failed assertion or a SUCCEED() invocation. + virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; + + // Fired after the test ends. + virtual void OnTestEnd(const TestInfo& test_info) = 0; + + // Fired after the test case ends. + virtual void OnTestCaseEnd(const TestCase& test_case) = 0; + + // Fired before environment tear-down for each iteration of tests starts. + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; + + // Fired after environment tear-down for each iteration of tests ends. + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; + + // Fired after each iteration of tests finishes. + virtual void OnTestIterationEnd(const UnitTest& unit_test, + int iteration) = 0; + + // Fired after all test activities have ended. + virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; +}; + +// The convenience class for users who need to override just one or two +// methods and are not concerned that a possible change to a signature of +// the methods they override will not be caught during the build. For +// comments about each method please see the definition of TestEventListener +// above. +class EmptyTestEventListener : public TestEventListener { + public: + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} + virtual void OnTestStart(const TestInfo& /*test_info*/) {} + virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} + virtual void OnTestEnd(const TestInfo& /*test_info*/) {} + virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} + virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int /*iteration*/) {} + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} +}; + +// TestEventListeners lets users add listeners to track events in Google Test. +class GTEST_API_ TestEventListeners { + public: + TestEventListeners(); + ~TestEventListeners(); + + // Appends an event listener to the end of the list. Google Test assumes + // the ownership of the listener (i.e. it will delete the listener when + // the test program finishes). + void Append(TestEventListener* listener); + + // Removes the given event listener from the list and returns it. It then + // becomes the caller's responsibility to delete the listener. Returns + // NULL if the listener is not found in the list. + TestEventListener* Release(TestEventListener* listener); + + // Returns the standard listener responsible for the default console + // output. Can be removed from the listeners list to shut down default + // console output. Note that removing this object from the listener list + // with Release transfers its ownership to the caller and makes this + // function return NULL the next time. + TestEventListener* default_result_printer() const { + return default_result_printer_; + } + + // Returns the standard listener responsible for the default XML output + // controlled by the --gtest_output=xml flag. Can be removed from the + // listeners list by users who want to shut down the default XML output + // controlled by this flag and substitute it with custom one. Note that + // removing this object from the listener list with Release transfers its + // ownership to the caller and makes this function return NULL the next + // time. + TestEventListener* default_xml_generator() const { + return default_xml_generator_; + } + + private: + friend class TestCase; + friend class TestInfo; + friend class internal::DefaultGlobalTestPartResultReporter; + friend class internal::NoExecDeathTest; + friend class internal::TestEventListenersAccessor; + friend class internal::UnitTestImpl; + + // Returns repeater that broadcasts the TestEventListener events to all + // subscribers. + TestEventListener* repeater(); + + // Sets the default_result_printer attribute to the provided listener. + // The listener is also added to the listener list and previous + // default_result_printer is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultResultPrinter(TestEventListener* listener); + + // Sets the default_xml_generator attribute to the provided listener. The + // listener is also added to the listener list and previous + // default_xml_generator is removed from it and deleted. The listener can + // also be NULL in which case it will not be added to the list. Does + // nothing if the previous and the current listener objects are the same. + void SetDefaultXmlGenerator(TestEventListener* listener); + + // Controls whether events will be forwarded by the repeater to the + // listeners in the list. + bool EventForwardingEnabled() const; + void SuppressEventForwarding(); + + // The actual list of listeners. + internal::TestEventRepeater* repeater_; + // Listener responsible for the standard result output. + TestEventListener* default_result_printer_; + // Listener responsible for the creation of the XML output file. + TestEventListener* default_xml_generator_; + + // We disallow copying TestEventListeners. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); +}; + +// A UnitTest consists of a vector of TestCases. +// +// This is a singleton class. The only instance of UnitTest is +// created when UnitTest::GetInstance() is first called. This +// instance is never deleted. +// +// UnitTest is not copyable. +// +// This class is thread-safe as long as the methods are called +// according to their specification. +class GTEST_API_ UnitTest { + public: + // Gets the singleton UnitTest object. The first time this method + // is called, a UnitTest object is constructed and returned. + // Consecutive calls will return the same object. + static UnitTest* GetInstance(); + + // Runs all tests in this UnitTest object and prints the result. + // Returns 0 if successful, or 1 otherwise. + // + // This method can only be called from the main thread. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + int Run() GTEST_MUST_USE_RESULT_; + + // Returns the working directory when the first TEST() or TEST_F() + // was executed. The UnitTest object owns the string. + const char* original_working_dir() const; + + // Returns the TestCase object for the test that's currently running, + // or NULL if no test is running. + const TestCase* current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the TestInfo object for the test that's currently running, + // or NULL if no test is running. + const TestInfo* current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_); + + // Returns the random seed used at the start of the current test run. + int random_seed() const; + +#if GTEST_HAS_PARAM_TEST + // Returns the ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + // + // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_); +#endif // GTEST_HAS_PARAM_TEST + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const; + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const; + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const; + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const; + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const; + + // Returns the TestResult containing information on test failures and + // properties logged outside of individual test cases. + const TestResult& ad_hoc_test_result() const; + + // Returns the list of event listeners that can be used to track events + // inside Google Test. + TestEventListeners& listeners(); + + private: + // Registers and returns a global test environment. When a test + // program is run, all global test environments will be set-up in + // the order they were registered. After all tests in the program + // have finished, all global test environments will be torn-down in + // the *reverse* order they were registered. + // + // The UnitTest object takes ownership of the given environment. + // + // This method can only be called from the main thread. + Environment* AddEnvironment(Environment* env); + + // Adds a TestPartResult to the current TestResult object. All + // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) + // eventually call this to report their results. The user code + // should use the assertion macros instead of calling this directly. + void AddTestPartResult(TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Adds a TestProperty to the current TestResult object when invoked from + // inside a test, to current TestCase's ad_hoc_test_result_ when invoked + // from SetUpTestCase or TearDownTestCase, or to the global property set + // when invoked elsewhere. If the result already contains a property with + // the same key, the value will be updated. + void RecordProperty(const std::string& key, const std::string& value); + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i); + + // Accessors for the implementation object. + internal::UnitTestImpl* impl() { return impl_; } + const internal::UnitTestImpl* impl() const { return impl_; } + + // These classes and funcions are friends as they need to access private + // members of UnitTest. + friend class Test; + friend class internal::AssertHelper; + friend class internal::ScopedTrace; + friend class internal::StreamingListenerTest; + friend class internal::UnitTestRecordPropertyTestHelper; + friend Environment* AddGlobalTestEnvironment(Environment* env); + friend internal::UnitTestImpl* internal::GetUnitTestImpl(); + friend void internal::ReportFailureInUnknownLocation( + TestPartResult::Type result_type, + const std::string& message); + + // Creates an empty UnitTest. + UnitTest(); + + // D'tor + virtual ~UnitTest(); + + // Pushes a trace defined by SCOPED_TRACE() on to the per-thread + // Google Test trace stack. + void PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Pops a trace from the per-thread Google Test trace stack. + void PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_); + + // Protects mutable state in *impl_. This is mutable as some const + // methods need to lock it too. + mutable internal::Mutex mutex_; + + // Opaque implementation object. This field is never changed once + // the object is constructed. We don't mark it as const here, as + // doing so will cause a warning in the constructor of UnitTest. + // Mutable state in *impl_ is protected by mutex_. + internal::UnitTestImpl* impl_; + + // We disallow copying UnitTest. + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); +}; + +// A convenient wrapper for adding an environment for the test +// program. +// +// You should call this before RUN_ALL_TESTS() is called, probably in +// main(). If you use gtest_main, you need to call this before main() +// starts for it to take effect. For example, you can define a global +// variable like this: +// +// testing::Environment* const foo_env = +// testing::AddGlobalTestEnvironment(new FooEnvironment); +// +// However, we strongly recommend you to write your own main() and +// call AddGlobalTestEnvironment() there, as relying on initialization +// of global variables makes the code harder to read and may cause +// problems when you register multiple environments from different +// translation units and the environments have dependencies among them +// (remember that the compiler doesn't guarantee the order in which +// global variables from different translation units are initialized). +inline Environment* AddGlobalTestEnvironment(Environment* env) { + return UnitTest::GetInstance()->AddEnvironment(env); +} + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +GTEST_API_ void InitGoogleTest(int* argc, char** argv); + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); + +namespace internal { + +// Separate the error generating code from the code path to reduce the stack +// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers +// when calling EXPECT_* in a tight loop. +template +AssertionResult CmpHelperEQFailure(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, const T2& rhs) { + return EqFailure(lhs_expression, + rhs_expression, + FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), + false); +} + +// The helper function for {ASSERT|EXPECT}_EQ. +template +AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs) { +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) + if (lhs == rhs) { + return AssertionSuccess(); + } +GTEST_DISABLE_MSC_WARNINGS_POP_() + + return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); +} + +// With this overloaded version, we allow anonymous enums to be used +// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums +// can be implicitly cast to BiggestInt. +GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs); + +// The helper class for {ASSERT|EXPECT}_EQ. The template argument +// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() +// is a null pointer literal. The following default implementation is +// for lhs_is_null_literal being false. +template +class EqHelper { + public: + // This templatized version is for the general case. + template + static AssertionResult Compare(const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs) { + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); + } + + // With this overloaded version, we allow anonymous enums to be used + // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous + // enums can be implicitly cast to BiggestInt. + // + // Even though its body looks the same as the above version, we + // cannot merge the two, as it will make anonymous enums unhappy. + static AssertionResult Compare(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs) { + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); + } +}; + +// This specialization is used when the first argument to ASSERT_EQ() +// is a null pointer literal, like NULL, false, or 0. +template <> +class EqHelper { + public: + // We define two overloaded versions of Compare(). The first + // version will be picked when the second argument to ASSERT_EQ() is + // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or + // EXPECT_EQ(false, a_bool). + template + static AssertionResult Compare( + const char* lhs_expression, + const char* rhs_expression, + const T1& lhs, + const T2& rhs, + // The following line prevents this overload from being considered if T2 + // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) + // expands to Compare("", "", NULL, my_ptr), which requires a conversion + // to match the Secret* in the other overload, which would otherwise make + // this template match better. + typename EnableIf::value>::type* = 0) { + return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); + } + + // This version will be picked when the second argument to ASSERT_EQ() is a + // pointer, e.g. ASSERT_EQ(NULL, a_pointer). + template + static AssertionResult Compare( + const char* lhs_expression, + const char* rhs_expression, + // We used to have a second template parameter instead of Secret*. That + // template parameter would deduce to 'long', making this a better match + // than the first overload even without the first overload's EnableIf. + // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to + // non-pointer argument" (even a deduced integral argument), so the old + // implementation caused warnings in user code. + Secret* /* lhs (NULL) */, + T* rhs) { + // We already know that 'lhs' is a null pointer. + return CmpHelperEQ(lhs_expression, rhs_expression, + static_cast(NULL), rhs); + } +}; + +// Separate the error generating code from the code path to reduce the stack +// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers +// when calling EXPECT_OP in a tight loop. +template +AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, + const T1& val1, const T2& val2, + const char* op) { + return AssertionFailure() + << "Expected: (" << expr1 << ") " << op << " (" << expr2 + << "), actual: " << FormatForComparisonFailureMessage(val1, val2) + << " vs " << FormatForComparisonFailureMessage(val2, val1); +} + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste +// of similar code. +// +// For each templatized helper function, we also define an overloaded +// version for BiggestInt in order to reduce code bloat and allow +// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled +// with gcc 4. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +template \ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + const T1& val1, const T2& val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ + }\ +}\ +GTEST_API_ AssertionResult CmpHelper##op_name(\ + const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) + +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. + +// Implements the helper function for {ASSERT|EXPECT}_NE +GTEST_IMPL_CMP_HELPER_(NE, !=); +// Implements the helper function for {ASSERT|EXPECT}_LE +GTEST_IMPL_CMP_HELPER_(LE, <=); +// Implements the helper function for {ASSERT|EXPECT}_LT +GTEST_IMPL_CMP_HELPER_(LT, <); +// Implements the helper function for {ASSERT|EXPECT}_GE +GTEST_IMPL_CMP_HELPER_(GE, >=); +// Implements the helper function for {ASSERT|EXPECT}_GT +GTEST_IMPL_CMP_HELPER_(GT, >); + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + +// The helper function for {ASSERT|EXPECT}_STRNE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2); + + +// Helper function for *_STREQ on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); + +// Helper function for *_STRNE on wide strings. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2); + +} // namespace internal + +// IsSubstring() and IsNotSubstring() are intended to be used as the +// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by +// themselves. They check whether needle is a substring of haystack +// (NULL is considered a substring of itself only), and return an +// appropriate error message when they fail. +// +// The {needle,haystack}_expr arguments are the stringified +// expressions that generated the two real arguments. +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); + +#if GTEST_HAS_STD_WSTRING +GTEST_API_ AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +// Helper template function for comparing floating-points. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +template +AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, + const char* rhs_expression, + RawType lhs_value, + RawType rhs_value) { + const FloatingPoint lhs(lhs_value), rhs(rhs_value); + + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + ::std::stringstream lhs_ss; + lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << lhs_value; + + ::std::stringstream rhs_ss; + rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << rhs_value; + + return EqFailure(lhs_expression, + rhs_expression, + StringStreamToString(&lhs_ss), + StringStreamToString(&rhs_ss), + false); +} + +// Helper function for implementing ASSERT_NEAR. +// +// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. +GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error); + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// A class that enables one to stream messages to assertion macros +class GTEST_API_ AssertHelper { + public: + // Constructor. + AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message); + ~AssertHelper(); + + // Message assignment is a semantic trick to enable assertion + // streaming; see the GTEST_MESSAGE_ macro below. + void operator=(const Message& message) const; + + private: + // We put our data in a struct so that the size of the AssertHelper class can + // be as small as possible. This is important because gcc is incapable of + // re-using stack space even for temporary variables, so every EXPECT_EQ + // reserves stack space for another AssertHelper. + struct AssertHelperData { + AssertHelperData(TestPartResult::Type t, + const char* srcfile, + int line_num, + const char* msg) + : type(t), file(srcfile), line(line_num), message(msg) { } + + TestPartResult::Type const type; + const char* const file; + int const line; + std::string const message; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); + }; + + AssertHelperData* const data_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); +}; + +} // namespace internal + +#if GTEST_HAS_PARAM_TEST +// The pure interface class that all value-parameterized tests inherit from. +// A value-parameterized class must inherit from both ::testing::Test and +// ::testing::WithParamInterface. In most cases that just means inheriting +// from ::testing::TestWithParam, but more complicated test hierarchies +// may need to inherit from Test and WithParamInterface at different levels. +// +// This interface has support for accessing the test parameter value via +// the GetParam() method. +// +// Use it with one of the parameter generator defining functions, like Range(), +// Values(), ValuesIn(), Bool(), and Combine(). +// +// class FooTest : public ::testing::TestWithParam { +// protected: +// FooTest() { +// // Can use GetParam() here. +// } +// virtual ~FooTest() { +// // Can use GetParam() here. +// } +// virtual void SetUp() { +// // Can use GetParam() here. +// } +// virtual void TearDown { +// // Can use GetParam() here. +// } +// }; +// TEST_P(FooTest, DoesBar) { +// // Can use GetParam() method here. +// Foo foo; +// ASSERT_TRUE(foo.DoesBar(GetParam())); +// } +// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); + +template +class WithParamInterface { + public: + typedef T ParamType; + virtual ~WithParamInterface() {} + + // The current parameter value. Is also available in the test fixture's + // constructor. This member function is non-static, even though it only + // references static data, to reduce the opportunity for incorrect uses + // like writing 'WithParamInterface::GetParam()' for a test that + // uses a fixture whose parameter type is int. + const ParamType& GetParam() const { + GTEST_CHECK_(parameter_ != NULL) + << "GetParam() can only be called inside a value-parameterized test " + << "-- did you intend to write TEST_P instead of TEST_F?"; + return *parameter_; + } + + private: + // Sets parameter value. The caller is responsible for making sure the value + // remains alive and unchanged throughout the current test. + static void SetParam(const ParamType* parameter) { + parameter_ = parameter; + } + + // Static value used for accessing parameter during a test lifetime. + static const ParamType* parameter_; + + // TestClass must be a subclass of WithParamInterface and Test. + template friend class internal::ParameterizedTestFactory; +}; + +template +const T* WithParamInterface::parameter_ = NULL; + +// Most value-parameterized classes can ignore the existence of +// WithParamInterface, and can just inherit from ::testing::TestWithParam. + +template +class TestWithParam : public Test, public WithParamInterface { +}; + +#endif // GTEST_HAS_PARAM_TEST + +// Macros for indicating success/failure in test code. + +// ADD_FAILURE unconditionally adds a failure to the current test. +// SUCCEED generates a success - it doesn't automatically make the +// current test successful, as a test is only successful when it has +// no failure. +// +// EXPECT_* verifies that a certain condition is satisfied. If not, +// it behaves like ADD_FAILURE. In particular: +// +// EXPECT_TRUE verifies that a Boolean condition is true. +// EXPECT_FALSE verifies that a Boolean condition is false. +// +// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except +// that they will also abort the current function on failure. People +// usually want the fail-fast behavior of FAIL and ASSERT_*, but those +// writing data-driven tests often find themselves using ADD_FAILURE +// and EXPECT_* more. + +// Generates a nonfatal failure with a generic message. +#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") + +// Generates a nonfatal failure at the given source file location with +// a generic message. +#define ADD_FAILURE_AT(file, line) \ + GTEST_MESSAGE_AT_(file, line, "Failed", \ + ::testing::TestPartResult::kNonFatalFailure) + +// Generates a fatal failure with a generic message. +#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") + +// Define this macro to 1 to omit the definition of FAIL(), which is a +// generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_FAIL +# define FAIL() GTEST_FAIL() +#endif + +// Generates a success with a generic message. +#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") + +// Define this macro to 1 to omit the definition of SUCCEED(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_SUCCEED +# define SUCCEED() GTEST_SUCCEED() +#endif + +// Macros for testing exceptions. +// +// * {ASSERT|EXPECT}_THROW(statement, expected_exception): +// Tests that the statement throws the expected exception. +// * {ASSERT|EXPECT}_NO_THROW(statement): +// Tests that the statement doesn't throw any exception. +// * {ASSERT|EXPECT}_ANY_THROW(statement): +// Tests that the statement throws an exception. + +#define EXPECT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) +#define EXPECT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define EXPECT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define ASSERT_THROW(statement, expected_exception) \ + GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) +#define ASSERT_NO_THROW(statement) \ + GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) +#define ASSERT_ANY_THROW(statement) \ + GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) + +// Boolean assertions. Condition can be either a Boolean expression or an +// AssertionResult. For more information on how to use AssertionResult with +// these macros see comments on that class. +#define EXPECT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ + GTEST_NONFATAL_FAILURE_) +#define EXPECT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_NONFATAL_FAILURE_) +#define ASSERT_TRUE(condition) \ + GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ + GTEST_FATAL_FAILURE_) +#define ASSERT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ + GTEST_FATAL_FAILURE_) + +// Includes the auto-generated header that implements a family of +// generic predicate assertion macros. +#include "gtest/gtest_pred_impl.h" + +// Macros for testing equalities and inequalities. +// +// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 +// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 +// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 +// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 +// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 +// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 +// +// When they are not, Google Test prints both the tested expressions and +// their actual values. The values must be compatible built-in types, +// or you will get a compiler error. By "compatible" we mean that the +// values can be compared by the respective operator. +// +// Note: +// +// 1. It is possible to make a user-defined type work with +// {ASSERT|EXPECT}_??(), but that requires overloading the +// comparison operators and is thus discouraged by the Google C++ +// Usage Guide. Therefore, you are advised to use the +// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are +// equal. +// +// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on +// pointers (in particular, C strings). Therefore, if you use it +// with two C strings, you are testing how their locations in memory +// are related, not how their content is related. To compare two C +// strings by content, use {ASSERT|EXPECT}_STR*(). +// +// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to +// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you +// what the actual value is when it fails, and similarly for the +// other comparisons. +// +// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() +// evaluate their arguments, which is undefined. +// +// 5. These macros evaluate their arguments exactly once. +// +// Examples: +// +// EXPECT_NE(5, Foo()); +// EXPECT_EQ(NULL, a_pointer); +// ASSERT_LT(i, array_size); +// ASSERT_GT(records.size(), 0) << "There is no record left."; + +#define EXPECT_EQ(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + val1, val2) +#define EXPECT_NE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define EXPECT_LE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define EXPECT_LT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define EXPECT_GE(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define EXPECT_GT(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +#define GTEST_ASSERT_EQ(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal:: \ + EqHelper::Compare, \ + val1, val2) +#define GTEST_ASSERT_NE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define GTEST_ASSERT_LE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define GTEST_ASSERT_LT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define GTEST_ASSERT_GE(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define GTEST_ASSERT_GT(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + +// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of +// ASSERT_XY(), which clashes with some users' own code. + +#if !GTEST_DONT_DEFINE_ASSERT_EQ +# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_NE +# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LE +# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_LT +# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GE +# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#endif + +#if !GTEST_DONT_DEFINE_ASSERT_GT +# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#endif + +// C-string Comparisons. All tests treat NULL and any non-NULL string +// as different. Two NULLs are equal. +// +// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 +// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 +// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case +// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case +// +// For wide or narrow string objects, you can use the +// {ASSERT|EXPECT}_??() macros. +// +// Don't depend on the order in which the arguments are evaluated, +// which is undefined. +// +// These macros evaluate their arguments exactly once. + +#define EXPECT_STREQ(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) +#define EXPECT_STRNE(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define EXPECT_STRCASEEQ(s1, s2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) +#define EXPECT_STRCASENE(s1, s2)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +#define ASSERT_STREQ(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) +#define ASSERT_STRNE(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define ASSERT_STRCASEEQ(s1, s2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) +#define ASSERT_STRCASENE(s1, s2)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +// Macros for comparing floating-point numbers. +// +// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2): +// Tests that two float values are almost equal. +// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2): +// Tests that two double values are almost equal. +// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): +// Tests that v1 and v2 are within the given distance to each other. +// +// Google Test uses ULP-based comparison to automatically pick a default +// error bound that is appropriate for the operands. See the +// FloatingPoint template class in gtest-internal.h if you are +// interested in the implementation details. + +#define EXPECT_FLOAT_EQ(val1, val2)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + val1, val2) + +#define EXPECT_DOUBLE_EQ(val1, val2)\ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + val1, val2) + +#define ASSERT_FLOAT_EQ(val1, val2)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + val1, val2) + +#define ASSERT_DOUBLE_EQ(val1, val2)\ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ + val1, val2) + +#define EXPECT_NEAR(val1, val2, abs_error)\ + EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +#define ASSERT_NEAR(val1, val2, abs_error)\ + ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ + val1, val2, abs_error) + +// These predicate format functions work on floating-point values, and +// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. +// +// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2); +GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2); + + +#if GTEST_OS_WINDOWS + +// Macros that test for HRESULT failure and success, these are only useful +// on Windows, and rely on Windows SDK macros and APIs to compile. +// +// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) +// +// When expr unexpectedly fails or succeeds, Google Test prints the +// expected result and the actual result with both a human-readable +// string representation of the error, if available, as well as the +// hex result code. +# define EXPECT_HRESULT_SUCCEEDED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define ASSERT_HRESULT_SUCCEEDED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) + +# define EXPECT_HRESULT_FAILED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +# define ASSERT_HRESULT_FAILED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) + +#endif // GTEST_OS_WINDOWS + +// Macros that execute statement and check that it doesn't generate new fatal +// failures in the current thread. +// +// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); +// +// Examples: +// +// EXPECT_NO_FATAL_FAILURE(Process()); +// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; +// +#define ASSERT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) +#define EXPECT_NO_FATAL_FAILURE(statement) \ + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) + +// Causes a trace (including the source file path, the current line +// number, and the given message) to be included in every test failure +// message generated by code in the current scope. The effect is +// undone when the control leaves the current scope. +// +// The message argument can be anything streamable to std::ostream. +// +// In the implementation, we include the current line number as part +// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s +// to appear in the same block - as long as they are on different +// lines. +#define SCOPED_TRACE(message) \ + ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ + __FILE__, __LINE__, ::testing::Message() << (message)) + +// Compile-time assertion for type equality. +// StaticAssertTypeEq() compiles iff type1 and type2 are +// the same type. The value it returns is not interesting. +// +// Instead of making StaticAssertTypeEq a class template, we make it a +// function template that invokes a helper class template. This +// prevents a user from misusing StaticAssertTypeEq by +// defining objects of that type. +// +// CAVEAT: +// +// When used inside a method of a class template, +// StaticAssertTypeEq() is effective ONLY IF the method is +// instantiated. For example, given: +// +// template class Foo { +// public: +// void Bar() { testing::StaticAssertTypeEq(); } +// }; +// +// the code: +// +// void Test1() { Foo foo; } +// +// will NOT generate a compiler error, as Foo::Bar() is never +// actually instantiated. Instead, you need: +// +// void Test2() { Foo foo; foo.Bar(); } +// +// to cause a compiler error. +template +bool StaticAssertTypeEq() { + (void)internal::StaticAssertTypeEqHelper(); + return true; +} + +// Defines a test. +// +// The first parameter is the name of the test case, and the second +// parameter is the name of the test within the test case. +// +// The convention is to end the test case name with "Test". For +// example, a test case for the Foo class can be named FooTest. +// +// Test code should appear between braces after an invocation of +// this macro. Example: +// +// TEST(FooTest, InitializesCorrectly) { +// Foo foo; +// EXPECT_TRUE(foo.StatusIsOK()); +// } + +// Note that we call GetTestTypeId() instead of GetTypeId< +// ::testing::Test>() here to get the type ID of testing::Test. This +// is to work around a suspected linker bug when using Google Test as +// a framework on Mac OS X. The bug causes GetTypeId< +// ::testing::Test>() to return different values depending on whether +// the call is from the Google Test framework itself or from user test +// code. GetTestTypeId() is guaranteed to always return the same +// value, as it always calls GetTypeId<>() from the Google Test +// framework. +#define GTEST_TEST(test_case_name, test_name)\ + GTEST_TEST_(test_case_name, test_name, \ + ::testing::Test, ::testing::internal::GetTestTypeId()) + +// Define this macro to 1 to omit the definition of TEST(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_TEST +# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#endif + +// Defines a test that uses a test fixture. +// +// The first parameter is the name of the test fixture class, which +// also doubles as the test case name. The second parameter is the +// name of the test within the test case. +// +// A test fixture class must be declared earlier. The user should put +// his test code between braces after using this macro. Example: +// +// class FooTest : public testing::Test { +// protected: +// virtual void SetUp() { b_.AddElement(3); } +// +// Foo a_; +// Foo b_; +// }; +// +// TEST_F(FooTest, InitializesCorrectly) { +// EXPECT_TRUE(a_.StatusIsOK()); +// } +// +// TEST_F(FooTest, ReturnsElementCountCorrectly) { +// EXPECT_EQ(0, a_.size()); +// EXPECT_EQ(1, b_.size()); +// } + +#define TEST_F(test_fixture, test_name)\ + GTEST_TEST_(test_fixture, test_name, test_fixture, \ + ::testing::internal::GetTypeId()) + +} // namespace testing + +// Use this function in main() to run all tests. It returns 0 if all +// tests are successful, or 1 otherwise. +// +// RUN_ALL_TESTS() should be invoked after the command line has been +// parsed by InitGoogleTest(). +// +// This function was formerly a macro; thus, it is in the global +// namespace and has an all-caps name. +int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; + +inline int RUN_ALL_TESTS() { + return ::testing::UnitTest::GetInstance()->Run(); +} + +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest_pred_impl.h b/gtestsrc/gtest/include/gtest/gtest_pred_impl.h new file mode 100644 index 0000000..30ae712 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest_pred_impl.h @@ -0,0 +1,358 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command +// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! +// +// Implements a family of generic predicate assertion macros. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ + +// Makes sure this header is not included before gtest.h. +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ +# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. +#endif // GTEST_INCLUDE_GTEST_GTEST_H_ + +// This header implements a family of generic predicate assertion +// macros: +// +// ASSERT_PRED_FORMAT1(pred_format, v1) +// ASSERT_PRED_FORMAT2(pred_format, v1, v2) +// ... +// +// where pred_format is a function or functor that takes n (in the +// case of ASSERT_PRED_FORMATn) values and their source expression +// text, and returns a testing::AssertionResult. See the definition +// of ASSERT_EQ in gtest.h for an example. +// +// If you don't care about formatting, you can use the more +// restrictive version: +// +// ASSERT_PRED1(pred, v1) +// ASSERT_PRED2(pred, v1, v2) +// ... +// +// where pred is an n-ary function or functor that returns bool, +// and the values v1, v2, ..., must support the << operator for +// streaming to std::ostream. +// +// We also define the EXPECT_* variations. +// +// For now we only support predicates whose arity is at most 5. +// Please email googletestframework@googlegroups.com if you need +// support for higher arities. + +// GTEST_ASSERT_ is the basic statement to which all of the assertions +// in this file reduce. Don't use this in your code. + +#define GTEST_ASSERT_(expression, on_failure) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar = (expression)) \ + ; \ + else \ + on_failure(gtest_ar.failure_message()) + + +// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +template +AssertionResult AssertPred1Helper(const char* pred_text, + const char* e1, + Pred pred, + const T1& v1) { + if (pred(v1)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. +// Don't use this in your code. +#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, v1), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use +// this in your code. +#define GTEST_PRED1_(pred, v1, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ + #v1, \ + pred, \ + v1), on_failure) + +// Unary predicate assertion macros. +#define EXPECT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT1(pred_format, v1) \ + GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED1(pred, v1) \ + GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +template +AssertionResult AssertPred2Helper(const char* pred_text, + const char* e1, + const char* e2, + Pred pred, + const T1& v1, + const T2& v2) { + if (pred(v1, v2)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. +// Don't use this in your code. +#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use +// this in your code. +#define GTEST_PRED2_(pred, v1, v2, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ + #v1, \ + #v2, \ + pred, \ + v1, \ + v2), on_failure) + +// Binary predicate assertion macros. +#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ + GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED2(pred, v1, v2) \ + GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +template +AssertionResult AssertPred3Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3) { + if (pred(v1, v2, v3)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. +// Don't use this in your code. +#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use +// this in your code. +#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + pred, \ + v1, \ + v2, \ + v3), on_failure) + +// Ternary predicate assertion macros. +#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ + GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED3(pred, v1, v2, v3) \ + GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +template +AssertionResult AssertPred4Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4) { + if (pred(v1, v2, v3, v4)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. +// Don't use this in your code. +#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use +// this in your code. +#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4), on_failure) + +// 4-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ + GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ + GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) + + + +// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +template +AssertionResult AssertPred5Helper(const char* pred_text, + const char* e1, + const char* e2, + const char* e3, + const char* e4, + const char* e5, + Pred pred, + const T1& v1, + const T2& v2, + const T3& v3, + const T4& v4, + const T5& v5) { + if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); + + return AssertionFailure() << pred_text << "(" + << e1 << ", " + << e2 << ", " + << e3 << ", " + << e4 << ", " + << e5 << ") evaluates to false, where" + << "\n" << e1 << " evaluates to " << v1 + << "\n" << e2 << " evaluates to " << v2 + << "\n" << e3 << " evaluates to " << v3 + << "\n" << e4 << " evaluates to " << v4 + << "\n" << e5 << " evaluates to " << v5; +} + +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. +// Don't use this in your code. +#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ + on_failure) + +// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use +// this in your code. +#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ + GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ + #v1, \ + #v2, \ + #v3, \ + #v4, \ + #v5, \ + pred, \ + v1, \ + v2, \ + v3, \ + v4, \ + v5), on_failure) + +// 5-ary predicate assertion macros. +#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ + GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ + GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) + + + +#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/gtestsrc/gtest/include/gtest/gtest_prod.h b/gtestsrc/gtest/include/gtest/gtest_prod.h new file mode 100644 index 0000000..da80ddc --- /dev/null +++ b/gtestsrc/gtest/include/gtest/gtest_prod.h @@ -0,0 +1,58 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Google C++ Testing Framework definitions useful in production code. + +#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ +#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ + +// When you need to test the private or protected members of a class, +// use the FRIEND_TEST macro to declare your tests as friends of the +// class. For example: +// +// class MyClass { +// private: +// void MyMethod(); +// FRIEND_TEST(MyClassTest, MyMethod); +// }; +// +// class MyClassTest : public testing::Test { +// // ... +// }; +// +// TEST_F(MyClassTest, MyMethod) { +// // Can call MyClass::MyMethod() here. +// } + +#define FRIEND_TEST(test_case_name, test_name)\ +friend class test_case_name##_##test_name##_Test + +#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/custom/gtest-port.h b/gtestsrc/gtest/include/gtest/internal/custom/gtest-port.h new file mode 100644 index 0000000..7e744bd --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/custom/gtest-port.h @@ -0,0 +1,69 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Injection point for custom user configurations. +// The following macros can be defined: +// +// Flag related macros: +// GTEST_FLAG(flag_name) +// GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its +// own flagfile flag parsing. +// GTEST_DECLARE_bool_(name) +// GTEST_DECLARE_int32_(name) +// GTEST_DECLARE_string_(name) +// GTEST_DEFINE_bool_(name, default_val, doc) +// GTEST_DEFINE_int32_(name, default_val, doc) +// GTEST_DEFINE_string_(name, default_val, doc) +// +// Test filtering: +// GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that +// will be used if --GTEST_FLAG(test_filter) +// is not provided. +// +// Logging: +// GTEST_LOG_(severity) +// GTEST_CHECK_(condition) +// Functions LogToStderr() and FlushInfoLog() have to be provided too. +// +// Threading: +// GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. +// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are +// already provided. +// Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and +// GTEST_DEFINE_STATIC_MUTEX_(mutex) +// +// GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +// GTEST_LOCK_EXCLUDED_(locks) +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/custom/gtest-printers.h b/gtestsrc/gtest/include/gtest/internal/custom/gtest-printers.h new file mode 100644 index 0000000..60c1ea0 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/custom/gtest-printers.h @@ -0,0 +1,42 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// This file provides an injection point for custom printers in a local +// installation of gTest. +// It will be included from gtest-printers.h and the overrides in this file +// will be visible to everyone. +// See documentation at gtest/gtest-printers.h for details on how to define a +// custom printer. +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/custom/gtest.h b/gtestsrc/gtest/include/gtest/internal/custom/gtest.h new file mode 100644 index 0000000..c27412a --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/custom/gtest.h @@ -0,0 +1,41 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Injection point for custom user configurations. +// The following macros can be defined: +// +// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of +// OsStackTraceGetterInterface. +// +// ** Custom implementation starts here ** + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-death-test-internal.h b/gtestsrc/gtest/include/gtest/internal/gtest-death-test-internal.h new file mode 100644 index 0000000..2b3a78f --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-death-test-internal.h @@ -0,0 +1,319 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines internal utilities needed for implementing +// death tests. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ + +#include "gtest/internal/gtest-internal.h" + +#include + +namespace testing { +namespace internal { + +GTEST_DECLARE_string_(internal_run_death_test); + +// Names of the flags (needed for parsing Google Test flags). +const char kDeathTestStyleFlag[] = "death_test_style"; +const char kDeathTestUseFork[] = "death_test_use_fork"; +const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; + +#if GTEST_HAS_DEATH_TEST + +// DeathTest is a class that hides much of the complexity of the +// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method +// returns a concrete class that depends on the prevailing death test +// style, as defined by the --gtest_death_test_style and/or +// --gtest_internal_run_death_test flags. + +// In describing the results of death tests, these terms are used with +// the corresponding definitions: +// +// exit status: The integer exit information in the format specified +// by wait(2) +// exit code: The integer code passed to exit(3), _exit(2), or +// returned from main() +class GTEST_API_ DeathTest { + public: + // Create returns false if there was an error determining the + // appropriate action to take for the current death test; for example, + // if the gtest_death_test_style flag is set to an invalid value. + // The LastMessage method will return a more detailed message in that + // case. Otherwise, the DeathTest pointer pointed to by the "test" + // argument is set. If the death test should be skipped, the pointer + // is set to NULL; otherwise, it is set to the address of a new concrete + // DeathTest object that controls the execution of the current test. + static bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); + DeathTest(); + virtual ~DeathTest() { } + + // A helper class that aborts a death test when it's deleted. + class ReturnSentinel { + public: + explicit ReturnSentinel(DeathTest* test) : test_(test) { } + ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: + DeathTest* const test_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); + } GTEST_ATTRIBUTE_UNUSED_; + + // An enumeration of possible roles that may be taken when a death + // test is encountered. EXECUTE means that the death test logic should + // be executed immediately. OVERSEE means that the program should prepare + // the appropriate environment for a child process to execute the death + // test, then wait for it to complete. + enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; + + // An enumeration of the three reasons that a test might be aborted. + enum AbortReason { + TEST_ENCOUNTERED_RETURN_STATEMENT, + TEST_THREW_EXCEPTION, + TEST_DID_NOT_DIE + }; + + // Assumes one of the above roles. + virtual TestRole AssumeRole() = 0; + + // Waits for the death test to finish and returns its status. + virtual int Wait() = 0; + + // Returns true if the death test passed; that is, the test process + // exited during the test, its exit status matches a user-supplied + // predicate, and its stderr output matches a user-supplied regular + // expression. + // The user-supplied predicate may be a macro expression rather + // than a function pointer or functor, or else Wait and Passed could + // be combined. + virtual bool Passed(bool exit_status_ok) = 0; + + // Signals that the death test did not die as expected. + virtual void Abort(AbortReason reason) = 0; + + // Returns a human-readable outcome message regarding the outcome of + // the last death test. + static const char* LastMessage(); + + static void set_last_death_test_message(const std::string& message); + + private: + // A string containing a description of the outcome of the last death test. + static std::string last_death_test_message_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); +}; + +// Factory interface for death tests. May be mocked out for testing. +class DeathTestFactory { + public: + virtual ~DeathTestFactory() { } + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) = 0; +}; + +// A concrete DeathTestFactory implementation for normal use. +class DefaultDeathTestFactory : public DeathTestFactory { + public: + virtual bool Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test); +}; + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +GTEST_API_ bool ExitedUnsuccessfully(int exit_status); + +// Traps C++ exceptions escaping statement and reports them as test +// failures. Note that trapping SEH exceptions is not implemented here. +# if GTEST_HAS_EXCEPTIONS +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (const ::std::exception& gtest_exception) { \ + fprintf(\ + stderr, \ + "\n%s: Caught std::exception-derived exception escaping the " \ + "death test statement. Exception message: %s\n", \ + ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ + gtest_exception.what()); \ + fflush(stderr); \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } catch (...) { \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } + +# else +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) + +# endif + +// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, +// ASSERT_EXIT*, and EXPECT_EXIT*. +# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::RE& gtest_regex = (regex); \ + ::testing::internal::DeathTest* gtest_dt; \ + if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ + __FILE__, __LINE__, >est_dt)) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + if (gtest_dt != NULL) { \ + ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ + gtest_dt_ptr(gtest_dt); \ + switch (gtest_dt->AssumeRole()) { \ + case ::testing::internal::DeathTest::OVERSEE_TEST: \ + if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + break; \ + case ::testing::internal::DeathTest::EXECUTE_TEST: { \ + ::testing::internal::DeathTest::ReturnSentinel \ + gtest_sentinel(gtest_dt); \ + GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ + gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ + break; \ + } \ + default: \ + break; \ + } \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ + fail(::testing::internal::DeathTest::LastMessage()) +// The symbol "fail" here expands to something into which a message +// can be streamed. + +// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in +// NDEBUG mode. In this case we need the statements to be executed, the regex is +// ignored, and the macro must accept a streamed message even though the message +// is never printed. +# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } else \ + ::testing::Message() + +// A class representing the parsed contents of the +// --gtest_internal_run_death_test flag, as it existed when +// RUN_ALL_TESTS was called. +class InternalRunDeathTestFlag { + public: + InternalRunDeathTestFlag(const std::string& a_file, + int a_line, + int an_index, + int a_write_fd) + : file_(a_file), line_(a_line), index_(an_index), + write_fd_(a_write_fd) {} + + ~InternalRunDeathTestFlag() { + if (write_fd_ >= 0) + posix::Close(write_fd_); + } + + const std::string& file() const { return file_; } + int line() const { return line_; } + int index() const { return index_; } + int write_fd() const { return write_fd_; } + + private: + std::string file_; + int line_; + int index_; + int write_fd_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); +}; + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); + +#else // GTEST_HAS_DEATH_TEST + +// This macro is used for implementing macros such as +// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where +// death tests are not supported. Those macros must compile on such systems +// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on +// systems that support death tests. This allows one to write such a macro +// on a system that does not support death tests and be sure that it will +// compile on a death-test supporting system. +// +// Parameters: +// statement - A statement that a macro such as EXPECT_DEATH would test +// for program termination. This macro has to make sure this +// statement is compiled but not executed, to ensure that +// EXPECT_DEATH_IF_SUPPORTED compiles with a certain +// parameter iff EXPECT_DEATH compiles with it. +// regex - A regex that a macro such as EXPECT_DEATH would use to test +// the output of statement. This parameter has to be +// compiled but not evaluated by this macro, to ensure that +// this macro only accepts expressions that a macro such as +// EXPECT_DEATH would accept. +// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED +// and a return statement for ASSERT_DEATH_IF_SUPPORTED. +// This ensures that ASSERT_DEATH_IF_SUPPORTED will not +// compile inside functions where ASSERT_DEATH doesn't +// compile. +// +// The branch that has an always false condition is used to ensure that +// statement and regex are compiled (and thus syntactically correct) but +// never executed. The unreachable code macro protects the terminator +// statement from generating an 'unreachable code' warning in case +// statement unconditionally returns or throws. The Message constructor at +// the end allows the syntax of streaming additional messages into the +// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. +# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) \ + << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ + ::testing::Message() + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-filepath.h b/gtestsrc/gtest/include/gtest/internal/gtest-filepath.h new file mode 100644 index 0000000..7a13b4b --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-filepath.h @@ -0,0 +1,206 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: keith.ray@gmail.com (Keith Ray) +// +// Google Test filepath utilities +// +// This header file declares classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included in . +// Do not include this header file separately! + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ + +#include "gtest/internal/gtest-string.h" + +namespace testing { +namespace internal { + +// FilePath - a class for file and directory pathname manipulation which +// handles platform-specific conventions (like the pathname separator). +// Used for helper functions for naming files in a directory for xml output. +// Except for Set methods, all methods are const or static, which provides an +// "immutable value object" -- useful for peace of mind. +// A FilePath with a value ending in a path separator ("like/this/") represents +// a directory, otherwise it is assumed to represent a file. In either case, +// it may or may not represent an actual file or directory in the file system. +// Names are NOT checked for syntax correctness -- no checking for illegal +// characters, malformed paths, etc. + +class GTEST_API_ FilePath { + public: + FilePath() : pathname_("") { } + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + + explicit FilePath(const std::string& pathname) : pathname_(pathname) { + Normalize(); + } + + FilePath& operator=(const FilePath& rhs) { + Set(rhs); + return *this; + } + + void Set(const FilePath& rhs) { + pathname_ = rhs.pathname_; + } + + const std::string& string() const { return pathname_; } + const char* c_str() const { return pathname_.c_str(); } + + // Returns the current working directory, or "" if unsuccessful. + static FilePath GetCurrentDir(); + + // Given directory = "dir", base_name = "test", number = 0, + // extension = "xml", returns "dir/test.xml". If number is greater + // than zero (e.g., 12), returns "dir/test_12.xml". + // On Windows platform, uses \ as the separator rather than /. + static FilePath MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension); + + // Given directory = "dir", relative_path = "test.xml", + // returns "dir/test.xml". + // On Windows, uses \ as the separator rather than /. + static FilePath ConcatPaths(const FilePath& directory, + const FilePath& relative_path); + + // Returns a pathname for a file that does not currently exist. The pathname + // will be directory/base_name.extension or + // directory/base_name_.extension if directory/base_name.extension + // already exists. The number will be incremented until a pathname is found + // that does not already exist. + // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. + // There could be a race condition if two or more processes are calling this + // function at the same time -- they could both pick the same filename. + static FilePath GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension); + + // Returns true iff the path is "". + bool IsEmpty() const { return pathname_.empty(); } + + // If input name has a trailing separator character, removes it and returns + // the name, otherwise return the name string unmodified. + // On Windows platform, uses \ as the separator, other platforms use /. + FilePath RemoveTrailingPathSeparator() const; + + // Returns a copy of the FilePath with the directory part removed. + // Example: FilePath("path/to/file").RemoveDirectoryName() returns + // FilePath("file"). If there is no directory part ("just_a_file"), it returns + // the FilePath unmodified. If there is no file part ("just_a_dir/") it + // returns an empty FilePath (""). + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveDirectoryName() const; + + // RemoveFileName returns the directory path with the filename removed. + // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". + // If the FilePath is "a_file" or "/a_file", RemoveFileName returns + // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does + // not have a file, like "just/a/dir/", it returns the FilePath unmodified. + // On Windows platform, '\' is the path separator, otherwise it is '/'. + FilePath RemoveFileName() const; + + // Returns a copy of the FilePath with the case-insensitive extension removed. + // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns + // FilePath("dir/file"). If a case-insensitive extension is not + // found, returns a copy of the original FilePath. + FilePath RemoveExtension(const char* extension) const; + + // Creates directories so that path exists. Returns true if successful or if + // the directories already exist; returns false if unable to create + // directories for any reason. Will also return false if the FilePath does + // not represent a directory (that is, it doesn't end with a path separator). + bool CreateDirectoriesRecursively() const; + + // Create the directory so that path exists. Returns true if successful or + // if the directory already exists; returns false if unable to create the + // directory for any reason, including if the parent directory does not + // exist. Not named "CreateDirectory" because that's a macro on Windows. + bool CreateFolder() const; + + // Returns true if FilePath describes something in the file-system, + // either a file, directory, or whatever, and that something exists. + bool FileOrDirectoryExists() const; + + // Returns true if pathname describes a directory in the file-system + // that exists. + bool DirectoryExists() const; + + // Returns true if FilePath ends with a path separator, which indicates that + // it is intended to represent a directory. Returns false otherwise. + // This does NOT check that a directory (or file) actually exists. + bool IsDirectory() const; + + // Returns true if pathname describes a root directory. (Windows has one + // root directory per disk drive.) + bool IsRootDirectory() const; + + // Returns true if pathname describes an absolute path. + bool IsAbsolutePath() const; + + private: + // Replaces multiple consecutive separators with a single separator. + // For example, "bar///foo" becomes "bar/foo". Does not eliminate other + // redundancies that might be in a pathname involving "." or "..". + // + // A pathname with multiple consecutive separators may occur either through + // user error or as a result of some scripts or APIs that generate a pathname + // with a trailing separator. On other platforms the same API or script + // may NOT generate a pathname with a trailing "/". Then elsewhere that + // pathname may have another "/" and pathname components added to it, + // without checking for the separator already being there. + // The script language and operating system may allow paths like "foo//bar" + // but some of the functions in FilePath will not handle that correctly. In + // particular, RemoveTrailingPathSeparator() only removes one separator, and + // it is called in CreateDirectoriesRecursively() assuming that it will change + // a pathname from directory syntax (trailing separator) to filename syntax. + // + // On Windows this method also replaces the alternate path separator '/' with + // the primary path separator '\\', so that for example "bar\\/\\foo" becomes + // "bar\\foo". + + void Normalize(); + + // Returns a pointer to the last occurence of a valid path separator in + // the FilePath. On Windows, for example, both '/' and '\' are valid path + // separators. Returns NULL if no path separator was found. + const char* FindLastPathSeparator() const; + + std::string pathname_; +}; // class FilePath + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-internal.h b/gtestsrc/gtest/include/gtest/internal/gtest-internal.h new file mode 100644 index 0000000..5afb722 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-internal.h @@ -0,0 +1,1237 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares functions and macros used internally by +// Google Test. They are subject to change without notice. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ + +#include "gtest/internal/gtest-port.h" + +#if GTEST_OS_LINUX +# include +# include +# include +# include +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-type-util.h" + +// Due to C++ preprocessor weirdness, we need double indirection to +// concatenate two tokens when one of them is __LINE__. Writing +// +// foo ## __LINE__ +// +// will result in the token foo__LINE__, instead of foo followed by +// the current line number. For more details, see +// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 +#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar + +class ProtocolMessage; +namespace proto2 { class Message; } + +namespace testing { + +// Forward declarations. + +class AssertionResult; // Result of an assertion. +class Message; // Represents a failure message. +class Test; // Represents a test. +class TestInfo; // Information about a test. +class TestPartResult; // Result of a test part. +class UnitTest; // A collection of test cases. + +template +::std::string PrintToString(const T& value); + +namespace internal { + +struct TraceInfo; // Information about a trace point. +class ScopedTrace; // Implements scoped trace. +class TestInfoImpl; // Opaque implementation of TestInfo +class UnitTestImpl; // Opaque implementation of UnitTest + +// The text used in failure messages to indicate the start of the +// stack trace. +GTEST_API_ extern const char kStackTraceMarker[]; + +// Two overloaded helpers for checking at compile time whether an +// expression is a null pointer literal (i.e. NULL or any 0-valued +// compile-time integral constant). Their return values have +// different sizes, so we can use sizeof() to test which version is +// picked by the compiler. These helpers have no implementations, as +// we only need their signatures. +// +// Given IsNullLiteralHelper(x), the compiler will pick the first +// version if x can be implicitly converted to Secret*, and pick the +// second version otherwise. Since Secret is a secret and incomplete +// type, the only expression a user can write that has type Secret* is +// a null pointer literal. Therefore, we know that x is a null +// pointer literal if and only if the first version is picked by the +// compiler. +char IsNullLiteralHelper(Secret* p); +char (&IsNullLiteralHelper(...))[2]; // NOLINT + +// A compile-time bool constant that is true if and only if x is a +// null pointer literal (i.e. NULL or any 0-valued compile-time +// integral constant). +#ifdef GTEST_ELLIPSIS_NEEDS_POD_ +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_IS_NULL_LITERAL_(x) false +#else +# define GTEST_IS_NULL_LITERAL_(x) \ + (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) +#endif // GTEST_ELLIPSIS_NEEDS_POD_ + +// Appends the user-supplied message to the Google-Test-generated message. +GTEST_API_ std::string AppendUserMessage( + const std::string& gtest_msg, const Message& user_msg); + +#if GTEST_HAS_EXCEPTIONS + +// This exception is thrown by (and only by) a failed Google Test +// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions +// are enabled). We derive it from std::runtime_error, which is for +// errors presumably detectable only at run time. Since +// std::runtime_error inherits from std::exception, many testing +// frameworks know how to extract and print the message inside it. +class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { + public: + explicit GoogleTestFailureException(const TestPartResult& failure); +}; + +#endif // GTEST_HAS_EXCEPTIONS + +// A helper class for creating scoped traces in user programs. +class GTEST_API_ ScopedTrace { + public: + // The c'tor pushes the given source file location and message onto + // a trace stack maintained by Google Test. + ScopedTrace(const char* file, int line, const Message& message); + + // The d'tor pops the info pushed by the c'tor. + // + // Note that the d'tor is not virtual in order to be efficient. + // Don't inherit from ScopedTrace! + ~ScopedTrace(); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); +} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its + // c'tor and d'tor. Therefore it doesn't + // need to be used otherwise. + +namespace edit_distance { +// Returns the optimal edits to go from 'left' to 'right'. +// All edits cost the same, with replace having lower priority than +// add/remove. +// Simple implementation of the Wagner–Fischer algorithm. +// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm +enum EditType { kMatch, kAdd, kRemove, kReplace }; +GTEST_API_ std::vector CalculateOptimalEdits( + const std::vector& left, const std::vector& right); + +// Same as above, but the input is represented as strings. +GTEST_API_ std::vector CalculateOptimalEdits( + const std::vector& left, + const std::vector& right); + +// Create a diff of the input strings in Unified diff format. +GTEST_API_ std::string CreateUnifiedDiff(const std::vector& left, + const std::vector& right, + size_t context = 2); + +} // namespace edit_distance + +// Calculate the diff between 'left' and 'right' and return it in unified diff +// format. +// If not null, stores in 'total_line_count' the total number of lines found +// in left + right. +GTEST_API_ std::string DiffStrings(const std::string& left, + const std::string& right, + size_t* total_line_count); + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// expected_expression: "foo" +// actual_expression: "bar" +// expected_value: "5" +// actual_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will +// be inserted into the message. +GTEST_API_ AssertionResult EqFailure(const char* expected_expression, + const char* actual_expression, + const std::string& expected_value, + const std::string& actual_value, + bool ignoring_case); + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +GTEST_API_ std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value); + +// This template class represents an IEEE floating-point number +// (either single-precision or double-precision, depending on the +// template parameters). +// +// The purpose of this class is to do more sophisticated number +// comparison. (Due to round-off error, etc, it's very unlikely that +// two floating-points will be equal exactly. Hence a naive +// comparison by the == operation often doesn't work.) +// +// Format of IEEE floating-point: +// +// The most-significant bit being the leftmost, an IEEE +// floating-point looks like +// +// sign_bit exponent_bits fraction_bits +// +// Here, sign_bit is a single bit that designates the sign of the +// number. +// +// For float, there are 8 exponent bits and 23 fraction bits. +// +// For double, there are 11 exponent bits and 52 fraction bits. +// +// More details can be found at +// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. +// +// Template parameter: +// +// RawType: the raw floating-point type (either float or double) +template +class FloatingPoint { + public: + // Defines the unsigned integer type that has the same size as the + // floating point number. + typedef typename TypeWithSize::UInt Bits; + + // Constants. + + // # of bits in a number. + static const size_t kBitCount = 8*sizeof(RawType); + + // # of fraction bits in a number. + static const size_t kFractionBitCount = + std::numeric_limits::digits - 1; + + // # of exponent bits in a number. + static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; + + // The mask for the sign bit. + static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); + + // The mask for the fraction bits. + static const Bits kFractionBitMask = + ~static_cast(0) >> (kExponentBitCount + 1); + + // The mask for the exponent bits. + static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); + + // How many ULP's (Units in the Last Place) we want to tolerate when + // comparing two numbers. The larger the value, the more error we + // allow. A 0 value means that two numbers must be exactly the same + // to be considered equal. + // + // The maximum error of a single floating-point operation is 0.5 + // units in the last place. On Intel CPU's, all floating-point + // calculations are done with 80-bit precision, while double has 64 + // bits. Therefore, 4 should be enough for ordinary use. + // + // See the following article for more details on ULP: + // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + static const size_t kMaxUlps = 4; + + // Constructs a FloatingPoint from a raw floating-point number. + // + // On an Intel CPU, passing a non-normalized NAN (Not a Number) + // around may change its bits, although the new value is guaranteed + // to be also a NAN. Therefore, don't expect this constructor to + // preserve the bits in x when x is a NAN. + explicit FloatingPoint(const RawType& x) { u_.value_ = x; } + + // Static methods + + // Reinterprets a bit pattern as a floating-point number. + // + // This function is needed to test the AlmostEquals() method. + static RawType ReinterpretBits(const Bits bits) { + FloatingPoint fp(0); + fp.u_.bits_ = bits; + return fp.u_.value_; + } + + // Returns the floating-point number that represent positive infinity. + static RawType Infinity() { + return ReinterpretBits(kExponentBitMask); + } + + // Returns the maximum representable finite floating-point number. + static RawType Max(); + + // Non-static methods + + // Returns the bits that represents this number. + const Bits &bits() const { return u_.bits_; } + + // Returns the exponent bits of this number. + Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } + + // Returns the fraction bits of this number. + Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } + + // Returns the sign bit of this number. + Bits sign_bit() const { return kSignBitMask & u_.bits_; } + + // Returns true iff this is NAN (not a number). + bool is_nan() const { + // It's a NAN if the exponent bits are all ones and the fraction + // bits are not entirely zeros. + return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); + } + + // Returns true iff this number is at most kMaxUlps ULP's away from + // rhs. In particular, this function: + // + // - returns false if either number is (or both are) NAN. + // - treats really large numbers as almost equal to infinity. + // - thinks +0.0 and -0.0 are 0 DLP's apart. + bool AlmostEquals(const FloatingPoint& rhs) const { + // The IEEE standard says that any comparison operation involving + // a NAN must return false. + if (is_nan() || rhs.is_nan()) return false; + + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) + <= kMaxUlps; + } + + private: + // The data type used to store the actual floating-point number. + union FloatingPointUnion { + RawType value_; // The raw floating-point number. + Bits bits_; // The bits that represent the number. + }; + + // Converts an integer from the sign-and-magnitude representation to + // the biased representation. More precisely, let N be 2 to the + // power of (kBitCount - 1), an integer x is represented by the + // unsigned number x + N. + // + // For instance, + // + // -N + 1 (the most negative number representable using + // sign-and-magnitude) is represented by 1; + // 0 is represented by N; and + // N - 1 (the biggest number representable using + // sign-and-magnitude) is represented by 2N - 1. + // + // Read http://en.wikipedia.org/wiki/Signed_number_representations + // for more details on signed number representations. + static Bits SignAndMagnitudeToBiased(const Bits &sam) { + if (kSignBitMask & sam) { + // sam represents a negative number. + return ~sam + 1; + } else { + // sam represents a positive number. + return kSignBitMask | sam; + } + } + + // Given two numbers in the sign-and-magnitude representation, + // returns the distance between them as an unsigned number. + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, + const Bits &sam2) { + const Bits biased1 = SignAndMagnitudeToBiased(sam1); + const Bits biased2 = SignAndMagnitudeToBiased(sam2); + return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); + } + + FloatingPointUnion u_; +}; + +// We cannot use std::numeric_limits::max() as it clashes with the max() +// macro defined by . +template <> +inline float FloatingPoint::Max() { return FLT_MAX; } +template <> +inline double FloatingPoint::Max() { return DBL_MAX; } + +// Typedefs the instances of the FloatingPoint template class that we +// care to use. +typedef FloatingPoint Float; +typedef FloatingPoint Double; + +// In order to catch the mistake of putting tests that use different +// test fixture classes in the same test case, we need to assign +// unique IDs to fixture classes and compare them. The TypeId type is +// used to hold such IDs. The user should treat TypeId as an opaque +// type: the only operation allowed on TypeId values is to compare +// them for equality using the == operator. +typedef const void* TypeId; + +template +class TypeIdHelper { + public: + // dummy_ must not have a const type. Otherwise an overly eager + // compiler (e.g. MSVC 7.1 & 8.0) may try to merge + // TypeIdHelper::dummy_ for different Ts as an "optimization". + static bool dummy_; +}; + +template +bool TypeIdHelper::dummy_ = false; + +// GetTypeId() returns the ID of type T. Different values will be +// returned for different types. Calling the function twice with the +// same type argument is guaranteed to return the same ID. +template +TypeId GetTypeId() { + // The compiler is required to allocate a different + // TypeIdHelper::dummy_ variable for each T used to instantiate + // the template. Therefore, the address of dummy_ is guaranteed to + // be unique. + return &(TypeIdHelper::dummy_); +} + +// Returns the type ID of ::testing::Test. Always call this instead +// of GetTypeId< ::testing::Test>() to get the type ID of +// ::testing::Test, as the latter may give the wrong result due to a +// suspected linker bug when compiling Google Test as a Mac OS X +// framework. +GTEST_API_ TypeId GetTestTypeId(); + +// Defines the abstract factory interface that creates instances +// of a Test object. +class TestFactoryBase { + public: + virtual ~TestFactoryBase() {} + + // Creates a test instance to run. The instance is both created and destroyed + // within TestInfoImpl::Run() + virtual Test* CreateTest() = 0; + + protected: + TestFactoryBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); +}; + +// This class provides implementation of TeastFactoryBase interface. +// It is used in TEST and TEST_F macros. +template +class TestFactoryImpl : public TestFactoryBase { + public: + virtual Test* CreateTest() { return new TestClass; } +}; + +#if GTEST_OS_WINDOWS + +// Predicate-formatters for implementing the HRESULT checking macros +// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} +// We pass a long instead of HRESULT to avoid causing an +// include dependency for the HRESULT type. +GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, + long hr); // NOLINT +GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, + long hr); // NOLINT + +#endif // GTEST_OS_WINDOWS + +// Types of SetUpTestCase() and TearDownTestCase() functions. +typedef void (*SetUpTestCaseFunc)(); +typedef void (*TearDownTestCaseFunc)(); + +struct CodeLocation { + CodeLocation(const string& a_file, int a_line) : file(a_file), line(a_line) {} + + string file; + int line; +}; + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param text representation of the test's value parameter, +// or NULL if this is not a type-parameterized test. +// code_location: code location where the test is defined +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +GTEST_API_ TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + CodeLocation code_location, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory); + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// State of the definition of a type-parameterized test case. +class GTEST_API_ TypedTestCasePState { + public: + TypedTestCasePState() : registered_(false) {} + + // Adds the given test name to defined_test_names_ and return true + // if the test case hasn't been registered; otherwise aborts the + // program. + bool AddTestName(const char* file, int line, const char* case_name, + const char* test_name) { + if (registered_) { + fprintf(stderr, "%s Test %s must be defined before " + "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", + FormatFileLocation(file, line).c_str(), test_name, case_name); + fflush(stderr); + posix::Abort(); + } + registered_tests_.insert( + ::std::make_pair(test_name, CodeLocation(file, line))); + return true; + } + + bool TestExists(const std::string& test_name) const { + return registered_tests_.count(test_name) > 0; + } + + const CodeLocation& GetCodeLocation(const std::string& test_name) const { + RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); + GTEST_CHECK_(it != registered_tests_.end()); + return it->second; + } + + // Verifies that registered_tests match the test names in + // defined_test_names_; returns registered_tests if successful, or + // aborts the program otherwise. + const char* VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests); + + private: + typedef ::std::map RegisteredTestsMap; + + bool registered_; + RegisteredTestsMap registered_tests_; +}; + +// Skips to the first non-space char after the first comma in 'str'; +// returns NULL if no comma is found in 'str'. +inline const char* SkipComma(const char* str) { + const char* comma = strchr(str, ','); + if (comma == NULL) { + return NULL; + } + while (IsSpace(*(++comma))) {} + return comma; +} + +// Returns the prefix of 'str' before the first comma in it; returns +// the entire string if it contains no comma. +inline std::string GetPrefixUntilComma(const char* str) { + const char* comma = strchr(str, ','); + return comma == NULL ? str : std::string(str, comma); +} + +// Splits a given string on a given delimiter, populating a given +// vector with the fields. +void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest); + +// TypeParameterizedTest::Register() +// registers a list of type-parameterized tests with Google Test. The +// return value is insignificant - we just need to return something +// such that we can call this function in a namespace scope. +// +// Implementation note: The GTEST_TEMPLATE_ macro declares a template +// template parameter. It's defined in gtest-type-util.h. +template +class TypeParameterizedTest { + public: + // 'index' is the index of the test in the type list 'Types' + // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, + // Types). Valid values for 'index' are [0, N - 1] where N is the + // length of Types. + static bool Register(const char* prefix, + CodeLocation code_location, + const char* case_name, const char* test_names, + int index) { + typedef typename Types::Head Type; + typedef Fixture FixtureClass; + typedef typename GTEST_BIND_(TestSel, Type) TestClass; + + // First, registers the first type-parameterized test in the type + // list. + MakeAndRegisterTestInfo( + (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + + StreamableToString(index)).c_str(), + StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), + GetTypeName().c_str(), + NULL, // No value parameter. + code_location, + GetTypeId(), + TestClass::SetUpTestCase, + TestClass::TearDownTestCase, + new TestFactoryImpl); + + // Next, recurses (at compile time) with the tail of the type list. + return TypeParameterizedTest + ::Register(prefix, code_location, case_name, test_names, index + 1); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTest { + public: + static bool Register(const char* /*prefix*/, CodeLocation, + const char* /*case_name*/, const char* /*test_names*/, + int /*index*/) { + return true; + } +}; + +// TypeParameterizedTestCase::Register() +// registers *all combinations* of 'Tests' and 'Types' with Google +// Test. The return value is insignificant - we just need to return +// something such that we can call this function in a namespace scope. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* prefix, CodeLocation code_location, + const TypedTestCasePState* state, + const char* case_name, const char* test_names) { + std::string test_name = StripTrailingSpaces( + GetPrefixUntilComma(test_names)); + if (!state->TestExists(test_name)) { + fprintf(stderr, "Failed to get code location for test %s.%s at %s.", + case_name, test_name.c_str(), + FormatFileLocation(code_location.file.c_str(), + code_location.line).c_str()); + fflush(stderr); + posix::Abort(); + } + const CodeLocation& test_location = state->GetCodeLocation(test_name); + + typedef typename Tests::Head Head; + + // First, register the first test in 'Test' for each type in 'Types'. + TypeParameterizedTest::Register( + prefix, test_location, case_name, test_names, 0); + + // Next, recurses (at compile time) with the tail of the test list. + return TypeParameterizedTestCase + ::Register(prefix, code_location, state, + case_name, SkipComma(test_names)); + } +}; + +// The base case for the compile time recursion. +template +class TypeParameterizedTestCase { + public: + static bool Register(const char* /*prefix*/, CodeLocation, + const TypedTestCasePState* /*state*/, + const char* /*case_name*/, const char* /*test_names*/) { + return true; + } +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( + UnitTest* unit_test, int skip_count); + +// Helpers for suppressing warnings on unreachable code or constant +// condition. + +// Always returns true. +GTEST_API_ bool AlwaysTrue(); + +// Always returns false. +inline bool AlwaysFalse() { return !AlwaysTrue(); } + +// Helper for suppressing false warning from Clang on a const char* +// variable declared in a conditional expression always being NULL in +// the else branch. +struct GTEST_API_ ConstCharPtr { + ConstCharPtr(const char* str) : value(str) {} + operator bool() const { return true; } + const char* value; +}; + +// A simple Linear Congruential Generator for generating random +// numbers with a uniform distribution. Unlike rand() and srand(), it +// doesn't use global state (and therefore can't interfere with user +// code). Unlike rand_r(), it's portable. An LCG isn't very random, +// but it's good enough for our purposes. +class GTEST_API_ Random { + public: + static const UInt32 kMaxRange = 1u << 31; + + explicit Random(UInt32 seed) : state_(seed) {} + + void Reseed(UInt32 seed) { state_ = seed; } + + // Generates a random number from [0, range). Crashes if 'range' is + // 0 or greater than kMaxRange. + UInt32 Generate(UInt32 range); + + private: + UInt32 state_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); +}; + +// Defining a variable of type CompileAssertTypesEqual will cause a +// compiler error iff T1 and T2 are different types. +template +struct CompileAssertTypesEqual; + +template +struct CompileAssertTypesEqual { +}; + +// Removes the reference from a type if it is a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::remove_reference, which is not widely available yet. +template +struct RemoveReference { typedef T type; }; // NOLINT +template +struct RemoveReference { typedef T type; }; // NOLINT + +// A handy wrapper around RemoveReference that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_REFERENCE_(T) \ + typename ::testing::internal::RemoveReference::type + +// Removes const from a type if it is a const type, otherwise leaves +// it unchanged. This is the same as tr1::remove_const, which is not +// widely available yet. +template +struct RemoveConst { typedef T type; }; // NOLINT +template +struct RemoveConst { typedef T type; }; // NOLINT + +// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above +// definition to fail to remove the const in 'const int[3]' and 'const +// char[3][4]'. The following specialization works around the bug. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +// This is the only specialization that allows VC++ 7.1 to remove const in +// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC +// and thus needs to be conditionally compiled. +template +struct RemoveConst { + typedef typename RemoveConst::type type[N]; +}; +#endif + +// A handy wrapper around RemoveConst that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_CONST_(T) \ + typename ::testing::internal::RemoveConst::type + +// Turns const U&, U&, const U, and U all into U. +#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ + GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) + +// Adds reference to a type if it is not a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::add_reference, which is not widely available yet. +template +struct AddReference { typedef T& type; }; // NOLINT +template +struct AddReference { typedef T& type; }; // NOLINT + +// A handy wrapper around AddReference that works when the argument T +// depends on template parameters. +#define GTEST_ADD_REFERENCE_(T) \ + typename ::testing::internal::AddReference::type + +// Adds a reference to const on top of T as necessary. For example, +// it transforms +// +// char ==> const char& +// const char ==> const char& +// char& ==> const char& +// const char& ==> const char& +// +// The argument T must depend on some template parameters. +#define GTEST_REFERENCE_TO_CONST_(T) \ + GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) + +// ImplicitlyConvertible::value is a compile-time bool +// constant that's true iff type From can be implicitly converted to +// type To. +template +class ImplicitlyConvertible { + private: + // We need the following helper functions only for their types. + // They have no implementations. + + // MakeFrom() is an expression whose type is From. We cannot simply + // use From(), as the type From may not have a public default + // constructor. + static typename AddReference::type MakeFrom(); + + // These two functions are overloaded. Given an expression + // Helper(x), the compiler will pick the first version if x can be + // implicitly converted to type To; otherwise it will pick the + // second version. + // + // The first version returns a value of size 1, and the second + // version returns a value of size 2. Therefore, by checking the + // size of Helper(x), which can be done at compile time, we can tell + // which version of Helper() is used, and hence whether x can be + // implicitly converted to type To. + static char Helper(To); + static char (&Helper(...))[2]; // NOLINT + + // We have to put the 'public' section after the 'private' section, + // or MSVC refuses to compile the code. + public: +#if defined(__BORLANDC__) + // C++Builder cannot use member overload resolution during template + // instantiation. The simplest workaround is to use its C++0x type traits + // functions (C++Builder 2009 and above only). + static const bool value = __is_convertible(From, To); +#else + // MSVC warns about implicitly converting from double to int for + // possible loss of data, so we need to temporarily disable the + // warning. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244) + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; + GTEST_DISABLE_MSC_WARNINGS_POP_() +#endif // __BORLANDC__ +}; +template +const bool ImplicitlyConvertible::value; + +// IsAProtocolMessage::value is a compile-time bool constant that's +// true iff T is type ProtocolMessage, proto2::Message, or a subclass +// of those. +template +struct IsAProtocolMessage + : public bool_constant< + ImplicitlyConvertible::value || + ImplicitlyConvertible::value> { +}; + +// When the compiler sees expression IsContainerTest(0), if C is an +// STL-style container class, the first overload of IsContainerTest +// will be viable (since both C::iterator* and C::const_iterator* are +// valid types and NULL can be implicitly converted to them). It will +// be picked over the second overload as 'int' is a perfect match for +// the type of argument 0. If C::iterator or C::const_iterator is not +// a valid type, the first overload is not viable, and the second +// overload will be picked. Therefore, we can determine whether C is +// a container class by checking the type of IsContainerTest(0). +// The value of the expression is insignificant. +// +// Note that we look for both C::iterator and C::const_iterator. The +// reason is that C++ injects the name of a class as a member of the +// class itself (e.g. you can refer to class iterator as either +// 'iterator' or 'iterator::iterator'). If we look for C::iterator +// only, for example, we would mistakenly think that a class named +// iterator is an STL container. +// +// Also note that the simpler approach of overloading +// IsContainerTest(typename C::const_iterator*) and +// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. +typedef int IsContainer; +template +IsContainer IsContainerTest(int /* dummy */, + typename C::iterator* /* it */ = NULL, + typename C::const_iterator* /* const_it */ = NULL) { + return 0; +} + +typedef char IsNotContainer; +template +IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } + +// EnableIf::type is void when 'Cond' is true, and +// undefined when 'Cond' is false. To use SFINAE to make a function +// overload only apply when a particular expression is true, add +// "typename EnableIf::type* = 0" as the last parameter. +template struct EnableIf; +template<> struct EnableIf { typedef void type; }; // NOLINT + +// Utilities for native arrays. + +// ArrayEq() compares two k-dimensional native arrays using the +// elements' operator==, where k can be any integer >= 0. When k is +// 0, ArrayEq() degenerates into comparing a single pair of values. + +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs); + +// This generic version is used when k is 0. +template +inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } + +// This overload is used when k >= 1. +template +inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { + return internal::ArrayEq(lhs, N, rhs); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous ArrayEq() function, arrays with different sizes would +// lead to different copies of the template code. +template +bool ArrayEq(const T* lhs, size_t size, const U* rhs) { + for (size_t i = 0; i != size; i++) { + if (!internal::ArrayEq(lhs[i], rhs[i])) + return false; + } + return true; +} + +// Finds the first element in the iterator range [begin, end) that +// equals elem. Element may be a native array type itself. +template +Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { + for (Iter it = begin; it != end; ++it) { + if (internal::ArrayEq(*it, elem)) + return it; + } + return end; +} + +// CopyArray() copies a k-dimensional native array using the elements' +// operator=, where k can be any integer >= 0. When k is 0, +// CopyArray() degenerates into copying a single value. + +template +void CopyArray(const T* from, size_t size, U* to); + +// This generic version is used when k is 0. +template +inline void CopyArray(const T& from, U* to) { *to = from; } + +// This overload is used when k >= 1. +template +inline void CopyArray(const T(&from)[N], U(*to)[N]) { + internal::CopyArray(from, N, *to); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous CopyArray() function, arrays with different sizes +// would lead to different copies of the template code. +template +void CopyArray(const T* from, size_t size, U* to) { + for (size_t i = 0; i != size; i++) { + internal::CopyArray(from[i], to + i); + } +} + +// The relation between an NativeArray object (see below) and the +// native array it represents. +// We use 2 different structs to allow non-copyable types to be used, as long +// as RelationToSourceReference() is passed. +struct RelationToSourceReference {}; +struct RelationToSourceCopy {}; + +// Adapts a native array to a read-only STL-style container. Instead +// of the complete STL container concept, this adaptor only implements +// members useful for Google Mock's container matchers. New members +// should be added as needed. To simplify the implementation, we only +// support Element being a raw type (i.e. having no top-level const or +// reference modifier). It's the client's responsibility to satisfy +// this requirement. Element can be an array type itself (hence +// multi-dimensional arrays are supported). +template +class NativeArray { + public: + // STL-style container typedefs. + typedef Element value_type; + typedef Element* iterator; + typedef const Element* const_iterator; + + // Constructs from a native array. References the source. + NativeArray(const Element* array, size_t count, RelationToSourceReference) { + InitRef(array, count); + } + + // Constructs from a native array. Copies the source. + NativeArray(const Element* array, size_t count, RelationToSourceCopy) { + InitCopy(array, count); + } + + // Copy constructor. + NativeArray(const NativeArray& rhs) { + (this->*rhs.clone_)(rhs.array_, rhs.size_); + } + + ~NativeArray() { + if (clone_ != &NativeArray::InitRef) + delete[] array_; + } + + // STL-style container methods. + size_t size() const { return size_; } + const_iterator begin() const { return array_; } + const_iterator end() const { return array_ + size_; } + bool operator==(const NativeArray& rhs) const { + return size() == rhs.size() && + ArrayEq(begin(), size(), rhs.begin()); + } + + private: + enum { + kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< + Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value, + }; + + // Initializes this object with a copy of the input. + void InitCopy(const Element* array, size_t a_size) { + Element* const copy = new Element[a_size]; + CopyArray(array, a_size, copy); + array_ = copy; + size_ = a_size; + clone_ = &NativeArray::InitCopy; + } + + // Initializes this object with a reference of the input. + void InitRef(const Element* array, size_t a_size) { + array_ = array; + size_ = a_size; + clone_ = &NativeArray::InitRef; + } + + const Element* array_; + size_t size_; + void (NativeArray::*clone_)(const Element*, size_t); + + GTEST_DISALLOW_ASSIGN_(NativeArray); +}; + +} // namespace internal +} // namespace testing + +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) \ + = ::testing::Message() + +#define GTEST_MESSAGE_(message, result_type) \ + GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) + +#define GTEST_FATAL_FAILURE_(message) \ + return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) + +#define GTEST_NONFATAL_FAILURE_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) + +#define GTEST_SUCCESS_(message) \ + GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) + +// Suppresses MSVC warnings 4072 (unreachable code) for the code following +// statement if it returns or throws (or doesn't return or throw in some +// situations). +#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ + if (::testing::internal::AlwaysTrue()) { statement; } + +#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (expected_exception const&) { \ + gtest_caught_expected = true; \ + } \ + catch (...) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ + fail(gtest_msg.value) + +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ + fail("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: it throws.") + +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ + fail("Expected: " #statement " throws an exception.\n" \ + " Actual: it doesn't.") + + +// Implements Boolean test assertions such as EXPECT_TRUE. expression can be +// either a boolean expression or an AssertionResult. text is a textual +// represenation of expression as it was passed into the EXPECT_TRUE. +#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar_ = \ + ::testing::AssertionResult(expression)) \ + ; \ + else \ + fail(::testing::internal::GetBoolAssertionFailureMessage(\ + gtest_ar_, text, #actual, #expected).c_str()) + +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ + fail("Expected: " #statement " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") + +// Expands to the name of the class that implements the given test. +#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ + test_case_name##_##test_name##_Test + +// Helper macro for defining tests. +#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ +class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ + public:\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ + private:\ + virtual void TestBody();\ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ + GTEST_DISALLOW_COPY_AND_ASSIGN_(\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ +};\ +\ +::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ + ::test_info_ =\ + ::testing::internal::MakeAndRegisterTestInfo(\ + #test_case_name, #test_name, NULL, NULL, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + (parent_id), \ + parent_class::SetUpTestCase, \ + parent_class::TearDownTestCase, \ + new ::testing::internal::TestFactoryImpl<\ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ +void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-linked_ptr.h b/gtestsrc/gtest/include/gtest/internal/gtest-linked_ptr.h new file mode 100644 index 0000000..3602942 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-linked_ptr.h @@ -0,0 +1,243 @@ +// Copyright 2003 Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: Dan Egnor (egnor@google.com) +// +// A "smart" pointer type with reference tracking. Every pointer to a +// particular object is kept on a circular linked list. When the last pointer +// to an object is destroyed or reassigned, the object is deleted. +// +// Used properly, this deletes the object when the last reference goes away. +// There are several caveats: +// - Like all reference counting schemes, cycles lead to leaks. +// - Each smart pointer is actually two pointers (8 bytes instead of 4). +// - Every time a pointer is assigned, the entire list of pointers to that +// object is traversed. This class is therefore NOT SUITABLE when there +// will often be more than two or three pointers to a particular object. +// - References are only tracked as long as linked_ptr<> objects are copied. +// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS +// will happen (double deletion). +// +// A good use of this class is storing object references in STL containers. +// You can safely put linked_ptr<> in a vector<>. +// Other uses may not be as good. +// +// Note: If you use an incomplete type with linked_ptr<>, the class +// *containing* linked_ptr<> must have a constructor and destructor (even +// if they do nothing!). +// +// Bill Gibbons suggested we use something like this. +// +// Thread Safety: +// Unlike other linked_ptr implementations, in this implementation +// a linked_ptr object is thread-safe in the sense that: +// - it's safe to copy linked_ptr objects concurrently, +// - it's safe to copy *from* a linked_ptr and read its underlying +// raw pointer (e.g. via get()) concurrently, and +// - it's safe to write to two linked_ptrs that point to the same +// shared object concurrently. +// TODO(wan@google.com): rename this to safe_linked_ptr to avoid +// confusion with normal linked_ptr. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ + +#include +#include + +#include "gtest/internal/gtest-port.h" + +namespace testing { +namespace internal { + +// Protects copying of all linked_ptr objects. +GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// This is used internally by all instances of linked_ptr<>. It needs to be +// a non-template class because different types of linked_ptr<> can refer to +// the same object (linked_ptr(obj) vs linked_ptr(obj)). +// So, it needs to be possible for different types of linked_ptr to participate +// in the same circular linked list, so we need a single class type here. +// +// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. +class linked_ptr_internal { + public: + // Create a new circle that includes only this instance. + void join_new() { + next_ = this; + } + + // Many linked_ptr operations may change p.link_ for some linked_ptr + // variable p in the same circle as this object. Therefore we need + // to prevent two such operations from occurring concurrently. + // + // Note that different types of linked_ptr objects can coexist in a + // circle (e.g. linked_ptr, linked_ptr, and + // linked_ptr). Therefore we must use a single mutex to + // protect all linked_ptr objects. This can create serious + // contention in production code, but is acceptable in a testing + // framework. + + // Join an existing circle. + void join(linked_ptr_internal const* ptr) + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + linked_ptr_internal const* p = ptr; + while (p->next_ != ptr) { + assert(p->next_ != this && + "Trying to join() a linked ring we are already in. " + "Is GMock thread safety enabled?"); + p = p->next_; + } + p->next_ = this; + next_ = ptr; + } + + // Leave whatever circle we're part of. Returns true if we were the + // last member of the circle. Once this is done, you can join() another. + bool depart() + GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + MutexLock lock(&g_linked_ptr_mutex); + + if (next_ == this) return true; + linked_ptr_internal const* p = next_; + while (p->next_ != this) { + assert(p->next_ != next_ && + "Trying to depart() a linked ring we are not in. " + "Is GMock thread safety enabled?"); + p = p->next_; + } + p->next_ = next_; + return false; + } + + private: + mutable linked_ptr_internal const* next_; +}; + +template +class linked_ptr { + public: + typedef T element_type; + + // Take over ownership of a raw pointer. This should happen as soon as + // possible after the object is created. + explicit linked_ptr(T* ptr = NULL) { capture(ptr); } + ~linked_ptr() { depart(); } + + // Copy an existing linked_ptr<>, adding ourselves to the list of references. + template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } + linked_ptr(linked_ptr const& ptr) { // NOLINT + assert(&ptr != this); + copy(&ptr); + } + + // Assignment releases the old value and acquires the new. + template linked_ptr& operator=(linked_ptr const& ptr) { + depart(); + copy(&ptr); + return *this; + } + + linked_ptr& operator=(linked_ptr const& ptr) { + if (&ptr != this) { + depart(); + copy(&ptr); + } + return *this; + } + + // Smart pointer members. + void reset(T* ptr = NULL) { + depart(); + capture(ptr); + } + T* get() const { return value_; } + T* operator->() const { return value_; } + T& operator*() const { return *value_; } + + bool operator==(T* p) const { return value_ == p; } + bool operator!=(T* p) const { return value_ != p; } + template + bool operator==(linked_ptr const& ptr) const { + return value_ == ptr.get(); + } + template + bool operator!=(linked_ptr const& ptr) const { + return value_ != ptr.get(); + } + + private: + template + friend class linked_ptr; + + T* value_; + linked_ptr_internal link_; + + void depart() { + if (link_.depart()) delete value_; + } + + void capture(T* ptr) { + value_ = ptr; + link_.join_new(); + } + + template void copy(linked_ptr const* ptr) { + value_ = ptr->get(); + if (value_) + link_.join(&ptr->link_); + else + link_.join_new(); + } +}; + +template inline +bool operator==(T* ptr, const linked_ptr& x) { + return ptr == x.get(); +} + +template inline +bool operator!=(T* ptr, const linked_ptr& x) { + return ptr != x.get(); +} + +// A function to convert T* into linked_ptr +// Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation +// for linked_ptr >(new FooBarBaz(arg)) +template +linked_ptr make_linked_ptr(T* ptr) { + return linked_ptr(ptr); +} + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h b/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h new file mode 100644 index 0000000..4d1d81d --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h @@ -0,0 +1,5146 @@ +// This file was GENERATED by command: +// pump.py gtest-param-util-generated.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently Google Test supports at most 50 arguments in Values, +// and at most 10 arguments in Combine. Please contact +// googletestframework@googlegroups.com if you need more. +// Please note that the number of arguments to Combine is limited +// by the maximum arity of the implementation of tuple which is +// currently set at 10. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end); + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]); + +template +internal::ParamGenerator ValuesIn( + const Container& container); + +namespace internal { + +// Used in the Values() function to provide polymorphic capabilities. +template +class ValueArray1 { + public: + explicit ValueArray1(T1 v1) : v1_(v1) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray1& other); + + const T1 v1_; +}; + +template +class ValueArray2 { + public: + ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray2& other); + + const T1 v1_; + const T2 v2_; +}; + +template +class ValueArray3 { + public: + ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray3& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; +}; + +template +class ValueArray4 { + public: + ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray4& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; +}; + +template +class ValueArray5 { + public: + ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray5& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; +}; + +template +class ValueArray6 { + public: + ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray6& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; +}; + +template +class ValueArray7 { + public: + ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray7& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; +}; + +template +class ValueArray8 { + public: + ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray8& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; +}; + +template +class ValueArray9 { + public: + ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray9& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; +}; + +template +class ValueArray10 { + public: + ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray10& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; +}; + +template +class ValueArray11 { + public: + ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray11& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; +}; + +template +class ValueArray12 { + public: + ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray12& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; +}; + +template +class ValueArray13 { + public: + ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray13& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; +}; + +template +class ValueArray14 { + public: + ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray14& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; +}; + +template +class ValueArray15 { + public: + ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray15& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; +}; + +template +class ValueArray16 { + public: + ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray16& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; +}; + +template +class ValueArray17 { + public: + ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, + T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray17& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; +}; + +template +class ValueArray18 { + public: + ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray18& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; +}; + +template +class ValueArray19 { + public: + ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray19& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; +}; + +template +class ValueArray20 { + public: + ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray20& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; +}; + +template +class ValueArray21 { + public: + ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray21& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; +}; + +template +class ValueArray22 { + public: + ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray22& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; +}; + +template +class ValueArray23 { + public: + ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray23& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; +}; + +template +class ValueArray24 { + public: + ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray24& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; +}; + +template +class ValueArray25 { + public: + ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray25& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; +}; + +template +class ValueArray26 { + public: + ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray26& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; +}; + +template +class ValueArray27 { + public: + ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray27& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; +}; + +template +class ValueArray28 { + public: + ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray28& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; +}; + +template +class ValueArray29 { + public: + ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray29& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; +}; + +template +class ValueArray30 { + public: + ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray30& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; +}; + +template +class ValueArray31 { + public: + ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray31& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; +}; + +template +class ValueArray32 { + public: + ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray32& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; +}; + +template +class ValueArray33 { + public: + ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, + T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray33& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; +}; + +template +class ValueArray34 { + public: + ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray34& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; +}; + +template +class ValueArray35 { + public: + ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray35& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; +}; + +template +class ValueArray36 { + public: + ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray36& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; +}; + +template +class ValueArray37 { + public: + ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray37& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; +}; + +template +class ValueArray38 { + public: + ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray38& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; +}; + +template +class ValueArray39 { + public: + ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray39& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; +}; + +template +class ValueArray40 { + public: + ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray40& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; +}; + +template +class ValueArray41 { + public: + ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, + T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray41& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; +}; + +template +class ValueArray42 { + public: + ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray42& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; +}; + +template +class ValueArray43 { + public: + ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), + v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), + v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), + v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), + v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), + v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), + v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray43& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; +}; + +template +class ValueArray44 { + public: + ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), + v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), + v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), + v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), + v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), + v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), + v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), + v43_(v43), v44_(v44) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray44& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; +}; + +template +class ValueArray45 { + public: + ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), + v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), + v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), + v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), + v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), + v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), + v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), + v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray45& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; +}; + +template +class ValueArray46 { + public: + ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), + v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray46& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; +}; + +template +class ValueArray47 { + public: + ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), + v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), + v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), + v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), + v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), + v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), + v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), + v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), + v47_(v47) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray47& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; +}; + +template +class ValueArray48 { + public: + ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), + v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), + v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), + v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), + v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), + v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), + v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), + v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), + v46_(v46), v47_(v47), v48_(v48) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray48& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; +}; + +template +class ValueArray49 { + public: + ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, + T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray49& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; +}; + +template +class ValueArray50 { + public: + ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, + T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, + T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, + T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, + T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, + T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), + v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), + v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), + v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), + v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), + v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), + v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), + v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} + + template + operator ParamGenerator() const { + const T array[] = {static_cast(v1_), static_cast(v2_), + static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), + static_cast(v12_), static_cast(v13_), static_cast(v14_), + static_cast(v15_), static_cast(v16_), static_cast(v17_), + static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), + static_cast(v24_), static_cast(v25_), static_cast(v26_), + static_cast(v27_), static_cast(v28_), static_cast(v29_), + static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), + static_cast(v39_), static_cast(v40_), static_cast(v41_), + static_cast(v42_), static_cast(v43_), static_cast(v44_), + static_cast(v45_), static_cast(v46_), static_cast(v47_), + static_cast(v48_), static_cast(v49_), static_cast(v50_)}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray50& other); + + const T1 v1_; + const T2 v2_; + const T3 v3_; + const T4 v4_; + const T5 v5_; + const T6 v6_; + const T7 v7_; + const T8 v8_; + const T9 v9_; + const T10 v10_; + const T11 v11_; + const T12 v12_; + const T13 v13_; + const T14 v14_; + const T15 v15_; + const T16 v16_; + const T17 v17_; + const T18 v18_; + const T19 v19_; + const T20 v20_; + const T21 v21_; + const T22 v22_; + const T23 v23_; + const T24 v24_; + const T25 v25_; + const T26 v26_; + const T27 v27_; + const T28 v28_; + const T29 v29_; + const T30 v30_; + const T31 v31_; + const T32 v32_; + const T33 v33_; + const T34 v34_; + const T35 v35_; + const T36 v36_; + const T37 v37_; + const T38 v38_; + const T39 v39_; + const T40 v40_; + const T41 v41_; + const T42 v42_; + const T43 v43_; + const T44 v44_; + const T45 v45_; + const T46 v46_; + const T47 v47_; + const T48 v48_; + const T49 v49_; + const T50 v50_; +}; + +# if GTEST_HAS_COMBINE +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Generates values from the Cartesian product of values produced +// by the argument generators. +// +template +class CartesianProductGenerator2 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator2(const ParamGenerator& g1, + const ParamGenerator& g2) + : g1_(g1), g2_(g2) {} + virtual ~CartesianProductGenerator2() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current2_; + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + ParamType current_value_; + }; // class CartesianProductGenerator2::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator2& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; +}; // class CartesianProductGenerator2 + + +template +class CartesianProductGenerator3 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator3(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + virtual ~CartesianProductGenerator3() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current3_; + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + ParamType current_value_; + }; // class CartesianProductGenerator3::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator3& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; +}; // class CartesianProductGenerator3 + + +template +class CartesianProductGenerator4 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator4(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + virtual ~CartesianProductGenerator4() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current4_; + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + ParamType current_value_; + }; // class CartesianProductGenerator4::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator4& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; +}; // class CartesianProductGenerator4 + + +template +class CartesianProductGenerator5 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator5(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + virtual ~CartesianProductGenerator5() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current5_; + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + ParamType current_value_; + }; // class CartesianProductGenerator5::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator5& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; +}; // class CartesianProductGenerator5 + + +template +class CartesianProductGenerator6 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator6(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + virtual ~CartesianProductGenerator6() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current6_; + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + ParamType current_value_; + }; // class CartesianProductGenerator6::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator6& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; +}; // class CartesianProductGenerator6 + + +template +class CartesianProductGenerator7 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator7(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + virtual ~CartesianProductGenerator7() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current7_; + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + ParamType current_value_; + }; // class CartesianProductGenerator7::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator7& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; +}; // class CartesianProductGenerator7 + + +template +class CartesianProductGenerator8 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator8(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + virtual ~CartesianProductGenerator8() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current8_; + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + ParamType current_value_; + }; // class CartesianProductGenerator8::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator8& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; +}; // class CartesianProductGenerator8 + + +template +class CartesianProductGenerator9 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator9(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + virtual ~CartesianProductGenerator9() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current9_; + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + ParamType current_value_; + }; // class CartesianProductGenerator9::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator9& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; +}; // class CartesianProductGenerator9 + + +template +class CartesianProductGenerator10 + : public ParamGeneratorInterface< ::testing::tuple > { + public: + typedef ::testing::tuple ParamType; + + CartesianProductGenerator10(const ParamGenerator& g1, + const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, + const ParamGenerator& g6, const ParamGenerator& g7, + const ParamGenerator& g8, const ParamGenerator& g9, + const ParamGenerator& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + virtual ~CartesianProductGenerator10() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, + g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, + g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), + g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, + g8_.end(), g9_, g9_.end(), g10_, g10_.end()); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, + const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, + const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, + const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, + const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, + const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, + const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, + const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, + const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9, + const ParamGenerator& g10, + const typename ParamGenerator::iterator& current10) + : base_(base), + begin1_(g1.begin()), end1_(g1.end()), current1_(current1), + begin2_(g2.begin()), end2_(g2.end()), current2_(current2), + begin3_(g3.begin()), end3_(g3.end()), current3_(current3), + begin4_(g4.begin()), end4_(g4.end()), current4_(current4), + begin5_(g5.begin()), end5_(g5.end()), current5_(current5), + begin6_(g6.begin()), end6_(g6.end()), current6_(current6), + begin7_(g7.begin()), end7_(g7.end()), current7_(current7), + begin8_(g8.begin()), end8_(g8.end()), current8_(current8), + begin9_(g9.begin()), end9_(g9.end()), current9_(current9), + begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current10_; + if (current10_ == end10_) { + current10_ = begin10_; + ++current9_; + } + if (current9_ == end9_) { + current9_ = begin9_; + ++current8_; + } + if (current8_ == end8_) { + current8_ = begin8_; + ++current7_; + } + if (current7_ == end7_) { + current7_ = begin7_; + ++current6_; + } + if (current6_ == end6_) { + current6_ = begin6_; + ++current5_; + } + if (current5_ == end5_) { + current5_ = begin5_; + ++current4_; + } + if (current4_ == end4_) { + current4_ = begin4_; + ++current3_; + } + if (current3_ == end3_) { + current3_ = begin3_; + ++current2_; + } + if (current2_ == end2_) { + current2_ = begin2_; + ++current1_; + } + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ( + current1_ == typed_other->current1_ && + current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && + current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && + current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && + current8_ == typed_other->current8_ && + current9_ == typed_other->current9_ && + current10_ == typed_other->current10_); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_), + begin10_(other.begin10_), + end10_(other.end10_), + current10_(other.current10_) { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType(*current1_, *current2_, *current3_, + *current4_, *current5_, *current6_, *current7_, *current8_, + *current9_, *current10_); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return + current1_ == end1_ || + current2_ == end2_ || + current3_ == end3_ || + current4_ == end4_ || + current5_ == end5_ || + current6_ == end6_ || + current7_ == end7_ || + current8_ == end8_ || + current9_ == end9_ || + current10_ == end10_; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. + const typename ParamGenerator::iterator begin1_; + const typename ParamGenerator::iterator end1_; + typename ParamGenerator::iterator current1_; + const typename ParamGenerator::iterator begin2_; + const typename ParamGenerator::iterator end2_; + typename ParamGenerator::iterator current2_; + const typename ParamGenerator::iterator begin3_; + const typename ParamGenerator::iterator end3_; + typename ParamGenerator::iterator current3_; + const typename ParamGenerator::iterator begin4_; + const typename ParamGenerator::iterator end4_; + typename ParamGenerator::iterator current4_; + const typename ParamGenerator::iterator begin5_; + const typename ParamGenerator::iterator end5_; + typename ParamGenerator::iterator current5_; + const typename ParamGenerator::iterator begin6_; + const typename ParamGenerator::iterator end6_; + typename ParamGenerator::iterator current6_; + const typename ParamGenerator::iterator begin7_; + const typename ParamGenerator::iterator end7_; + typename ParamGenerator::iterator current7_; + const typename ParamGenerator::iterator begin8_; + const typename ParamGenerator::iterator end8_; + typename ParamGenerator::iterator current8_; + const typename ParamGenerator::iterator begin9_; + const typename ParamGenerator::iterator end9_; + typename ParamGenerator::iterator current9_; + const typename ParamGenerator::iterator begin10_; + const typename ParamGenerator::iterator end10_; + typename ParamGenerator::iterator current10_; + ParamType current_value_; + }; // class CartesianProductGenerator10::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator10& other); + + const ParamGenerator g1_; + const ParamGenerator g2_; + const ParamGenerator g3_; + const ParamGenerator g4_; + const ParamGenerator g5_; + const ParamGenerator g6_; + const ParamGenerator g7_; + const ParamGenerator g8_; + const ParamGenerator g9_; + const ParamGenerator g10_; +}; // class CartesianProductGenerator10 + + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Helper classes providing Combine() with polymorphic features. They allow +// casting CartesianProductGeneratorN to ParamGenerator if T is +// convertible to U. +// +template +class CartesianProductHolder2 { + public: +CartesianProductHolder2(const Generator1& g1, const Generator2& g2) + : g1_(g1), g2_(g2) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator2( + static_cast >(g1_), + static_cast >(g2_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder2& other); + + const Generator1 g1_; + const Generator2 g2_; +}; // class CartesianProductHolder2 + +template +class CartesianProductHolder3 { + public: +CartesianProductHolder3(const Generator1& g1, const Generator2& g2, + const Generator3& g3) + : g1_(g1), g2_(g2), g3_(g3) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator3( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder3& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; +}; // class CartesianProductHolder3 + +template +class CartesianProductHolder4 { + public: +CartesianProductHolder4(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator4( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder4& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; +}; // class CartesianProductHolder4 + +template +class CartesianProductHolder5 { + public: +CartesianProductHolder5(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator5( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder5& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; +}; // class CartesianProductHolder5 + +template +class CartesianProductHolder6 { + public: +CartesianProductHolder6(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator6( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder6& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; +}; // class CartesianProductHolder6 + +template +class CartesianProductHolder7 { + public: +CartesianProductHolder7(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator7( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder7& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; +}; // class CartesianProductHolder7 + +template +class CartesianProductHolder8 { + public: +CartesianProductHolder8(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), + g8_(g8) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator8( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder8& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; +}; // class CartesianProductHolder8 + +template +class CartesianProductHolder9 { + public: +CartesianProductHolder9(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator9( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder9& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; +}; // class CartesianProductHolder9 + +template +class CartesianProductHolder10 { + public: +CartesianProductHolder10(const Generator1& g1, const Generator2& g2, + const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9, const Generator10& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), + g9_(g9), g10_(g10) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator10( + static_cast >(g1_), + static_cast >(g2_), + static_cast >(g3_), + static_cast >(g4_), + static_cast >(g5_), + static_cast >(g6_), + static_cast >(g7_), + static_cast >(g8_), + static_cast >(g9_), + static_cast >(g10_))); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder10& other); + + const Generator1 g1_; + const Generator2 g2_; + const Generator3 g3_; + const Generator4 g4_; + const Generator5 g5_; + const Generator6 g6_; + const Generator7 g7_; + const Generator8 g8_; + const Generator9 g9_; + const Generator10 g10_; +}; // class CartesianProductHolder10 + +# endif // GTEST_HAS_COMBINE + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h.pump new file mode 100644 index 0000000..5c7c47a --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -0,0 +1,286 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of Values arguments we want to support. +$var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. +// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently Google Test supports at most $n arguments in Values, +// and at most $maxtuple arguments in Combine. Please contact +// googletestframework@googlegroups.com if you need more. +// Please note that the number of arguments to Combine is limited +// by the maximum arity of the implementation of tuple which is +// currently set at $maxtuple. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-port.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Forward declarations of ValuesIn(), which is implemented in +// include/gtest/gtest-param-test.h. +template +internal::ParamGenerator< + typename ::testing::internal::IteratorTraits::value_type> +ValuesIn(ForwardIterator begin, ForwardIterator end); + +template +internal::ParamGenerator ValuesIn(const T (&array)[N]); + +template +internal::ParamGenerator ValuesIn( + const Container& container); + +namespace internal { + +// Used in the Values() function to provide polymorphic capabilities. +$range i 1..n +$for i [[ +$range j 1..i + +template <$for j, [[typename T$j]]> +class ValueArray$i { + public: + $if i==1 [[explicit ]]ValueArray$i($for j, [[T$j v$j]]) : $for j, [[v$(j)_(v$j)]] {} + + template + operator ParamGenerator() const { + const T array[] = {$for j, [[static_cast(v$(j)_)]]}; + return ValuesIn(array); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const ValueArray$i& other); + +$for j [[ + + const T$j v$(j)_; +]] + +}; + +]] + +# if GTEST_HAS_COMBINE +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Generates values from the Cartesian product of values produced +// by the argument generators. +// +$range i 2..maxtuple +$for i [[ +$range j 1..i +$range k 2..i + +template <$for j, [[typename T$j]]> +class CartesianProductGenerator$i + : public ParamGeneratorInterface< ::testing::tuple<$for j, [[T$j]]> > { + public: + typedef ::testing::tuple<$for j, [[T$j]]> ParamType; + + CartesianProductGenerator$i($for j, [[const ParamGenerator& g$j]]) + : $for j, [[g$(j)_(g$j)]] {} + virtual ~CartesianProductGenerator$i() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, $for j, [[g$(j)_, g$(j)_.begin()]]); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, $for j, [[g$(j)_, g$(j)_.end()]]); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, $for j, [[ + + const ParamGenerator& g$j, + const typename ParamGenerator::iterator& current$(j)]]) + : base_(base), +$for j, [[ + + begin$(j)_(g$j.begin()), end$(j)_(g$j.end()), current$(j)_(current$j) +]] { + ComputeCurrentValue(); + } + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + // Advance should not be called on beyond-of-range iterators + // so no component iterators must be beyond end of range, either. + virtual void Advance() { + assert(!AtEnd()); + ++current$(i)_; + +$for k [[ + if (current$(i+2-k)_ == end$(i+2-k)_) { + current$(i+2-k)_ = begin$(i+2-k)_; + ++current$(i+2-k-1)_; + } + +]] + ComputeCurrentValue(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const ParamType* Current() const { return ¤t_value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = + CheckedDowncastToActualType(&other); + // We must report iterators equal if they both point beyond their + // respective ranges. That can happen in a variety of fashions, + // so we have to consult AtEnd(). + return (AtEnd() && typed_other->AtEnd()) || + ($for j && [[ + + current$(j)_ == typed_other->current$(j)_ +]]); + } + + private: + Iterator(const Iterator& other) + : base_(other.base_), $for j, [[ + + begin$(j)_(other.begin$(j)_), + end$(j)_(other.end$(j)_), + current$(j)_(other.current$(j)_) +]] { + ComputeCurrentValue(); + } + + void ComputeCurrentValue() { + if (!AtEnd()) + current_value_ = ParamType($for j, [[*current$(j)_]]); + } + bool AtEnd() const { + // We must report iterator past the end of the range when either of the + // component iterators has reached the end of its range. + return +$for j || [[ + + current$(j)_ == end$(j)_ +]]; + } + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. + // current[i]_ is the actual traversing iterator. +$for j [[ + + const typename ParamGenerator::iterator begin$(j)_; + const typename ParamGenerator::iterator end$(j)_; + typename ParamGenerator::iterator current$(j)_; +]] + + ParamType current_value_; + }; // class CartesianProductGenerator$i::Iterator + + // No implementation - assignment is unsupported. + void operator=(const CartesianProductGenerator$i& other); + + +$for j [[ + const ParamGenerator g$(j)_; + +]] +}; // class CartesianProductGenerator$i + + +]] + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Helper classes providing Combine() with polymorphic features. They allow +// casting CartesianProductGeneratorN to ParamGenerator if T is +// convertible to U. +// +$range i 2..maxtuple +$for i [[ +$range j 1..i + +template <$for j, [[class Generator$j]]> +class CartesianProductHolder$i { + public: +CartesianProductHolder$i($for j, [[const Generator$j& g$j]]) + : $for j, [[g$(j)_(g$j)]] {} + template <$for j, [[typename T$j]]> + operator ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >() const { + return ParamGenerator< ::testing::tuple<$for j, [[T$j]]> >( + new CartesianProductGenerator$i<$for j, [[T$j]]>( +$for j,[[ + + static_cast >(g$(j)_) +]])); + } + + private: + // No implementation - assignment is unsupported. + void operator=(const CartesianProductHolder$i& other); + + +$for j [[ + const Generator$j g$(j)_; + +]] +}; // class CartesianProductHolder$i + +]] + +# endif // GTEST_HAS_COMBINE + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-param-util.h b/gtestsrc/gtest/include/gtest/internal/gtest-param-util.h new file mode 100644 index 0000000..82cab9b --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-param-util.h @@ -0,0 +1,731 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) + +// Type and function utilities for implementing parameterized tests. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ + +#include + +#include +#include +#include +#include + +// scripts/fuse_gtest.py depends on gtest's own header being #included +// *unconditionally*. Therefore these #includes cannot be moved +// inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-linked_ptr.h" +#include "gtest/internal/gtest-port.h" +#include "gtest/gtest-printers.h" + +#if GTEST_HAS_PARAM_TEST + +namespace testing { + +// Input to a parameterized test name generator, describing a test parameter. +// Consists of the parameter value and the integer parameter index. +template +struct TestParamInfo { + TestParamInfo(const ParamType& a_param, size_t an_index) : + param(a_param), + index(an_index) {} + ParamType param; + size_t index; +}; + +// A builtin parameterized test name generator which returns the result of +// testing::PrintToString. +struct PrintToStringParamName { + template + std::string operator()(const TestParamInfo& info) const { + return PrintToString(info.param); + } +}; + +namespace internal { + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Outputs a message explaining invalid registration of different +// fixture class for the same test case. This may happen when +// TEST_P macro is used to define two tests with the same name +// but in different namespaces. +GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, + CodeLocation code_location); + +template class ParamGeneratorInterface; +template class ParamGenerator; + +// Interface for iterating over elements provided by an implementation +// of ParamGeneratorInterface. +template +class ParamIteratorInterface { + public: + virtual ~ParamIteratorInterface() {} + // A pointer to the base generator instance. + // Used only for the purposes of iterator comparison + // to make sure that two iterators belong to the same generator. + virtual const ParamGeneratorInterface* BaseGenerator() const = 0; + // Advances iterator to point to the next element + // provided by the generator. The caller is responsible + // for not calling Advance() on an iterator equal to + // BaseGenerator()->End(). + virtual void Advance() = 0; + // Clones the iterator object. Used for implementing copy semantics + // of ParamIterator. + virtual ParamIteratorInterface* Clone() const = 0; + // Dereferences the current iterator and provides (read-only) access + // to the pointed value. It is the caller's responsibility not to call + // Current() on an iterator equal to BaseGenerator()->End(). + // Used for implementing ParamGenerator::operator*(). + virtual const T* Current() const = 0; + // Determines whether the given iterator and other point to the same + // element in the sequence generated by the generator. + // Used for implementing ParamGenerator::operator==(). + virtual bool Equals(const ParamIteratorInterface& other) const = 0; +}; + +// Class iterating over elements provided by an implementation of +// ParamGeneratorInterface. It wraps ParamIteratorInterface +// and implements the const forward iterator concept. +template +class ParamIterator { + public: + typedef T value_type; + typedef const T& reference; + typedef ptrdiff_t difference_type; + + // ParamIterator assumes ownership of the impl_ pointer. + ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} + ParamIterator& operator=(const ParamIterator& other) { + if (this != &other) + impl_.reset(other.impl_->Clone()); + return *this; + } + + const T& operator*() const { return *impl_->Current(); } + const T* operator->() const { return impl_->Current(); } + // Prefix version of operator++. + ParamIterator& operator++() { + impl_->Advance(); + return *this; + } + // Postfix version of operator++. + ParamIterator operator++(int /*unused*/) { + ParamIteratorInterface* clone = impl_->Clone(); + impl_->Advance(); + return ParamIterator(clone); + } + bool operator==(const ParamIterator& other) const { + return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); + } + bool operator!=(const ParamIterator& other) const { + return !(*this == other); + } + + private: + friend class ParamGenerator; + explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} + scoped_ptr > impl_; +}; + +// ParamGeneratorInterface is the binary interface to access generators +// defined in other translation units. +template +class ParamGeneratorInterface { + public: + typedef T ParamType; + + virtual ~ParamGeneratorInterface() {} + + // Generator interface definition + virtual ParamIteratorInterface* Begin() const = 0; + virtual ParamIteratorInterface* End() const = 0; +}; + +// Wraps ParamGeneratorInterface and provides general generator syntax +// compatible with the STL Container concept. +// This class implements copy initialization semantics and the contained +// ParamGeneratorInterface instance is shared among all copies +// of the original object. This is possible because that instance is immutable. +template +class ParamGenerator { + public: + typedef ParamIterator iterator; + + explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} + ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} + + ParamGenerator& operator=(const ParamGenerator& other) { + impl_ = other.impl_; + return *this; + } + + iterator begin() const { return iterator(impl_->Begin()); } + iterator end() const { return iterator(impl_->End()); } + + private: + linked_ptr > impl_; +}; + +// Generates values from a range of two comparable values. Can be used to +// generate sequences of user-defined types that implement operator+() and +// operator<(). +// This class is used in the Range() function. +template +class RangeGenerator : public ParamGeneratorInterface { + public: + RangeGenerator(T begin, T end, IncrementT step) + : begin_(begin), end_(end), + step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + virtual ~RangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, begin_, 0, step_); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, end_, end_index_, step_); + } + + private: + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, T value, int index, + IncrementT step) + : base_(base), value_(value), index_(index), step_(step) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + value_ = static_cast(value_ + step_); + index_++; + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + virtual const T* Current() const { return &value_; } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const int other_index = + CheckedDowncastToActualType(&other)->index_; + return index_ == other_index; + } + + private: + Iterator(const Iterator& other) + : ParamIteratorInterface(), + base_(other.base_), value_(other.value_), index_(other.index_), + step_(other.step_) {} + + // No implementation - assignment is unsupported. + void operator=(const Iterator& other); + + const ParamGeneratorInterface* const base_; + T value_; + int index_; + const IncrementT step_; + }; // class RangeGenerator::Iterator + + static int CalculateEndIndex(const T& begin, + const T& end, + const IncrementT& step) { + int end_index = 0; + for (T i = begin; i < end; i = static_cast(i + step)) + end_index++; + return end_index; + } + + // No implementation - assignment is unsupported. + void operator=(const RangeGenerator& other); + + const T begin_; + const T end_; + const IncrementT step_; + // The index for the end() iterator. All the elements in the generated + // sequence are indexed (0-based) to aid iterator comparison. + const int end_index_; +}; // class RangeGenerator + + +// Generates values from a pair of STL-style iterators. Used in the +// ValuesIn() function. The elements are copied from the source range +// since the source can be located on the stack, and the generator +// is likely to persist beyond that stack frame. +template +class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { + public: + template + ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) + : container_(begin, end) {} + virtual ~ValuesInIteratorRangeGenerator() {} + + virtual ParamIteratorInterface* Begin() const { + return new Iterator(this, container_.begin()); + } + virtual ParamIteratorInterface* End() const { + return new Iterator(this, container_.end()); + } + + private: + typedef typename ::std::vector ContainerType; + + class Iterator : public ParamIteratorInterface { + public: + Iterator(const ParamGeneratorInterface* base, + typename ContainerType::const_iterator iterator) + : base_(base), iterator_(iterator) {} + virtual ~Iterator() {} + + virtual const ParamGeneratorInterface* BaseGenerator() const { + return base_; + } + virtual void Advance() { + ++iterator_; + value_.reset(); + } + virtual ParamIteratorInterface* Clone() const { + return new Iterator(*this); + } + // We need to use cached value referenced by iterator_ because *iterator_ + // can return a temporary object (and of type other then T), so just + // having "return &*iterator_;" doesn't work. + // value_ is updated here and not in Advance() because Advance() + // can advance iterator_ beyond the end of the range, and we cannot + // detect that fact. The client code, on the other hand, is + // responsible for not calling Current() on an out-of-range iterator. + virtual const T* Current() const { + if (value_.get() == NULL) + value_.reset(new T(*iterator_)); + return value_.get(); + } + virtual bool Equals(const ParamIteratorInterface& other) const { + // Having the same base generator guarantees that the other + // iterator is of the same type and we can downcast. + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) + << "The program attempted to compare iterators " + << "from different generators." << std::endl; + return iterator_ == + CheckedDowncastToActualType(&other)->iterator_; + } + + private: + Iterator(const Iterator& other) + // The explicit constructor call suppresses a false warning + // emitted by gcc when supplied with the -Wextra option. + : ParamIteratorInterface(), + base_(other.base_), + iterator_(other.iterator_) {} + + const ParamGeneratorInterface* const base_; + typename ContainerType::const_iterator iterator_; + // A cached value of *iterator_. We keep it here to allow access by + // pointer in the wrapping iterator's operator->(). + // value_ needs to be mutable to be accessed in Current(). + // Use of scoped_ptr helps manage cached value's lifetime, + // which is bound by the lifespan of the iterator itself. + mutable scoped_ptr value_; + }; // class ValuesInIteratorRangeGenerator::Iterator + + // No implementation - assignment is unsupported. + void operator=(const ValuesInIteratorRangeGenerator& other); + + const ContainerType container_; +}; // class ValuesInIteratorRangeGenerator + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Default parameterized test name generator, returns a string containing the +// integer test parameter index. +template +std::string DefaultParamName(const TestParamInfo& info) { + Message name_stream; + name_stream << info.index; + return name_stream.GetString(); +} + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Parameterized test name overload helpers, which help the +// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized +// test name generator and user param name generator. +template +ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) { + return func; +} + +template +struct ParamNameGenFunc { + typedef std::string Type(const TestParamInfo&); +}; + +template +typename ParamNameGenFunc::Type *GetParamNameGen() { + return DefaultParamName; +} + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Stores a parameter value and later creates tests parameterized with that +// value. +template +class ParameterizedTestFactory : public TestFactoryBase { + public: + typedef typename TestClass::ParamType ParamType; + explicit ParameterizedTestFactory(ParamType parameter) : + parameter_(parameter) {} + virtual Test* CreateTest() { + TestClass::SetParam(¶meter_); + return new TestClass(); + } + + private: + const ParamType parameter_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactoryBase is a base class for meta-factories that create +// test factories for passing into MakeAndRegisterTestInfo function. +template +class TestMetaFactoryBase { + public: + virtual ~TestMetaFactoryBase() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// TestMetaFactory creates test factories for passing into +// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives +// ownership of test factory pointer, same factory object cannot be passed +// into that method twice. But ParameterizedTestCaseInfo is going to call +// it for each Test/Parameter value combination. Thus it needs meta factory +// creator class. +template +class TestMetaFactory + : public TestMetaFactoryBase { + public: + typedef typename TestCase::ParamType ParamType; + + TestMetaFactory() {} + + virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { + return new ParameterizedTestFactory(parameter); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfoBase is a generic interface +// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase +// accumulates test information provided by TEST_P macro invocations +// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations +// and uses that information to register all resulting test instances +// in RegisterTests method. The ParameterizeTestCaseRegistry class holds +// a collection of pointers to the ParameterizedTestCaseInfo objects +// and calls RegisterTests() on each of them when asked. +class ParameterizedTestCaseInfoBase { + public: + virtual ~ParameterizedTestCaseInfoBase() {} + + // Base part of test case name for display purposes. + virtual const string& GetTestCaseName() const = 0; + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const = 0; + // UnitTest class invokes this method to register tests in this + // test case right before running them in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + virtual void RegisterTests() = 0; + + protected: + ParameterizedTestCaseInfoBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); +}; + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P +// macro invocations for a particular test case and generators +// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that +// test case. It registers tests with all values generated by all +// generators when asked. +template +class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { + public: + // ParamType and GeneratorCreationFunc are private types but are required + // for declarations of public methods AddTestPattern() and + // AddTestCaseInstantiation(). + typedef typename TestCase::ParamType ParamType; + // A function that returns an instance of appropriate generator type. + typedef ParamGenerator(GeneratorCreationFunc)(); + typedef typename ParamNameGenFunc::Type ParamNameGeneratorFunc; + + explicit ParameterizedTestCaseInfo( + const char* name, CodeLocation code_location) + : test_case_name_(name), code_location_(code_location) {} + + // Test case base name for display purposes. + virtual const string& GetTestCaseName() const { return test_case_name_; } + // Test case id to verify identity. + virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } + // TEST_P macro uses AddTestPattern() to record information + // about a single test in a LocalTestInfo structure. + // test_case_name is the base name of the test case (without invocation + // prefix). test_base_name is the name of an individual test without + // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is + // test case base name and DoBar is test base name. + void AddTestPattern(const char* test_case_name, + const char* test_base_name, + TestMetaFactoryBase* meta_factory) { + tests_.push_back(linked_ptr(new TestInfo(test_case_name, + test_base_name, + meta_factory))); + } + // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information + // about a generator. + int AddTestCaseInstantiation(const string& instantiation_name, + GeneratorCreationFunc* func, + ParamNameGeneratorFunc* name_func, + const char* file, + int line) { + instantiations_.push_back( + InstantiationInfo(instantiation_name, func, name_func, file, line)); + return 0; // Return value used only to run this method in namespace scope. + } + // UnitTest class invokes this method to register tests in this test case + // test cases right before running tests in RUN_ALL_TESTS macro. + // This method should not be called more then once on any single + // instance of a ParameterizedTestCaseInfoBase derived class. + // UnitTest has a guard to prevent from calling this method more then once. + virtual void RegisterTests() { + for (typename TestInfoContainer::iterator test_it = tests_.begin(); + test_it != tests_.end(); ++test_it) { + linked_ptr test_info = *test_it; + for (typename InstantiationContainer::iterator gen_it = + instantiations_.begin(); gen_it != instantiations_.end(); + ++gen_it) { + const string& instantiation_name = gen_it->name; + ParamGenerator generator((*gen_it->generator)()); + ParamNameGeneratorFunc* name_func = gen_it->name_func; + const char* file = gen_it->file; + int line = gen_it->line; + + string test_case_name; + if ( !instantiation_name.empty() ) + test_case_name = instantiation_name + "/"; + test_case_name += test_info->test_case_base_name; + + size_t i = 0; + std::set test_param_names; + for (typename ParamGenerator::iterator param_it = + generator.begin(); + param_it != generator.end(); ++param_it, ++i) { + Message test_name_stream; + + std::string param_name = name_func( + TestParamInfo(*param_it, i)); + + GTEST_CHECK_(IsValidParamName(param_name)) + << "Parameterized test name '" << param_name + << "' is invalid, in " << file + << " line " << line << std::endl; + + GTEST_CHECK_(test_param_names.count(param_name) == 0) + << "Duplicate parameterized test name '" << param_name + << "', in " << file << " line " << line << std::endl; + + test_param_names.insert(param_name); + + test_name_stream << test_info->test_base_name << "/" << param_name; + MakeAndRegisterTestInfo( + test_case_name.c_str(), + test_name_stream.GetString().c_str(), + NULL, // No type parameter. + PrintToString(*param_it).c_str(), + code_location_, + GetTestCaseTypeId(), + TestCase::SetUpTestCase, + TestCase::TearDownTestCase, + test_info->test_meta_factory->CreateTestFactory(*param_it)); + } // for param_it + } // for gen_it + } // for test_it + } // RegisterTests + + private: + // LocalTestInfo structure keeps information about a single test registered + // with TEST_P macro. + struct TestInfo { + TestInfo(const char* a_test_case_base_name, + const char* a_test_base_name, + TestMetaFactoryBase* a_test_meta_factory) : + test_case_base_name(a_test_case_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} + + const string test_case_base_name; + const string test_base_name; + const scoped_ptr > test_meta_factory; + }; + typedef ::std::vector > TestInfoContainer; + // Records data received from INSTANTIATE_TEST_CASE_P macros: + // + struct InstantiationInfo { + InstantiationInfo(const std::string &name_in, + GeneratorCreationFunc* generator_in, + ParamNameGeneratorFunc* name_func_in, + const char* file_in, + int line_in) + : name(name_in), + generator(generator_in), + name_func(name_func_in), + file(file_in), + line(line_in) {} + + std::string name; + GeneratorCreationFunc* generator; + ParamNameGeneratorFunc* name_func; + const char* file; + int line; + }; + typedef ::std::vector InstantiationContainer; + + static bool IsValidParamName(const std::string& name) { + // Check for empty string + if (name.empty()) + return false; + + // Check for invalid characters + for (std::string::size_type index = 0; index < name.size(); ++index) { + if (!isalnum(name[index]) && name[index] != '_') + return false; + } + + return true; + } + + const string test_case_name_; + CodeLocation code_location_; + TestInfoContainer tests_; + InstantiationContainer instantiations_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); +}; // class ParameterizedTestCaseInfo + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase +// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P +// macros use it to locate their corresponding ParameterizedTestCaseInfo +// descriptors. +class ParameterizedTestCaseRegistry { + public: + ParameterizedTestCaseRegistry() {} + ~ParameterizedTestCaseRegistry() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + delete *it; + } + } + + // Looks up or creates and returns a structure containing information about + // tests and instantiations of a particular test case. + template + ParameterizedTestCaseInfo* GetTestCasePatternHolder( + const char* test_case_name, + CodeLocation code_location) { + ParameterizedTestCaseInfo* typed_test_info = NULL; + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + if ((*it)->GetTestCaseName() == test_case_name) { + if ((*it)->GetTestCaseTypeId() != GetTypeId()) { + // Complain about incorrect usage of Google Test facilities + // and terminate the program since we cannot guaranty correct + // test case setup and tear-down in this case. + ReportInvalidTestCaseType(test_case_name, code_location); + posix::Abort(); + } else { + // At this point we are sure that the object we found is of the same + // type we are looking for, so we downcast it to that type + // without further checks. + typed_test_info = CheckedDowncastToActualType< + ParameterizedTestCaseInfo >(*it); + } + break; + } + } + if (typed_test_info == NULL) { + typed_test_info = new ParameterizedTestCaseInfo( + test_case_name, code_location); + test_case_infos_.push_back(typed_test_info); + } + return typed_test_info; + } + void RegisterTests() { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); + it != test_case_infos_.end(); ++it) { + (*it)->RegisterTests(); + } + } + + private: + typedef ::std::vector TestCaseInfoContainer; + + TestCaseInfoContainer test_case_infos_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); +}; + +} // namespace internal +} // namespace testing + +#endif // GTEST_HAS_PARAM_TEST + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-port-arch.h b/gtestsrc/gtest/include/gtest/internal/gtest-port-arch.h new file mode 100644 index 0000000..74ab949 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-port-arch.h @@ -0,0 +1,93 @@ +// Copyright 2015, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// The Google C++ Testing Framework (Google Test) +// +// This header file defines the GTEST_OS_* macro. +// It is separate from gtest-port.h so that custom/gtest-port.h can include it. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ + +// Determines the platform on which Google Test is compiled. +#ifdef __CYGWIN__ +# define GTEST_OS_CYGWIN 1 +#elif defined __SYMBIAN32__ +# define GTEST_OS_SYMBIAN 1 +#elif defined _WIN32 +# define GTEST_OS_WINDOWS 1 +# ifdef _WIN32_WCE +# define GTEST_OS_WINDOWS_MOBILE 1 +# elif defined(__MINGW__) || defined(__MINGW32__) +# define GTEST_OS_WINDOWS_MINGW 1 +# elif defined(WINAPI_FAMILY) +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define GTEST_OS_WINDOWS_DESKTOP 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) +# define GTEST_OS_WINDOWS_PHONE 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +# define GTEST_OS_WINDOWS_RT 1 +# else + // WINAPI_FAMILY defined but no known partition matched. + // Default to desktop. +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif +# else +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif // _WIN32_WCE +#elif defined __APPLE__ +# define GTEST_OS_MAC 1 +# if TARGET_OS_IPHONE +# define GTEST_OS_IOS 1 +# endif +#elif defined __FreeBSD__ +# define GTEST_OS_FREEBSD 1 +#elif defined __linux__ +# define GTEST_OS_LINUX 1 +# if defined __ANDROID__ +# define GTEST_OS_LINUX_ANDROID 1 +# endif +#elif defined __MVS__ +# define GTEST_OS_ZOS 1 +#elif defined(__sun) && defined(__SVR4) +# define GTEST_OS_SOLARIS 1 +#elif defined(_AIX) +# define GTEST_OS_AIX 1 +#elif defined(__hpux) +# define GTEST_OS_HPUX 1 +#elif defined __native_client__ +# define GTEST_OS_NACL 1 +#elif defined __OpenBSD__ +# define GTEST_OS_OPENBSD 1 +#elif defined __QNX__ +# define GTEST_OS_QNX 1 +#endif // __CYGWIN__ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-port.h b/gtestsrc/gtest/include/gtest/internal/gtest-port.h new file mode 100644 index 0000000..0094ed5 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-port.h @@ -0,0 +1,2554 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan) +// +// Low-level types and utilities for porting Google Test to various +// platforms. All macros ending with _ and symbols defined in an +// internal namespace are subject to change without notice. Code +// outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't +// end with _ are part of Google Test's public API and can be used by +// code outside Google Test. +// +// This file is fundamental to Google Test. All other Google Test source +// files are expected to #include this. Therefore, it cannot #include +// any other Google Test header. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ + +// Environment-describing macros +// ----------------------------- +// +// Google Test can be used in many different environments. Macros in +// this section tell Google Test what kind of environment it is being +// used in, such that Google Test can provide environment-specific +// features and implementations. +// +// Google Test tries to automatically detect the properties of its +// environment, so users usually don't need to worry about these +// macros. However, the automatic detection is not perfect. +// Sometimes it's necessary for a user to define some of the following +// macros in the build script to override Google Test's decisions. +// +// If the user doesn't define a macro in the list, Google Test will +// provide a default definition. After this header is #included, all +// macros in this list will be defined to either 1 or 0. +// +// Notes to maintainers: +// - Each macro here is a user-tweakable knob; do not grow the list +// lightly. +// - Use #if to key off these macros. Don't use #ifdef or "#if +// defined(...)", which will not work as these macros are ALWAYS +// defined. +// +// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) +// is/isn't available. +// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions +// are enabled. +// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::string, which is different to std::string). +// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string +// is/isn't available (some systems define +// ::wstring, which is different to std::wstring). +// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular +// expressions are/aren't available. +// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that +// is/isn't available. +// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't +// enabled. +// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that +// std::wstring does/doesn't work (Google Test can +// be used where std::wstring is unavailable). +// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple +// is/isn't available. +// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the +// compiler supports Microsoft's "Structured +// Exception Handling". +// GTEST_HAS_STREAM_REDIRECTION +// - Define it to 1/0 to indicate whether the +// platform supports I/O stream redirection using +// dup() and dup2(). +// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google +// Test's own tr1 tuple implementation should be +// used. Unused when the user sets +// GTEST_HAS_TR1_TUPLE to 0. +// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test +// is building in C++11/C++98 mode. +// GTEST_LINKED_AS_SHARED_LIBRARY +// - Define to 1 when compiling tests that use +// Google Test as a shared library (known as +// DLL on Windows). +// GTEST_CREATE_SHARED_LIBRARY +// - Define to 1 when compiling Google Test itself +// as a shared library. + +// Platform-indicating macros +// -------------------------- +// +// Macros indicating the platform on which Google Test is being used +// (a macro is defined to 1 if compiled on the given platform; +// otherwise UNDEFINED -- it's never defined to 0.). Google Test +// defines these macros automatically. Code outside Google Test MUST +// NOT define them. +// +// GTEST_OS_AIX - IBM AIX +// GTEST_OS_CYGWIN - Cygwin +// GTEST_OS_FREEBSD - FreeBSD +// GTEST_OS_HPUX - HP-UX +// GTEST_OS_LINUX - Linux +// GTEST_OS_LINUX_ANDROID - Google Android +// GTEST_OS_MAC - Mac OS X +// GTEST_OS_IOS - iOS +// GTEST_OS_NACL - Google Native Client (NaCl) +// GTEST_OS_OPENBSD - OpenBSD +// GTEST_OS_QNX - QNX +// GTEST_OS_SOLARIS - Sun Solaris +// GTEST_OS_SYMBIAN - Symbian +// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) +// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop +// GTEST_OS_WINDOWS_MINGW - MinGW +// GTEST_OS_WINDOWS_MOBILE - Windows Mobile +// GTEST_OS_WINDOWS_PHONE - Windows Phone +// GTEST_OS_WINDOWS_RT - Windows Store App/WinRT +// GTEST_OS_ZOS - z/OS +// +// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the +// most stable support. Since core members of the Google Test project +// don't have access to other platforms, support for them may be less +// stable. If you notice any problems on your platform, please notify +// googletestframework@googlegroups.com (patches for fixing them are +// even more welcome!). +// +// It is possible that none of the GTEST_OS_* macros are defined. + +// Feature-indicating macros +// ------------------------- +// +// Macros indicating which Google Test features are available (a macro +// is defined to 1 if the corresponding feature is supported; +// otherwise UNDEFINED -- it's never defined to 0.). Google Test +// defines these macros automatically. Code outside Google Test MUST +// NOT define them. +// +// These macros are public so that portable tests can be written. +// Such tests typically surround code using a feature with an #if +// which controls that code. For example: +// +// #if GTEST_HAS_DEATH_TEST +// EXPECT_DEATH(DoSomethingDeadly()); +// #endif +// +// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized +// tests) +// GTEST_HAS_DEATH_TEST - death tests +// GTEST_HAS_PARAM_TEST - value-parameterized tests +// GTEST_HAS_TYPED_TEST - typed tests +// GTEST_HAS_TYPED_TEST_P - type-parameterized tests +// GTEST_IS_THREADSAFE - Google Test is thread-safe. +// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with +// GTEST_HAS_POSIX_RE (see above) which users can +// define themselves. +// GTEST_USES_SIMPLE_RE - our own simple regex is used; +// the above two are mutually exclusive. +// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). + +// Misc public macros +// ------------------ +// +// GTEST_FLAG(flag_name) - references the variable corresponding to +// the given Google Test flag. + +// Internal utilities +// ------------------ +// +// The following macros and utilities are for Google Test's INTERNAL +// use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. +// +// Macros for basic C++ coding: +// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. +// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a +// variable don't have to be used. +// GTEST_DISALLOW_ASSIGN_ - disables operator=. +// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. +// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. +// GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is +// suppressed (constant conditional). +// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 +// is suppressed. +// +// C++11 feature wrappers: +// +// testing::internal::move - portability wrapper for std::move. +// +// Synchronization: +// Mutex, MutexLock, ThreadLocal, GetThreadCount() +// - synchronization primitives. +// +// Template meta programming: +// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. +// IteratorTraits - partial implementation of std::iterator_traits, which +// is not available in libCstd when compiled with Sun C++. +// +// Smart pointers: +// scoped_ptr - as in TR2. +// +// Regular expressions: +// RE - a simple regular expression class using the POSIX +// Extended Regular Expression syntax on UNIX-like +// platforms, or a reduced regular exception syntax on +// other platforms, including Windows. +// +// Logging: +// GTEST_LOG_() - logs messages at the specified severity level. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. +// +// Stdout and stderr capturing: +// CaptureStdout() - starts capturing stdout. +// GetCapturedStdout() - stops capturing stdout and returns the captured +// string. +// CaptureStderr() - starts capturing stderr. +// GetCapturedStderr() - stops capturing stderr and returns the captured +// string. +// +// Integer types: +// TypeWithSize - maps an integer to a int type. +// Int32, UInt32, Int64, UInt64, TimeInMillis +// - integers of known sizes. +// BiggestInt - the biggest signed integer type. +// +// Command-line utilities: +// GTEST_DECLARE_*() - declares a flag. +// GTEST_DEFINE_*() - defines a flag. +// GetInjectableArgvs() - returns the command line as a vector of strings. +// +// Environment variable utilities: +// GetEnv() - gets the value of an environment variable. +// BoolFromGTestEnv() - parses a bool environment variable. +// Int32FromGTestEnv() - parses an Int32 environment variable. +// StringFromGTestEnv() - parses a string environment variable. + +#include // for isspace, etc +#include // for ptrdiff_t +#include +#include +#include +#ifndef _WIN32_WCE +# include +# include +#endif // !_WIN32_WCE + +#if defined __APPLE__ +# include +# include +#endif + +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT +#include +#include // NOLINT + +#include "gtest/internal/gtest-port-arch.h" +#include "gtest/internal/custom/gtest-port.h" + +#if !defined(GTEST_DEV_EMAIL_) +# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +# define GTEST_FLAG_PREFIX_ "gtest_" +# define GTEST_FLAG_PREFIX_DASH_ "gtest-" +# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +# define GTEST_NAME_ "Google Test" +# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" +#endif // !defined(GTEST_DEV_EMAIL_) + +#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) +# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" +#endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) + +// Determines the version of gcc that is used to compile this. +#ifdef __GNUC__ +// 40302 means version 4.3.2. +# define GTEST_GCC_VER_ \ + (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#endif // __GNUC__ + +// Macros for disabling Microsoft Visual C++ warnings. +// +// GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) +// /* code that triggers warnings C4800 and C4385 */ +// GTEST_DISABLE_MSC_WARNINGS_POP_() +#if _MSC_VER >= 1500 +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ + __pragma(warning(push)) \ + __pragma(warning(disable: warnings)) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ + __pragma(warning(pop)) +#else +// Older versions of MSVC don't have __pragma. +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() +#endif + +#ifndef GTEST_LANG_CXX11 +// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when +// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a +// value for __cplusplus, and recent versions of clang, gcc, and +// probably other compilers set that too in C++11 mode. +# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L +// Compiling in at least C++11 mode. +# define GTEST_LANG_CXX11 1 +# else +# define GTEST_LANG_CXX11 0 +# endif +#endif + +// Distinct from C++11 language support, some environments don't provide +// proper C++11 library support. Notably, it's possible to build in +// C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ +// with no C++11 support. +// +// libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ +// 20110325, but maintenance releases in the 4.4 and 4.5 series followed +// this date, so check for those versions by their date stamps. +// https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning +#if GTEST_LANG_CXX11 && \ + (!defined(__GLIBCXX__) || ( \ + __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ + /* Blacklist of patch releases of older branches: */ \ + __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ + __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ + __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ + __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ +# define GTEST_STDLIB_CXX11 1 +#endif + +// Only use C++11 library features if the library provides them. +#if GTEST_STDLIB_CXX11 +# define GTEST_HAS_STD_BEGIN_AND_END_ 1 +# define GTEST_HAS_STD_FORWARD_LIST_ 1 +# define GTEST_HAS_STD_FUNCTION_ 1 +# define GTEST_HAS_STD_INITIALIZER_LIST_ 1 +# define GTEST_HAS_STD_MOVE_ 1 +# define GTEST_HAS_STD_SHARED_PTR_ 1 +# define GTEST_HAS_STD_TYPE_TRAITS_ 1 +# define GTEST_HAS_STD_UNIQUE_PTR_ 1 +#endif + +// C++11 specifies that provides std::tuple. +// Some platforms still might not have it, however. +#if GTEST_LANG_CXX11 +# define GTEST_HAS_STD_TUPLE_ 1 +# if defined(__clang__) +// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include +# if defined(__has_include) && !__has_include() +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(_MSC_VER) +// Inspired by boost/config/stdlib/dinkumware.hpp +# if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(__GLIBCXX__) +// Inspired by boost/config/stdlib/libstdcpp3.hpp, +// http://gcc.gnu.org/gcc-4.2/changes.html and +// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x +# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) +# undef GTEST_HAS_STD_TUPLE_ +# endif +# endif +#endif + +// Brings in definitions for functions used in the testing::internal::posix +// namespace (read, write, close, chdir, isatty, stat). We do not currently +// use them on Windows Mobile. +#if GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS_MOBILE +# include +# include +# endif +// In order to avoid having to include , use forward declaration +// assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. +// This assumption is verified by +// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. +struct _RTL_CRITICAL_SECTION; +#else +// This assumes that non-Windows OSes provide unistd.h. For OSes where this +// is not the case, we need to include headers that provide the functions +// mentioned above. +# include +# include +#endif // GTEST_OS_WINDOWS + +#if GTEST_OS_LINUX_ANDROID +// Used to define __ANDROID_API__ matching the target NDK API level. +# include // NOLINT +#endif + +// Defines this to true iff Google Test can use POSIX regular expressions. +#ifndef GTEST_HAS_POSIX_RE +# if GTEST_OS_LINUX_ANDROID +// On Android, is only available starting with Gingerbread. +# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +# else +# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# endif +#endif + +#if GTEST_USES_PCRE +// The appropriate headers have already been included. + +#elif GTEST_HAS_POSIX_RE + +// On some platforms, needs someone to define size_t, and +// won't compile otherwise. We can #include it here as we already +// included , which is guaranteed to define size_t through +// . +# include // NOLINT + +# define GTEST_USES_POSIX_RE 1 + +#elif GTEST_OS_WINDOWS + +// is not available on Windows. Use our own simple regex +// implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#else + +// may not be available on this platform. Use our own +// simple regex implementation instead. +# define GTEST_USES_SIMPLE_RE 1 + +#endif // GTEST_USES_PCRE + +#ifndef GTEST_HAS_EXCEPTIONS +// The user didn't tell us whether exceptions are enabled, so we need +// to figure it out. +# if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS +// macro to enable exceptions, so we'll do the same. +// Assumes that exceptions are enabled by default. +# ifndef _HAS_EXCEPTIONS +# define _HAS_EXCEPTIONS 1 +# endif // _HAS_EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +# elif defined(__clang__) +// clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, +// but iff cleanups are enabled after that. In Obj-C++ files, there can be +// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions +// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ +// exceptions starting at clang r206352, but which checked for cleanups prior to +// that. To reliably check for C++ exception availability with clang, check for +// __EXCEPTIONS && __has_feature(cxx_exceptions). +# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) +# elif defined(__GNUC__) && __EXCEPTIONS +// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__SUNPRO_CC) +// Sun Pro CC supports exceptions. However, there is no compile-time way of +// detecting whether they are enabled or not. Therefore, we assume that +// they are enabled unless the user tells us otherwise. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__IBMCPP__) && __EXCEPTIONS +// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__HP_aCC) +// Exception handling is in effect by default in HP aCC compiler. It has to +// be turned of by +noeh compiler option if desired. +# define GTEST_HAS_EXCEPTIONS 1 +# else +// For other compilers, we assume exceptions are disabled to be +// conservative. +# define GTEST_HAS_EXCEPTIONS 0 +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#endif // GTEST_HAS_EXCEPTIONS + +#if !defined(GTEST_HAS_STD_STRING) +// Even though we don't use this macro any longer, we keep it in case +// some clients still depend on it. +# define GTEST_HAS_STD_STRING 1 +#elif !GTEST_HAS_STD_STRING +// The user told us that ::std::string isn't available. +# error "Google Test cannot be used where ::std::string isn't available." +#endif // !defined(GTEST_HAS_STD_STRING) + +#ifndef GTEST_HAS_GLOBAL_STRING +// The user didn't tell us whether ::string is available, so we need +// to figure it out. + +# define GTEST_HAS_GLOBAL_STRING 0 + +#endif // GTEST_HAS_GLOBAL_STRING + +#ifndef GTEST_HAS_STD_WSTRING +// The user didn't tell us whether ::std::wstring is available, so we need +// to figure it out. +// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring +// is available. + +// Cygwin 1.7 and below doesn't support ::std::wstring. +// Solaris' libc++ doesn't support it either. Android has +// no support for it at least as recent as Froyo (2.2). +# define GTEST_HAS_STD_WSTRING \ + (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) + +#endif // GTEST_HAS_STD_WSTRING + +#ifndef GTEST_HAS_GLOBAL_WSTRING +// The user didn't tell us whether ::wstring is available, so we need +// to figure it out. +# define GTEST_HAS_GLOBAL_WSTRING \ + (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Determines whether RTTI is available. +#ifndef GTEST_HAS_RTTI +// The user didn't tell us whether RTTI is enabled, so we need to +// figure it out. + +# ifdef _MSC_VER + +# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) + +# ifdef __GXX_RTTI +// When building against STLport with the Android NDK and with +// -frtti -fno-exceptions, the build fails at link time with undefined +// references to __cxa_bad_typeid. Note sure if STL or toolchain bug, +// so disable RTTI when detected. +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ + !defined(__EXCEPTIONS) +# define GTEST_HAS_RTTI 0 +# else +# define GTEST_HAS_RTTI 1 +# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +# else +# define GTEST_HAS_RTTI 0 +# endif // __GXX_RTTI + +// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends +// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the +// first version with C++ support. +# elif defined(__clang__) + +# define GTEST_HAS_RTTI __has_feature(cxx_rtti) + +// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if +// both the typeid and dynamic_cast features are present. +# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) + +# ifdef __RTTI_ALL__ +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif + +# else + +// For all other compilers, we assume RTTI is enabled. +# define GTEST_HAS_RTTI 1 + +# endif // _MSC_VER + +#endif // GTEST_HAS_RTTI + +// It's this header's responsibility to #include when RTTI +// is enabled. +#if GTEST_HAS_RTTI +# include +#endif + +// Determines whether Google Test can use the pthreads library. +#ifndef GTEST_HAS_PTHREAD +// The user didn't tell us explicitly, so we make reasonable assumptions about +// which platforms have pthreads support. +// +// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 +// to your compiler flags. +# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ + || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) +#endif // GTEST_HAS_PTHREAD + +#if GTEST_HAS_PTHREAD +// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is +// true. +# include // NOLINT + +// For timespec and nanosleep, used below. +# include // NOLINT +#endif + +// Determines if hash_map/hash_set are available. +// Only used for testing against those containers. +#if !defined(GTEST_HAS_HASH_MAP_) +# if _MSC_VER +# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. +# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. +# endif // _MSC_VER +#endif // !defined(GTEST_HAS_HASH_MAP_) + +// Determines whether Google Test can use tr1/tuple. You can define +// this macro to 0 to prevent Google Test from using tuple (any +// feature depending on tuple with be disabled in this mode). +#ifndef GTEST_HAS_TR1_TUPLE +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) +// STLport, provided with the Android NDK, has neither or . +# define GTEST_HAS_TR1_TUPLE 0 +# else +// The user didn't tell us not to do it, so we assume it's OK. +# define GTEST_HAS_TR1_TUPLE 1 +# endif +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether Google Test's own tr1 tuple implementation +// should be used. +#ifndef GTEST_USE_OWN_TR1_TUPLE +// The user didn't tell us, so we need to figure it out. + +// We use our own TR1 tuple if we aren't sure the user has an +// implementation of it already. At this time, libstdc++ 4.0.0+ and +// MSVC 2010 are the only mainstream standard libraries that come +// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler +// pretends to be GCC by defining __GNUC__ and friends, but cannot +// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 +// tuple in a 323 MB Feature Pack download, which we cannot assume the +// user has. QNX's QCC compiler is a modified GCC but it doesn't +// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, +// and it can be used with some compilers that define __GNUC__. +# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ + && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 +# define GTEST_ENV_HAS_TR1_TUPLE_ 1 +# endif + +// C++11 specifies that provides std::tuple. Use that if gtest is used +// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 +// can build with clang but need to use gcc4.2's libstdc++). +# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) +# define GTEST_ENV_HAS_STD_TUPLE_ 1 +# endif + +# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ +# define GTEST_USE_OWN_TR1_TUPLE 0 +# else +# define GTEST_USE_OWN_TR1_TUPLE 1 +# endif + +#endif // GTEST_USE_OWN_TR1_TUPLE + +// To avoid conditional compilation everywhere, we make it +// gtest-port.h's responsibility to #include the header implementing +// tuple. +#if GTEST_HAS_STD_TUPLE_ +# include // IWYU pragma: export +# define GTEST_TUPLE_NAMESPACE_ ::std +#endif // GTEST_HAS_STD_TUPLE_ + +// We include tr1::tuple even if std::tuple is available to define printers for +// them. +#if GTEST_HAS_TR1_TUPLE +# ifndef GTEST_TUPLE_NAMESPACE_ +# define GTEST_TUPLE_NAMESPACE_ ::std::tr1 +# endif // GTEST_TUPLE_NAMESPACE_ + +# if GTEST_USE_OWN_TR1_TUPLE +# include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT +# elif GTEST_ENV_HAS_STD_TUPLE_ +# include +// C++11 puts its tuple into the ::std namespace rather than +// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. +// This causes undefined behavior, but supported compilers react in +// the way we intend. +namespace std { +namespace tr1 { +using ::std::get; +using ::std::make_tuple; +using ::std::tuple; +using ::std::tuple_element; +using ::std::tuple_size; +} +} + +# elif GTEST_OS_SYMBIAN + +// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to +// use STLport's tuple implementation, which unfortunately doesn't +// work as the copy of STLport distributed with Symbian is incomplete. +// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to +// use its own tuple implementation. +# ifdef BOOST_HAS_TR1_TUPLE +# undef BOOST_HAS_TR1_TUPLE +# endif // BOOST_HAS_TR1_TUPLE + +// This prevents , which defines +// BOOST_HAS_TR1_TUPLE, from being #included by Boost's . +# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED +# include // IWYU pragma: export // NOLINT + +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +// GCC 4.0+ implements tr1/tuple in the header. This does +// not conform to the TR1 spec, which requires the header to be . + +# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 +// Until version 4.3.2, gcc has a bug that causes , +// which is #included by , to not compile when RTTI is +// disabled. _TR1_FUNCTIONAL is the header guard for +// . Hence the following #define is a hack to prevent +// from being included. +# define _TR1_FUNCTIONAL 1 +# include +# undef _TR1_FUNCTIONAL // Allows the user to #include + // if he chooses to. +# else +# include // NOLINT +# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 + +# else +// If the compiler is not GCC 4.0+, we assume the user is using a +// spec-conforming TR1 implementation. +# include // IWYU pragma: export // NOLINT +# endif // GTEST_USE_OWN_TR1_TUPLE + +#endif // GTEST_HAS_TR1_TUPLE + +// Determines whether clone(2) is supported. +// Usually it will only be available on Linux, excluding +// Linux on the Itanium architecture. +// Also see http://linux.die.net/man/2/clone. +#ifndef GTEST_HAS_CLONE +// The user didn't tell us, so we need to figure it out. + +# if GTEST_OS_LINUX && !defined(__ia64__) +# if GTEST_OS_LINUX_ANDROID +// On Android, clone() is only available on ARM starting with Gingerbread. +# if defined(__arm__) && __ANDROID_API__ >= 9 +# define GTEST_HAS_CLONE 1 +# else +# define GTEST_HAS_CLONE 0 +# endif +# else +# define GTEST_HAS_CLONE 1 +# endif +# else +# define GTEST_HAS_CLONE 0 +# endif // GTEST_OS_LINUX && !defined(__ia64__) + +#endif // GTEST_HAS_CLONE + +// Determines whether to support stream redirection. This is used to test +// output correctness and to implement death tests. +#ifndef GTEST_HAS_STREAM_REDIRECTION +// By default, we assume that stream redirection is supported on all +// platforms except known mobile ones. +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ + GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +# define GTEST_HAS_STREAM_REDIRECTION 0 +# else +# define GTEST_HAS_STREAM_REDIRECTION 1 +# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#endif // GTEST_HAS_STREAM_REDIRECTION + +// Determines whether to support death tests. +// Google Test does not support death tests for VC 7.1 and earlier as +// abort() in a VC 7.1 application compiled as GUI in debug config +// pops up a dialog window that cannot be suppressed programmatically. +#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ + (GTEST_OS_MAC && !GTEST_OS_IOS) || \ + (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ + GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ + GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) +# define GTEST_HAS_DEATH_TEST 1 +#endif + +// We don't support MSVC 7.1 with exceptions disabled now. Therefore +// all the compilers we care about are adequate for supporting +// value-parameterized tests. +#define GTEST_HAS_PARAM_TEST 1 + +// Determines whether to support type-driven tests. + +// Typed tests need and variadic macros, which GCC, VC++ 8.0, +// Sun Pro CC, IBM Visual Age, and HP aCC support. +#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ + defined(__IBMCPP__) || defined(__HP_aCC) +# define GTEST_HAS_TYPED_TEST 1 +# define GTEST_HAS_TYPED_TEST_P 1 +#endif + +// Determines whether to support Combine(). This only makes sense when +// value-parameterized tests are enabled. The implementation doesn't +// work on Sun Studio since it doesn't understand templated conversion +// operators. +#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) +# define GTEST_HAS_COMBINE 1 +#endif + +// Determines whether the system compiler uses UTF-16 for encoding wide strings. +#define GTEST_WIDE_STRING_USES_UTF16_ \ + (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) + +// Determines whether test results can be streamed to a socket. +#if GTEST_OS_LINUX +# define GTEST_CAN_STREAM_RESULTS_ 1 +#endif + +// Defines some utility macros. + +// The GNU compiler emits a warning if nested "if" statements are followed by +// an "else" statement and braces are not used to explicitly disambiguate the +// "else" binding. This leads to problems with code like: +// +// if (gate) +// ASSERT_*(condition) << "Some message"; +// +// The "switch (0) case 0:" idiom is used to suppress this. +#ifdef __INTEL_COMPILER +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +#else +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +#endif + +// Use this annotation at the end of a struct/class definition to +// prevent the compiler from optimizing away instances that are never +// used. This is useful when all interesting logic happens inside the +// c'tor and / or d'tor. Example: +// +// struct Foo { +// Foo() { ... } +// } GTEST_ATTRIBUTE_UNUSED_; +// +// Also use it after a variable or parameter declaration to tell the +// compiler the variable/parameter does not have to be used. +#if defined(__GNUC__) && !defined(COMPILER_ICC) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +#elif defined(__clang__) +# if __has_attribute(unused) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +# endif +#endif +#ifndef GTEST_ATTRIBUTE_UNUSED_ +# define GTEST_ATTRIBUTE_UNUSED_ +#endif + +// A macro to disallow operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_ASSIGN_(type)\ + void operator=(type const &) + +// A macro to disallow copy constructor and operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ + type(type const &);\ + GTEST_DISALLOW_ASSIGN_(type) + +// Tell the compiler to warn about unused return values for functions declared +// with this macro. The macro should be used on function declarations +// following the argument list: +// +// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; +#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) +# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +#else +# define GTEST_MUST_USE_RESULT_ +#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC + +// MS C++ compiler emits warning when a conditional expression is compile time +// constant. In some contexts this warning is false positive and needs to be +// suppressed. Use the following two macros in such cases: +// +// GTEST_INTENTIONAL_CONST_COND_PUSH_() +// while (true) { +// GTEST_INTENTIONAL_CONST_COND_POP_() +// } +# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) +# define GTEST_INTENTIONAL_CONST_COND_POP_() \ + GTEST_DISABLE_MSC_WARNINGS_POP_() + +// Determine whether the compiler supports Microsoft's Structured Exception +// Handling. This is supported by several Windows compilers but generally +// does not exist on any other system. +#ifndef GTEST_HAS_SEH +// The user didn't tell us, so we need to figure it out. + +# if defined(_MSC_VER) || defined(__BORLANDC__) +// These two compilers are known to support SEH. +# define GTEST_HAS_SEH 1 +# else +// Assume no SEH. +# define GTEST_HAS_SEH 0 +# endif + +#define GTEST_IS_THREADSAFE \ + (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ + || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ + || GTEST_HAS_PTHREAD) + +#endif // GTEST_HAS_SEH + +#ifdef _MSC_VER +# if GTEST_LINKED_AS_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllimport) +# elif GTEST_CREATE_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllexport) +# endif +#elif __GNUC__ >= 4 || defined(__clang__) +# define GTEST_API_ __attribute__((visibility ("default"))) +#endif // _MSC_VER + +#ifndef GTEST_API_ +# define GTEST_API_ +#endif + +#ifdef __GNUC__ +// Ask the compiler to never inline a given function. +# define GTEST_NO_INLINE_ __attribute__((noinline)) +#else +# define GTEST_NO_INLINE_ +#endif + +// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. +#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) +# define GTEST_HAS_CXXABI_H_ 1 +#else +# define GTEST_HAS_CXXABI_H_ 0 +#endif + +// A function level attribute to disable checking for use of uninitialized +// memory when built with MemorySanitizer. +#if defined(__clang__) +# if __has_feature(memory_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ + __attribute__((no_sanitize_memory)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +# endif // __has_feature(memory_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#endif // __clang__ + +// A function level attribute to disable AddressSanitizer instrumentation. +#if defined(__clang__) +# if __has_feature(address_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ + __attribute__((no_sanitize_address)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +# endif // __has_feature(address_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#endif // __clang__ + +// A function level attribute to disable ThreadSanitizer instrumentation. +#if defined(__clang__) +# if __has_feature(thread_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ + __attribute__((no_sanitize_thread)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +# endif // __has_feature(thread_sanitizer) +#else +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#endif // __clang__ + +namespace testing { + +class Message; + +#if defined(GTEST_TUPLE_NAMESPACE_) +// Import tuple and friends into the ::testing namespace. +// It is part of our interface, having them in ::testing allows us to change +// their types as needed. +using GTEST_TUPLE_NAMESPACE_::get; +using GTEST_TUPLE_NAMESPACE_::make_tuple; +using GTEST_TUPLE_NAMESPACE_::tuple; +using GTEST_TUPLE_NAMESPACE_::tuple_size; +using GTEST_TUPLE_NAMESPACE_::tuple_element; +#endif // defined(GTEST_TUPLE_NAMESPACE_) + +namespace internal { + +// A secret type that Google Test users don't know about. It has no +// definition on purpose. Therefore it's impossible to create a +// Secret object, which is what we want. +class Secret; + +// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time +// expression is true. For example, you could use it to verify the +// size of a static array: +// +// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, +// names_incorrect_size); +// +// or to make sure a struct is smaller than a certain size: +// +// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); +// +// The second argument to the macro is the name of the variable. If +// the expression is false, most compilers will issue a warning/error +// containing the name of the variable. + +#if GTEST_LANG_CXX11 +# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) +#else // !GTEST_LANG_CXX11 +template + struct CompileAssert { +}; + +# define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ + msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ +#endif // !GTEST_LANG_CXX11 + +// Implementation details of GTEST_COMPILE_ASSERT_: +// +// (In C++11, we simply use static_assert instead of the following) +// +// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 +// elements (and thus is invalid) when the expression is false. +// +// - The simpler definition +// +// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] +// +// does not work, as gcc supports variable-length arrays whose sizes +// are determined at run-time (this is gcc's extension and not part +// of the C++ standard). As a result, gcc fails to reject the +// following code with the simple definition: +// +// int foo; +// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is +// // not a compile-time constant. +// +// - By using the type CompileAssert<(bool(expr))>, we ensures that +// expr is a compile-time constant. (Template arguments must be +// determined at compile-time.) +// +// - The outter parentheses in CompileAssert<(bool(expr))> are necessary +// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written +// +// CompileAssert +// +// instead, these compilers will refuse to compile +// +// GTEST_COMPILE_ASSERT_(5 > 0, some_message); +// +// (They seem to think the ">" in "5 > 0" marks the end of the +// template argument list.) +// +// - The array size is (bool(expr) ? 1 : -1), instead of simply +// +// ((expr) ? 1 : -1). +// +// This is to avoid running into a bug in MS VC 7.1, which +// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. + +// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. +// +// This template is declared, but intentionally undefined. +template +struct StaticAssertTypeEqHelper; + +template +struct StaticAssertTypeEqHelper { + enum { value = true }; +}; + +// Evaluates to the number of elements in 'array'. +#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) + +#if GTEST_HAS_GLOBAL_STRING +typedef ::string string; +#else +typedef ::std::string string; +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_WSTRING +typedef ::wstring wstring; +#elif GTEST_HAS_STD_WSTRING +typedef ::std::wstring wstring; +#endif // GTEST_HAS_GLOBAL_WSTRING + +// A helper for suppressing warnings on constant condition. It just +// returns 'condition'. +GTEST_API_ bool IsTrue(bool condition); + +// Defines scoped_ptr. + +// This implementation of scoped_ptr is PARTIAL - it only contains +// enough stuff to satisfy Google Test's need. +template +class scoped_ptr { + public: + typedef T element_type; + + explicit scoped_ptr(T* p = NULL) : ptr_(p) {} + ~scoped_ptr() { reset(); } + + T& operator*() const { return *ptr_; } + T* operator->() const { return ptr_; } + T* get() const { return ptr_; } + + T* release() { + T* const ptr = ptr_; + ptr_ = NULL; + return ptr; + } + + void reset(T* p = NULL) { + if (p != ptr_) { + if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. + delete ptr_; + } + ptr_ = p; + } + } + + friend void swap(scoped_ptr& a, scoped_ptr& b) { + using std::swap; + swap(a.ptr_, b.ptr_); + } + + private: + T* ptr_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); +}; + +// Defines RE. + +// A simple C++ wrapper for . It uses the POSIX Extended +// Regular Expression syntax. +class GTEST_API_ RE { + public: + // A copy constructor is required by the Standard to initialize object + // references from r-values. + RE(const RE& other) { Init(other.pattern()); } + + // Constructs an RE from a string. + RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + + RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT + +#endif // GTEST_HAS_GLOBAL_STRING + + RE(const char* regex) { Init(regex); } // NOLINT + ~RE(); + + // Returns the string representation of the regex. + const char* pattern() const { return pattern_; } + + // FullMatch(str, re) returns true iff regular expression re matches + // the entire str. + // PartialMatch(str, re) returns true iff regular expression re + // matches a substring of str (including str itself). + // + // TODO(wan@google.com): make FullMatch() and PartialMatch() work + // when str contains NUL characters. + static bool FullMatch(const ::std::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::std::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#if GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const ::string& str, const RE& re) { + return FullMatch(str.c_str(), re); + } + static bool PartialMatch(const ::string& str, const RE& re) { + return PartialMatch(str.c_str(), re); + } + +#endif // GTEST_HAS_GLOBAL_STRING + + static bool FullMatch(const char* str, const RE& re); + static bool PartialMatch(const char* str, const RE& re); + + private: + void Init(const char* regex); + + // We use a const char* instead of an std::string, as Google Test used to be + // used where std::string is not available. TODO(wan@google.com): change to + // std::string. + const char* pattern_; + bool is_valid_; + +#if GTEST_USES_POSIX_RE + + regex_t full_regex_; // For FullMatch(). + regex_t partial_regex_; // For PartialMatch(). + +#else // GTEST_USES_SIMPLE_RE + + const char* full_pattern_; // For FullMatch(); + +#endif + + GTEST_DISALLOW_ASSIGN_(RE); +}; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, + int line); + +// Defines logging utilities: +// GTEST_LOG_(severity) - logs messages at the specified severity level. The +// message itself is streamed into the macro. +// LogToStderr() - directs all log messages to stderr. +// FlushInfoLog() - flushes informational log messages. + +enum GTestLogSeverity { + GTEST_INFO, + GTEST_WARNING, + GTEST_ERROR, + GTEST_FATAL +}; + +// Formats log entry severity, provides a stream object for streaming the +// log message, and terminates the message with a newline when going out of +// scope. +class GTEST_API_ GTestLog { + public: + GTestLog(GTestLogSeverity severity, const char* file, int line); + + // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. + ~GTestLog(); + + ::std::ostream& GetStream() { return ::std::cerr; } + + private: + const GTestLogSeverity severity_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); +}; + +#if !defined(GTEST_LOG_) + +# define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ + __FILE__, __LINE__).GetStream() + +inline void LogToStderr() {} +inline void FlushInfoLog() { fflush(NULL); } + +#endif // !defined(GTEST_LOG_) + +#if !defined(GTEST_CHECK_) +// INTERNAL IMPLEMENTATION - DO NOT USE. +// +// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition +// is not satisfied. +// Synopsys: +// GTEST_CHECK_(boolean_condition); +// or +// GTEST_CHECK_(boolean_condition) << "Additional message"; +// +// This checks the condition and if the condition is not satisfied +// it prints message about the condition violation, including the +// condition itself, plus additional message streamed into it, if any, +// and then it aborts the program. It aborts the program irrespective of +// whether it is built in the debug mode or not. +# define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " +#endif // !defined(GTEST_CHECK_) + +// An all-mode assert to verify that the given POSIX-style function +// call returns 0 (indicating success). Known limitation: this +// doesn't expand to a balanced 'if' statement, so enclose the macro +// in {} if you need to use it as the only statement in an 'if' +// branch. +#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ + << gtest_error + +#if GTEST_HAS_STD_MOVE_ +using std::move; +#else // GTEST_HAS_STD_MOVE_ +template +const T& move(const T& t) { + return t; +} +#endif // GTEST_HAS_STD_MOVE_ + +// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. +// +// Use ImplicitCast_ as a safe version of static_cast for upcasting in +// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a +// const Foo*). When you use ImplicitCast_, the compiler checks that +// the cast is safe. Such explicit ImplicitCast_s are necessary in +// surprisingly many situations where C++ demands an exact type match +// instead of an argument type convertable to a target type. +// +// The syntax for using ImplicitCast_ is the same as for static_cast: +// +// ImplicitCast_(expr) +// +// ImplicitCast_ would have been part of the C++ standard library, +// but the proposal was submitted too late. It will probably make +// its way into the language in the future. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., implicit_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template +inline To ImplicitCast_(To x) { return x; } + +// When you upcast (that is, cast a pointer from type Foo to type +// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts +// always succeed. When you downcast (that is, cast a pointer from +// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because +// how do you know the pointer is really of type SubclassOfFoo? It +// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, +// when you downcast, you should use this macro. In debug mode, we +// use dynamic_cast<> to double-check the downcast is legal (we die +// if it's not). In normal mode, we do the efficient static_cast<> +// instead. Thus, it's important to test in debug mode to make sure +// the cast is legal! +// This is the only place in the code we should use dynamic_cast<>. +// In particular, you SHOULDN'T be using dynamic_cast<> in order to +// do RTTI (eg code like this: +// if (dynamic_cast(foo)) HandleASubclass1Object(foo); +// if (dynamic_cast(foo)) HandleASubclass2Object(foo); +// You should design the code some other way not to need this. +// +// This relatively ugly name is intentional. It prevents clashes with +// similar functions users may have (e.g., down_cast). The internal +// namespace alone is not enough because the function can be found by ADL. +template // use like this: DownCast_(foo); +inline To DownCast_(From* f) { // so we only accept pointers + // Ensures that To is a sub-type of From *. This test is here only + // for compile-time type checking, and has no overhead in an + // optimized build at run-time, as it will be optimized away + // completely. + GTEST_INTENTIONAL_CONST_COND_PUSH_() + if (false) { + GTEST_INTENTIONAL_CONST_COND_POP_() + const To to = NULL; + ::testing::internal::ImplicitCast_(to); + } + +#if GTEST_HAS_RTTI + // RTTI: debug mode only! + GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); +#endif + return static_cast(f); +} + +// Downcasts the pointer of type Base to Derived. +// Derived must be a subclass of Base. The parameter MUST +// point to a class of type Derived, not any subclass of it. +// When RTTI is available, the function performs a runtime +// check to enforce this. +template +Derived* CheckedDowncastToActualType(Base* base) { +#if GTEST_HAS_RTTI + GTEST_CHECK_(typeid(*base) == typeid(Derived)); +#endif + +#if GTEST_HAS_DOWNCAST_ + return ::down_cast(base); +#elif GTEST_HAS_RTTI + return dynamic_cast(base); // NOLINT +#else + return static_cast(base); // Poor man's downcast. +#endif +} + +#if GTEST_HAS_STREAM_REDIRECTION + +// Defines the stderr capturer: +// CaptureStdout - starts capturing stdout. +// GetCapturedStdout - stops capturing stdout and returns the captured string. +// CaptureStderr - starts capturing stderr. +// GetCapturedStderr - stops capturing stderr and returns the captured string. +// +GTEST_API_ void CaptureStdout(); +GTEST_API_ std::string GetCapturedStdout(); +GTEST_API_ void CaptureStderr(); +GTEST_API_ std::string GetCapturedStderr(); + +#endif // GTEST_HAS_STREAM_REDIRECTION + +// Returns a path to temporary directory. +GTEST_API_ std::string TempDir(); + +// Returns the size (in bytes) of a file. +GTEST_API_ size_t GetFileSize(FILE* file); + +// Reads the entire content of a file as a string. +GTEST_API_ std::string ReadEntireFile(FILE* file); + +// All command line arguments. +GTEST_API_ const ::std::vector& GetArgvs(); + +#if GTEST_HAS_DEATH_TEST + +const ::std::vector& GetInjectableArgvs(); +void SetInjectableArgvs(const ::std::vector* + new_argvs); + + +#endif // GTEST_HAS_DEATH_TEST + +// Defines synchronization primitives. +#if GTEST_IS_THREADSAFE +# if GTEST_HAS_PTHREAD +// Sleeps for (roughly) n milliseconds. This function is only for testing +// Google Test's own constructs. Don't use it in user tests, either +// directly or indirectly. +inline void SleepMilliseconds(int n) { + const timespec time = { + 0, // 0 seconds. + n * 1000L * 1000L, // And n ms. + }; + nanosleep(&time, NULL); +} +# endif // GTEST_HAS_PTHREAD + +# if GTEST_HAS_NOTIFICATION_ +// Notification has already been imported into the namespace. +// Nothing to do here. + +# elif GTEST_HAS_PTHREAD +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class Notification { + public: + Notification() : notified_(false) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + } + ~Notification() { + pthread_mutex_destroy(&mutex_); + } + + // Notifies all threads created with this notification to start. Must + // be called from the controller thread. + void Notify() { + pthread_mutex_lock(&mutex_); + notified_ = true; + pthread_mutex_unlock(&mutex_); + } + + // Blocks until the controller thread notifies. Must be called from a test + // thread. + void WaitForNotification() { + for (;;) { + pthread_mutex_lock(&mutex_); + const bool notified = notified_; + pthread_mutex_unlock(&mutex_); + if (notified) + break; + SleepMilliseconds(10); + } + } + + private: + pthread_mutex_t mutex_; + bool notified_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; + +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + +GTEST_API_ void SleepMilliseconds(int n); + +// Provides leak-safe Windows kernel handle ownership. +// Used in death tests and in threading support. +class GTEST_API_ AutoHandle { + public: + // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to + // avoid including in this header file. Including is + // undesirable because it defines a lot of symbols and macros that tend to + // conflict with client code. This assumption is verified by + // WindowsTypesTest.HANDLEIsVoidStar. + typedef void* Handle; + AutoHandle(); + explicit AutoHandle(Handle handle); + + ~AutoHandle(); + + Handle Get() const; + void Reset(); + void Reset(Handle handle); + + private: + // Returns true iff the handle is a valid handle object that can be closed. + bool IsCloseable() const; + + Handle handle_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); +}; + +// Allows a controller thread to pause execution of newly created +// threads until notified. Instances of this class must be created +// and destroyed in the controller thread. +// +// This class is only for testing Google Test's own constructs. Do not +// use it in user tests, either directly or indirectly. +class GTEST_API_ Notification { + public: + Notification(); + void Notify(); + void WaitForNotification(); + + private: + AutoHandle event_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); +}; +# endif // GTEST_HAS_NOTIFICATION_ + +// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD +// defined, but we don't want to use MinGW's pthreads implementation, which +// has conformance problems with some versions of the POSIX standard. +# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW + +// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. +// Consequently, it cannot select a correct instantiation of ThreadWithParam +// in order to call its Run(). Introducing ThreadWithParamBase as a +// non-templated base class for ThreadWithParam allows us to bypass this +// problem. +class ThreadWithParamBase { + public: + virtual ~ThreadWithParamBase() {} + virtual void Run() = 0; +}; + +// pthread_create() accepts a pointer to a function type with the C linkage. +// According to the Standard (7.5/1), function types with different linkages +// are different even if they are otherwise identical. Some compilers (for +// example, SunStudio) treat them as different types. Since class methods +// cannot be defined with C-linkage we need to define a free C-function to +// pass into pthread_create(). +extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { + static_cast(thread)->Run(); + return NULL; +} + +// Helper class for testing Google Test's multi-threading constructs. +// To use it, write: +// +// void ThreadFunc(int param) { /* Do things with param */ } +// Notification thread_can_start; +// ... +// // The thread_can_start parameter is optional; you can supply NULL. +// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); +// thread_can_start.Notify(); +// +// These classes are only for testing Google Test's own constructs. Do +// not use them in user tests, either directly or indirectly. +template +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void UserThreadFunc(T); + + ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) + : func_(func), + param_(param), + thread_can_start_(thread_can_start), + finished_(false) { + ThreadWithParamBase* const base = this; + // The thread can be created only after all fields except thread_ + // have been initialized. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); + } + ~ThreadWithParam() { Join(); } + + void Join() { + if (!finished_) { + GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); + finished_ = true; + } + } + + virtual void Run() { + if (thread_can_start_ != NULL) + thread_can_start_->WaitForNotification(); + func_(param_); + } + + private: + UserThreadFunc* const func_; // User-supplied thread function. + const T param_; // User-supplied parameter to the thread function. + // When non-NULL, used to block execution until the controller thread + // notifies. + Notification* const thread_can_start_; + bool finished_; // true iff we know that the thread function has finished. + pthread_t thread_; // The native thread object. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; +# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || + // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ + +# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +// Mutex and ThreadLocal have already been imported into the namespace. +// Nothing to do here. + +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + +// Mutex implements mutex on Windows platforms. It is used in conjunction +// with class MutexLock: +// +// Mutex mutex; +// ... +// MutexLock lock(&mutex); // Acquires the mutex and releases it at the +// // end of the current scope. +// +// A static Mutex *must* be defined or declared using one of the following +// macros: +// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); +// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); +// +// (A non-static Mutex is defined/declared in the usual way). +class GTEST_API_ Mutex { + public: + enum MutexType { kStatic = 0, kDynamic = 1 }; + // We rely on kStaticMutex being 0 as it is to what the linker initializes + // type_ in static mutexes. critical_section_ will be initialized lazily + // in ThreadSafeLazyInit(). + enum StaticConstructorSelector { kStaticMutex = 0 }; + + // This constructor intentionally does nothing. It relies on type_ being + // statically initialized to 0 (effectively setting it to kStatic) and on + // ThreadSafeLazyInit() to lazily initialize the rest of the members. + explicit Mutex(StaticConstructorSelector /*dummy*/) {} + + Mutex(); + ~Mutex(); + + void Lock(); + + void Unlock(); + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld(); + + private: + // Initializes owner_thread_id_ and critical_section_ in static mutexes. + void ThreadSafeLazyInit(); + + // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, + // we assume that 0 is an invalid value for thread IDs. + unsigned int owner_thread_id_; + + // For static mutexes, we rely on these members being initialized to zeros + // by the linker. + MutexType type_; + long critical_section_init_phase_; // NOLINT + _RTL_CRITICAL_SECTION* critical_section_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) + +// We cannot name this class MutexLock because the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(Mutex* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + Mutex* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Base class for ValueHolder. Allows a caller to hold and delete a value +// without knowing its type. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Provides a way for a thread to send notifications to a ThreadLocal +// regardless of its parameter type. +class ThreadLocalBase { + public: + // Creates a new ValueHolder object holding a default value passed to + // this ThreadLocal's constructor and returns it. It is the caller's + // responsibility not to call this when the ThreadLocal instance already + // has a value on the current thread. + virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; + + protected: + ThreadLocalBase() {} + virtual ~ThreadLocalBase() {} + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); +}; + +// Maps a thread to a set of ThreadLocals that have values instantiated on that +// thread and notifies them when the thread exits. A ThreadLocal instance is +// expected to persist until all threads it has values on have terminated. +class GTEST_API_ ThreadLocalRegistry { + public: + // Registers thread_local_instance as having value on the current thread. + // Returns a value that can be used to identify the thread from other threads. + static ThreadLocalValueHolderBase* GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance); + + // Invoked when a ThreadLocal instance is destroyed. + static void OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance); +}; + +class GTEST_API_ ThreadWithParamBase { + public: + void Join(); + + protected: + class Runnable { + public: + virtual ~Runnable() {} + virtual void Run() = 0; + }; + + ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); + virtual ~ThreadWithParamBase(); + + private: + AutoHandle thread_; +}; + +// Helper class for testing Google Test's multi-threading constructs. +template +class ThreadWithParam : public ThreadWithParamBase { + public: + typedef void UserThreadFunc(T); + + ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) + : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { + } + virtual ~ThreadWithParam() {} + + private: + class RunnableImpl : public Runnable { + public: + RunnableImpl(UserThreadFunc* func, T param) + : func_(func), + param_(param) { + } + virtual ~RunnableImpl() {} + virtual void Run() { + func_(param_); + } + + private: + UserThreadFunc* const func_; + const T param_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); + }; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); +}; + +// Implements thread-local storage on Windows systems. +// +// // Thread 1 +// ThreadLocal tl(100); // 100 is the default value for each thread. +// +// // Thread 2 +// tl.set(150); // Changes the value for thread 2 only. +// EXPECT_EQ(150, tl.get()); +// +// // Thread 1 +// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. +// tl.set(200); +// EXPECT_EQ(200, tl.get()); +// +// The template type argument T must have a public copy constructor. +// In addition, the default ThreadLocal constructor requires T to have +// a public default constructor. +// +// The users of a TheadLocal instance have to make sure that all but one +// threads (including the main one) using that instance have exited before +// destroying it. Otherwise, the per-thread objects managed for them by the +// ThreadLocal instance are not guaranteed to be destroyed on all platforms. +// +// Google Test only uses global ThreadLocal objects. That means they +// will die after main() has returned. Therefore, no per-thread +// object managed by Google Test will be leaked as long as all threads +// using Google Test have exited when main() returns. +template +class ThreadLocal : public ThreadLocalBase { + public: + ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} + explicit ThreadLocal(const T& value) + : default_factory_(new InstanceValueHolderFactory(value)) {} + + ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of T. Can be deleted via its base class without the caller + // knowing the type of T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + ValueHolder() : value_() {} + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + + T* GetOrCreateValue() const { + return static_cast( + ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); + } + + virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { + return default_factory_->MakeNewHolder(); + } + + class ValueHolderFactory { + public: + ValueHolderFactory() {} + virtual ~ValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + }; + + class DefaultValueHolderFactory : public ValueHolderFactory { + public: + DefaultValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + }; + + class InstanceValueHolderFactory : public ValueHolderFactory { + public: + explicit InstanceValueHolderFactory(const T& value) : value_(value) {} + virtual ValueHolder* MakeNewHolder() const { + return new ValueHolder(value_); + } + + private: + const T value_; // The value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + }; + + scoped_ptr default_factory_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +# elif GTEST_HAS_PTHREAD + +// MutexBase and Mutex implement mutex on pthreads-based platforms. +class MutexBase { + public: + // Acquires this mutex. + void Lock() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); + owner_ = pthread_self(); + has_owner_ = true; + } + + // Releases this mutex. + void Unlock() { + // Since the lock is being released the owner_ field should no longer be + // considered valid. We don't protect writing to has_owner_ here, as it's + // the caller's responsibility to ensure that the current thread holds the + // mutex when this is called. + has_owner_ = false; + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); + } + + // Does nothing if the current thread holds the mutex. Otherwise, crashes + // with high probability. + void AssertHeld() const { + GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) + << "The current thread is not holding the mutex @" << this; + } + + // A static mutex may be used before main() is entered. It may even + // be used before the dynamic initialization stage. Therefore we + // must be able to initialize a static mutex object at link time. + // This means MutexBase has to be a POD and its member variables + // have to be public. + public: + pthread_mutex_t mutex_; // The underlying pthread mutex. + // has_owner_ indicates whether the owner_ field below contains a valid thread + // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All + // accesses to the owner_ field should be protected by a check of this field. + // An alternative might be to memset() owner_ to all zeros, but there's no + // guarantee that a zero'd pthread_t is necessarily invalid or even different + // from pthread_self(). + bool has_owner_; + pthread_t owner_; // The thread holding the mutex. +}; + +// Forward-declares a static mutex. +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex + +// Defines and statically (i.e. at link time) initializes a static mutex. +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } + +// The Mutex class can only be used for mutexes created at runtime. It +// shares its API with MutexBase otherwise. +class Mutex : public MutexBase { + public: + Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); + has_owner_ = false; + } + ~Mutex() { + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); +}; + +// We cannot name this class MutexLock because the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(MutexBase* mutex) + : mutex_(mutex) { mutex_->Lock(); } + + ~GTestMutexLock() { mutex_->Unlock(); } + + private: + MutexBase* const mutex_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); +}; + +typedef GTestMutexLock MutexLock; + +// Helpers for ThreadLocal. + +// pthread_key_create() requires DeleteThreadLocalValue() to have +// C-linkage. Therefore it cannot be templatized to access +// ThreadLocal. Hence the need for class +// ThreadLocalValueHolderBase. +class ThreadLocalValueHolderBase { + public: + virtual ~ThreadLocalValueHolderBase() {} +}; + +// Called by pthread to delete thread-local data stored by +// pthread_setspecific(). +extern "C" inline void DeleteThreadLocalValue(void* value_holder) { + delete static_cast(value_holder); +} + +// Implements thread-local storage on pthreads-based systems. +template +class ThreadLocal { + public: + ThreadLocal() + : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} + explicit ThreadLocal(const T& value) + : key_(CreateKey()), + default_factory_(new InstanceValueHolderFactory(value)) {} + + ~ThreadLocal() { + // Destroys the managed object for the current thread, if any. + DeleteThreadLocalValue(pthread_getspecific(key_)); + + // Releases resources associated with the key. This will *not* + // delete managed objects for other threads. + GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); + } + + T* pointer() { return GetOrCreateValue(); } + const T* pointer() const { return GetOrCreateValue(); } + const T& get() const { return *pointer(); } + void set(const T& value) { *pointer() = value; } + + private: + // Holds a value of type T. + class ValueHolder : public ThreadLocalValueHolderBase { + public: + ValueHolder() : value_() {} + explicit ValueHolder(const T& value) : value_(value) {} + + T* pointer() { return &value_; } + + private: + T value_; + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); + }; + + static pthread_key_t CreateKey() { + pthread_key_t key; + // When a thread exits, DeleteThreadLocalValue() will be called on + // the object managed for that thread. + GTEST_CHECK_POSIX_SUCCESS_( + pthread_key_create(&key, &DeleteThreadLocalValue)); + return key; + } + + T* GetOrCreateValue() const { + ThreadLocalValueHolderBase* const holder = + static_cast(pthread_getspecific(key_)); + if (holder != NULL) { + return CheckedDowncastToActualType(holder)->pointer(); + } + + ValueHolder* const new_holder = default_factory_->MakeNewHolder(); + ThreadLocalValueHolderBase* const holder_base = new_holder; + GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); + return new_holder->pointer(); + } + + class ValueHolderFactory { + public: + ValueHolderFactory() {} + virtual ~ValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const = 0; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); + }; + + class DefaultValueHolderFactory : public ValueHolderFactory { + public: + DefaultValueHolderFactory() {} + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); + }; + + class InstanceValueHolderFactory : public ValueHolderFactory { + public: + explicit InstanceValueHolderFactory(const T& value) : value_(value) {} + virtual ValueHolder* MakeNewHolder() const { + return new ValueHolder(value_); + } + + private: + const T value_; // The value for each thread. + + GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); + }; + + // A key pthreads uses for looking up per-thread values. + const pthread_key_t key_; + scoped_ptr default_factory_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); +}; + +# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ + +#else // GTEST_IS_THREADSAFE + +// A dummy implementation of synchronization primitives (mutex, lock, +// and thread-local variable). Necessary for compiling Google Test where +// mutex is not supported - using Google Test in multiple threads is not +// supported on such platforms. + +class Mutex { + public: + Mutex() {} + void Lock() {} + void Unlock() {} + void AssertHeld() const {} +}; + +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex + +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex + +// We cannot name this class MutexLock because the ctor declaration would +// conflict with a macro named MutexLock, which is defined on some +// platforms. That macro is used as a defensive measure to prevent against +// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than +// "MutexLock l(&mu)". Hence the typedef trick below. +class GTestMutexLock { + public: + explicit GTestMutexLock(Mutex*) {} // NOLINT +}; + +typedef GTestMutexLock MutexLock; + +template +class ThreadLocal { + public: + ThreadLocal() : value_() {} + explicit ThreadLocal(const T& value) : value_(value) {} + T* pointer() { return &value_; } + const T* pointer() const { return &value_; } + const T& get() const { return value_; } + void set(const T& value) { value_ = value; } + private: + T value_; +}; + +#endif // GTEST_IS_THREADSAFE + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +GTEST_API_ size_t GetThreadCount(); + +// Passing non-POD classes through ellipsis (...) crashes the ARM +// compiler and generates a warning in Sun Studio. The Nokia Symbian +// and the IBM XL C/C++ compiler try to instantiate a copy constructor +// for objects passed through ellipsis (...), failing for uncopyable +// objects. We define this to ensure that only POD is passed through +// ellipsis on these systems. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) +// We lose support for NULL detection where the compiler doesn't like +// passing non-POD classes through ellipsis (...). +# define GTEST_ELLIPSIS_NEEDS_POD_ 1 +#else +# define GTEST_CAN_COMPARE_NULL 1 +#endif + +// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between +// const T& and const T* in a function template. These compilers +// _can_ decide between class template specializations for T and T*, +// so a tr1::type_traits-like is_pointer works. +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) +# define GTEST_NEEDS_IS_POINTER_ 1 +#endif + +template +struct bool_constant { + typedef bool_constant type; + static const bool value = bool_value; +}; +template const bool bool_constant::value; + +typedef bool_constant false_type; +typedef bool_constant true_type; + +template +struct is_pointer : public false_type {}; + +template +struct is_pointer : public true_type {}; + +template +struct IteratorTraits { + typedef typename Iterator::value_type value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +template +struct IteratorTraits { + typedef T value_type; +}; + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_SEP_ "\\" +# define GTEST_HAS_ALT_PATH_SEP_ 1 +// The biggest signed integer type the compiler supports. +typedef __int64 BiggestInt; +#else +# define GTEST_PATH_SEP_ "/" +# define GTEST_HAS_ALT_PATH_SEP_ 0 +typedef long long BiggestInt; // NOLINT +#endif // GTEST_OS_WINDOWS + +// Utilities for char. + +// isspace(int ch) and friends accept an unsigned char or EOF. char +// may be signed, depending on the compiler (or compiler flags). +// Therefore we need to cast a char to unsigned char before calling +// isspace(), etc. + +inline bool IsAlpha(char ch) { + return isalpha(static_cast(ch)) != 0; +} +inline bool IsAlNum(char ch) { + return isalnum(static_cast(ch)) != 0; +} +inline bool IsDigit(char ch) { + return isdigit(static_cast(ch)) != 0; +} +inline bool IsLower(char ch) { + return islower(static_cast(ch)) != 0; +} +inline bool IsSpace(char ch) { + return isspace(static_cast(ch)) != 0; +} +inline bool IsUpper(char ch) { + return isupper(static_cast(ch)) != 0; +} +inline bool IsXDigit(char ch) { + return isxdigit(static_cast(ch)) != 0; +} +inline bool IsXDigit(wchar_t ch) { + const unsigned char low_byte = static_cast(ch); + return ch == low_byte && isxdigit(low_byte) != 0; +} + +inline char ToLower(char ch) { + return static_cast(tolower(static_cast(ch))); +} +inline char ToUpper(char ch) { + return static_cast(toupper(static_cast(ch))); +} + +inline std::string StripTrailingSpaces(std::string str) { + std::string::iterator it = str.end(); + while (it != str.begin() && IsSpace(*--it)) + it = str.erase(it); + return str; +} + +// The testing::internal::posix namespace holds wrappers for common +// POSIX functions. These wrappers hide the differences between +// Windows/MSVC and POSIX systems. Since some compilers define these +// standard functions as macros, the wrapper cannot have the same name +// as the wrapped function. + +namespace posix { + +// Functions with a different name on Windows. + +#if GTEST_OS_WINDOWS + +typedef struct _stat StatStruct; + +# ifdef __BORLANDC__ +inline int IsATTY(int fd) { return isatty(fd); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +# else // !__BORLANDC__ +# if GTEST_OS_WINDOWS_MOBILE +inline int IsATTY(int /* fd */) { return 0; } +# else +inline int IsATTY(int fd) { return _isatty(fd); } +# endif // GTEST_OS_WINDOWS_MOBILE +inline int StrCaseCmp(const char* s1, const char* s2) { + return _stricmp(s1, s2); +} +inline char* StrDup(const char* src) { return _strdup(src); } +# endif // __BORLANDC__ + +# if GTEST_OS_WINDOWS_MOBILE +inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } +// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this +// time and thus not defined there. +# else +inline int FileNo(FILE* file) { return _fileno(file); } +inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } +inline int RmDir(const char* dir) { return _rmdir(dir); } +inline bool IsDir(const StatStruct& st) { + return (_S_IFDIR & st.st_mode) != 0; +} +# endif // GTEST_OS_WINDOWS_MOBILE + +#else + +typedef struct stat StatStruct; + +inline int FileNo(FILE* file) { return fileno(file); } +inline int IsATTY(int fd) { return isatty(fd); } +inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } +inline int StrCaseCmp(const char* s1, const char* s2) { + return strcasecmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +inline int RmDir(const char* dir) { return rmdir(dir); } +inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } + +#endif // GTEST_OS_WINDOWS + +// Functions deprecated by MSVC 8.0. + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) + +inline const char* StrNCpy(char* dest, const char* src, size_t n) { + return strncpy(dest, src, n); +} + +// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and +// StrError() aren't needed on Windows CE at this time and thus not +// defined there. + +#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +inline int ChDir(const char* dir) { return chdir(dir); } +#endif +inline FILE* FOpen(const char* path, const char* mode) { + return fopen(path, mode); +} +#if !GTEST_OS_WINDOWS_MOBILE +inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { + return freopen(path, mode, stream); +} +inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } +#endif +inline int FClose(FILE* fp) { return fclose(fp); } +#if !GTEST_OS_WINDOWS_MOBILE +inline int Read(int fd, void* buf, unsigned int count) { + return static_cast(read(fd, buf, count)); +} +inline int Write(int fd, const void* buf, unsigned int count) { + return static_cast(write(fd, buf, count)); +} +inline int Close(int fd) { return close(fd); } +inline const char* StrError(int errnum) { return strerror(errnum); } +#endif +inline const char* GetEnv(const char* name) { +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT + // We are on Windows CE, which has no environment variables. + static_cast(name); // To prevent 'unused argument' warning. + return NULL; +#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) + // Environment variables which we programmatically clear will be set to the + // empty string rather than unset (NULL). Handle that case. + const char* const env = getenv(name); + return (env != NULL && env[0] != '\0') ? env : NULL; +#else + return getenv(name); +#endif +} + +GTEST_DISABLE_MSC_WARNINGS_POP_() + +#if GTEST_OS_WINDOWS_MOBILE +// Windows CE has no C library. The abort() function is used in +// several places in Google Test. This implementation provides a reasonable +// imitation of standard behaviour. +void Abort(); +#else +inline void Abort() { abort(); } +#endif // GTEST_OS_WINDOWS_MOBILE + +} // namespace posix + +// MSVC "deprecates" snprintf and issues warnings wherever it is used. In +// order to avoid these warnings, we need to use _snprintf or _snprintf_s on +// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate +// function in order to achieve that. We use macro definition here because +// snprintf is a variadic function. +#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE +// MSVC 2005 and above support variadic macros. +# define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#elif defined(_MSC_VER) +// Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't +// complain about _snprintf. +# define GTEST_SNPRINTF_ _snprintf +#else +# define GTEST_SNPRINTF_ snprintf +#endif + +// The maximum number a BiggestInt can represent. This definition +// works no matter BiggestInt is represented in one's complement or +// two's complement. +// +// We cannot rely on numeric_limits in STL, as __int64 and long long +// are not part of standard C++ and numeric_limits doesn't need to be +// defined for them. +const BiggestInt kMaxBiggestInt = + ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); + +// This template class serves as a compile-time function from size to +// type. It maps a size in bytes to a primitive type with that +// size. e.g. +// +// TypeWithSize<4>::UInt +// +// is typedef-ed to be unsigned int (unsigned integer made up of 4 +// bytes). +// +// Such functionality should belong to STL, but I cannot find it +// there. +// +// Google Test uses this class in the implementation of floating-point +// comparison. +// +// For now it only handles UInt (unsigned int) as that's all Google Test +// needs. Other types can be easily added in the future if need +// arises. +template +class TypeWithSize { + public: + // This prevents the user from using TypeWithSize with incorrect + // values of N. + typedef void UInt; +}; + +// The specialization for size 4. +template <> +class TypeWithSize<4> { + public: + // unsigned int has size 4 in both gcc and MSVC. + // + // As base/basictypes.h doesn't compile on Windows, we cannot use + // uint32, uint64, and etc here. + typedef int Int; + typedef unsigned int UInt; +}; + +// The specialization for size 8. +template <> +class TypeWithSize<8> { + public: +#if GTEST_OS_WINDOWS + typedef __int64 Int; + typedef unsigned __int64 UInt; +#else + typedef long long Int; // NOLINT + typedef unsigned long long UInt; // NOLINT +#endif // GTEST_OS_WINDOWS +}; + +// Integer types of known sizes. +typedef TypeWithSize<4>::Int Int32; +typedef TypeWithSize<4>::UInt UInt32; +typedef TypeWithSize<8>::Int Int64; +typedef TypeWithSize<8>::UInt UInt64; +typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. + +// Utilities for command line flags and environment variables. + +// Macro for referencing flags. +#if !defined(GTEST_FLAG) +# define GTEST_FLAG(name) FLAGS_gtest_##name +#endif // !defined(GTEST_FLAG) + +#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) +# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 +#endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) + +#if !defined(GTEST_DECLARE_bool_) +# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver + +// Macros for declaring flags. +# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) +# define GTEST_DECLARE_int32_(name) \ + GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) +#define GTEST_DECLARE_string_(name) \ + GTEST_API_ extern ::std::string GTEST_FLAG(name) + +// Macros for defining flags. +#define GTEST_DEFINE_bool_(name, default_val, doc) \ + GTEST_API_ bool GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_int32_(name, default_val, doc) \ + GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_string_(name, default_val, doc) \ + GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) + +#endif // !defined(GTEST_DECLARE_bool_) + +// Thread annotations +#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) +# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +# define GTEST_LOCK_EXCLUDED_(locks) +#endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) + +// Parses 'str' for a 32-bit signed integer. If successful, writes the result +// to *value and returns true; otherwise leaves *value unchanged and returns +// false. +// TODO(chandlerc): Find a better way to refactor flag and environment parsing +// out of both gtest-port.cc and gtest.cc to avoid exporting this utility +// function. +bool ParseInt32(const Message& src_text, const char* str, Int32* value); + +// Parses a bool/Int32/string from the environment variable +// corresponding to the given Google Test flag. +bool BoolFromGTestEnv(const char* flag, bool default_val); +GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); +std::string StringFromGTestEnv(const char* flag, const char* default_val); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-string.h b/gtestsrc/gtest/include/gtest/internal/gtest-string.h new file mode 100644 index 0000000..97f1a7f --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-string.h @@ -0,0 +1,167 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) +// +// The Google C++ Testing Framework (Google Test) +// +// This header file declares the String class and functions used internally by +// Google Test. They are subject to change without notice. They should not used +// by code external to Google Test. +// +// This header file is #included by . +// It should not be #included by other files. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ + +#ifdef __BORLANDC__ +// string.h is not guaranteed to provide strcpy on C++ Builder. +# include +#endif + +#include +#include + +#include "gtest/internal/gtest-port.h" + +namespace testing { +namespace internal { + +// String - an abstract class holding static string utilities. +class GTEST_API_ String { + public: + // Static utility methods + + // Clones a 0-terminated C string, allocating memory using new. The + // caller is responsible for deleting the return value using + // delete[]. Returns the cloned string, or NULL if the input is + // NULL. + // + // This is different from strdup() in string.h, which allocates + // memory using malloc(). + static const char* CloneCString(const char* c_str); + +#if GTEST_OS_WINDOWS_MOBILE + // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be + // able to pass strings to Win32 APIs on CE we need to convert them + // to 'Unicode', UTF-16. + + // Creates a UTF-16 wide string from the given ANSI string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the wide string, or NULL if the + // input is NULL. + // + // The wide string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static LPCWSTR AnsiToUtf16(const char* c_str); + + // Creates an ANSI string from the given wide string, allocating + // memory using new. The caller is responsible for deleting the return + // value using delete[]. Returns the ANSI string, or NULL if the + // input is NULL. + // + // The returned string is created using the ANSI codepage (CP_ACP) to + // match the behaviour of the ANSI versions of Win32 calls and the + // C runtime. + static const char* Utf16ToAnsi(LPCWSTR utf16_str); +#endif + + // Compares two C strings. Returns true iff they have the same content. + // + // Unlike strcmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CStringEquals(const char* lhs, const char* rhs); + + // Converts a wide C string to a String using the UTF-8 encoding. + // NULL will be converted to "(null)". If an error occurred during + // the conversion, "(failed to convert from wide string)" is + // returned. + static std::string ShowWideCString(const wchar_t* wide_c_str); + + // Compares two wide C strings. Returns true iff they have the same + // content. + // + // Unlike wcscmp(), this function can handle NULL argument(s). A + // NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); + + // Compares two C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike strcasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL C string, + // including the empty string. + static bool CaseInsensitiveCStringEquals(const char* lhs, + const char* rhs); + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. + static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs); + + // Returns true iff the given string ends with the given suffix, ignoring + // case. Any string is considered to end with an empty suffix. + static bool EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix); + + // Formats an int value as "%02d". + static std::string FormatIntWidth2(int value); // "%02d" for width == 2 + + // Formats an int value as "%X". + static std::string FormatHexInt(int value); + + // Formats a byte as "%02X". + static std::string FormatByte(unsigned char value); + + private: + String(); // Not meant to be instantiated. +}; // class String + +// Gets the content of the stringstream's buffer as an std::string. Each '\0' +// character in the buffer is replaced with "\\0". +GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h b/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h new file mode 100644 index 0000000..e9b4053 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h @@ -0,0 +1,1020 @@ +// This file was GENERATED by command: +// pump.py gtest-tuple.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2009 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements a subset of TR1 tuple needed by Google Test and Google Mock. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ + +#include // For ::std::pair. + +// The compiler used in Symbian has a bug that prevents us from declaring the +// tuple template as a friend (it complains that tuple is redefined). This +// hack bypasses the bug by declaring the members that should otherwise be +// private as public. +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +#else +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template friend class tuple; \ + private: +#endif + +// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict +// with our own definitions. Therefore using our own tuple does not work on +// those compilers. +#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ +# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ +GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." +#endif + +// GTEST_n_TUPLE_(T) is the type of an n-tuple. +#define GTEST_0_TUPLE_(T) tuple<> +#define GTEST_1_TUPLE_(T) tuple +#define GTEST_2_TUPLE_(T) tuple +#define GTEST_3_TUPLE_(T) tuple +#define GTEST_4_TUPLE_(T) tuple +#define GTEST_5_TUPLE_(T) tuple +#define GTEST_6_TUPLE_(T) tuple +#define GTEST_7_TUPLE_(T) tuple +#define GTEST_8_TUPLE_(T) tuple +#define GTEST_9_TUPLE_(T) tuple +#define GTEST_10_TUPLE_(T) tuple + +// GTEST_n_TYPENAMES_(T) declares a list of n typenames. +#define GTEST_0_TYPENAMES_(T) +#define GTEST_1_TYPENAMES_(T) typename T##0 +#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 +#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 +#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3 +#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4 +#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5 +#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6 +#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 +#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8 +#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ + typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8, typename T##9 + +// In theory, defining stuff in the ::std namespace is undefined +// behavior. We can do this as we are playing the role of a standard +// library vendor. +namespace std { +namespace tr1 { + +template +class tuple; + +// Anything in namespace gtest_internal is Google Test's INTERNAL +// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. +namespace gtest_internal { + +// ByRef::type is T if T is a reference; otherwise it's const T&. +template +struct ByRef { typedef const T& type; }; // NOLINT +template +struct ByRef { typedef T& type; }; // NOLINT + +// A handy wrapper for ByRef. +#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type + +// AddRef::type is T if T is a reference; otherwise it's T&. This +// is the same as tr1::add_reference::type. +template +struct AddRef { typedef T& type; }; // NOLINT +template +struct AddRef { typedef T& type; }; // NOLINT + +// A handy wrapper for AddRef. +#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type + +// A helper for implementing get(). +template class Get; + +// A helper for implementing tuple_element. kIndexValid is true +// iff k < the number of fields in tuple type T. +template +struct TupleElement; + +template +struct TupleElement { + typedef T0 type; +}; + +template +struct TupleElement { + typedef T1 type; +}; + +template +struct TupleElement { + typedef T2 type; +}; + +template +struct TupleElement { + typedef T3 type; +}; + +template +struct TupleElement { + typedef T4 type; +}; + +template +struct TupleElement { + typedef T5 type; +}; + +template +struct TupleElement { + typedef T6 type; +}; + +template +struct TupleElement { + typedef T7 type; +}; + +template +struct TupleElement { + typedef T8 type; +}; + +template +struct TupleElement { + typedef T9 type; +}; + +} // namespace gtest_internal + +template <> +class tuple<> { + public: + tuple() {} + tuple(const tuple& /* t */) {} + tuple& operator=(const tuple& /* t */) { return *this; } +}; + +template +class GTEST_1_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} + + tuple(const tuple& t) : f0_(t.f0_) {} + + template + tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_1_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { + f0_ = t.f0_; + return *this; + } + + T0 f0_; +}; + +template +class GTEST_2_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), + f1_(f1) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} + + template + tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} + template + tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_2_TUPLE_(U)& t) { + return CopyFrom(t); + } + template + tuple& operator=(const ::std::pair& p) { + f0_ = p.first; + f1_ = p.second; + return *this; + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + return *this; + } + + T0 f0_; + T1 f1_; +}; + +template +class GTEST_3_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + template + tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_3_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; +}; + +template +class GTEST_4_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} + + template + tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_4_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; +}; + +template +class GTEST_5_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_) {} + + template + tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_5_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; +}; + +template +class GTEST_6_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_) {} + + template + tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_6_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; +}; + +template +class GTEST_7_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + template + tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_7_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; +}; + +template +class GTEST_8_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, + GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + template + tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_8_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; +}; + +template +class GTEST_9_TUPLE_(T) { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), + f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + template + tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_9_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; +}; + +template +class tuple { + public: + template friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), + f9_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, + GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, + GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), + f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} + + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), + f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} + + template + tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), + f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), + f9_(t.f9_) {} + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_10_TUPLE_(U)& t) { + return CopyFrom(t); + } + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { + f0_ = t.f0_; + f1_ = t.f1_; + f2_ = t.f2_; + f3_ = t.f3_; + f4_ = t.f4_; + f5_ = t.f5_; + f6_ = t.f6_; + f7_ = t.f7_; + f8_ = t.f8_; + f9_ = t.f9_; + return *this; + } + + T0 f0_; + T1 f1_; + T2 f2_; + T3 f3_; + T4 f4_; + T5 f5_; + T6 f6_; + T7 f7_; + T8 f8_; + T9 f9_; +}; + +// 6.1.3.2 Tuple creation functions. + +// Known limitations: we don't support passing an +// std::tr1::reference_wrapper to make_tuple(). And we don't +// implement tie(). + +inline tuple<> make_tuple() { return tuple<>(); } + +template +inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { + return GTEST_1_TUPLE_(T)(f0); +} + +template +inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { + return GTEST_2_TUPLE_(T)(f0, f1); +} + +template +inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { + return GTEST_3_TUPLE_(T)(f0, f1, f2); +} + +template +inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3) { + return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); +} + +template +inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4) { + return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); +} + +template +inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5) { + return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); +} + +template +inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6) { + return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); +} + +template +inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { + return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); +} + +template +inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8) { + return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); +} + +template +inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, + const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, + const T8& f8, const T9& f9) { + return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); +} + +// 6.1.3.3 Tuple helper classes. + +template struct tuple_size; + +template +struct tuple_size { + static const int value = 0; +}; + +template +struct tuple_size { + static const int value = 1; +}; + +template +struct tuple_size { + static const int value = 2; +}; + +template +struct tuple_size { + static const int value = 3; +}; + +template +struct tuple_size { + static const int value = 4; +}; + +template +struct tuple_size { + static const int value = 5; +}; + +template +struct tuple_size { + static const int value = 6; +}; + +template +struct tuple_size { + static const int value = 7; +}; + +template +struct tuple_size { + static const int value = 8; +}; + +template +struct tuple_size { + static const int value = 9; +}; + +template +struct tuple_size { + static const int value = 10; +}; + +template +struct tuple_element { + typedef typename gtest_internal::TupleElement< + k < (tuple_size::value), k, Tuple>::type type; +}; + +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type + +// 6.1.3.4 Element access. + +namespace gtest_internal { + +template <> +class Get<0> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + Field(Tuple& t) { return t.f0_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) + ConstField(const Tuple& t) { return t.f0_; } +}; + +template <> +class Get<1> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + Field(Tuple& t) { return t.f1_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) + ConstField(const Tuple& t) { return t.f1_; } +}; + +template <> +class Get<2> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + Field(Tuple& t) { return t.f2_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) + ConstField(const Tuple& t) { return t.f2_; } +}; + +template <> +class Get<3> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + Field(Tuple& t) { return t.f3_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) + ConstField(const Tuple& t) { return t.f3_; } +}; + +template <> +class Get<4> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + Field(Tuple& t) { return t.f4_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) + ConstField(const Tuple& t) { return t.f4_; } +}; + +template <> +class Get<5> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + Field(Tuple& t) { return t.f5_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) + ConstField(const Tuple& t) { return t.f5_; } +}; + +template <> +class Get<6> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + Field(Tuple& t) { return t.f6_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) + ConstField(const Tuple& t) { return t.f6_; } +}; + +template <> +class Get<7> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + Field(Tuple& t) { return t.f7_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) + ConstField(const Tuple& t) { return t.f7_; } +}; + +template <> +class Get<8> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + Field(Tuple& t) { return t.f8_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) + ConstField(const Tuple& t) { return t.f8_; } +}; + +template <> +class Get<9> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + Field(Tuple& t) { return t.f9_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) + ConstField(const Tuple& t) { return t.f9_; } +}; + +} // namespace gtest_internal + +template +GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::Field(t); +} + +template +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(const GTEST_10_TUPLE_(T)& t) { + return gtest_internal::Get::ConstField(t); +} + +// 6.1.3.5 Relational operators + +// We only implement == and !=, as we don't have a need for the rest yet. + +namespace gtest_internal { + +// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the +// first k fields of t1 equals the first k fields of t2. +// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if +// k1 != k2. +template +struct SameSizeTuplePrefixComparator; + +template <> +struct SameSizeTuplePrefixComparator<0, 0> { + template + static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { + return true; + } +}; + +template +struct SameSizeTuplePrefixComparator { + template + static bool Eq(const Tuple1& t1, const Tuple2& t2) { + return SameSizeTuplePrefixComparator::Eq(t1, t2) && + ::std::tr1::get(t1) == ::std::tr1::get(t2); + } +}; + +} // namespace gtest_internal + +template +inline bool operator==(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { + return gtest_internal::SameSizeTuplePrefixComparator< + tuple_size::value, + tuple_size::value>::Eq(t, u); +} + +template +inline bool operator!=(const GTEST_10_TUPLE_(T)& t, + const GTEST_10_TUPLE_(U)& u) { return !(t == u); } + +// 6.1.4 Pairs. +// Unimplemented. + +} // namespace tr1 +} // namespace std + +#undef GTEST_0_TUPLE_ +#undef GTEST_1_TUPLE_ +#undef GTEST_2_TUPLE_ +#undef GTEST_3_TUPLE_ +#undef GTEST_4_TUPLE_ +#undef GTEST_5_TUPLE_ +#undef GTEST_6_TUPLE_ +#undef GTEST_7_TUPLE_ +#undef GTEST_8_TUPLE_ +#undef GTEST_9_TUPLE_ +#undef GTEST_10_TUPLE_ + +#undef GTEST_0_TYPENAMES_ +#undef GTEST_1_TYPENAMES_ +#undef GTEST_2_TYPENAMES_ +#undef GTEST_3_TYPENAMES_ +#undef GTEST_4_TYPENAMES_ +#undef GTEST_5_TYPENAMES_ +#undef GTEST_6_TYPENAMES_ +#undef GTEST_7_TYPENAMES_ +#undef GTEST_8_TYPENAMES_ +#undef GTEST_9_TYPENAMES_ +#undef GTEST_10_TYPENAMES_ + +#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ +#undef GTEST_BY_REF_ +#undef GTEST_ADD_REF_ +#undef GTEST_TUPLE_ELEMENT_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h.pump b/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h.pump new file mode 100644 index 0000000..429ddfe --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-tuple.h.pump @@ -0,0 +1,347 @@ +$$ -*- mode: c++; -*- +$var n = 10 $$ Maximum number of tuple fields we want to support. +$$ This meta comment fixes auto-indentation in Emacs. }} +// Copyright 2009 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Implements a subset of TR1 tuple needed by Google Test and Google Mock. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ + +#include // For ::std::pair. + +// The compiler used in Symbian has a bug that prevents us from declaring the +// tuple template as a friend (it complains that tuple is redefined). This +// hack bypasses the bug by declaring the members that should otherwise be +// private as public. +// Sun Studio versions < 12 also have the above bug. +#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +#else +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template friend class tuple; \ + private: +#endif + +// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict +// with our own definitions. Therefore using our own tuple does not work on +// those compilers. +#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ +# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ +GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." +#endif + + +$range i 0..n-1 +$range j 0..n +$range k 1..n +// GTEST_n_TUPLE_(T) is the type of an n-tuple. +#define GTEST_0_TUPLE_(T) tuple<> + +$for k [[ +$range m 0..k-1 +$range m2 k..n-1 +#define GTEST_$(k)_TUPLE_(T) tuple<$for m, [[T##$m]]$for m2 [[, void]]> + +]] + +// GTEST_n_TYPENAMES_(T) declares a list of n typenames. + +$for j [[ +$range m 0..j-1 +#define GTEST_$(j)_TYPENAMES_(T) $for m, [[typename T##$m]] + + +]] + +// In theory, defining stuff in the ::std namespace is undefined +// behavior. We can do this as we are playing the role of a standard +// library vendor. +namespace std { +namespace tr1 { + +template <$for i, [[typename T$i = void]]> +class tuple; + +// Anything in namespace gtest_internal is Google Test's INTERNAL +// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. +namespace gtest_internal { + +// ByRef::type is T if T is a reference; otherwise it's const T&. +template +struct ByRef { typedef const T& type; }; // NOLINT +template +struct ByRef { typedef T& type; }; // NOLINT + +// A handy wrapper for ByRef. +#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type + +// AddRef::type is T if T is a reference; otherwise it's T&. This +// is the same as tr1::add_reference::type. +template +struct AddRef { typedef T& type; }; // NOLINT +template +struct AddRef { typedef T& type; }; // NOLINT + +// A handy wrapper for AddRef. +#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type + +// A helper for implementing get(). +template class Get; + +// A helper for implementing tuple_element. kIndexValid is true +// iff k < the number of fields in tuple type T. +template +struct TupleElement; + + +$for i [[ +template +struct TupleElement { + typedef T$i type; +}; + + +]] +} // namespace gtest_internal + +template <> +class tuple<> { + public: + tuple() {} + tuple(const tuple& /* t */) {} + tuple& operator=(const tuple& /* t */) { return *this; } +}; + + +$for k [[ +$range m 0..k-1 +template +class $if k < n [[GTEST_$(k)_TUPLE_(T)]] $else [[tuple]] { + public: + template friend class gtest_internal::Get; + + tuple() : $for m, [[f$(m)_()]] {} + + explicit tuple($for m, [[GTEST_BY_REF_(T$m) f$m]]) : [[]] +$for m, [[f$(m)_(f$m)]] {} + + tuple(const tuple& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} + + template + tuple(const GTEST_$(k)_TUPLE_(U)& t) : $for m, [[f$(m)_(t.f$(m)_)]] {} + +$if k == 2 [[ + template + tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} + +]] + + tuple& operator=(const tuple& t) { return CopyFrom(t); } + + template + tuple& operator=(const GTEST_$(k)_TUPLE_(U)& t) { + return CopyFrom(t); + } + +$if k == 2 [[ + template + tuple& operator=(const ::std::pair& p) { + f0_ = p.first; + f1_ = p.second; + return *this; + } + +]] + + GTEST_DECLARE_TUPLE_AS_FRIEND_ + + template + tuple& CopyFrom(const GTEST_$(k)_TUPLE_(U)& t) { + +$for m [[ + f$(m)_ = t.f$(m)_; + +]] + return *this; + } + + +$for m [[ + T$m f$(m)_; + +]] +}; + + +]] +// 6.1.3.2 Tuple creation functions. + +// Known limitations: we don't support passing an +// std::tr1::reference_wrapper to make_tuple(). And we don't +// implement tie(). + +inline tuple<> make_tuple() { return tuple<>(); } + +$for k [[ +$range m 0..k-1 + +template +inline GTEST_$(k)_TUPLE_(T) make_tuple($for m, [[const T$m& f$m]]) { + return GTEST_$(k)_TUPLE_(T)($for m, [[f$m]]); +} + +]] + +// 6.1.3.3 Tuple helper classes. + +template struct tuple_size; + + +$for j [[ +template +struct tuple_size { + static const int value = $j; +}; + + +]] +template +struct tuple_element { + typedef typename gtest_internal::TupleElement< + k < (tuple_size::value), k, Tuple>::type type; +}; + +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type + +// 6.1.3.4 Element access. + +namespace gtest_internal { + + +$for i [[ +template <> +class Get<$i> { + public: + template + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) + Field(Tuple& t) { return t.f$(i)_; } // NOLINT + + template + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_($i, Tuple)) + ConstField(const Tuple& t) { return t.f$(i)_; } +}; + + +]] +} // namespace gtest_internal + +template +GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) +get(GTEST_$(n)_TUPLE_(T)& t) { + return gtest_internal::Get::Field(t); +} + +template +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_$(n)_TUPLE_(T))) +get(const GTEST_$(n)_TUPLE_(T)& t) { + return gtest_internal::Get::ConstField(t); +} + +// 6.1.3.5 Relational operators + +// We only implement == and !=, as we don't have a need for the rest yet. + +namespace gtest_internal { + +// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the +// first k fields of t1 equals the first k fields of t2. +// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if +// k1 != k2. +template +struct SameSizeTuplePrefixComparator; + +template <> +struct SameSizeTuplePrefixComparator<0, 0> { + template + static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { + return true; + } +}; + +template +struct SameSizeTuplePrefixComparator { + template + static bool Eq(const Tuple1& t1, const Tuple2& t2) { + return SameSizeTuplePrefixComparator::Eq(t1, t2) && + ::std::tr1::get(t1) == ::std::tr1::get(t2); + } +}; + +} // namespace gtest_internal + +template +inline bool operator==(const GTEST_$(n)_TUPLE_(T)& t, + const GTEST_$(n)_TUPLE_(U)& u) { + return gtest_internal::SameSizeTuplePrefixComparator< + tuple_size::value, + tuple_size::value>::Eq(t, u); +} + +template +inline bool operator!=(const GTEST_$(n)_TUPLE_(T)& t, + const GTEST_$(n)_TUPLE_(U)& u) { return !(t == u); } + +// 6.1.4 Pairs. +// Unimplemented. + +} // namespace tr1 +} // namespace std + + +$for j [[ +#undef GTEST_$(j)_TUPLE_ + +]] + + +$for j [[ +#undef GTEST_$(j)_TYPENAMES_ + +]] + +#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ +#undef GTEST_BY_REF_ +#undef GTEST_ADD_REF_ +#undef GTEST_TUPLE_ELEMENT_ + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h b/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h new file mode 100644 index 0000000..e46f7cf --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h @@ -0,0 +1,3331 @@ +// This file was GENERATED by command: +// pump.py gtest-type-util.h.pump +// DO NOT EDIT BY HAND!!! + +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Type utilities needed for implementing typed and type-parameterized +// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently we support at most 50 types in a list, and at most 50 +// type-parameterized tests in one type-parameterized test case. +// Please contact googletestframework@googlegroups.com if you need +// more. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + +#include "gtest/internal/gtest-port.h" + +// #ifdef __GNUC__ is too general here. It is possible to use gcc without using +// libstdc++ (which is where cxxabi.h comes from). +# if GTEST_HAS_CXXABI_H_ +# include +# elif defined(__HP_aCC) +# include +# endif // GTEST_HASH_CXXABI_H_ + +namespace testing { +namespace internal { + +// GetTypeName() returns a human-readable name of type T. +// NB: This function is also used in Google Mock, so don't move it inside of +// the typed-test-only section below. +template +std::string GetTypeName() { +# if GTEST_HAS_RTTI + + const char* const name = typeid(T).name(); +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) + int status = 0; + // gcc's implementation of typeid(T).name() mangles the type name, + // so we have to demangle it. +# if GTEST_HAS_CXXABI_H_ + using abi::__cxa_demangle; +# endif // GTEST_HAS_CXXABI_H_ + char* const readable_name = __cxa_demangle(name, 0, 0, &status); + const std::string name_str(status == 0 ? readable_name : name); + free(readable_name); + return name_str; +# else + return name; +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC + +# else + + return ""; + +# endif // GTEST_HAS_RTTI +} + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// AssertyTypeEq::type is defined iff T1 and T2 are the same +// type. This can be used as a compile-time assertion to ensure that +// two types are equal. + +template +struct AssertTypeEq; + +template +struct AssertTypeEq { + typedef bool type; +}; + +// A unique type used as the default value for the arguments of class +// template Types. This allows us to simulate variadic templates +// (e.g. Types, Type, and etc), which C++ doesn't +// support directly. +struct None {}; + +// The following family of struct and struct templates are used to +// represent type lists. In particular, TypesN +// represents a type list with N types (T1, T2, ..., and TN) in it. +// Except for Types0, every struct in the family has two member types: +// Head for the first type in the list, and Tail for the rest of the +// list. + +// The empty type list. +struct Types0 {}; + +// Type lists of length 1, 2, 3, and so on. + +template +struct Types1 { + typedef T1 Head; + typedef Types0 Tail; +}; +template +struct Types2 { + typedef T1 Head; + typedef Types1 Tail; +}; + +template +struct Types3 { + typedef T1 Head; + typedef Types2 Tail; +}; + +template +struct Types4 { + typedef T1 Head; + typedef Types3 Tail; +}; + +template +struct Types5 { + typedef T1 Head; + typedef Types4 Tail; +}; + +template +struct Types6 { + typedef T1 Head; + typedef Types5 Tail; +}; + +template +struct Types7 { + typedef T1 Head; + typedef Types6 Tail; +}; + +template +struct Types8 { + typedef T1 Head; + typedef Types7 Tail; +}; + +template +struct Types9 { + typedef T1 Head; + typedef Types8 Tail; +}; + +template +struct Types10 { + typedef T1 Head; + typedef Types9 Tail; +}; + +template +struct Types11 { + typedef T1 Head; + typedef Types10 Tail; +}; + +template +struct Types12 { + typedef T1 Head; + typedef Types11 Tail; +}; + +template +struct Types13 { + typedef T1 Head; + typedef Types12 Tail; +}; + +template +struct Types14 { + typedef T1 Head; + typedef Types13 Tail; +}; + +template +struct Types15 { + typedef T1 Head; + typedef Types14 Tail; +}; + +template +struct Types16 { + typedef T1 Head; + typedef Types15 Tail; +}; + +template +struct Types17 { + typedef T1 Head; + typedef Types16 Tail; +}; + +template +struct Types18 { + typedef T1 Head; + typedef Types17 Tail; +}; + +template +struct Types19 { + typedef T1 Head; + typedef Types18 Tail; +}; + +template +struct Types20 { + typedef T1 Head; + typedef Types19 Tail; +}; + +template +struct Types21 { + typedef T1 Head; + typedef Types20 Tail; +}; + +template +struct Types22 { + typedef T1 Head; + typedef Types21 Tail; +}; + +template +struct Types23 { + typedef T1 Head; + typedef Types22 Tail; +}; + +template +struct Types24 { + typedef T1 Head; + typedef Types23 Tail; +}; + +template +struct Types25 { + typedef T1 Head; + typedef Types24 Tail; +}; + +template +struct Types26 { + typedef T1 Head; + typedef Types25 Tail; +}; + +template +struct Types27 { + typedef T1 Head; + typedef Types26 Tail; +}; + +template +struct Types28 { + typedef T1 Head; + typedef Types27 Tail; +}; + +template +struct Types29 { + typedef T1 Head; + typedef Types28 Tail; +}; + +template +struct Types30 { + typedef T1 Head; + typedef Types29 Tail; +}; + +template +struct Types31 { + typedef T1 Head; + typedef Types30 Tail; +}; + +template +struct Types32 { + typedef T1 Head; + typedef Types31 Tail; +}; + +template +struct Types33 { + typedef T1 Head; + typedef Types32 Tail; +}; + +template +struct Types34 { + typedef T1 Head; + typedef Types33 Tail; +}; + +template +struct Types35 { + typedef T1 Head; + typedef Types34 Tail; +}; + +template +struct Types36 { + typedef T1 Head; + typedef Types35 Tail; +}; + +template +struct Types37 { + typedef T1 Head; + typedef Types36 Tail; +}; + +template +struct Types38 { + typedef T1 Head; + typedef Types37 Tail; +}; + +template +struct Types39 { + typedef T1 Head; + typedef Types38 Tail; +}; + +template +struct Types40 { + typedef T1 Head; + typedef Types39 Tail; +}; + +template +struct Types41 { + typedef T1 Head; + typedef Types40 Tail; +}; + +template +struct Types42 { + typedef T1 Head; + typedef Types41 Tail; +}; + +template +struct Types43 { + typedef T1 Head; + typedef Types42 Tail; +}; + +template +struct Types44 { + typedef T1 Head; + typedef Types43 Tail; +}; + +template +struct Types45 { + typedef T1 Head; + typedef Types44 Tail; +}; + +template +struct Types46 { + typedef T1 Head; + typedef Types45 Tail; +}; + +template +struct Types47 { + typedef T1 Head; + typedef Types46 Tail; +}; + +template +struct Types48 { + typedef T1 Head; + typedef Types47 Tail; +}; + +template +struct Types49 { + typedef T1 Head; + typedef Types48 Tail; +}; + +template +struct Types50 { + typedef T1 Head; + typedef Types49 Tail; +}; + + +} // namespace internal + +// We don't want to require the users to write TypesN<...> directly, +// as that would require them to count the length. Types<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Types +// will appear as Types in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Types, and Google Test will translate +// that to TypesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Types template. +template +struct Types { + typedef internal::Types50 type; +}; + +template <> +struct Types { + typedef internal::Types0 type; +}; +template +struct Types { + typedef internal::Types1 type; +}; +template +struct Types { + typedef internal::Types2 type; +}; +template +struct Types { + typedef internal::Types3 type; +}; +template +struct Types { + typedef internal::Types4 type; +}; +template +struct Types { + typedef internal::Types5 type; +}; +template +struct Types { + typedef internal::Types6 type; +}; +template +struct Types { + typedef internal::Types7 type; +}; +template +struct Types { + typedef internal::Types8 type; +}; +template +struct Types { + typedef internal::Types9 type; +}; +template +struct Types { + typedef internal::Types10 type; +}; +template +struct Types { + typedef internal::Types11 type; +}; +template +struct Types { + typedef internal::Types12 type; +}; +template +struct Types { + typedef internal::Types13 type; +}; +template +struct Types { + typedef internal::Types14 type; +}; +template +struct Types { + typedef internal::Types15 type; +}; +template +struct Types { + typedef internal::Types16 type; +}; +template +struct Types { + typedef internal::Types17 type; +}; +template +struct Types { + typedef internal::Types18 type; +}; +template +struct Types { + typedef internal::Types19 type; +}; +template +struct Types { + typedef internal::Types20 type; +}; +template +struct Types { + typedef internal::Types21 type; +}; +template +struct Types { + typedef internal::Types22 type; +}; +template +struct Types { + typedef internal::Types23 type; +}; +template +struct Types { + typedef internal::Types24 type; +}; +template +struct Types { + typedef internal::Types25 type; +}; +template +struct Types { + typedef internal::Types26 type; +}; +template +struct Types { + typedef internal::Types27 type; +}; +template +struct Types { + typedef internal::Types28 type; +}; +template +struct Types { + typedef internal::Types29 type; +}; +template +struct Types { + typedef internal::Types30 type; +}; +template +struct Types { + typedef internal::Types31 type; +}; +template +struct Types { + typedef internal::Types32 type; +}; +template +struct Types { + typedef internal::Types33 type; +}; +template +struct Types { + typedef internal::Types34 type; +}; +template +struct Types { + typedef internal::Types35 type; +}; +template +struct Types { + typedef internal::Types36 type; +}; +template +struct Types { + typedef internal::Types37 type; +}; +template +struct Types { + typedef internal::Types38 type; +}; +template +struct Types { + typedef internal::Types39 type; +}; +template +struct Types { + typedef internal::Types40 type; +}; +template +struct Types { + typedef internal::Types41 type; +}; +template +struct Types { + typedef internal::Types42 type; +}; +template +struct Types { + typedef internal::Types43 type; +}; +template +struct Types { + typedef internal::Types44 type; +}; +template +struct Types { + typedef internal::Types45 type; +}; +template +struct Types { + typedef internal::Types46 type; +}; +template +struct Types { + typedef internal::Types47 type; +}; +template +struct Types { + typedef internal::Types48 type; +}; +template +struct Types { + typedef internal::Types49 type; +}; + +namespace internal { + +# define GTEST_TEMPLATE_ template class + +// The template "selector" struct TemplateSel is used to +// represent Tmpl, which must be a class template with one type +// parameter, as a type. TemplateSel::Bind::type is defined +// as the type Tmpl. This allows us to actually instantiate the +// template "selected" by TemplateSel. +// +// This trick is necessary for simulating typedef for class templates, +// which C++ doesn't support directly. +template +struct TemplateSel { + template + struct Bind { + typedef Tmpl type; + }; +}; + +# define GTEST_BIND_(TmplSel, T) \ + TmplSel::template Bind::type + +// A unique struct template used as the default value for the +// arguments of class template Templates. This allows us to simulate +// variadic templates (e.g. Templates, Templates, +// and etc), which C++ doesn't support directly. +template +struct NoneT {}; + +// The following family of struct and struct templates are used to +// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except +// for Templates0, every struct in the family has two member types: +// Head for the selector of the first template in the list, and Tail +// for the rest of the list. + +// The empty template list. +struct Templates0 {}; + +// Template lists of length 1, 2, 3, and so on. + +template +struct Templates1 { + typedef TemplateSel Head; + typedef Templates0 Tail; +}; +template +struct Templates2 { + typedef TemplateSel Head; + typedef Templates1 Tail; +}; + +template +struct Templates3 { + typedef TemplateSel Head; + typedef Templates2 Tail; +}; + +template +struct Templates4 { + typedef TemplateSel Head; + typedef Templates3 Tail; +}; + +template +struct Templates5 { + typedef TemplateSel Head; + typedef Templates4 Tail; +}; + +template +struct Templates6 { + typedef TemplateSel Head; + typedef Templates5 Tail; +}; + +template +struct Templates7 { + typedef TemplateSel Head; + typedef Templates6 Tail; +}; + +template +struct Templates8 { + typedef TemplateSel Head; + typedef Templates7 Tail; +}; + +template +struct Templates9 { + typedef TemplateSel Head; + typedef Templates8 Tail; +}; + +template +struct Templates10 { + typedef TemplateSel Head; + typedef Templates9 Tail; +}; + +template +struct Templates11 { + typedef TemplateSel Head; + typedef Templates10 Tail; +}; + +template +struct Templates12 { + typedef TemplateSel Head; + typedef Templates11 Tail; +}; + +template +struct Templates13 { + typedef TemplateSel Head; + typedef Templates12 Tail; +}; + +template +struct Templates14 { + typedef TemplateSel Head; + typedef Templates13 Tail; +}; + +template +struct Templates15 { + typedef TemplateSel Head; + typedef Templates14 Tail; +}; + +template +struct Templates16 { + typedef TemplateSel Head; + typedef Templates15 Tail; +}; + +template +struct Templates17 { + typedef TemplateSel Head; + typedef Templates16 Tail; +}; + +template +struct Templates18 { + typedef TemplateSel Head; + typedef Templates17 Tail; +}; + +template +struct Templates19 { + typedef TemplateSel Head; + typedef Templates18 Tail; +}; + +template +struct Templates20 { + typedef TemplateSel Head; + typedef Templates19 Tail; +}; + +template +struct Templates21 { + typedef TemplateSel Head; + typedef Templates20 Tail; +}; + +template +struct Templates22 { + typedef TemplateSel Head; + typedef Templates21 Tail; +}; + +template +struct Templates23 { + typedef TemplateSel Head; + typedef Templates22 Tail; +}; + +template +struct Templates24 { + typedef TemplateSel Head; + typedef Templates23 Tail; +}; + +template +struct Templates25 { + typedef TemplateSel Head; + typedef Templates24 Tail; +}; + +template +struct Templates26 { + typedef TemplateSel Head; + typedef Templates25 Tail; +}; + +template +struct Templates27 { + typedef TemplateSel Head; + typedef Templates26 Tail; +}; + +template +struct Templates28 { + typedef TemplateSel Head; + typedef Templates27 Tail; +}; + +template +struct Templates29 { + typedef TemplateSel Head; + typedef Templates28 Tail; +}; + +template +struct Templates30 { + typedef TemplateSel Head; + typedef Templates29 Tail; +}; + +template +struct Templates31 { + typedef TemplateSel Head; + typedef Templates30 Tail; +}; + +template +struct Templates32 { + typedef TemplateSel Head; + typedef Templates31 Tail; +}; + +template +struct Templates33 { + typedef TemplateSel Head; + typedef Templates32 Tail; +}; + +template +struct Templates34 { + typedef TemplateSel Head; + typedef Templates33 Tail; +}; + +template +struct Templates35 { + typedef TemplateSel Head; + typedef Templates34 Tail; +}; + +template +struct Templates36 { + typedef TemplateSel Head; + typedef Templates35 Tail; +}; + +template +struct Templates37 { + typedef TemplateSel Head; + typedef Templates36 Tail; +}; + +template +struct Templates38 { + typedef TemplateSel Head; + typedef Templates37 Tail; +}; + +template +struct Templates39 { + typedef TemplateSel Head; + typedef Templates38 Tail; +}; + +template +struct Templates40 { + typedef TemplateSel Head; + typedef Templates39 Tail; +}; + +template +struct Templates41 { + typedef TemplateSel Head; + typedef Templates40 Tail; +}; + +template +struct Templates42 { + typedef TemplateSel Head; + typedef Templates41 Tail; +}; + +template +struct Templates43 { + typedef TemplateSel Head; + typedef Templates42 Tail; +}; + +template +struct Templates44 { + typedef TemplateSel Head; + typedef Templates43 Tail; +}; + +template +struct Templates45 { + typedef TemplateSel Head; + typedef Templates44 Tail; +}; + +template +struct Templates46 { + typedef TemplateSel Head; + typedef Templates45 Tail; +}; + +template +struct Templates47 { + typedef TemplateSel Head; + typedef Templates46 Tail; +}; + +template +struct Templates48 { + typedef TemplateSel Head; + typedef Templates47 Tail; +}; + +template +struct Templates49 { + typedef TemplateSel Head; + typedef Templates48 Tail; +}; + +template +struct Templates50 { + typedef TemplateSel Head; + typedef Templates49 Tail; +}; + + +// We don't want to require the users to write TemplatesN<...> directly, +// as that would require them to count the length. Templates<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Templates +// will appear as Templates in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Templates, and Google Test will translate +// that to TemplatesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Templates template. +template +struct Templates { + typedef Templates50 type; +}; + +template <> +struct Templates { + typedef Templates0 type; +}; +template +struct Templates { + typedef Templates1 type; +}; +template +struct Templates { + typedef Templates2 type; +}; +template +struct Templates { + typedef Templates3 type; +}; +template +struct Templates { + typedef Templates4 type; +}; +template +struct Templates { + typedef Templates5 type; +}; +template +struct Templates { + typedef Templates6 type; +}; +template +struct Templates { + typedef Templates7 type; +}; +template +struct Templates { + typedef Templates8 type; +}; +template +struct Templates { + typedef Templates9 type; +}; +template +struct Templates { + typedef Templates10 type; +}; +template +struct Templates { + typedef Templates11 type; +}; +template +struct Templates { + typedef Templates12 type; +}; +template +struct Templates { + typedef Templates13 type; +}; +template +struct Templates { + typedef Templates14 type; +}; +template +struct Templates { + typedef Templates15 type; +}; +template +struct Templates { + typedef Templates16 type; +}; +template +struct Templates { + typedef Templates17 type; +}; +template +struct Templates { + typedef Templates18 type; +}; +template +struct Templates { + typedef Templates19 type; +}; +template +struct Templates { + typedef Templates20 type; +}; +template +struct Templates { + typedef Templates21 type; +}; +template +struct Templates { + typedef Templates22 type; +}; +template +struct Templates { + typedef Templates23 type; +}; +template +struct Templates { + typedef Templates24 type; +}; +template +struct Templates { + typedef Templates25 type; +}; +template +struct Templates { + typedef Templates26 type; +}; +template +struct Templates { + typedef Templates27 type; +}; +template +struct Templates { + typedef Templates28 type; +}; +template +struct Templates { + typedef Templates29 type; +}; +template +struct Templates { + typedef Templates30 type; +}; +template +struct Templates { + typedef Templates31 type; +}; +template +struct Templates { + typedef Templates32 type; +}; +template +struct Templates { + typedef Templates33 type; +}; +template +struct Templates { + typedef Templates34 type; +}; +template +struct Templates { + typedef Templates35 type; +}; +template +struct Templates { + typedef Templates36 type; +}; +template +struct Templates { + typedef Templates37 type; +}; +template +struct Templates { + typedef Templates38 type; +}; +template +struct Templates { + typedef Templates39 type; +}; +template +struct Templates { + typedef Templates40 type; +}; +template +struct Templates { + typedef Templates41 type; +}; +template +struct Templates { + typedef Templates42 type; +}; +template +struct Templates { + typedef Templates43 type; +}; +template +struct Templates { + typedef Templates44 type; +}; +template +struct Templates { + typedef Templates45 type; +}; +template +struct Templates { + typedef Templates46 type; +}; +template +struct Templates { + typedef Templates47 type; +}; +template +struct Templates { + typedef Templates48 type; +}; +template +struct Templates { + typedef Templates49 type; +}; + +// The TypeList template makes it possible to use either a single type +// or a Types<...> list in TYPED_TEST_CASE() and +// INSTANTIATE_TYPED_TEST_CASE_P(). + +template +struct TypeList { + typedef Types1 type; +}; + +template +struct TypeList > { + typedef typename Types::type type; +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h.pump b/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h.pump new file mode 100644 index 0000000..251fdf0 --- /dev/null +++ b/gtestsrc/gtest/include/gtest/internal/gtest-type-util.h.pump @@ -0,0 +1,297 @@ +$$ -*- mode: c++; -*- +$var n = 50 $$ Maximum length of type lists we want to support. +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Type utilities needed for implementing typed and type-parameterized +// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// +// Currently we support at most $n types in a list, and at most $n +// type-parameterized tests in one type-parameterized test case. +// Please contact googletestframework@googlegroups.com if you need +// more. + +#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ +#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ + +#include "gtest/internal/gtest-port.h" + +// #ifdef __GNUC__ is too general here. It is possible to use gcc without using +// libstdc++ (which is where cxxabi.h comes from). +# if GTEST_HAS_CXXABI_H_ +# include +# elif defined(__HP_aCC) +# include +# endif // GTEST_HASH_CXXABI_H_ + +namespace testing { +namespace internal { + +// GetTypeName() returns a human-readable name of type T. +// NB: This function is also used in Google Mock, so don't move it inside of +// the typed-test-only section below. +template +std::string GetTypeName() { +# if GTEST_HAS_RTTI + + const char* const name = typeid(T).name(); +# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) + int status = 0; + // gcc's implementation of typeid(T).name() mangles the type name, + // so we have to demangle it. +# if GTEST_HAS_CXXABI_H_ + using abi::__cxa_demangle; +# endif // GTEST_HAS_CXXABI_H_ + char* const readable_name = __cxa_demangle(name, 0, 0, &status); + const std::string name_str(status == 0 ? readable_name : name); + free(readable_name); + return name_str; +# else + return name; +# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC + +# else + + return ""; + +# endif // GTEST_HAS_RTTI +} + +#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +// AssertyTypeEq::type is defined iff T1 and T2 are the same +// type. This can be used as a compile-time assertion to ensure that +// two types are equal. + +template +struct AssertTypeEq; + +template +struct AssertTypeEq { + typedef bool type; +}; + +// A unique type used as the default value for the arguments of class +// template Types. This allows us to simulate variadic templates +// (e.g. Types, Type, and etc), which C++ doesn't +// support directly. +struct None {}; + +// The following family of struct and struct templates are used to +// represent type lists. In particular, TypesN +// represents a type list with N types (T1, T2, ..., and TN) in it. +// Except for Types0, every struct in the family has two member types: +// Head for the first type in the list, and Tail for the rest of the +// list. + +// The empty type list. +struct Types0 {}; + +// Type lists of length 1, 2, 3, and so on. + +template +struct Types1 { + typedef T1 Head; + typedef Types0 Tail; +}; + +$range i 2..n + +$for i [[ +$range j 1..i +$range k 2..i +template <$for j, [[typename T$j]]> +struct Types$i { + typedef T1 Head; + typedef Types$(i-1)<$for k, [[T$k]]> Tail; +}; + + +]] + +} // namespace internal + +// We don't want to require the users to write TypesN<...> directly, +// as that would require them to count the length. Types<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Types +// will appear as Types in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Types, and Google Test will translate +// that to TypesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Types template. + +$range i 1..n +template <$for i, [[typename T$i = internal::None]]> +struct Types { + typedef internal::Types$n<$for i, [[T$i]]> type; +}; + +template <> +struct Types<$for i, [[internal::None]]> { + typedef internal::Types0 type; +}; + +$range i 1..n-1 +$for i [[ +$range j 1..i +$range k i+1..n +template <$for j, [[typename T$j]]> +struct Types<$for j, [[T$j]]$for k[[, internal::None]]> { + typedef internal::Types$i<$for j, [[T$j]]> type; +}; + +]] + +namespace internal { + +# define GTEST_TEMPLATE_ template class + +// The template "selector" struct TemplateSel is used to +// represent Tmpl, which must be a class template with one type +// parameter, as a type. TemplateSel::Bind::type is defined +// as the type Tmpl. This allows us to actually instantiate the +// template "selected" by TemplateSel. +// +// This trick is necessary for simulating typedef for class templates, +// which C++ doesn't support directly. +template +struct TemplateSel { + template + struct Bind { + typedef Tmpl type; + }; +}; + +# define GTEST_BIND_(TmplSel, T) \ + TmplSel::template Bind::type + +// A unique struct template used as the default value for the +// arguments of class template Templates. This allows us to simulate +// variadic templates (e.g. Templates, Templates, +// and etc), which C++ doesn't support directly. +template +struct NoneT {}; + +// The following family of struct and struct templates are used to +// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except +// for Templates0, every struct in the family has two member types: +// Head for the selector of the first template in the list, and Tail +// for the rest of the list. + +// The empty template list. +struct Templates0 {}; + +// Template lists of length 1, 2, 3, and so on. + +template +struct Templates1 { + typedef TemplateSel Head; + typedef Templates0 Tail; +}; + +$range i 2..n + +$for i [[ +$range j 1..i +$range k 2..i +template <$for j, [[GTEST_TEMPLATE_ T$j]]> +struct Templates$i { + typedef TemplateSel Head; + typedef Templates$(i-1)<$for k, [[T$k]]> Tail; +}; + + +]] + +// We don't want to require the users to write TemplatesN<...> directly, +// as that would require them to count the length. Templates<...> is much +// easier to write, but generates horrible messages when there is a +// compiler error, as gcc insists on printing out each template +// argument, even if it has the default value (this means Templates +// will appear as Templates in the compiler +// errors). +// +// Our solution is to combine the best part of the two approaches: a +// user would write Templates, and Google Test will translate +// that to TemplatesN internally to make error messages +// readable. The translation is done by the 'type' member of the +// Templates template. + +$range i 1..n +template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]> +struct Templates { + typedef Templates$n<$for i, [[T$i]]> type; +}; + +template <> +struct Templates<$for i, [[NoneT]]> { + typedef Templates0 type; +}; + +$range i 1..n-1 +$for i [[ +$range j 1..i +$range k i+1..n +template <$for j, [[GTEST_TEMPLATE_ T$j]]> +struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { + typedef Templates$i<$for j, [[T$j]]> type; +}; + +]] + +// The TypeList template makes it possible to use either a single type +// or a Types<...> list in TYPED_TEST_CASE() and +// INSTANTIATE_TYPED_TEST_CASE_P(). + +template +struct TypeList { + typedef Types1 type; +}; + + +$range i 1..n +template <$for i, [[typename T$i]]> +struct TypeList > { + typedef typename Types<$for i, [[T$i]]>::type type; +}; + +#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing + +#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/gtestsrc/gtest/src/gtest-all.cc b/gtestsrc/gtest/src/gtest-all.cc new file mode 100644 index 0000000..0a9cee5 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-all.cc @@ -0,0 +1,48 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// Google C++ Testing Framework (Google Test) +// +// Sometimes it's desirable to build Google Test by compiling a single file. +// This file serves this purpose. + +// This line ensures that gtest.h can be compiled on its own, even +// when it's fused. +#include "gtest/gtest.h" + +// The following lines pull in the real gtest *.cc files. +#include "src/gtest.cc" +#include "src/gtest-death-test.cc" +#include "src/gtest-filepath.cc" +#include "src/gtest-port.cc" +#include "src/gtest-printers.cc" +#include "src/gtest-test-part.cc" +#include "src/gtest-typed-test.cc" diff --git a/gtestsrc/gtest/src/gtest-death-test.cc b/gtestsrc/gtest/src/gtest-death-test.cc new file mode 100644 index 0000000..a01a369 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-death-test.cc @@ -0,0 +1,1342 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) +// +// This file implements death tests. + +#include "gtest/gtest-death-test.h" +#include "gtest/internal/gtest-port.h" +#include "gtest/internal/custom/gtest.h" + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_OS_MAC +# include +# endif // GTEST_OS_MAC + +# include +# include +# include + +# if GTEST_OS_LINUX +# include +# endif // GTEST_OS_LINUX + +# include + +# if GTEST_OS_WINDOWS +# include +# else +# include +# include +# endif // GTEST_OS_WINDOWS + +# if GTEST_OS_QNX +# include +# endif // GTEST_OS_QNX + +#endif // GTEST_HAS_DEATH_TEST + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-string.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +// Constants. + +// The default death test style. +static const char kDefaultDeathTestStyle[] = "fast"; + +GTEST_DEFINE_string_( + death_test_style, + internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), + "Indicates how to run a death test in a forked child process: " + "\"threadsafe\" (child process re-executes the test binary " + "from the beginning, running only the specific death test) or " + "\"fast\" (child process runs the death test immediately " + "after forking)."); + +GTEST_DEFINE_bool_( + death_test_use_fork, + internal::BoolFromGTestEnv("death_test_use_fork", false), + "Instructs to use fork()/_exit() instead of clone() in death tests. " + "Ignored and always uses fork() on POSIX systems where clone() is not " + "implemented. Useful when running under valgrind or similar tools if " + "those do not support clone(). Valgrind 3.3.1 will just fail if " + "it sees an unsupported combination of clone() flags. " + "It is not recommended to use this flag w/o valgrind though it will " + "work in 99% of the cases. Once valgrind is fixed, this flag will " + "most likely be removed."); + +namespace internal { +GTEST_DEFINE_string_( + internal_run_death_test, "", + "Indicates the file, line number, temporal index of " + "the single death test to run, and a file descriptor to " + "which a success code may be sent, all separated by " + "the '|' characters. This flag is specified if and only if the current " + "process is a sub-process launched for running a thread-safe " + "death test. FOR INTERNAL USE ONLY."); +} // namespace internal + +#if GTEST_HAS_DEATH_TEST + +namespace internal { + +// Valid only for fast death tests. Indicates the code is running in the +// child process of a fast style death test. +# if !GTEST_OS_WINDOWS +static bool g_in_fast_death_test_child = false; +# endif + +// Returns a Boolean value indicating whether the caller is currently +// executing in the context of the death test child process. Tools such as +// Valgrind heap checkers may need this to modify their behavior in death +// tests. IMPORTANT: This is an internal utility. Using it may break the +// implementation of death tests. User code MUST NOT use it. +bool InDeathTestChild() { +# if GTEST_OS_WINDOWS + + // On Windows, death tests are thread-safe regardless of the value of the + // death_test_style flag. + return !GTEST_FLAG(internal_run_death_test).empty(); + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") + return !GTEST_FLAG(internal_run_death_test).empty(); + else + return g_in_fast_death_test_child; +#endif +} + +} // namespace internal + +// ExitedWithCode constructor. +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { +} + +// ExitedWithCode function-call operator. +bool ExitedWithCode::operator()(int exit_status) const { +# if GTEST_OS_WINDOWS + + return exit_status == exit_code_; + +# else + + return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; + +# endif // GTEST_OS_WINDOWS +} + +# if !GTEST_OS_WINDOWS +// KilledBySignal constructor. +KilledBySignal::KilledBySignal(int signum) : signum_(signum) { +} + +// KilledBySignal function-call operator. +bool KilledBySignal::operator()(int exit_status) const { +# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) + { + bool result; + if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { + return result; + } + } +# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) + return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; +} +# endif // !GTEST_OS_WINDOWS + +namespace internal { + +// Utilities needed for death tests. + +// Generates a textual description of a given exit code, in the format +// specified by wait(2). +static std::string ExitSummary(int exit_code) { + Message m; + +# if GTEST_OS_WINDOWS + + m << "Exited with exit status " << exit_code; + +# else + + if (WIFEXITED(exit_code)) { + m << "Exited with exit status " << WEXITSTATUS(exit_code); + } else if (WIFSIGNALED(exit_code)) { + m << "Terminated by signal " << WTERMSIG(exit_code); + } +# ifdef WCOREDUMP + if (WCOREDUMP(exit_code)) { + m << " (core dumped)"; + } +# endif +# endif // GTEST_OS_WINDOWS + + return m.GetString(); +} + +// Returns true if exit_status describes a process that was terminated +// by a signal, or exited normally with a nonzero exit code. +bool ExitedUnsuccessfully(int exit_status) { + return !ExitedWithCode(0)(exit_status); +} + +# if !GTEST_OS_WINDOWS +// Generates a textual failure message when a death test finds more than +// one thread running, or cannot determine the number of threads, prior +// to executing the given statement. It is the responsibility of the +// caller not to pass a thread_count of 1. +static std::string DeathTestThreadWarning(size_t thread_count) { + Message msg; + msg << "Death tests use fork(), which is unsafe particularly" + << " in a threaded context. For this test, " << GTEST_NAME_ << " "; + if (thread_count == 0) + msg << "couldn't detect the number of threads."; + else + msg << "detected " << thread_count << " threads."; + return msg.GetString(); +} +# endif // !GTEST_OS_WINDOWS + +// Flag characters for reporting a death test that did not die. +static const char kDeathTestLived = 'L'; +static const char kDeathTestReturned = 'R'; +static const char kDeathTestThrew = 'T'; +static const char kDeathTestInternalError = 'I'; + +// An enumeration describing all of the possible ways that a death test can +// conclude. DIED means that the process died while executing the test +// code; LIVED means that process lived beyond the end of the test code; +// RETURNED means that the test statement attempted to execute a return +// statement, which is not allowed; THREW means that the test statement +// returned control by throwing an exception. IN_PROGRESS means the test +// has not yet concluded. +// TODO(vladl@google.com): Unify names and possibly values for +// AbortReason, DeathTestOutcome, and flag characters above. +enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; + +// Routine for aborting the program which is safe to call from an +// exec-style death test child process, in which case the error +// message is propagated back to the parent process. Otherwise, the +// message is simply printed to stderr. In either case, the program +// then exits with status 1. +void DeathTestAbort(const std::string& message) { + // On a POSIX system, this function may be called from a threadsafe-style + // death test child process, which operates on a very small stack. Use + // the heap for any additional non-minuscule memory requirements. + const InternalRunDeathTestFlag* const flag = + GetUnitTestImpl()->internal_run_death_test_flag(); + if (flag != NULL) { + FILE* parent = posix::FDOpen(flag->write_fd(), "w"); + fputc(kDeathTestInternalError, parent); + fprintf(parent, "%s", message.c_str()); + fflush(parent); + _exit(1); + } else { + fprintf(stderr, "%s", message.c_str()); + fflush(stderr); + posix::Abort(); + } +} + +// A replacement for CHECK that calls DeathTestAbort if the assertion +// fails. +# define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for +// evaluating any system call that fulfills two conditions: it must return +// -1 on failure, and set errno to EINTR when it is interrupted and +// should be tried again. The macro expands to a loop that repeatedly +// evaluates the expression as long as it evaluates to -1 and sets +// errno to EINTR. If the expression evaluates to -1 but errno is +// something other than EINTR, DeathTestAbort is called. +# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort( \ + ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + + ::testing::internal::StreamableToString(__LINE__) + ": " \ + + #expression + " != -1"); \ + } \ + } while (::testing::internal::AlwaysFalse()) + +// Returns the message describing the last system error in errno. +std::string GetLastErrnoDescription() { + return errno == 0 ? "" : posix::StrError(errno); +} + +// This is called from a death test parent process to read a failure +// message from the death test child process and log it with the FATAL +// severity. On Windows, the message is read from a pipe handle. On other +// platforms, it is read from a file descriptor. +static void FailFromInternalError(int fd) { + Message error; + char buffer[256]; + int num_read; + + do { + while ((num_read = posix::Read(fd, buffer, 255)) > 0) { + buffer[num_read] = '\0'; + error << buffer; + } + } while (num_read == -1 && errno == EINTR); + + if (num_read == 0) { + GTEST_LOG_(FATAL) << error.GetString(); + } else { + const int last_error = errno; + GTEST_LOG_(FATAL) << "Error while reading death test internal: " + << GetLastErrnoDescription() << " [" << last_error << "]"; + } +} + +// Death test constructor. Increments the running death test count +// for the current test. +DeathTest::DeathTest() { + TestInfo* const info = GetUnitTestImpl()->current_test_info(); + if (info == NULL) { + DeathTestAbort("Cannot run a death test outside of a TEST or " + "TEST_F construct"); + } +} + +// Creates and returns a death test by dispatching to the current +// death test factory. +bool DeathTest::Create(const char* statement, const RE* regex, + const char* file, int line, DeathTest** test) { + return GetUnitTestImpl()->death_test_factory()->Create( + statement, regex, file, line, test); +} + +const char* DeathTest::LastMessage() { + return last_death_test_message_.c_str(); +} + +void DeathTest::set_last_death_test_message(const std::string& message) { + last_death_test_message_ = message; +} + +std::string DeathTest::last_death_test_message_; + +// Provides cross platform implementation for some death functionality. +class DeathTestImpl : public DeathTest { + protected: + DeathTestImpl(const char* a_statement, const RE* a_regex) + : statement_(a_statement), + regex_(a_regex), + spawned_(false), + status_(-1), + outcome_(IN_PROGRESS), + read_fd_(-1), + write_fd_(-1) {} + + // read_fd_ is expected to be closed and cleared by a derived class. + ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } + + void Abort(AbortReason reason); + virtual bool Passed(bool status_ok); + + const char* statement() const { return statement_; } + const RE* regex() const { return regex_; } + bool spawned() const { return spawned_; } + void set_spawned(bool is_spawned) { spawned_ = is_spawned; } + int status() const { return status_; } + void set_status(int a_status) { status_ = a_status; } + DeathTestOutcome outcome() const { return outcome_; } + void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } + int read_fd() const { return read_fd_; } + void set_read_fd(int fd) { read_fd_ = fd; } + int write_fd() const { return write_fd_; } + void set_write_fd(int fd) { write_fd_ = fd; } + + // Called in the parent process only. Reads the result code of the death + // test child process via a pipe, interprets it to set the outcome_ + // member, and closes read_fd_. Outputs diagnostics and terminates in + // case of unexpected codes. + void ReadAndInterpretStatusByte(); + + private: + // The textual content of the code this object is testing. This class + // doesn't own this string and should not attempt to delete it. + const char* const statement_; + // The regular expression which test output must match. DeathTestImpl + // doesn't own this object and should not attempt to delete it. + const RE* const regex_; + // True if the death test child process has been successfully spawned. + bool spawned_; + // The exit status of the child process. + int status_; + // How the death test concluded. + DeathTestOutcome outcome_; + // Descriptor to the read end of the pipe to the child process. It is + // always -1 in the child process. The child keeps its write end of the + // pipe in write_fd_. + int read_fd_; + // Descriptor to the child's write end of the pipe to the parent process. + // It is always -1 in the parent process. The parent keeps its end of the + // pipe in read_fd_. + int write_fd_; +}; + +// Called in the parent process only. Reads the result code of the death +// test child process via a pipe, interprets it to set the outcome_ +// member, and closes read_fd_. Outputs diagnostics and terminates in +// case of unexpected codes. +void DeathTestImpl::ReadAndInterpretStatusByte() { + char flag; + int bytes_read; + + // The read() here blocks until data is available (signifying the + // failure of the death test) or until the pipe is closed (signifying + // its success), so it's okay to call this in the parent before + // the child process has exited. + do { + bytes_read = posix::Read(read_fd(), &flag, 1); + } while (bytes_read == -1 && errno == EINTR); + + if (bytes_read == 0) { + set_outcome(DIED); + } else if (bytes_read == 1) { + switch (flag) { + case kDeathTestReturned: + set_outcome(RETURNED); + break; + case kDeathTestThrew: + set_outcome(THREW); + break; + case kDeathTestLived: + set_outcome(LIVED); + break; + case kDeathTestInternalError: + FailFromInternalError(read_fd()); // Does not return. + break; + default: + GTEST_LOG_(FATAL) << "Death test child process reported " + << "unexpected status byte (" + << static_cast(flag) << ")"; + } + } else { + GTEST_LOG_(FATAL) << "Read from death test child process failed: " + << GetLastErrnoDescription(); + } + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); + set_read_fd(-1); +} + +// Signals that the death test code which should have exited, didn't. +// Should be called only in a death test child process. +// Writes a status byte to the child's status file descriptor, then +// calls _exit(1). +void DeathTestImpl::Abort(AbortReason reason) { + // The parent process considers the death test to be a failure if + // it finds any data in our pipe. So, here we write a single flag byte + // to the pipe, then exit. + const char status_ch = + reason == TEST_DID_NOT_DIE ? kDeathTestLived : + reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + + GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); + // We are leaking the descriptor here because on some platforms (i.e., + // when built as Windows DLL), destructors of global objects will still + // run after calling _exit(). On such systems, write_fd_ will be + // indirectly closed from the destructor of UnitTestImpl, causing double + // close if it is also closed here. On debug configurations, double close + // may assert. As there are no in-process buffers to flush here, we are + // relying on the OS to close the descriptor after the process terminates + // when the destructors are not run. + _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) +} + +// Returns an indented copy of stderr output for a death test. +// This makes distinguishing death test output lines from regular log lines +// much easier. +static ::std::string FormatDeathTestOutput(const ::std::string& output) { + ::std::string ret; + for (size_t at = 0; ; ) { + const size_t line_end = output.find('\n', at); + ret += "[ DEATH ] "; + if (line_end == ::std::string::npos) { + ret += output.substr(at); + break; + } + ret += output.substr(at, line_end + 1 - at); + at = line_end + 1; + } + return ret; +} + +// Assesses the success or failure of a death test, using both private +// members which have previously been set, and one argument: +// +// Private data members: +// outcome: An enumeration describing how the death test +// concluded: DIED, LIVED, THREW, or RETURNED. The death test +// fails in the latter three cases. +// status: The exit status of the child process. On *nix, it is in the +// in the format specified by wait(2). On Windows, this is the +// value supplied to the ExitProcess() API or a numeric code +// of the exception that terminated the program. +// regex: A regular expression object to be applied to +// the test's captured standard error output; the death test +// fails if it does not match. +// +// Argument: +// status_ok: true if exit_status is acceptable in the context of +// this particular death test, which fails if it is false +// +// Returns true iff all of the above conditions are met. Otherwise, the +// first failing condition, in the order given above, is the one that is +// reported. Also sets the last death test message string. +bool DeathTestImpl::Passed(bool status_ok) { + if (!spawned()) + return false; + + const std::string error_message = GetCapturedStderr(); + + bool success = false; + Message buffer; + + buffer << "Death test: " << statement() << "\n"; + switch (outcome()) { + case LIVED: + buffer << " Result: failed to die.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case THREW: + buffer << " Result: threw an exception.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case RETURNED: + buffer << " Result: illegal return in test statement.\n" + << " Error msg:\n" << FormatDeathTestOutput(error_message); + break; + case DIED: + if (status_ok) { + const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); + if (matched) { + success = true; + } else { + buffer << " Result: died but not with expected error.\n" + << " Expected: " << regex()->pattern() << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + } else { + buffer << " Result: died but not with expected exit code:\n" + << " " << ExitSummary(status()) << "\n" + << "Actual msg:\n" << FormatDeathTestOutput(error_message); + } + break; + case IN_PROGRESS: + default: + GTEST_LOG_(FATAL) + << "DeathTest::Passed somehow called before conclusion of test"; + } + + DeathTest::set_last_death_test_message(buffer.GetString()); + return success; +} + +# if GTEST_OS_WINDOWS +// WindowsDeathTest implements death tests on Windows. Due to the +// specifics of starting new processes on Windows, death tests there are +// always threadsafe, and Google Test considers the +// --gtest_death_test_style=fast setting to be equivalent to +// --gtest_death_test_style=threadsafe there. +// +// A few implementation notes: Like the Linux version, the Windows +// implementation uses pipes for child-to-parent communication. But due to +// the specifics of pipes on Windows, some extra steps are required: +// +// 1. The parent creates a communication pipe and stores handles to both +// ends of it. +// 2. The parent starts the child and provides it with the information +// necessary to acquire the handle to the write end of the pipe. +// 3. The child acquires the write end of the pipe and signals the parent +// using a Windows event. +// 4. Now the parent can release the write end of the pipe on its side. If +// this is done before step 3, the object's reference count goes down to +// 0 and it is destroyed, preventing the child from acquiring it. The +// parent now has to release it, or read operations on the read end of +// the pipe will not return when the child terminates. +// 5. The parent reads child's output through the pipe (outcome code and +// any possible error messages) from the pipe, and its stderr and then +// determines whether to fail the test. +// +// Note: to distinguish Win32 API calls from the local method and function +// calls, the former are explicitly resolved in the global namespace. +// +class WindowsDeathTest : public DeathTestImpl { + public: + WindowsDeathTest(const char* a_statement, + const RE* a_regex, + const char* file, + int line) + : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + virtual TestRole AssumeRole(); + + private: + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; + // Handle to the write end of the pipe to the child process. + AutoHandle write_handle_; + // Child process handle. + AutoHandle child_handle_; + // Event the child process uses to signal the parent that it has + // acquired the handle to the write end of the pipe. After seeing this + // event the parent can release its own handles to make sure its + // ReadFile() calls return when the child terminates. + AutoHandle event_handle_; +}; + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int WindowsDeathTest::Wait() { + if (!spawned()) + return 0; + + // Wait until the child either signals that it has acquired the write end + // of the pipe or it dies. + const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; + switch (::WaitForMultipleObjects(2, + wait_handles, + FALSE, // Waits for any of the handles. + INFINITE)) { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + break; + default: + GTEST_DEATH_TEST_CHECK_(false); // Should not get here. + } + + // The child has acquired the write end of the pipe or exited. + // We release the handle on our side and continue. + write_handle_.Reset(); + event_handle_.Reset(); + + ReadAndInterpretStatusByte(); + + // Waits for the child process to exit if it haven't already. This + // returns immediately if the child has already exited, regardless of + // whether previous calls to WaitForMultipleObjects synchronized on this + // handle or not. + GTEST_DEATH_TEST_CHECK_( + WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), + INFINITE)); + DWORD status_code; + GTEST_DEATH_TEST_CHECK_( + ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); + child_handle_.Reset(); + set_status(static_cast(status_code)); + return status(); +} + +// The AssumeRole process for a Windows death test. It creates a child +// process with the same executable as the current process to run the +// death test. The child process is given the --gtest_filter and +// --gtest_internal_run_death_test flags such that it knows to run the +// current death test only. +DeathTest::TestRole WindowsDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + // ParseInternalRunDeathTestFlag() has performed all the necessary + // processing. + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + // WindowsDeathTest uses an anonymous pipe to communicate results of + // a death test. + SECURITY_ATTRIBUTES handles_are_inheritable = { + sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + HANDLE read_handle, write_handle; + GTEST_DEATH_TEST_CHECK_( + ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, + 0) // Default buffer size. + != FALSE); + set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), + O_RDONLY)); + write_handle_.Reset(write_handle); + event_handle_.Reset(::CreateEvent( + &handles_are_inheritable, + TRUE, // The event will automatically reset to non-signaled state. + FALSE, // The initial state is non-signalled. + NULL)); // The even is unnamed. + GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + + "=" + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(static_cast(::GetCurrentProcessId())) + + // size_t has the same width as pointers on both 32-bit and 64-bit + // Windows platforms. + // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. + "|" + StreamableToString(reinterpret_cast(write_handle)) + + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); + + char executable_path[_MAX_PATH + 1]; // NOLINT + GTEST_DEATH_TEST_CHECK_( + _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, + executable_path, + _MAX_PATH)); + + std::string command_line = + std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + + internal_flag + "\""; + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // Flush the log buffers since the log streams are shared with the child. + FlushInfoLog(); + + // The child process will share the standard handles with the parent. + STARTUPINFOA startup_info; + memset(&startup_info, 0, sizeof(STARTUPINFO)); + startup_info.dwFlags = STARTF_USESTDHANDLES; + startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); + startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); + startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); + + PROCESS_INFORMATION process_info; + GTEST_DEATH_TEST_CHECK_(::CreateProcessA( + executable_path, + const_cast(command_line.c_str()), + NULL, // Retuned process handle is not inheritable. + NULL, // Retuned thread handle is not inheritable. + TRUE, // Child inherits all inheritable handles (for write_handle_). + 0x0, // Default creation flags. + NULL, // Inherit the parent's environment. + UnitTest::GetInstance()->original_working_dir(), + &startup_info, + &process_info) != FALSE); + child_handle_.Reset(process_info.hProcess); + ::CloseHandle(process_info.hThread); + set_spawned(true); + return OVERSEE_TEST; +} +# else // We are not on Windows. + +// ForkingDeathTest provides implementations for most of the abstract +// methods of the DeathTest interface. Only the AssumeRole method is +// left undefined. +class ForkingDeathTest : public DeathTestImpl { + public: + ForkingDeathTest(const char* statement, const RE* regex); + + // All of these virtual functions are inherited from DeathTest. + virtual int Wait(); + + protected: + void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } + + private: + // PID of child process during death test; 0 in the child process itself. + pid_t child_pid_; +}; + +// Constructs a ForkingDeathTest. +ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) + : DeathTestImpl(a_statement, a_regex), + child_pid_(-1) {} + +// Waits for the child in a death test to exit, returning its exit +// status, or 0 if no child process exists. As a side effect, sets the +// outcome data member. +int ForkingDeathTest::Wait() { + if (!spawned()) + return 0; + + ReadAndInterpretStatusByte(); + + int status_value; + GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); + set_status(status_value); + return status_value; +} + +// A concrete death test class that forks, then immediately runs the test +// in the child process. +class NoExecDeathTest : public ForkingDeathTest { + public: + NoExecDeathTest(const char* a_statement, const RE* a_regex) : + ForkingDeathTest(a_statement, a_regex) { } + virtual TestRole AssumeRole(); +}; + +// The AssumeRole process for a fork-and-run death test. It implements a +// straightforward fork, with a simple pipe to transmit the status byte. +DeathTest::TestRole NoExecDeathTest::AssumeRole() { + const size_t thread_count = GetThreadCount(); + if (thread_count != 1) { + GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + + DeathTest::set_last_death_test_message(""); + CaptureStderr(); + // When we fork the process below, the log file buffers are copied, but the + // file descriptors are shared. We flush all log files here so that closing + // the file descriptors in the child process doesn't throw off the + // synchronization between descriptors and buffers in the parent process. + // This is as close to the fork as possible to avoid a race condition in case + // there are multiple threads running before the death test, and another + // thread writes to the log file. + FlushInfoLog(); + + const pid_t child_pid = fork(); + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + set_child_pid(child_pid); + if (child_pid == 0) { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); + set_write_fd(pipe_fd[1]); + // Redirects all logging to stderr in the child process to prevent + // concurrent writes to the log files. We capture stderr in the parent + // process and append the child process' output to a log. + LogToStderr(); + // Event forwarding to the listeners of event listener API mush be shut + // down in death test subprocesses. + GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + g_in_fast_death_test_child = true; + return EXECUTE_TEST; + } else { + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; + } +} + +// A concrete death test class that forks and re-executes the main +// program from the beginning, with command-line flags set that cause +// only this specific death test to be run. +class ExecDeathTest : public ForkingDeathTest { + public: + ExecDeathTest(const char* a_statement, const RE* a_regex, + const char* file, int line) : + ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } + virtual TestRole AssumeRole(); + private: + static ::std::vector + GetArgvsForDeathTestChildProcess() { + ::std::vector args = GetInjectableArgvs(); +# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) + ::std::vector extra_args = + GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); + args.insert(args.end(), extra_args.begin(), extra_args.end()); +# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) + return args; + } + // The name of the file in which the death test is located. + const char* const file_; + // The line number on which the death test is located. + const int line_; +}; + +// Utility class for accumulating command-line arguments. +class Arguments { + public: + Arguments() { + args_.push_back(NULL); + } + + ~Arguments() { + for (std::vector::iterator i = args_.begin(); i != args_.end(); + ++i) { + free(*i); + } + } + void AddArgument(const char* argument) { + args_.insert(args_.end() - 1, posix::StrDup(argument)); + } + + template + void AddArguments(const ::std::vector& arguments) { + for (typename ::std::vector::const_iterator i = arguments.begin(); + i != arguments.end(); + ++i) { + args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); + } + } + char* const* Argv() { + return &args_[0]; + } + + private: + std::vector args_; +}; + +// A struct that encompasses the arguments to the child process of a +// threadsafe-style death test process. +struct ExecDeathTestArgs { + char* const* argv; // Command-line arguments for the child's call to exec + int close_fd; // File descriptor to close; the read end of a pipe +}; + +# if GTEST_OS_MAC +inline char** GetEnviron() { + // When Google Test is built as a framework on MacOS X, the environ variable + // is unavailable. Apple's documentation (man environ) recommends using + // _NSGetEnviron() instead. + return *_NSGetEnviron(); +} +# else +// Some POSIX platforms expect you to declare environ. extern "C" makes +// it reside in the global namespace. +extern "C" char** environ; +inline char** GetEnviron() { return environ; } +# endif // GTEST_OS_MAC + +# if !GTEST_OS_QNX +// The main function for a threadsafe-style death test child process. +// This function is called in a clone()-ed process and thus must avoid +// any potentially unsafe operations like malloc or libc functions. +static int ExecDeathTestChildMain(void* child_arg) { + ExecDeathTestArgs* const args = static_cast(child_arg); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); + + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + // We can safely call execve() as it's a direct system call. We + // cannot use execvp() as it's a libc function and thus potentially + // unsafe. Since execve() doesn't search the PATH, the user must + // invoke the test program via a valid path that contains at least + // one path separator. + execve(args->argv[0], args->argv, GetEnviron()); + DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + + original_dir + " failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; +} +# endif // !GTEST_OS_QNX + +// Two utility routines that together determine the direction the stack +// grows. +// This could be accomplished more elegantly by a single recursive +// function, but we want to guard against the unlikely possibility of +// a smart compiler optimizing the recursion away. +// +// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining +// StackLowerThanAddress into StackGrowsDown, which then doesn't give +// correct answer. +void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; +void StackLowerThanAddress(const void* ptr, bool* result) { + int dummy; + *result = (&dummy < ptr); +} + +// Make sure AddressSanitizer does not tamper with the stack here. +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +bool StackGrowsDown() { + int dummy; + bool result; + StackLowerThanAddress(&dummy, &result); + return result; +} + +// Spawns a child process with the same executable as the current process in +// a thread-safe manner and instructs it to run the death test. The +// implementation uses fork(2) + exec. On systems where clone(2) is +// available, it is used instead, being slightly more thread-safe. On QNX, +// fork supports only single-threaded environments, so this function uses +// spawn(2) there instead. The function dies with an error message if +// anything goes wrong. +static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { + ExecDeathTestArgs args = { argv, close_fd }; + pid_t child_pid = -1; + +# if GTEST_OS_QNX + // Obtains the current directory and sets it to be closed in the child + // process. + const int cwd_fd = open(".", O_RDONLY); + GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); + // We need to execute the test program in the same environment where + // it was originally invoked. Therefore we change to the original + // working directory first. + const char* const original_dir = + UnitTest::GetInstance()->original_working_dir(); + // We can safely call chdir() as it's a direct system call. + if (chdir(original_dir) != 0) { + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + + GetLastErrnoDescription()); + return EXIT_FAILURE; + } + + int fd_flags; + // Set close_fd to be closed after spawn. + GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, + fd_flags | FD_CLOEXEC)); + struct inheritance inherit = {0}; + // spawn is a system call. + child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); + // Restores the current working directory. + GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); + +# else // GTEST_OS_QNX +# if GTEST_OS_LINUX + // When a SIGPROF signal is received while fork() or clone() are executing, + // the process may hang. To avoid this, we ignore SIGPROF here and re-enable + // it after the call to fork()/clone() is complete. + struct sigaction saved_sigprof_action; + struct sigaction ignore_sigprof_action; + memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); + sigemptyset(&ignore_sigprof_action.sa_mask); + ignore_sigprof_action.sa_handler = SIG_IGN; + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( + SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +# endif // GTEST_OS_LINUX + +# if GTEST_HAS_CLONE + const bool use_fork = GTEST_FLAG(death_test_use_fork); + + if (!use_fork) { + static const bool stack_grows_down = StackGrowsDown(); + const size_t stack_size = getpagesize(); + // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. + void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); + + // Maximum stack alignment in bytes: For a downward-growing stack, this + // amount is subtracted from size of the stack space to get an address + // that is within the stack space and is aligned on all systems we care + // about. As far as I know there is no ABI with stack alignment greater + // than 64. We assume stack and stack_size already have alignment of + // kMaxStackAlignment. + const size_t kMaxStackAlignment = 64; + void* const stack_top = + static_cast(stack) + + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && + reinterpret_cast(stack_top) % kMaxStackAlignment == 0); + + child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); + + GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); + } +# else + const bool use_fork = true; +# endif // GTEST_HAS_CLONE + + if (use_fork && (child_pid = fork()) == 0) { + ExecDeathTestChildMain(&args); + _exit(0); + } +# endif // GTEST_OS_QNX +# if GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_( + sigaction(SIGPROF, &saved_sigprof_action, NULL)); +# endif // GTEST_OS_LINUX + + GTEST_DEATH_TEST_CHECK_(child_pid != -1); + return child_pid; +} + +// The AssumeRole process for a fork-and-exec death test. It re-executes the +// main program from the beginning, setting the --gtest_filter +// and --gtest_internal_run_death_test flags to cause only the current +// death test to be re-run. +DeathTest::TestRole ExecDeathTest::AssumeRole() { + const UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const TestInfo* const info = impl->current_test_info(); + const int death_test_index = info->result()->death_test_count(); + + if (flag != NULL) { + set_write_fd(flag->write_fd()); + return EXECUTE_TEST; + } + + int pipe_fd[2]; + GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); + // Clear the close-on-exec flag on the write end of the pipe, lest + // it be closed when the child process does an exec: + GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); + + const std::string filter_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + + info->test_case_name() + "." + info->name(); + const std::string internal_flag = + std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + + file_ + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); + Arguments args; + args.AddArguments(GetArgvsForDeathTestChildProcess()); + args.AddArgument(filter_flag.c_str()); + args.AddArgument(internal_flag.c_str()); + + DeathTest::set_last_death_test_message(""); + + CaptureStderr(); + // See the comment in NoExecDeathTest::AssumeRole for why the next line + // is necessary. + FlushInfoLog(); + + const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); + GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); + set_child_pid(child_pid); + set_read_fd(pipe_fd[0]); + set_spawned(true); + return OVERSEE_TEST; +} + +# endif // !GTEST_OS_WINDOWS + +// Creates a concrete DeathTest-derived class that depends on the +// --gtest_death_test_style flag, and sets the pointer pointed to +// by the "test" argument to its address. If the test should be +// skipped, sets that pointer to NULL. Returns true, unless the +// flag is set to an invalid value. +bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, + const char* file, int line, + DeathTest** test) { + UnitTestImpl* const impl = GetUnitTestImpl(); + const InternalRunDeathTestFlag* const flag = + impl->internal_run_death_test_flag(); + const int death_test_index = impl->current_test_info() + ->increment_death_test_count(); + + if (flag != NULL) { + if (death_test_index > flag->index()) { + DeathTest::set_last_death_test_message( + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); + return false; + } + + if (!(flag->file() == file && flag->line() == line && + flag->index() == death_test_index)) { + *test = NULL; + return true; + } + } + +# if GTEST_OS_WINDOWS + + if (GTEST_FLAG(death_test_style) == "threadsafe" || + GTEST_FLAG(death_test_style) == "fast") { + *test = new WindowsDeathTest(statement, regex, file, line); + } + +# else + + if (GTEST_FLAG(death_test_style) == "threadsafe") { + *test = new ExecDeathTest(statement, regex, file, line); + } else if (GTEST_FLAG(death_test_style) == "fast") { + *test = new NoExecDeathTest(statement, regex); + } + +# endif // GTEST_OS_WINDOWS + + else { // NOLINT - this is more readable than unbalanced brackets inside #if. + DeathTest::set_last_death_test_message( + "Unknown death test style \"" + GTEST_FLAG(death_test_style) + + "\" encountered"); + return false; + } + + return true; +} + +# if GTEST_OS_WINDOWS +// Recreates the pipe and event handles from the provided parameters, +// signals the event, and returns a file descriptor wrapped around the pipe +// handle. This function is called in the child process only. +int GetStatusFileDescriptor(unsigned int parent_process_id, + size_t write_handle_as_size_t, + size_t event_handle_as_size_t) { + AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, + FALSE, // Non-inheritable. + parent_process_id)); + if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { + DeathTestAbort("Unable to open parent process " + + StreamableToString(parent_process_id)); + } + + // TODO(vladl@google.com): Replace the following check with a + // compile-time assertion when available. + GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); + + const HANDLE write_handle = + reinterpret_cast(write_handle_as_size_t); + HANDLE dup_write_handle; + + // The newly initialized handle is accessible only in in the parent + // process. To obtain one accessible within the child, we need to use + // DuplicateHandle. + if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, + ::GetCurrentProcess(), &dup_write_handle, + 0x0, // Requested privileges ignored since + // DUPLICATE_SAME_ACCESS is used. + FALSE, // Request non-inheritable handler. + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the pipe handle " + + StreamableToString(write_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); + HANDLE dup_event_handle; + + if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, + ::GetCurrentProcess(), &dup_event_handle, + 0x0, + FALSE, + DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the event handle " + + StreamableToString(event_handle_as_size_t) + + " from the parent process " + + StreamableToString(parent_process_id)); + } + + const int write_fd = + ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); + if (write_fd == -1) { + DeathTestAbort("Unable to convert pipe handle " + + StreamableToString(write_handle_as_size_t) + + " to a file descriptor"); + } + + // Signals the parent that the write end of the pipe has been acquired + // so the parent can release its own write end. + ::SetEvent(dup_event_handle); + + return write_fd; +} +# endif // GTEST_OS_WINDOWS + +// Returns a newly created InternalRunDeathTestFlag object with fields +// initialized from the GTEST_FLAG(internal_run_death_test) flag if +// the flag is specified; otherwise returns NULL. +InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { + if (GTEST_FLAG(internal_run_death_test) == "") return NULL; + + // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we + // can use it here. + int line = -1; + int index = -1; + ::std::vector< ::std::string> fields; + SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); + int write_fd = -1; + +# if GTEST_OS_WINDOWS + + unsigned int parent_process_id = 0; + size_t write_handle_as_size_t = 0; + size_t event_handle_as_size_t = 0; + + if (fields.size() != 6 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &parent_process_id) + || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) + || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + write_fd = GetStatusFileDescriptor(parent_process_id, + write_handle_as_size_t, + event_handle_as_size_t); +# else + + if (fields.size() != 4 + || !ParseNaturalNumber(fields[1], &line) + || !ParseNaturalNumber(fields[2], &index) + || !ParseNaturalNumber(fields[3], &write_fd)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG(internal_run_death_test)); + } + +# endif // GTEST_OS_WINDOWS + + return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); +} + +} // namespace internal + +#endif // GTEST_HAS_DEATH_TEST + +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest-filepath.cc b/gtestsrc/gtest/src/gtest-filepath.cc new file mode 100644 index 0000000..0292dc1 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-filepath.cc @@ -0,0 +1,387 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: keith.ray@gmail.com (Keith Ray) + +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-port.h" + +#include + +#if GTEST_OS_WINDOWS_MOBILE +# include +#elif GTEST_OS_WINDOWS +# include +# include +#elif GTEST_OS_SYMBIAN +// Symbian OpenC has PATH_MAX in sys/syslimits.h +# include +#else +# include +# include // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE + +#if GTEST_OS_WINDOWS +# define GTEST_PATH_MAX_ _MAX_PATH +#elif defined(PATH_MAX) +# define GTEST_PATH_MAX_ PATH_MAX +#elif defined(_XOPEN_PATH_MAX) +# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +#else +# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +#endif // GTEST_OS_WINDOWS + +#include "gtest/internal/gtest-string.h" + +namespace testing { +namespace internal { + +#if GTEST_OS_WINDOWS +// On Windows, '\\' is the standard path separator, but many tools and the +// Windows API also accept '/' as an alternate path separator. Unless otherwise +// noted, a file path can contain either kind of path separators, or a mixture +// of them. +const char kPathSeparator = '\\'; +const char kAlternatePathSeparator = '/'; +const char kAlternatePathSeparatorString[] = "/"; +# if GTEST_OS_WINDOWS_MOBILE +// Windows CE doesn't have a current directory. You should not use +// the current directory in tests on Windows CE, but this at least +// provides a reasonable fallback. +const char kCurrentDirectoryString[] = "\\"; +// Windows CE doesn't define INVALID_FILE_ATTRIBUTES +const DWORD kInvalidFileAttributes = 0xffffffff; +# else +const char kCurrentDirectoryString[] = ".\\"; +# endif // GTEST_OS_WINDOWS_MOBILE +#else +const char kPathSeparator = '/'; +const char kCurrentDirectoryString[] = "./"; +#endif // GTEST_OS_WINDOWS + +// Returns whether the given character is a valid path separator. +static bool IsPathSeparator(char c) { +#if GTEST_HAS_ALT_PATH_SEP_ + return (c == kPathSeparator) || (c == kAlternatePathSeparator); +#else + return c == kPathSeparator; +#endif +} + +// Returns the current working directory, or "" if unsuccessful. +FilePath FilePath::GetCurrentDir() { +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT + // Windows CE doesn't have a current directory, so we just return + // something reasonable. + return FilePath(kCurrentDirectoryString); +#elif GTEST_OS_WINDOWS + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); +#else + char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char* result = getcwd(cwd, sizeof(cwd)); +# if GTEST_OS_NACL + // getcwd will likely fail in NaCl due to the sandbox, so return something + // reasonable. The user may have provided a shim implementation for getcwd, + // however, so fallback only when failure is detected. + return FilePath(result == NULL ? kCurrentDirectoryString : cwd); +# endif // GTEST_OS_NACL + return FilePath(result == NULL ? "" : cwd); +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns a copy of the FilePath with the case-insensitive extension removed. +// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns +// FilePath("dir/file"). If a case-insensitive extension is not +// found, returns a copy of the original FilePath. +FilePath FilePath::RemoveExtension(const char* extension) const { + const std::string dot_extension = std::string(".") + extension; + if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { + return FilePath(pathname_.substr( + 0, pathname_.length() - dot_extension.length())); + } + return *this; +} + +// Returns a pointer to the last occurence of a valid path separator in +// the FilePath. On Windows, for example, both '/' and '\' are valid path +// separators. Returns NULL if no path separator was found. +const char* FilePath::FindLastPathSeparator() const { + const char* const last_sep = strrchr(c_str(), kPathSeparator); +#if GTEST_HAS_ALT_PATH_SEP_ + const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); + // Comparing two pointers of which only one is NULL is undefined. + if (last_alt_sep != NULL && + (last_sep == NULL || last_alt_sep > last_sep)) { + return last_alt_sep; + } +#endif + return last_sep; +} + +// Returns a copy of the FilePath with the directory part removed. +// Example: FilePath("path/to/file").RemoveDirectoryName() returns +// FilePath("file"). If there is no directory part ("just_a_file"), it returns +// the FilePath unmodified. If there is no file part ("just_a_dir/") it +// returns an empty FilePath (""). +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveDirectoryName() const { + const char* const last_sep = FindLastPathSeparator(); + return last_sep ? FilePath(last_sep + 1) : *this; +} + +// RemoveFileName returns the directory path with the filename removed. +// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". +// If the FilePath is "a_file" or "/a_file", RemoveFileName returns +// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does +// not have a file, like "just/a/dir/", it returns the FilePath unmodified. +// On Windows platform, '\' is the path separator, otherwise it is '/'. +FilePath FilePath::RemoveFileName() const { + const char* const last_sep = FindLastPathSeparator(); + std::string dir; + if (last_sep) { + dir = std::string(c_str(), last_sep + 1 - c_str()); + } else { + dir = kCurrentDirectoryString; + } + return FilePath(dir); +} + +// Helper functions for naming files in a directory for xml output. + +// Given directory = "dir", base_name = "test", number = 0, +// extension = "xml", returns "dir/test.xml". If number is greater +// than zero (e.g., 12), returns "dir/test_12.xml". +// On Windows platform, uses \ as the separator rather than /. +FilePath FilePath::MakeFileName(const FilePath& directory, + const FilePath& base_name, + int number, + const char* extension) { + std::string file; + if (number == 0) { + file = base_name.string() + "." + extension; + } else { + file = base_name.string() + "_" + StreamableToString(number) + + "." + extension; + } + return ConcatPaths(directory, FilePath(file)); +} + +// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". +// On Windows, uses \ as the separator rather than /. +FilePath FilePath::ConcatPaths(const FilePath& directory, + const FilePath& relative_path) { + if (directory.IsEmpty()) + return relative_path; + const FilePath dir(directory.RemoveTrailingPathSeparator()); + return FilePath(dir.string() + kPathSeparator + relative_path.string()); +} + +// Returns true if pathname describes something findable in the file-system, +// either a file, directory, or whatever. +bool FilePath::FileOrDirectoryExists() const { +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + return attributes != kInvalidFileAttributes; +#else + posix::StatStruct file_stat; + return posix::Stat(pathname_.c_str(), &file_stat) == 0; +#endif // GTEST_OS_WINDOWS_MOBILE +} + +// Returns true if pathname describes a directory in the file-system +// that exists. +bool FilePath::DirectoryExists() const { + bool result = false; +#if GTEST_OS_WINDOWS + // Don't strip off trailing separator if path is a root directory on + // Windows (like "C:\\"). + const FilePath& path(IsRootDirectory() ? *this : + RemoveTrailingPathSeparator()); +#else + const FilePath& path(*this); +#endif + +#if GTEST_OS_WINDOWS_MOBILE + LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); + const DWORD attributes = GetFileAttributes(unicode); + delete [] unicode; + if ((attributes != kInvalidFileAttributes) && + (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + result = true; + } +#else + posix::StatStruct file_stat; + result = posix::Stat(path.c_str(), &file_stat) == 0 && + posix::IsDir(file_stat); +#endif // GTEST_OS_WINDOWS_MOBILE + + return result; +} + +// Returns true if pathname describes a root directory. (Windows has one +// root directory per disk drive.) +bool FilePath::IsRootDirectory() const { +#if GTEST_OS_WINDOWS + // TODO(wan@google.com): on Windows a network share like + // \\server\share can be a root directory, although it cannot be the + // current directory. Handle this properly. + return pathname_.length() == 3 && IsAbsolutePath(); +#else + return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); +#endif +} + +// Returns true if pathname describes an absolute path. +bool FilePath::IsAbsolutePath() const { + const char* const name = pathname_.c_str(); +#if GTEST_OS_WINDOWS + return pathname_.length() >= 3 && + ((name[0] >= 'a' && name[0] <= 'z') || + (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && + IsPathSeparator(name[2]); +#else + return IsPathSeparator(name[0]); +#endif +} + +// Returns a pathname for a file that does not currently exist. The pathname +// will be directory/base_name.extension or +// directory/base_name_.extension if directory/base_name.extension +// already exists. The number will be incremented until a pathname is found +// that does not already exist. +// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. +// There could be a race condition if two or more processes are calling this +// function at the same time -- they could both pick the same filename. +FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, + const FilePath& base_name, + const char* extension) { + FilePath full_pathname; + int number = 0; + do { + full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); + } while (full_pathname.FileOrDirectoryExists()); + return full_pathname; +} + +// Returns true if FilePath ends with a path separator, which indicates that +// it is intended to represent a directory. Returns false otherwise. +// This does NOT check that a directory (or file) actually exists. +bool FilePath::IsDirectory() const { + return !pathname_.empty() && + IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); +} + +// Create directories so that path exists. Returns true if successful or if +// the directories already exist; returns false if unable to create directories +// for any reason. +bool FilePath::CreateDirectoriesRecursively() const { + if (!this->IsDirectory()) { + return false; + } + + if (pathname_.length() == 0 || this->DirectoryExists()) { + return true; + } + + const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); + return parent.CreateDirectoriesRecursively() && this->CreateFolder(); +} + +// Create the directory so that path exists. Returns true if successful or +// if the directory already exists; returns false if unable to create the +// directory for any reason, including if the parent directory does not +// exist. Not named "CreateDirectory" because that's a macro on Windows. +bool FilePath::CreateFolder() const { +#if GTEST_OS_WINDOWS_MOBILE + FilePath removed_sep(this->RemoveTrailingPathSeparator()); + LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); + int result = CreateDirectory(unicode, NULL) ? 0 : -1; + delete [] unicode; +#elif GTEST_OS_WINDOWS + int result = _mkdir(pathname_.c_str()); +#else + int result = mkdir(pathname_.c_str(), 0777); +#endif // GTEST_OS_WINDOWS_MOBILE + + if (result == -1) { + return this->DirectoryExists(); // An error is OK if the directory exists. + } + return true; // No error. +} + +// If input name has a trailing separator character, remove it and return the +// name, otherwise return the name string unmodified. +// On Windows platform, uses \ as the separator, other platforms use /. +FilePath FilePath::RemoveTrailingPathSeparator() const { + return IsDirectory() + ? FilePath(pathname_.substr(0, pathname_.length() - 1)) + : *this; +} + +// Removes any redundant separators that might be in the pathname. +// For example, "bar///foo" becomes "bar/foo". Does not eliminate other +// redundancies that might be in a pathname involving "." or "..". +// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). +void FilePath::Normalize() { + if (pathname_.c_str() == NULL) { + pathname_ = ""; + return; + } + const char* src = pathname_.c_str(); + char* const dest = new char[pathname_.length() + 1]; + char* dest_ptr = dest; + memset(dest_ptr, 0, pathname_.length() + 1); + + while (*src != '\0') { + *dest_ptr = *src; + if (!IsPathSeparator(*src)) { + src++; + } else { +#if GTEST_HAS_ALT_PATH_SEP_ + if (*dest_ptr == kAlternatePathSeparator) { + *dest_ptr = kPathSeparator; + } +#endif + while (IsPathSeparator(*src)) + src++; + } + dest_ptr++; + } + *dest_ptr = '\0'; + pathname_ = dest; + delete[] dest; +} + +} // namespace internal +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest-internal-inl.h b/gtestsrc/gtest/src/gtest-internal-inl.h new file mode 100644 index 0000000..ed8a682 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-internal-inl.h @@ -0,0 +1,1183 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Utility functions and classes used by the Google C++ testing framework. +// +// Author: wan@google.com (Zhanyong Wan) +// +// This file contains purely Google Test's internal implementation. Please +// DO NOT #INCLUDE IT IN A USER PROGRAM. + +#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ +#define GTEST_SRC_GTEST_INTERNAL_INL_H_ + +// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is +// part of Google Test's implementation; otherwise it's undefined. +#if !GTEST_IMPLEMENTATION_ +// If this file is included from the user's code, just say no. +# error "gtest-internal-inl.h is part of Google Test's internal implementation." +# error "It must not be included except by Google Test itself." +#endif // GTEST_IMPLEMENTATION_ + +#ifndef _WIN32_WCE +# include +#endif // !_WIN32_WCE +#include +#include // For strtoll/_strtoul64/malloc/free. +#include // For memmove. + +#include +#include +#include + +#include "gtest/internal/gtest-port.h" + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +#endif + +#if GTEST_OS_WINDOWS +# include // NOLINT +#endif // GTEST_OS_WINDOWS + +#include "gtest/gtest.h" // NOLINT +#include "gtest/gtest-spi.h" + +namespace testing { + +// Declares the flags. +// +// We don't want the users to modify this flag in the code, but want +// Google Test's own unit tests to be able to access it. Therefore we +// declare it here as opposed to in gtest.h. +GTEST_DECLARE_bool_(death_test_use_fork); + +namespace internal { + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; + +// Names of the flags (needed for parsing Google Test flags). +const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; +const char kBreakOnFailureFlag[] = "break_on_failure"; +const char kCatchExceptionsFlag[] = "catch_exceptions"; +const char kColorFlag[] = "color"; +const char kFilterFlag[] = "filter"; +const char kListTestsFlag[] = "list_tests"; +const char kOutputFlag[] = "output"; +const char kPrintTimeFlag[] = "print_time"; +const char kRandomSeedFlag[] = "random_seed"; +const char kRepeatFlag[] = "repeat"; +const char kShuffleFlag[] = "shuffle"; +const char kStackTraceDepthFlag[] = "stack_trace_depth"; +const char kStreamResultToFlag[] = "stream_result_to"; +const char kThrowOnFailureFlag[] = "throw_on_failure"; +const char kFlagfileFlag[] = "flagfile"; + +// A valid random seed must be in [1, kMaxRandomSeed]. +const int kMaxRandomSeed = 99999; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +GTEST_API_ extern bool g_help_flag; + +// Returns the current time in milliseconds. +GTEST_API_ TimeInMillis GetTimeInMillis(); + +// Returns true iff Google Test should use colors in the output. +GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); + +// Formats the given time in milliseconds as seconds. +GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); + +// Converts the given time in milliseconds to a date string in the ISO 8601 +// format, without the timezone information. N.B.: due to the use the +// non-reentrant localtime() function, this function is not thread safe. Do +// not use it in any code that can be called from multiple threads. +GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +GTEST_API_ bool ParseInt32Flag( + const char* str, const char* flag, Int32* value); + +// Returns a random seed in range [1, kMaxRandomSeed] based on the +// given --gtest_random_seed flag value. +inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { + const unsigned int raw_seed = (random_seed_flag == 0) ? + static_cast(GetTimeInMillis()) : + static_cast(random_seed_flag); + + // Normalizes the actual seed to range [1, kMaxRandomSeed] such that + // it's easy to type. + const int normalized_seed = + static_cast((raw_seed - 1U) % + static_cast(kMaxRandomSeed)) + 1; + return normalized_seed; +} + +// Returns the first valid random seed after 'seed'. The behavior is +// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is +// considered to be 1. +inline int GetNextRandomSeed(int seed) { + GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) + << "Invalid random seed " << seed << " - must be in [1, " + << kMaxRandomSeed << "]."; + const int next_seed = seed + 1; + return (next_seed > kMaxRandomSeed) ? 1 : next_seed; +} + +// This class saves the values of all Google Test flags in its c'tor, and +// restores them in its d'tor. +class GTestFlagSaver { + public: + // The c'tor. + GTestFlagSaver() { + also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); + break_on_failure_ = GTEST_FLAG(break_on_failure); + catch_exceptions_ = GTEST_FLAG(catch_exceptions); + color_ = GTEST_FLAG(color); + death_test_style_ = GTEST_FLAG(death_test_style); + death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); + filter_ = GTEST_FLAG(filter); + internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); + list_tests_ = GTEST_FLAG(list_tests); + output_ = GTEST_FLAG(output); + print_time_ = GTEST_FLAG(print_time); + random_seed_ = GTEST_FLAG(random_seed); + repeat_ = GTEST_FLAG(repeat); + shuffle_ = GTEST_FLAG(shuffle); + stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); + stream_result_to_ = GTEST_FLAG(stream_result_to); + throw_on_failure_ = GTEST_FLAG(throw_on_failure); + } + + // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. + ~GTestFlagSaver() { + GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; + GTEST_FLAG(break_on_failure) = break_on_failure_; + GTEST_FLAG(catch_exceptions) = catch_exceptions_; + GTEST_FLAG(color) = color_; + GTEST_FLAG(death_test_style) = death_test_style_; + GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; + GTEST_FLAG(filter) = filter_; + GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; + GTEST_FLAG(list_tests) = list_tests_; + GTEST_FLAG(output) = output_; + GTEST_FLAG(print_time) = print_time_; + GTEST_FLAG(random_seed) = random_seed_; + GTEST_FLAG(repeat) = repeat_; + GTEST_FLAG(shuffle) = shuffle_; + GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; + GTEST_FLAG(stream_result_to) = stream_result_to_; + GTEST_FLAG(throw_on_failure) = throw_on_failure_; + } + + private: + // Fields for saving the original values of flags. + bool also_run_disabled_tests_; + bool break_on_failure_; + bool catch_exceptions_; + std::string color_; + std::string death_test_style_; + bool death_test_use_fork_; + std::string filter_; + std::string internal_run_death_test_; + bool list_tests_; + std::string output_; + bool print_time_; + internal::Int32 random_seed_; + internal::Int32 repeat_; + bool shuffle_; + internal::Int32 stack_trace_depth_; + std::string stream_result_to_; + bool throw_on_failure_; +} GTEST_ATTRIBUTE_UNUSED_; + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded(); + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (e.g., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +GTEST_API_ bool ShouldShard(const char* total_shards_str, + const char* shard_index_str, + bool in_subprocess_for_death_test); + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error and +// and aborts. +GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +GTEST_API_ bool ShouldRunTestOnShard( + int total_shards, int shard_index, int test_id); + +// STL container utilities. + +// Returns the number of elements in the given container that satisfy +// the given predicate. +template +inline int CountIf(const Container& c, Predicate predicate) { + // Implemented as an explicit loop since std::count_if() in libCstd on + // Solaris has a non-standard signature. + int count = 0; + for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { + if (predicate(*it)) + ++count; + } + return count; +} + +// Applies a function/functor to each element in the container. +template +void ForEach(const Container& c, Functor functor) { + std::for_each(c.begin(), c.end(), functor); +} + +// Returns the i-th element of the vector, or default_value if i is not +// in range [0, v.size()). +template +inline E GetElementOr(const std::vector& v, int i, E default_value) { + return (i < 0 || i >= static_cast(v.size())) ? default_value : v[i]; +} + +// Performs an in-place shuffle of a range of the vector's elements. +// 'begin' and 'end' are element indices as an STL-style range; +// i.e. [begin, end) are shuffled, where 'end' == size() means to +// shuffle to the end of the vector. +template +void ShuffleRange(internal::Random* random, int begin, int end, + std::vector* v) { + const int size = static_cast(v->size()); + GTEST_CHECK_(0 <= begin && begin <= size) + << "Invalid shuffle range start " << begin << ": must be in range [0, " + << size << "]."; + GTEST_CHECK_(begin <= end && end <= size) + << "Invalid shuffle range finish " << end << ": must be in range [" + << begin << ", " << size << "]."; + + // Fisher-Yates shuffle, from + // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + for (int range_width = end - begin; range_width >= 2; range_width--) { + const int last_in_range = begin + range_width - 1; + const int selected = begin + random->Generate(range_width); + std::swap((*v)[selected], (*v)[last_in_range]); + } +} + +// Performs an in-place shuffle of the vector's elements. +template +inline void Shuffle(internal::Random* random, std::vector* v) { + ShuffleRange(random, 0, static_cast(v->size()), v); +} + +// A function for deleting an object. Handy for being used as a +// functor. +template +static void Delete(T* x) { + delete x; +} + +// A predicate that checks the key of a TestProperty against a known key. +// +// TestPropertyKeyIs is copyable. +class TestPropertyKeyIs { + public: + // Constructor. + // + // TestPropertyKeyIs has NO default constructor. + explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} + + // Returns true iff the test name of test property matches on key_. + bool operator()(const TestProperty& test_property) const { + return test_property.key() == key_; + } + + private: + std::string key_; +}; + +// Class UnitTestOptions. +// +// This class contains functions for processing options the user +// specifies when running the tests. It has only static members. +// +// In most cases, the user can specify an option using either an +// environment variable or a command line flag. E.g. you can set the +// test filter using either GTEST_FILTER or --gtest_filter. If both +// the variable and the flag are present, the latter overrides the +// former. +class GTEST_API_ UnitTestOptions { + public: + // Functions for processing the gtest_output flag. + + // Returns the output format, or "" for normal printed output. + static std::string GetOutputFormat(); + + // Returns the absolute path of the requested output file, or the + // default (test_detail.xml in the original working directory) if + // none was explicitly specified. + static std::string GetAbsolutePathToOutputFile(); + + // Functions for processing the gtest_filter flag. + + // Returns true iff the wildcard pattern matches the string. The + // first ':' or '\0' character in pattern marks the end of it. + // + // This recursive algorithm isn't very efficient, but is clear and + // works well enough for matching test names, which are short. + static bool PatternMatchesString(const char *pattern, const char *str); + + // Returns true iff the user-specified filter matches the test case + // name and the test name. + static bool FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name); + +#if GTEST_OS_WINDOWS + // Function for supporting the gtest_catch_exception flag. + + // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the + // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. + // This function is useful as an __except condition. + static int GTestShouldProcessSEH(DWORD exception_code); +#endif // GTEST_OS_WINDOWS + + // Returns true if "name" matches the ':' separated list of glob-style + // filters in "filter". + static bool MatchesFilter(const std::string& name, const char* filter); +}; + +// Returns the current application's name, removing directory path if that +// is present. Used by UnitTestOptions::GetOutputFile. +GTEST_API_ FilePath GetCurrentExecutableName(); + +// The role interface for getting the OS stack trace as a string. +class OsStackTraceGetterInterface { + public: + OsStackTraceGetterInterface() {} + virtual ~OsStackTraceGetterInterface() {} + + // Returns the current OS stack trace as an std::string. Parameters: + // + // max_depth - the maximum number of stack frames to be included + // in the trace. + // skip_count - the number of top frames to be skipped; doesn't count + // against max_depth. + virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; + + // UponLeavingGTest() should be called immediately before Google Test calls + // user code. It saves some information about the current stack that + // CurrentStackTrace() will use to find and hide Google Test stack frames. + virtual void UponLeavingGTest() = 0; + + // This string is inserted in place of stack frames that are part of + // Google Test's implementation. + static const char* const kElidedFramesMarker; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); +}; + +// A working implementation of the OsStackTraceGetterInterface interface. +class OsStackTraceGetter : public OsStackTraceGetterInterface { + public: + OsStackTraceGetter() {} + + virtual string CurrentStackTrace(int max_depth, int skip_count); + virtual void UponLeavingGTest(); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); +}; + +// Information about a Google Test trace point. +struct TraceInfo { + const char* file; + int line; + std::string message; +}; + +// This is the default global test part result reporter used in UnitTestImpl. +// This class should only be used by UnitTestImpl. +class DefaultGlobalTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. Reports the test part + // result in the current test. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); +}; + +// This is the default per thread test part result reporter used in +// UnitTestImpl. This class should only be used by UnitTestImpl. +class DefaultPerThreadTestPartResultReporter + : public TestPartResultReporterInterface { + public: + explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); + // Implements the TestPartResultReporterInterface. The implementation just + // delegates to the current global test part result reporter of *unit_test_. + virtual void ReportTestPartResult(const TestPartResult& result); + + private: + UnitTestImpl* const unit_test_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); +}; + +// The private implementation of the UnitTest class. We don't protect +// the methods under a mutex, as this class is not accessible by a +// user and the UnitTest class that delegates work to this class does +// proper locking. +class GTEST_API_ UnitTestImpl { + public: + explicit UnitTestImpl(UnitTest* parent); + virtual ~UnitTestImpl(); + + // There are two different ways to register your own TestPartResultReporter. + // You can register your own repoter to listen either only for test results + // from the current thread or for results from all threads. + // By default, each per-thread test result repoter just passes a new + // TestPartResult to the global test result reporter, which registers the + // test part result for the currently running test. + + // Returns the global test part result reporter. + TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); + + // Sets the global test part result reporter. + void SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter); + + // Returns the test part result reporter for the current thread. + TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); + + // Sets the test part result reporter for the current thread. + void SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter); + + // Gets the number of successful test cases. + int successful_test_case_count() const; + + // Gets the number of failed test cases. + int failed_test_case_count() const; + + // Gets the number of all test cases. + int total_test_case_count() const; + + // Gets the number of all test cases that contain at least one test + // that should run. + int test_case_to_run_count() const; + + // Gets the number of successful tests. + int successful_test_count() const; + + // Gets the number of failed tests. + int failed_test_count() const; + + // Gets the number of disabled tests that will be reported in the XML report. + int reportable_disabled_test_count() const; + + // Gets the number of disabled tests. + int disabled_test_count() const; + + // Gets the number of tests to be printed in the XML report. + int reportable_test_count() const; + + // Gets the number of all tests. + int total_test_count() const; + + // Gets the number of tests that should run. + int test_to_run_count() const; + + // Gets the time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp() const { return start_timestamp_; } + + // Gets the elapsed time, in milliseconds. + TimeInMillis elapsed_time() const { return elapsed_time_; } + + // Returns true iff the unit test passed (i.e. all test cases passed). + bool Passed() const { return !Failed(); } + + // Returns true iff the unit test failed (i.e. some test case failed + // or something outside of all tests failed). + bool Failed() const { + return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + const TestCase* GetTestCase(int i) const { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[i]; + } + + // Gets the i-th test case among all the test cases. i can range from 0 to + // total_test_case_count() - 1. If i is not in that range, returns NULL. + TestCase* GetMutableTestCase(int i) { + const int index = GetElementOr(test_case_indices_, i, -1); + return index < 0 ? NULL : test_cases_[index]; + } + + // Provides access to the event listener list. + TestEventListeners* listeners() { return &listeners_; } + + // Returns the TestResult for the test that's currently running, or + // the TestResult for the ad hoc test if no test is running. + TestResult* current_test_result(); + + // Returns the TestResult for the ad hoc test. + const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } + + // Sets the OS stack trace getter. + // + // Does nothing if the input and the current OS stack trace getter + // are the same; otherwise, deletes the old getter and makes the + // input the current getter. + void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); + + // Returns the current OS stack trace getter if it is not NULL; + // otherwise, creates an OsStackTraceGetter, makes it the current + // getter, and returns it. + OsStackTraceGetterInterface* os_stack_trace_getter(); + + // Returns the current OS stack trace as an std::string. + // + // The maximum number of stack frames to be included is specified by + // the gtest_stack_trace_depth flag. The skip_count parameter + // specifies the number of top frames to be skipped, which doesn't + // count against the number of frames to be included. + // + // For example, if Foo() calls Bar(), which in turn calls + // CurrentOsStackTraceExceptTop(1), Foo() will be included in the + // trace but Bar() and CurrentOsStackTraceExceptTop() won't. + std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; + + // Finds and returns a TestCase with the given name. If one doesn't + // exist, creates one and returns it. + // + // Arguments: + // + // test_case_name: name of the test case + // type_param: the name of the test's type parameter, or NULL if + // this is not a typed or a type-parameterized test. + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + TestCase* GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc); + + // Adds a TestInfo to the unit test. + // + // Arguments: + // + // set_up_tc: pointer to the function that sets up the test case + // tear_down_tc: pointer to the function that tears down the test case + // test_info: the TestInfo object + void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, + TestInfo* test_info) { + // In order to support thread-safe death tests, we need to + // remember the original working directory when the test program + // was first invoked. We cannot do this in RUN_ALL_TESTS(), as + // the user may have changed the current directory before calling + // RUN_ALL_TESTS(). Therefore we capture the current directory in + // AddTestInfo(), which is called to register a TEST or TEST_F + // before main() is reached. + if (original_working_dir_.IsEmpty()) { + original_working_dir_.Set(FilePath::GetCurrentDir()); + GTEST_CHECK_(!original_working_dir_.IsEmpty()) + << "Failed to get the current working directory."; + } + + GetTestCase(test_info->test_case_name(), + test_info->type_param(), + set_up_tc, + tear_down_tc)->AddTestInfo(test_info); + } + +#if GTEST_HAS_PARAM_TEST + // Returns ParameterizedTestCaseRegistry object used to keep track of + // value-parameterized tests and instantiate and register them. + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { + return parameterized_test_registry_; + } +#endif // GTEST_HAS_PARAM_TEST + + // Sets the TestCase object for the test that's currently running. + void set_current_test_case(TestCase* a_current_test_case) { + current_test_case_ = a_current_test_case; + } + + // Sets the TestInfo object for the test that's currently running. If + // current_test_info is NULL, the assertion results will be stored in + // ad_hoc_test_result_. + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; + } + + // Registers all parameterized tests defined using TEST_P and + // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter + // combination. This method can be called more then once; it has guards + // protecting from registering the tests more then once. If + // value-parameterized tests are disabled, RegisterParameterizedTests is + // present but does nothing. + void RegisterParameterizedTests(); + + // Runs all tests in this UnitTest object, prints the result, and + // returns true if all tests are successful. If any exception is + // thrown during a test, this test is considered to be failed, but + // the rest of the tests will still be run. + bool RunAllTests(); + + // Clears the results of all tests, except the ad hoc tests. + void ClearNonAdHocTestResult() { + ForEach(test_cases_, TestCase::ClearTestCaseResult); + } + + // Clears the results of ad-hoc test assertions. + void ClearAdHocTestResult() { + ad_hoc_test_result_.Clear(); + } + + // Adds a TestProperty to the current TestResult object when invoked in a + // context of a test or a test case, or to the global property set. If the + // result already contains a property with the same key, the value will be + // updated. + void RecordProperty(const TestProperty& test_property); + + enum ReactionToSharding { + HONOR_SHARDING_PROTOCOL, + IGNORE_SHARDING_PROTOCOL + }; + + // Matches the full name of each test against the user-specified + // filter to decide whether the test should run, then records the + // result in each TestCase and TestInfo object. + // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests + // based on sharding variables in the environment. + // Returns the number of tests that should run. + int FilterTests(ReactionToSharding shard_tests); + + // Prints the names of the tests matching the user-specified filter flag. + void ListTestsMatchingFilter(); + + const TestCase* current_test_case() const { return current_test_case_; } + TestInfo* current_test_info() { return current_test_info_; } + const TestInfo* current_test_info() const { return current_test_info_; } + + // Returns the vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector& environments() { return environments_; } + + // Getters for the per-thread Google Test trace stack. + std::vector& gtest_trace_stack() { + return *(gtest_trace_stack_.pointer()); + } + const std::vector& gtest_trace_stack() const { + return gtest_trace_stack_.get(); + } + +#if GTEST_HAS_DEATH_TEST + void InitDeathTestSubprocessControlInfo() { + internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); + } + // Returns a pointer to the parsed --gtest_internal_run_death_test + // flag, or NULL if that flag was not specified. + // This information is useful only in a death test child process. + // Must not be called before a call to InitGoogleTest. + const InternalRunDeathTestFlag* internal_run_death_test_flag() const { + return internal_run_death_test_flag_.get(); + } + + // Returns a pointer to the current death test factory. + internal::DeathTestFactory* death_test_factory() { + return death_test_factory_.get(); + } + + void SuppressTestEventsIfInSubprocess(); + + friend class ReplaceDeathTestFactory; +#endif // GTEST_HAS_DEATH_TEST + + // Initializes the event listener performing XML output as specified by + // UnitTestOptions. Must not be called before InitGoogleTest. + void ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Initializes the event listener for streaming test results to a socket. + // Must not be called before InitGoogleTest. + void ConfigureStreamingOutput(); +#endif + + // Performs initialization dependent upon flag values obtained in + // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to + // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest + // this function is also called from RunAllTests. Since this function can be + // called more than once, it has to be idempotent. + void PostFlagParsingInit(); + + // Gets the random seed used at the start of the current test iteration. + int random_seed() const { return random_seed_; } + + // Gets the random number generator. + internal::Random* random() { return &random_; } + + // Shuffles all test cases, and the tests within each test case, + // making sure that death tests are still run first. + void ShuffleTests(); + + // Restores the test cases and tests to their order before the first shuffle. + void UnshuffleTests(); + + // Returns the value of GTEST_FLAG(catch_exceptions) at the moment + // UnitTest::Run() starts. + bool catch_exceptions() const { return catch_exceptions_; } + + private: + friend class ::testing::UnitTest; + + // Used by UnitTest::Run() to capture the state of + // GTEST_FLAG(catch_exceptions) at the moment it starts. + void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + + // The UnitTest object that owns this implementation object. + UnitTest* const parent_; + + // The working directory when the first TEST() or TEST_F() was + // executed. + internal::FilePath original_working_dir_; + + // The default test part result reporters. + DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; + DefaultPerThreadTestPartResultReporter + default_per_thread_test_part_result_reporter_; + + // Points to (but doesn't own) the global test part result reporter. + TestPartResultReporterInterface* global_test_part_result_repoter_; + + // Protects read and write access to global_test_part_result_reporter_. + internal::Mutex global_test_part_result_reporter_mutex_; + + // Points to (but doesn't own) the per-thread test part result reporter. + internal::ThreadLocal + per_thread_test_part_result_reporter_; + + // The vector of environments that need to be set-up/torn-down + // before/after the tests are run. + std::vector environments_; + + // The vector of TestCases in their original order. It owns the + // elements in the vector. + std::vector test_cases_; + + // Provides a level of indirection for the test case list to allow + // easy shuffling and restoring the test case order. The i-th + // element of this vector is the index of the i-th test case in the + // shuffled order. + std::vector test_case_indices_; + +#if GTEST_HAS_PARAM_TEST + // ParameterizedTestRegistry object used to register value-parameterized + // tests. + internal::ParameterizedTestCaseRegistry parameterized_test_registry_; + + // Indicates whether RegisterParameterizedTests() has been called already. + bool parameterized_tests_registered_; +#endif // GTEST_HAS_PARAM_TEST + + // Index of the last death test case registered. Initially -1. + int last_death_test_case_; + + // This points to the TestCase for the currently running test. It + // changes as Google Test goes through one test case after another. + // When no test is running, this is set to NULL and Google Test + // stores assertion results in ad_hoc_test_result_. Initially NULL. + TestCase* current_test_case_; + + // This points to the TestInfo for the currently running test. It + // changes as Google Test goes through one test after another. When + // no test is running, this is set to NULL and Google Test stores + // assertion results in ad_hoc_test_result_. Initially NULL. + TestInfo* current_test_info_; + + // Normally, a user only writes assertions inside a TEST or TEST_F, + // or inside a function called by a TEST or TEST_F. Since Google + // Test keeps track of which test is current running, it can + // associate such an assertion with the test it belongs to. + // + // If an assertion is encountered when no TEST or TEST_F is running, + // Google Test attributes the assertion result to an imaginary "ad hoc" + // test, and records the result in ad_hoc_test_result_. + TestResult ad_hoc_test_result_; + + // The list of event listeners that can be used to track events inside + // Google Test. + TestEventListeners listeners_; + + // The OS stack trace getter. Will be deleted when the UnitTest + // object is destructed. By default, an OsStackTraceGetter is used, + // but the user can set this field to use a custom getter if that is + // desired. + OsStackTraceGetterInterface* os_stack_trace_getter_; + + // True iff PostFlagParsingInit() has been called. + bool post_flag_parse_init_performed_; + + // The random number seed used at the beginning of the test run. + int random_seed_; + + // Our random number generator. + internal::Random random_; + + // The time of the test program start, in ms from the start of the + // UNIX epoch. + TimeInMillis start_timestamp_; + + // How long the test took to run, in milliseconds. + TimeInMillis elapsed_time_; + +#if GTEST_HAS_DEATH_TEST + // The decomposed components of the gtest_internal_run_death_test flag, + // parsed when RUN_ALL_TESTS is called. + internal::scoped_ptr internal_run_death_test_flag_; + internal::scoped_ptr death_test_factory_; +#endif // GTEST_HAS_DEATH_TEST + + // A per-thread stack of traces created by the SCOPED_TRACE() macro. + internal::ThreadLocal > gtest_trace_stack_; + + // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() + // starts. + bool catch_exceptions_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); +}; // class UnitTestImpl + +// Convenience function for accessing the global UnitTest +// implementation object. +inline UnitTestImpl* GetUnitTestImpl() { + return UnitTest::GetInstance()->impl(); +} + +#if GTEST_USES_SIMPLE_RE + +// Internal helper functions for implementing the simple regular +// expression matcher. +GTEST_API_ bool IsInSet(char ch, const char* str); +GTEST_API_ bool IsAsciiDigit(char ch); +GTEST_API_ bool IsAsciiPunct(char ch); +GTEST_API_ bool IsRepeat(char ch); +GTEST_API_ bool IsAsciiWhiteSpace(char ch); +GTEST_API_ bool IsAsciiWordChar(char ch); +GTEST_API_ bool IsValidEscape(char ch); +GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); +GTEST_API_ bool ValidateRegex(const char* regex); +GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead( + bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); + +#endif // GTEST_USES_SIMPLE_RE + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); +GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); + +#if GTEST_HAS_DEATH_TEST + +// Returns the message describing the last system error, regardless of the +// platform. +GTEST_API_ std::string GetLastErrnoDescription(); + +// Attempts to parse a string into a positive integer pointed to by the +// number parameter. Returns true if that is possible. +// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use +// it here. +template +bool ParseNaturalNumber(const ::std::string& str, Integer* number) { + // Fail fast if the given string does not begin with a digit; + // this bypasses strtoXXX's "optional leading whitespace and plus + // or minus sign" semantics, which are undesirable here. + if (str.empty() || !IsDigit(str[0])) { + return false; + } + errno = 0; + + char* end; + // BiggestConvertible is the largest integer type that system-provided + // string-to-number conversion routines can return. + +# if GTEST_OS_WINDOWS && !defined(__GNUC__) + + // MSVC and C++ Builder define __int64 instead of the standard long long. + typedef unsigned __int64 BiggestConvertible; + const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); + +# else + + typedef unsigned long long BiggestConvertible; // NOLINT + const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); + +# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) + + const bool parse_success = *end == '\0' && errno == 0; + + // TODO(vladl@google.com): Convert this to compile time assertion when it is + // available. + GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); + + const Integer result = static_cast(parsed); + if (parse_success && static_cast(result) == parsed) { + *number = result; + return true; + } + return false; +} +#endif // GTEST_HAS_DEATH_TEST + +// TestResult contains some private methods that should be hidden from +// Google Test user but are required for testing. This class allow our tests +// to access them. +// +// This class is supplied only for the purpose of testing Google Test's own +// constructs. Do not use it in user tests, either directly or indirectly. +class TestResultAccessor { + public: + static void RecordProperty(TestResult* test_result, + const std::string& xml_element, + const TestProperty& property) { + test_result->RecordProperty(xml_element, property); + } + + static void ClearTestPartResults(TestResult* test_result) { + test_result->ClearTestPartResults(); + } + + static const std::vector& test_part_results( + const TestResult& test_result) { + return test_result.test_part_results(); + } +}; + +#if GTEST_CAN_STREAM_RESULTS_ + +// Streams test results to the given port on the given host machine. +class GTEST_API_ StreamingListener : public EmptyTestEventListener { + public: + // Abstract base class for writing strings to a socket. + class AbstractSocketWriter { + public: + virtual ~AbstractSocketWriter() {} + + // Sends a string to the socket. + virtual void Send(const string& message) = 0; + + // Closes the socket. + virtual void CloseConnection() {} + + // Sends a string and a newline to the socket. + void SendLn(const string& message) { + Send(message + "\n"); + } + }; + + // Concrete class for actually writing strings to a socket. + class SocketWriter : public AbstractSocketWriter { + public: + SocketWriter(const string& host, const string& port) + : sockfd_(-1), host_name_(host), port_num_(port) { + MakeConnection(); + } + + virtual ~SocketWriter() { + if (sockfd_ != -1) + CloseConnection(); + } + + // Sends a string to the socket. + virtual void Send(const string& message) { + GTEST_CHECK_(sockfd_ != -1) + << "Send() can be called only when there is a connection."; + + const int len = static_cast(message.length()); + if (write(sockfd_, message.c_str(), len) != len) { + GTEST_LOG_(WARNING) + << "stream_result_to: failed to stream to " + << host_name_ << ":" << port_num_; + } + } + + private: + // Creates a client socket and connects to the server. + void MakeConnection(); + + // Closes the socket. + void CloseConnection() { + GTEST_CHECK_(sockfd_ != -1) + << "CloseConnection() can be called only when there is a connection."; + + close(sockfd_); + sockfd_ = -1; + } + + int sockfd_; // socket file descriptor + const string host_name_; + const string port_num_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); + }; // class SocketWriter + + // Escapes '=', '&', '%', and '\n' characters in str as "%xx". + static string UrlEncode(const char* str); + + StreamingListener(const string& host, const string& port) + : socket_writer_(new SocketWriter(host, port)) { Start(); } + + explicit StreamingListener(AbstractSocketWriter* socket_writer) + : socket_writer_(socket_writer) { Start(); } + + void OnTestProgramStart(const UnitTest& /* unit_test */) { + SendLn("event=TestProgramStart"); + } + + void OnTestProgramEnd(const UnitTest& unit_test) { + // Note that Google Test current only report elapsed time for each + // test iteration, not for the entire test program. + SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); + + // Notify the streaming server to stop. + socket_writer_->CloseConnection(); + } + + void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { + SendLn("event=TestIterationStart&iteration=" + + StreamableToString(iteration)); + } + + void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { + SendLn("event=TestIterationEnd&passed=" + + FormatBool(unit_test.Passed()) + "&elapsed_time=" + + StreamableToString(unit_test.elapsed_time()) + "ms"); + } + + void OnTestCaseStart(const TestCase& test_case) { + SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); + } + + void OnTestCaseEnd(const TestCase& test_case) { + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + + "ms"); + } + + void OnTestStart(const TestInfo& test_info) { + SendLn(std::string("event=TestStart&name=") + test_info.name()); + } + + void OnTestEnd(const TestInfo& test_info) { + SendLn("event=TestEnd&passed=" + + FormatBool((test_info.result())->Passed()) + + "&elapsed_time=" + + StreamableToString((test_info.result())->elapsed_time()) + "ms"); + } + + void OnTestPartResult(const TestPartResult& test_part_result) { + const char* file_name = test_part_result.file_name(); + if (file_name == NULL) + file_name = ""; + SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + + "&line=" + StreamableToString(test_part_result.line_number()) + + "&message=" + UrlEncode(test_part_result.message())); + } + + private: + // Sends the given message and a newline to the socket. + void SendLn(const string& message) { socket_writer_->SendLn(message); } + + // Called at the start of streaming to notify the receiver what + // protocol we are using. + void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } + + string FormatBool(bool value) { return value ? "1" : "0"; } + + const scoped_ptr socket_writer_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); +}; // class StreamingListener + +#endif // GTEST_CAN_STREAM_RESULTS_ + +} // namespace internal +} // namespace testing + +#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ diff --git a/gtestsrc/gtest/src/gtest-port.cc b/gtestsrc/gtest/src/gtest-port.cc new file mode 100644 index 0000000..e5bf3dd --- /dev/null +++ b/gtestsrc/gtest/src/gtest-port.cc @@ -0,0 +1,1259 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/internal/gtest-port.h" + +#include +#include +#include +#include +#include + +#if GTEST_OS_WINDOWS +# include +# include +# include +# include // Used in ThreadLocal. +#else +# include +#endif // GTEST_OS_WINDOWS + +#if GTEST_OS_MAC +# include +# include +# include +#endif // GTEST_OS_MAC + +#if GTEST_OS_QNX +# include +# include +# include +#endif // GTEST_OS_QNX + +#if GTEST_OS_AIX +# include +# include +#endif // GTEST_OS_AIX + +#include "gtest/gtest-spi.h" +#include "gtest/gtest-message.h" +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { +namespace internal { + +#if defined(_MSC_VER) || defined(__BORLANDC__) +// MSVC and C++Builder do not provide a definition of STDERR_FILENO. +const int kStdOutFileno = 1; +const int kStdErrFileno = 2; +#else +const int kStdOutFileno = STDOUT_FILENO; +const int kStdErrFileno = STDERR_FILENO; +#endif // _MSC_VER + +#if GTEST_OS_LINUX + +namespace { +template +T ReadProcFileField(const string& filename, int field) { + std::string dummy; + std::ifstream file(filename.c_str()); + while (field-- > 0) { + file >> dummy; + } + T output = 0; + file >> output; + return output; +} +} // namespace + +// Returns the number of active threads, or 0 when there is an error. +size_t GetThreadCount() { + const string filename = + (Message() << "/proc/" << getpid() << "/stat").GetString(); + return ReadProcFileField(filename, 19); +} + +#elif GTEST_OS_MAC + +size_t GetThreadCount() { + const task_t task = mach_task_self(); + mach_msg_type_number_t thread_count; + thread_act_array_t thread_list; + const kern_return_t status = task_threads(task, &thread_list, &thread_count); + if (status == KERN_SUCCESS) { + // task_threads allocates resources in thread_list and we need to free them + // to avoid leaks. + vm_deallocate(task, + reinterpret_cast(thread_list), + sizeof(thread_t) * thread_count); + return static_cast(thread_count); + } else { + return 0; + } +} + +#elif GTEST_OS_QNX + +// Returns the number of threads running in the process, or 0 to indicate that +// we cannot detect it. +size_t GetThreadCount() { + const int fd = open("/proc/self/as", O_RDONLY); + if (fd < 0) { + return 0; + } + procfs_info process_info; + const int status = + devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); + close(fd); + if (status == EOK) { + return static_cast(process_info.num_threads); + } else { + return 0; + } +} + +#elif GTEST_OS_AIX + +size_t GetThreadCount() { + struct procentry64 entry; + pid_t pid = getpid(); + int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1); + if (status == 1) { + return entry.pi_thcount; + } else { + return 0; + } +} + +#else + +size_t GetThreadCount() { + // There's no portable way to detect the number of threads, so we just + // return 0 to indicate that we cannot detect it. + return 0; +} + +#endif // GTEST_OS_LINUX + +#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS + +void SleepMilliseconds(int n) { + ::Sleep(n); +} + +AutoHandle::AutoHandle() + : handle_(INVALID_HANDLE_VALUE) {} + +AutoHandle::AutoHandle(Handle handle) + : handle_(handle) {} + +AutoHandle::~AutoHandle() { + Reset(); +} + +AutoHandle::Handle AutoHandle::Get() const { + return handle_; +} + +void AutoHandle::Reset() { + Reset(INVALID_HANDLE_VALUE); +} + +void AutoHandle::Reset(HANDLE handle) { + // Resetting with the same handle we already own is invalid. + if (handle_ != handle) { + if (IsCloseable()) { + ::CloseHandle(handle_); + } + handle_ = handle; + } else { + GTEST_CHECK_(!IsCloseable()) + << "Resetting a valid handle to itself is likely a programmer error " + "and thus not allowed."; + } +} + +bool AutoHandle::IsCloseable() const { + // Different Windows APIs may use either of these values to represent an + // invalid handle. + return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE; +} + +Notification::Notification() + : event_(::CreateEvent(NULL, // Default security attributes. + TRUE, // Do not reset automatically. + FALSE, // Initially unset. + NULL)) { // Anonymous event. + GTEST_CHECK_(event_.Get() != NULL); +} + +void Notification::Notify() { + GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); +} + +void Notification::WaitForNotification() { + GTEST_CHECK_( + ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); +} + +Mutex::Mutex() + : owner_thread_id_(0), + type_(kDynamic), + critical_section_init_phase_(0), + critical_section_(new CRITICAL_SECTION) { + ::InitializeCriticalSection(critical_section_); +} + +Mutex::~Mutex() { + // Static mutexes are leaked intentionally. It is not thread-safe to try + // to clean them up. + // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires + // nothing to clean it up but is available only on Vista and later. + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx + if (type_ == kDynamic) { + ::DeleteCriticalSection(critical_section_); + delete critical_section_; + critical_section_ = NULL; + } +} + +void Mutex::Lock() { + ThreadSafeLazyInit(); + ::EnterCriticalSection(critical_section_); + owner_thread_id_ = ::GetCurrentThreadId(); +} + +void Mutex::Unlock() { + ThreadSafeLazyInit(); + // We don't protect writing to owner_thread_id_ here, as it's the + // caller's responsibility to ensure that the current thread holds the + // mutex when this is called. + owner_thread_id_ = 0; + ::LeaveCriticalSection(critical_section_); +} + +// Does nothing if the current thread holds the mutex. Otherwise, crashes +// with high probability. +void Mutex::AssertHeld() { + ThreadSafeLazyInit(); + GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) + << "The current thread is not holding the mutex @" << this; +} + +// Initializes owner_thread_id_ and critical_section_ in static mutexes. +void Mutex::ThreadSafeLazyInit() { + // Dynamic mutexes are initialized in the constructor. + if (type_ == kStatic) { + switch ( + ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { + case 0: + // If critical_section_init_phase_ was 0 before the exchange, we + // are the first to test it and need to perform the initialization. + owner_thread_id_ = 0; + critical_section_ = new CRITICAL_SECTION; + ::InitializeCriticalSection(critical_section_); + // Updates the critical_section_init_phase_ to 2 to signal + // initialization complete. + GTEST_CHECK_(::InterlockedCompareExchange( + &critical_section_init_phase_, 2L, 1L) == + 1L); + break; + case 1: + // Somebody else is already initializing the mutex; spin until they + // are done. + while (::InterlockedCompareExchange(&critical_section_init_phase_, + 2L, + 2L) != 2L) { + // Possibly yields the rest of the thread's time slice to other + // threads. + ::Sleep(0); + } + break; + + case 2: + break; // The mutex is already initialized and ready for use. + + default: + GTEST_CHECK_(false) + << "Unexpected value of critical_section_init_phase_ " + << "while initializing a static mutex."; + } + } +} + +namespace { + +class ThreadWithParamSupport : public ThreadWithParamBase { + public: + static HANDLE CreateThread(Runnable* runnable, + Notification* thread_can_start) { + ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); + DWORD thread_id; + // TODO(yukawa): Consider to use _beginthreadex instead. + HANDLE thread_handle = ::CreateThread( + NULL, // Default security. + 0, // Default stack size. + &ThreadWithParamSupport::ThreadMain, + param, // Parameter to ThreadMainStatic + 0x0, // Default creation flags. + &thread_id); // Need a valid pointer for the call to work under Win98. + GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " + << ::GetLastError() << "."; + if (thread_handle == NULL) { + delete param; + } + return thread_handle; + } + + private: + struct ThreadMainParam { + ThreadMainParam(Runnable* runnable, Notification* thread_can_start) + : runnable_(runnable), + thread_can_start_(thread_can_start) { + } + scoped_ptr runnable_; + // Does not own. + Notification* thread_can_start_; + }; + + static DWORD WINAPI ThreadMain(void* ptr) { + // Transfers ownership. + scoped_ptr param(static_cast(ptr)); + if (param->thread_can_start_ != NULL) + param->thread_can_start_->WaitForNotification(); + param->runnable_->Run(); + return 0; + } + + // Prohibit instantiation. + ThreadWithParamSupport(); + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); +}; + +} // namespace + +ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, + Notification* thread_can_start) + : thread_(ThreadWithParamSupport::CreateThread(runnable, + thread_can_start)) { +} + +ThreadWithParamBase::~ThreadWithParamBase() { + Join(); +} + +void ThreadWithParamBase::Join() { + GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) + << "Failed to join the thread with error " << ::GetLastError() << "."; +} + +// Maps a thread to a set of ThreadIdToThreadLocals that have values +// instantiated on that thread and notifies them when the thread exits. A +// ThreadLocal instance is expected to persist until all threads it has +// values on have terminated. +class ThreadLocalRegistryImpl { + public: + // Registers thread_local_instance as having value on the current thread. + // Returns a value that can be used to identify the thread from other threads. + static ThreadLocalValueHolderBase* GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance) { + DWORD current_thread = ::GetCurrentThreadId(); + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = + thread_to_thread_locals->find(current_thread); + if (thread_local_pos == thread_to_thread_locals->end()) { + thread_local_pos = thread_to_thread_locals->insert( + std::make_pair(current_thread, ThreadLocalValues())).first; + StartWatcherThreadFor(current_thread); + } + ThreadLocalValues& thread_local_values = thread_local_pos->second; + ThreadLocalValues::iterator value_pos = + thread_local_values.find(thread_local_instance); + if (value_pos == thread_local_values.end()) { + value_pos = + thread_local_values + .insert(std::make_pair( + thread_local_instance, + linked_ptr( + thread_local_instance->NewValueForCurrentThread()))) + .first; + } + return value_pos->second.get(); + } + + static void OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance) { + std::vector > value_holders; + // Clean up the ThreadLocalValues data structure while holding the lock, but + // defer the destruction of the ThreadLocalValueHolderBases. + { + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + for (ThreadIdToThreadLocals::iterator it = + thread_to_thread_locals->begin(); + it != thread_to_thread_locals->end(); + ++it) { + ThreadLocalValues& thread_local_values = it->second; + ThreadLocalValues::iterator value_pos = + thread_local_values.find(thread_local_instance); + if (value_pos != thread_local_values.end()) { + value_holders.push_back(value_pos->second); + thread_local_values.erase(value_pos); + // This 'if' can only be successful at most once, so theoretically we + // could break out of the loop here, but we don't bother doing so. + } + } + } + // Outside the lock, let the destructor for 'value_holders' deallocate the + // ThreadLocalValueHolderBases. + } + + static void OnThreadExit(DWORD thread_id) { + GTEST_CHECK_(thread_id != 0) << ::GetLastError(); + std::vector > value_holders; + // Clean up the ThreadIdToThreadLocals data structure while holding the + // lock, but defer the destruction of the ThreadLocalValueHolderBases. + { + MutexLock lock(&mutex_); + ThreadIdToThreadLocals* const thread_to_thread_locals = + GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = + thread_to_thread_locals->find(thread_id); + if (thread_local_pos != thread_to_thread_locals->end()) { + ThreadLocalValues& thread_local_values = thread_local_pos->second; + for (ThreadLocalValues::iterator value_pos = + thread_local_values.begin(); + value_pos != thread_local_values.end(); + ++value_pos) { + value_holders.push_back(value_pos->second); + } + thread_to_thread_locals->erase(thread_local_pos); + } + } + // Outside the lock, let the destructor for 'value_holders' deallocate the + // ThreadLocalValueHolderBases. + } + + private: + // In a particular thread, maps a ThreadLocal object to its value. + typedef std::map > ThreadLocalValues; + // Stores all ThreadIdToThreadLocals having values in a thread, indexed by + // thread's ID. + typedef std::map ThreadIdToThreadLocals; + + // Holds the thread id and thread handle that we pass from + // StartWatcherThreadFor to WatcherThreadFunc. + typedef std::pair ThreadIdAndHandle; + + static void StartWatcherThreadFor(DWORD thread_id) { + // The returned handle will be kept in thread_map and closed by + // watcher_thread in WatcherThreadFunc. + HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, + FALSE, + thread_id); + GTEST_CHECK_(thread != NULL); + // We need to to pass a valid thread ID pointer into CreateThread for it + // to work correctly under Win98. + DWORD watcher_thread_id; + HANDLE watcher_thread = ::CreateThread( + NULL, // Default security. + 0, // Default stack size + &ThreadLocalRegistryImpl::WatcherThreadFunc, + reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), + CREATE_SUSPENDED, + &watcher_thread_id); + GTEST_CHECK_(watcher_thread != NULL); + // Give the watcher thread the same priority as ours to avoid being + // blocked by it. + ::SetThreadPriority(watcher_thread, + ::GetThreadPriority(::GetCurrentThread())); + ::ResumeThread(watcher_thread); + ::CloseHandle(watcher_thread); + } + + // Monitors exit from a given thread and notifies those + // ThreadIdToThreadLocals about thread termination. + static DWORD WINAPI WatcherThreadFunc(LPVOID param) { + const ThreadIdAndHandle* tah = + reinterpret_cast(param); + GTEST_CHECK_( + ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); + OnThreadExit(tah->first); + ::CloseHandle(tah->second); + delete tah; + return 0; + } + + // Returns map of thread local instances. + static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { + mutex_.AssertHeld(); + static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals; + return map; + } + + // Protects access to GetThreadLocalsMapLocked() and its return value. + static Mutex mutex_; + // Protects access to GetThreadMapLocked() and its return value. + static Mutex thread_map_mutex_; +}; + +Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); +Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); + +ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( + const ThreadLocalBase* thread_local_instance) { + return ThreadLocalRegistryImpl::GetValueOnCurrentThread( + thread_local_instance); +} + +void ThreadLocalRegistry::OnThreadLocalDestroyed( + const ThreadLocalBase* thread_local_instance) { + ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); +} + +#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS + +#if GTEST_USES_POSIX_RE + +// Implements RE. Currently only needed for death tests. + +RE::~RE() { + if (is_valid_) { + // regfree'ing an invalid regex might crash because the content + // of the regex is undefined. Since the regex's are essentially + // the same, one cannot be valid (or invalid) without the other + // being so too. + regfree(&partial_regex_); + regfree(&full_regex_); + } + free(const_cast(pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.full_regex_, str, 1, &match, 0) == 0; +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + if (!re.is_valid_) return false; + + regmatch_t match; + return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = posix::StrDup(regex); + + // Reserves enough bytes to hold the regular expression used for a + // full match. + const size_t full_regex_len = strlen(regex) + 10; + char* const full_pattern = new char[full_regex_len]; + + snprintf(full_pattern, full_regex_len, "^(%s)$", regex); + is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; + // We want to call regcomp(&partial_regex_, ...) even if the + // previous expression returns false. Otherwise partial_regex_ may + // not be properly initialized can may cause trouble when it's + // freed. + // + // Some implementation of POSIX regex (e.g. on at least some + // versions of Cygwin) doesn't accept the empty string as a valid + // regex. We change it to an equivalent form "()" to be safe. + if (is_valid_) { + const char* const partial_regex = (*regex == '\0') ? "()" : regex; + is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + } + EXPECT_TRUE(is_valid_) + << "Regular expression \"" << regex + << "\" is not a valid POSIX Extended regular expression."; + + delete[] full_pattern; +} + +#elif GTEST_USES_SIMPLE_RE + +// Returns true iff ch appears anywhere in str (excluding the +// terminating '\0' character). +bool IsInSet(char ch, const char* str) { + return ch != '\0' && strchr(str, ch) != NULL; +} + +// Returns true iff ch belongs to the given classification. Unlike +// similar functions in , these aren't affected by the +// current locale. +bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } +bool IsAsciiPunct(char ch) { + return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); +} +bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } +bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } +bool IsAsciiWordChar(char ch) { + return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || + ('0' <= ch && ch <= '9') || ch == '_'; +} + +// Returns true iff "\\c" is a supported escape sequence. +bool IsValidEscape(char c) { + return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); +} + +// Returns true iff the given atom (specified by escaped and pattern) +// matches ch. The result is undefined if the atom is invalid. +bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { + if (escaped) { // "\\p" where p is pattern_char. + switch (pattern_char) { + case 'd': return IsAsciiDigit(ch); + case 'D': return !IsAsciiDigit(ch); + case 'f': return ch == '\f'; + case 'n': return ch == '\n'; + case 'r': return ch == '\r'; + case 's': return IsAsciiWhiteSpace(ch); + case 'S': return !IsAsciiWhiteSpace(ch); + case 't': return ch == '\t'; + case 'v': return ch == '\v'; + case 'w': return IsAsciiWordChar(ch); + case 'W': return !IsAsciiWordChar(ch); + } + return IsAsciiPunct(pattern_char) && pattern_char == ch; + } + + return (pattern_char == '.' && ch != '\n') || pattern_char == ch; +} + +// Helper function used by ValidateRegex() to format error messages. +std::string FormatRegexSyntaxError(const char* regex, int index) { + return (Message() << "Syntax error at index " << index + << " in simple regular expression \"" << regex << "\": ").GetString(); +} + +// Generates non-fatal failures and returns false if regex is invalid; +// otherwise returns true. +bool ValidateRegex(const char* regex) { + if (regex == NULL) { + // TODO(wan@google.com): fix the source file location in the + // assertion failures to match where the regex is used in user + // code. + ADD_FAILURE() << "NULL is not a valid simple regular expression."; + return false; + } + + bool is_valid = true; + + // True iff ?, *, or + can follow the previous atom. + bool prev_repeatable = false; + for (int i = 0; regex[i]; i++) { + if (regex[i] == '\\') { // An escape sequence + i++; + if (regex[i] == '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "'\\' cannot appear at the end."; + return false; + } + + if (!IsValidEscape(regex[i])) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) + << "invalid escape sequence \"\\" << regex[i] << "\"."; + is_valid = false; + } + prev_repeatable = true; + } else { // Not an escape sequence. + const char ch = regex[i]; + + if (ch == '^' && i > 0) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'^' can only appear at the beginning."; + is_valid = false; + } else if (ch == '$' && regex[i + 1] != '\0') { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'$' can only appear at the end."; + is_valid = false; + } else if (IsInSet(ch, "()[]{}|")) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' is unsupported."; + is_valid = false; + } else if (IsRepeat(ch) && !prev_repeatable) { + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) + << "'" << ch << "' can only follow a repeatable token."; + is_valid = false; + } + + prev_repeatable = !IsInSet(ch, "^$?*+"); + } + } + + return is_valid; +} + +// Matches a repeated regex atom followed by a valid simple regular +// expression. The regex atom is defined as c if escaped is false, +// or \c otherwise. repeat is the repetition meta character (?, *, +// or +). The behavior is undefined if str contains too many +// characters to be indexable by size_t, in which case the test will +// probably time out anyway. We are fine with this limitation as +// std::string has it too. +bool MatchRepetitionAndRegexAtHead( + bool escaped, char c, char repeat, const char* regex, + const char* str) { + const size_t min_count = (repeat == '+') ? 1 : 0; + const size_t max_count = (repeat == '?') ? 1 : + static_cast(-1) - 1; + // We cannot call numeric_limits::max() as it conflicts with the + // max() macro on Windows. + + for (size_t i = 0; i <= max_count; ++i) { + // We know that the atom matches each of the first i characters in str. + if (i >= min_count && MatchRegexAtHead(regex, str + i)) { + // We have enough matches at the head, and the tail matches too. + // Since we only care about *whether* the pattern matches str + // (as opposed to *how* it matches), there is no need to find a + // greedy match. + return true; + } + if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) + return false; + } + return false; +} + +// Returns true iff regex matches a prefix of str. regex must be a +// valid simple regular expression and not start with "^", or the +// result is undefined. +bool MatchRegexAtHead(const char* regex, const char* str) { + if (*regex == '\0') // An empty regex matches a prefix of anything. + return true; + + // "$" only matches the end of a string. Note that regex being + // valid guarantees that there's nothing after "$" in it. + if (*regex == '$') + return *str == '\0'; + + // Is the first thing in regex an escape sequence? + const bool escaped = *regex == '\\'; + if (escaped) + ++regex; + if (IsRepeat(regex[1])) { + // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so + // here's an indirect recursion. It terminates as the regex gets + // shorter in each recursion. + return MatchRepetitionAndRegexAtHead( + escaped, regex[0], regex[1], regex + 2, str); + } else { + // regex isn't empty, isn't "$", and doesn't start with a + // repetition. We match the first atom of regex with the first + // character of str and recurse. + return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && + MatchRegexAtHead(regex + 1, str + 1); + } +} + +// Returns true iff regex matches any substring of str. regex must be +// a valid simple regular expression, or the result is undefined. +// +// The algorithm is recursive, but the recursion depth doesn't exceed +// the regex length, so we won't need to worry about running out of +// stack space normally. In rare cases the time complexity can be +// exponential with respect to the regex length + the string length, +// but usually it's must faster (often close to linear). +bool MatchRegexAnywhere(const char* regex, const char* str) { + if (regex == NULL || str == NULL) + return false; + + if (*regex == '^') + return MatchRegexAtHead(regex + 1, str); + + // A successful match can be anywhere in str. + do { + if (MatchRegexAtHead(regex, str)) + return true; + } while (*str++ != '\0'); + return false; +} + +// Implements the RE class. + +RE::~RE() { + free(const_cast(pattern_)); + free(const_cast(full_pattern_)); +} + +// Returns true iff regular expression re matches the entire str. +bool RE::FullMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); +} + +// Returns true iff regular expression re matches a substring of str +// (including str itself). +bool RE::PartialMatch(const char* str, const RE& re) { + return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); +} + +// Initializes an RE from its string representation. +void RE::Init(const char* regex) { + pattern_ = full_pattern_ = NULL; + if (regex != NULL) { + pattern_ = posix::StrDup(regex); + } + + is_valid_ = ValidateRegex(regex); + if (!is_valid_) { + // No need to calculate the full pattern when the regex is invalid. + return; + } + + const size_t len = strlen(regex); + // Reserves enough bytes to hold the regular expression used for a + // full match: we need space to prepend a '^', append a '$', and + // terminate the string with '\0'. + char* buffer = static_cast(malloc(len + 3)); + full_pattern_ = buffer; + + if (*regex != '^') + *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. + + // We don't use snprintf or strncpy, as they trigger a warning when + // compiled with VC++ 8.0. + memcpy(buffer, regex, len); + buffer += len; + + if (len == 0 || regex[len - 1] != '$') + *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. + + *buffer = '\0'; +} + +#endif // GTEST_USES_POSIX_RE + +const char kUnknownFile[] = "unknown file"; + +// Formats a source file path and a line number as they would appear +// in an error message from the compiler used to compile this code. +GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) { + return file_name + ":"; + } +#ifdef _MSC_VER + return file_name + "(" + StreamableToString(line) + "):"; +#else + return file_name + ":" + StreamableToString(line) + ":"; +#endif // _MSC_VER +} + +// Formats a file location for compiler-independent XML output. +// Although this function is not platform dependent, we put it next to +// FormatFileLocation in order to contrast the two functions. +// Note that FormatCompilerIndependentFileLocation() does NOT append colon +// to the file location it produces, unlike FormatFileLocation(). +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( + const char* file, int line) { + const std::string file_name(file == NULL ? kUnknownFile : file); + + if (line < 0) + return file_name; + else + return file_name + ":" + StreamableToString(line); +} + +GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) + : severity_(severity) { + const char* const marker = + severity == GTEST_INFO ? "[ INFO ]" : + severity == GTEST_WARNING ? "[WARNING]" : + severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; + GetStream() << ::std::endl << marker << " " + << FormatFileLocation(file, line).c_str() << ": "; +} + +// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. +GTestLog::~GTestLog() { + GetStream() << ::std::endl; + if (severity_ == GTEST_FATAL) { + fflush(stderr); + posix::Abort(); + } +} +// Disable Microsoft deprecation warnings for POSIX functions called from +// this class (creat, dup, dup2, and close) +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) + +#if GTEST_HAS_STREAM_REDIRECTION + +// Object that captures an output stream (stdout/stderr). +class CapturedStream { + public: + // The ctor redirects the stream to a temporary file. + explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { +# if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT + char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT + + ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); + const UINT success = ::GetTempFileNameA(temp_dir_path, + "gtest_redir", + 0, // Generate unique file name. + temp_file_path); + GTEST_CHECK_(success != 0) + << "Unable to create a temporary file in " << temp_dir_path; + const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); + GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " + << temp_file_path; + filename_ = temp_file_path; +# else + // There's no guarantee that a test has write access to the current + // directory, so we create the temporary file in the /tmp directory + // instead. We use /tmp on most systems, and /sdcard on Android. + // That's because Android doesn't have /tmp. +# if GTEST_OS_LINUX_ANDROID + // Note: Android applications are expected to call the framework's + // Context.getExternalStorageDirectory() method through JNI to get + // the location of the world-writable SD Card directory. However, + // this requires a Context handle, which cannot be retrieved + // globally from native code. Doing so also precludes running the + // code as part of a regular standalone executable, which doesn't + // run in a Dalvik process (e.g. when running it through 'adb shell'). + // + // The location /sdcard is directly accessible from native code + // and is the only location (unofficially) supported by the Android + // team. It's generally a symlink to the real SD Card mount point + // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or + // other OEM-customized locations. Never rely on these, and always + // use /sdcard. + char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; +# else + char name_template[] = "/tmp/captured_stream.XXXXXX"; +# endif // GTEST_OS_LINUX_ANDROID + const int captured_fd = mkstemp(name_template); + filename_ = name_template; +# endif // GTEST_OS_WINDOWS + fflush(NULL); + dup2(captured_fd, fd_); + close(captured_fd); + } + + ~CapturedStream() { + remove(filename_.c_str()); + } + + std::string GetCapturedString() { + if (uncaptured_fd_ != -1) { + // Restores the original stream. + fflush(NULL); + dup2(uncaptured_fd_, fd_); + close(uncaptured_fd_); + uncaptured_fd_ = -1; + } + + FILE* const file = posix::FOpen(filename_.c_str(), "r"); + const std::string content = ReadEntireFile(file); + posix::FClose(file); + return content; + } + + private: + const int fd_; // A stream to capture. + int uncaptured_fd_; + // Name of the temporary file holding the stderr output. + ::std::string filename_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); +}; + +GTEST_DISABLE_MSC_WARNINGS_POP_() + +static CapturedStream* g_captured_stderr = NULL; +static CapturedStream* g_captured_stdout = NULL; + +// Starts capturing an output stream (stdout/stderr). +void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { + if (*stream != NULL) { + GTEST_LOG_(FATAL) << "Only one " << stream_name + << " capturer can exist at a time."; + } + *stream = new CapturedStream(fd); +} + +// Stops capturing the output stream and returns the captured string. +std::string GetCapturedStream(CapturedStream** captured_stream) { + const std::string content = (*captured_stream)->GetCapturedString(); + + delete *captured_stream; + *captured_stream = NULL; + + return content; +} + +// Starts capturing stdout. +void CaptureStdout() { + CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); +} + +// Starts capturing stderr. +void CaptureStderr() { + CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); +} + +// Stops capturing stdout and returns the captured string. +std::string GetCapturedStdout() { + return GetCapturedStream(&g_captured_stdout); +} + +// Stops capturing stderr and returns the captured string. +std::string GetCapturedStderr() { + return GetCapturedStream(&g_captured_stderr); +} + +#endif // GTEST_HAS_STREAM_REDIRECTION + +std::string TempDir() { +#if GTEST_OS_WINDOWS_MOBILE + return "\\temp\\"; +#elif GTEST_OS_WINDOWS + const char* temp_dir = posix::GetEnv("TEMP"); + if (temp_dir == NULL || temp_dir[0] == '\0') + return "\\temp\\"; + else if (temp_dir[strlen(temp_dir) - 1] == '\\') + return temp_dir; + else + return std::string(temp_dir) + "\\"; +#elif GTEST_OS_LINUX_ANDROID + return "/sdcard/"; +#else + return "/tmp/"; +#endif // GTEST_OS_WINDOWS_MOBILE +} + +size_t GetFileSize(FILE* file) { + fseek(file, 0, SEEK_END); + return static_cast(ftell(file)); +} + +std::string ReadEntireFile(FILE* file) { + const size_t file_size = GetFileSize(file); + char* const buffer = new char[file_size]; + + size_t bytes_last_read = 0; // # of bytes read in the last fread() + size_t bytes_read = 0; // # of bytes read so far + + fseek(file, 0, SEEK_SET); + + // Keeps reading the file until we cannot read further or the + // pre-determined file size is reached. + do { + bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_read += bytes_last_read; + } while (bytes_last_read > 0 && bytes_read < file_size); + + const std::string content(buffer, bytes_read); + delete[] buffer; + + return content; +} + +#if GTEST_HAS_DEATH_TEST + +static const ::std::vector* g_injected_test_argvs = + NULL; // Owned. + +void SetInjectableArgvs(const ::std::vector* argvs) { + if (g_injected_test_argvs != argvs) + delete g_injected_test_argvs; + g_injected_test_argvs = argvs; +} + +const ::std::vector& GetInjectableArgvs() { + if (g_injected_test_argvs != NULL) { + return *g_injected_test_argvs; + } + return GetArgvs(); +} +#endif // GTEST_HAS_DEATH_TEST + +#if GTEST_OS_WINDOWS_MOBILE +namespace posix { +void Abort() { + DebugBreak(); + TerminateProcess(GetCurrentProcess(), 1); +} +} // namespace posix +#endif // GTEST_OS_WINDOWS_MOBILE + +// Returns the name of the environment variable corresponding to the +// given flag. For example, FlagToEnvVar("foo") will return +// "GTEST_FOO" in the open-source version. +static std::string FlagToEnvVar(const char* flag) { + const std::string full_flag = + (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); + + Message env_var; + for (size_t i = 0; i != full_flag.length(); i++) { + env_var << ToUpper(full_flag.c_str()[i]); + } + + return env_var.GetString(); +} + +// Parses 'str' for a 32-bit signed integer. If successful, writes +// the result to *value and returns true; otherwise leaves *value +// unchanged and returns false. +bool ParseInt32(const Message& src_text, const char* str, Int32* value) { + // Parses the environment variable as a decimal integer. + char* end = NULL; + const long long_value = strtol(str, &end, 10); // NOLINT + + // Has strtol() consumed all characters in the string? + if (*end != '\0') { + // No - an invalid character was encountered. + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value \"" << str << "\".\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + // Is the parsed value in the range of an Int32? + const Int32 result = static_cast(long_value); + if (long_value == LONG_MAX || long_value == LONG_MIN || + // The parsed value overflows as a long. (strtol() returns + // LONG_MAX or LONG_MIN when the input overflows.) + result != long_value + // The parsed value overflows as an Int32. + ) { + Message msg; + msg << "WARNING: " << src_text + << " is expected to be a 32-bit integer, but actually" + << " has value " << str << ", which overflows.\n"; + printf("%s", msg.GetString().c_str()); + fflush(stdout); + return false; + } + + *value = result; + return true; +} + +// Reads and returns the Boolean environment variable corresponding to +// the given flag; if it's not set, returns default_value. +// +// The value is considered true iff it's not "0". +bool BoolFromGTestEnv(const char* flag, bool default_value) { +#if defined(GTEST_GET_BOOL_FROM_ENV_) + return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_BOOL_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + return string_value == NULL ? + default_value : strcmp(string_value, "0") != 0; +} + +// Reads and returns a 32-bit integer stored in the environment +// variable corresponding to the given flag; if it isn't set or +// doesn't represent a valid 32-bit integer, returns default_value. +Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { +#if defined(GTEST_GET_INT32_FROM_ENV_) + return GTEST_GET_INT32_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_INT32_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); + const char* const string_value = posix::GetEnv(env_var.c_str()); + if (string_value == NULL) { + // The environment variable is not set. + return default_value; + } + + Int32 result = default_value; + if (!ParseInt32(Message() << "Environment variable " << env_var, + string_value, &result)) { + printf("The default value %s is used.\n", + (Message() << default_value).GetString().c_str()); + fflush(stdout); + return default_value; + } + + return result; +} + +// Reads and returns the string environment variable corresponding to +// the given flag; if it's not set, returns default_value. +std::string StringFromGTestEnv(const char* flag, const char* default_value) { +#if defined(GTEST_GET_STRING_FROM_ENV_) + return GTEST_GET_STRING_FROM_ENV_(flag, default_value); +#endif // defined(GTEST_GET_STRING_FROM_ENV_) + const std::string env_var = FlagToEnvVar(flag); + const char* value = posix::GetEnv(env_var.c_str()); + if (value != NULL) { + return value; + } + + // As a special case for the 'output' flag, if GTEST_OUTPUT is not + // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build + // system. The value of XML_OUTPUT_FILE is a filename without the + // "xml:" prefix of GTEST_OUTPUT. + // + // The net priority order after flag processing is thus: + // --gtest_output command line flag + // GTEST_OUTPUT environment variable + // XML_OUTPUT_FILE environment variable + // 'default_value' + if (strcmp(flag, "output") == 0) { + value = posix::GetEnv("XML_OUTPUT_FILE"); + if (value != NULL) { + return std::string("xml:") + value; + } + } + return default_value; +} + +} // namespace internal +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest-printers.cc b/gtestsrc/gtest/src/gtest-printers.cc new file mode 100644 index 0000000..a2df412 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-printers.cc @@ -0,0 +1,373 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing Framework +// +// This file implements a universal value printer that can print a +// value of any type T: +// +// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); +// +// It uses the << operator when possible, and prints the bytes in the +// object otherwise. A user can override its behavior for a class +// type Foo by defining either operator<<(::std::ostream&, const Foo&) +// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that +// defines Foo. + +#include "gtest/gtest-printers.h" +#include +#include +#include +#include // NOLINT +#include +#include "gtest/internal/gtest-port.h" + +namespace testing { + +namespace { + +using ::std::ostream; + +// Prints a segment of bytes in the given object. +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, + size_t count, ostream* os) { + char text[5] = ""; + for (size_t i = 0; i != count; i++) { + const size_t j = start + i; + if (i != 0) { + // Organizes the bytes into groups of 2 for easy parsing by + // human. + if ((j % 2) == 0) + *os << ' '; + else + *os << '-'; + } + GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); + *os << text; + } +} + +// Prints the bytes in the given value to the given ostream. +void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, + ostream* os) { + // Tells the user how big the object is. + *os << count << "-byte object <"; + + const size_t kThreshold = 132; + const size_t kChunkSize = 64; + // If the object size is bigger than kThreshold, we'll have to omit + // some details by printing only the first and the last kChunkSize + // bytes. + // TODO(wan): let the user control the threshold using a flag. + if (count < kThreshold) { + PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); + } else { + PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); + *os << " ... "; + // Rounds up to 2-byte boundary. + const size_t resume_pos = (count - kChunkSize + 1)/2*2; + PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); + } + *os << ">"; +} + +} // namespace + +namespace internal2 { + +// Delegates to PrintBytesInObjectToImpl() to print the bytes in the +// given object. The delegation simplifies the implementation, which +// uses the << operator and thus is easier done outside of the +// ::testing::internal namespace, which contains a << operator that +// sometimes conflicts with the one in STL. +void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, + ostream* os) { + PrintBytesInObjectToImpl(obj_bytes, count, os); +} + +} // namespace internal2 + +namespace internal { + +// Depending on the value of a char (or wchar_t), we print it in one +// of three formats: +// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), +// - as a hexidecimal escape sequence (e.g. '\x7F'), or +// - as a special escape sequence (e.g. '\r', '\n'). +enum CharFormat { + kAsIs, + kHexEscape, + kSpecialEscape +}; + +// Returns true if c is a printable ASCII character. We test the +// value of c directly instead of calling isprint(), which is buggy on +// Windows Mobile. +inline bool IsPrintableAscii(wchar_t c) { + return 0x20 <= c && c <= 0x7E; +} + +// Prints a wide or narrow char c as a character literal without the +// quotes, escaping it when necessary; returns how c was formatted. +// The template argument UnsignedChar is the unsigned version of Char, +// which is the type of c. +template +static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { + switch (static_cast(c)) { + case L'\0': + *os << "\\0"; + break; + case L'\'': + *os << "\\'"; + break; + case L'\\': + *os << "\\\\"; + break; + case L'\a': + *os << "\\a"; + break; + case L'\b': + *os << "\\b"; + break; + case L'\f': + *os << "\\f"; + break; + case L'\n': + *os << "\\n"; + break; + case L'\r': + *os << "\\r"; + break; + case L'\t': + *os << "\\t"; + break; + case L'\v': + *os << "\\v"; + break; + default: + if (IsPrintableAscii(c)) { + *os << static_cast(c); + return kAsIs; + } else { + *os << "\\x" + String::FormatHexInt(static_cast(c)); + return kHexEscape; + } + } + return kSpecialEscape; +} + +// Prints a wchar_t c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { + switch (c) { + case L'\'': + *os << "'"; + return kAsIs; + case L'"': + *os << "\\\""; + return kSpecialEscape; + default: + return PrintAsCharLiteralTo(c, os); + } +} + +// Prints a char c as if it's part of a string literal, escaping it when +// necessary; returns how c was formatted. +static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { + return PrintAsStringLiteralTo( + static_cast(static_cast(c)), os); +} + +// Prints a wide or narrow character c and its code. '\0' is printed +// as "'\\0'", other unprintable characters are also properly escaped +// using the standard C++ escape sequence. The template argument +// UnsignedChar is the unsigned version of Char, which is the type of c. +template +void PrintCharAndCodeTo(Char c, ostream* os) { + // First, print c as a literal in the most readable form we can find. + *os << ((sizeof(c) > 1) ? "L'" : "'"); + const CharFormat format = PrintAsCharLiteralTo(c, os); + *os << "'"; + + // To aid user debugging, we also print c's code in decimal, unless + // it's 0 (in which case c was printed as '\\0', making the code + // obvious). + if (c == 0) + return; + *os << " (" << static_cast(c); + + // For more convenience, we print c's code again in hexidecimal, + // unless c was already printed in the form '\x##' or the code is in + // [1, 9]. + if (format == kHexEscape || (1 <= c && c <= 9)) { + // Do nothing. + } else { + *os << ", 0x" << String::FormatHexInt(static_cast(c)); + } + *os << ")"; +} + +void PrintTo(unsigned char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} +void PrintTo(signed char c, ::std::ostream* os) { + PrintCharAndCodeTo(c, os); +} + +// Prints a wchar_t as a symbol if it is printable or as its internal +// code otherwise and also as its code. L'\0' is printed as "L'\\0'". +void PrintTo(wchar_t wc, ostream* os) { + PrintCharAndCodeTo(wc, os); +} + +// Prints the given array of characters to the ostream. CharType must be either +// char or wchar_t. +// The array starts at begin, the length is len, it may include '\0' characters +// and may not be NUL-terminated. +template +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +static void PrintCharsAsStringTo( + const CharType* begin, size_t len, ostream* os) { + const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; + *os << kQuoteBegin; + bool is_previous_hex = false; + for (size_t index = 0; index < len; ++index) { + const CharType cur = begin[index]; + if (is_previous_hex && IsXDigit(cur)) { + // Previous character is of '\x..' form and this character can be + // interpreted as another hexadecimal digit in its number. Break string to + // disambiguate. + *os << "\" " << kQuoteBegin; + } + is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; + } + *os << "\""; +} + +// Prints a (const) char/wchar_t array of 'len' elements, starting at address +// 'begin'. CharType must be either char or wchar_t. +template +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +static void UniversalPrintCharArray( + const CharType* begin, size_t len, ostream* os) { + // The code + // const char kFoo[] = "foo"; + // generates an array of 4, not 3, elements, with the last one being '\0'. + // + // Therefore when printing a char array, we don't print the last element if + // it's '\0', such that the output matches the string literal as it's + // written in the source code. + if (len > 0 && begin[len - 1] == '\0') { + PrintCharsAsStringTo(begin, len - 1, os); + return; + } + + // If, however, the last element in the array is not '\0', e.g. + // const char kFoo[] = { 'f', 'o', 'o' }; + // we must print the entire array. We also print a message to indicate + // that the array is not NUL-terminated. + PrintCharsAsStringTo(begin, len, os); + *os << " (no terminating NUL)"; +} + +// Prints a (const) char array of 'len' elements, starting at address 'begin'. +void UniversalPrintArray(const char* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints a (const) wchar_t array of 'len' elements, starting at address +// 'begin'. +void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { + UniversalPrintCharArray(begin, len, os); +} + +// Prints the given C string to the ostream. +void PrintTo(const char* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, strlen(s), os); + } +} + +// MSVC compiler can be configured to define whar_t as a typedef +// of unsigned short. Defining an overload for const wchar_t* in that case +// would cause pointers to unsigned shorts be printed as wide strings, +// possibly accessing more memory than intended and causing invalid +// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when +// wchar_t is implemented as a native type. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) +// Prints the given wide C string to the ostream. +void PrintTo(const wchar_t* s, ostream* os) { + if (s == NULL) { + *os << "NULL"; + } else { + *os << ImplicitCast_(s) << " pointing to "; + PrintCharsAsStringTo(s, std::wcslen(s), os); + } +} +#endif // wchar_t is native + +// Prints a ::string object. +#if GTEST_HAS_GLOBAL_STRING +void PrintStringTo(const ::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_STRING + +void PrintStringTo(const ::std::string& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} + +// Prints a ::wstring object. +#if GTEST_HAS_GLOBAL_WSTRING +void PrintWideStringTo(const ::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +void PrintWideStringTo(const ::std::wstring& s, ostream* os) { + PrintCharsAsStringTo(s.data(), s.size(), os); +} +#endif // GTEST_HAS_STD_WSTRING + +} // namespace internal + +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest-test-part.cc b/gtestsrc/gtest/src/gtest-test-part.cc new file mode 100644 index 0000000..fb0e354 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-test-part.cc @@ -0,0 +1,110 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// +// The Google C++ Testing Framework (Google Test) + +#include "gtest/gtest-test-part.h" + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick exists to +// prevent the accidental inclusion of gtest-internal-inl.h in the +// user's code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +namespace testing { + +using internal::GetUnitTestImpl; + +// Gets the summary of the failure message by omitting the stack trace +// in it. +std::string TestPartResult::ExtractSummary(const char* message) { + const char* const stack_trace = strstr(message, internal::kStackTraceMarker); + return stack_trace == NULL ? message : + std::string(message, stack_trace); +} + +// Prints a TestPartResult object. +std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { + return os + << result.file_name() << ":" << result.line_number() << ": " + << (result.type() == TestPartResult::kSuccess ? "Success" : + result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : + "Non-fatal failure") << ":\n" + << result.message() << std::endl; +} + +// Appends a TestPartResult to the array. +void TestPartResultArray::Append(const TestPartResult& result) { + array_.push_back(result); +} + +// Returns the TestPartResult at the given index (0-based). +const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { + if (index < 0 || index >= size()) { + printf("\nInvalid index (%d) into TestPartResultArray.\n", index); + internal::posix::Abort(); + } + + return array_[index]; +} + +// Returns the number of TestPartResult objects in the array. +int TestPartResultArray::size() const { + return static_cast(array_.size()); +} + +namespace internal { + +HasNewFatalFailureHelper::HasNewFatalFailureHelper() + : has_new_fatal_failure_(false), + original_reporter_(GetUnitTestImpl()-> + GetTestPartResultReporterForCurrentThread()) { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); +} + +HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( + original_reporter_); +} + +void HasNewFatalFailureHelper::ReportTestPartResult( + const TestPartResult& result) { + if (result.fatally_failed()) + has_new_fatal_failure_ = true; + original_reporter_->ReportTestPartResult(result); +} + +} // namespace internal + +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest-typed-test.cc b/gtestsrc/gtest/src/gtest-typed-test.cc new file mode 100644 index 0000000..df1eef4 --- /dev/null +++ b/gtestsrc/gtest/src/gtest-typed-test.cc @@ -0,0 +1,118 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/gtest-typed-test.h" +#include "gtest/gtest.h" + +namespace testing { +namespace internal { + +#if GTEST_HAS_TYPED_TEST_P + +// Skips to the first non-space char in str. Returns an empty string if str +// contains only whitespace characters. +static const char* SkipSpaces(const char* str) { + while (IsSpace(*str)) + str++; + return str; +} + +static std::vector SplitIntoTestNames(const char* src) { + std::vector name_vec; + src = SkipSpaces(src); + for (; src != NULL; src = SkipComma(src)) { + name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); + } + return name_vec; +} + +// Verifies that registered_tests match the test names in +// registered_tests_; returns registered_tests if successful, or +// aborts the program otherwise. +const char* TypedTestCasePState::VerifyRegisteredTestNames( + const char* file, int line, const char* registered_tests) { + typedef RegisteredTestsMap::const_iterator RegisteredTestIter; + registered_ = true; + + std::vector name_vec = SplitIntoTestNames(registered_tests); + + Message errors; + + std::set tests; + for (std::vector::const_iterator name_it = name_vec.begin(); + name_it != name_vec.end(); ++name_it) { + const std::string& name = *name_it; + if (tests.count(name) != 0) { + errors << "Test " << name << " is listed more than once.\n"; + continue; + } + + bool found = false; + for (RegisteredTestIter it = registered_tests_.begin(); + it != registered_tests_.end(); + ++it) { + if (name == it->first) { + found = true; + break; + } + } + + if (found) { + tests.insert(name); + } else { + errors << "No test named " << name + << " can be found in this test case.\n"; + } + } + + for (RegisteredTestIter it = registered_tests_.begin(); + it != registered_tests_.end(); + ++it) { + if (tests.count(it->first) == 0) { + errors << "You forgot to list test " << it->first << ".\n"; + } + } + + const std::string& errors_str = errors.GetString(); + if (errors_str != "") { + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), + errors_str.c_str()); + fflush(stderr); + posix::Abort(); + } + + return registered_tests; +} + +#endif // GTEST_HAS_TYPED_TEST_P + +} // namespace internal +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest.cc b/gtestsrc/gtest/src/gtest.cc new file mode 100644 index 0000000..d882ab2 --- /dev/null +++ b/gtestsrc/gtest/src/gtest.cc @@ -0,0 +1,5388 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// The Google C++ Testing Framework (Google Test) + +#include "gtest/gtest.h" +#include "gtest/internal/custom/gtest.h" +#include "gtest/gtest-spi.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include // NOLINT +#include +#include + +#if GTEST_OS_LINUX + +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +# include // NOLINT +# include // NOLINT +# include // NOLINT +// Declares vsnprintf(). This header is not available on Windows. +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include + +#elif GTEST_OS_SYMBIAN +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +#elif GTEST_OS_ZOS +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT + +// On z/OS we additionally need strings.h for strcasecmp. +# include // NOLINT + +#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. + +# include // NOLINT +# undef min + +#elif GTEST_OS_WINDOWS // We are on Windows proper. + +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT + +# if GTEST_OS_WINDOWS_MINGW +// MinGW has gettimeofday() but not _ftime64(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +// TODO(kenton@google.com): There are other ways to get the time on +// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW +// supports these. consider using them instead. +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT +# endif // GTEST_OS_WINDOWS_MINGW + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT +# undef min + +#else + +// Assume other platforms have gettimeofday(). +// TODO(kenton@google.com): Use autoconf to detect availability of +// gettimeofday(). +# define GTEST_HAS_GETTIMEOFDAY_ 1 + +// cpplint thinks that the header is already included, so we want to +// silence it. +# include // NOLINT +# include // NOLINT + +#endif // GTEST_OS_LINUX + +#if GTEST_HAS_EXCEPTIONS +# include +#endif + +#if GTEST_CAN_STREAM_RESULTS_ +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +#endif + +// Indicates that this translation unit is part of Google Test's +// implementation. It must come before gtest-internal-inl.h is +// included, or there will be a compiler error. This trick is to +// prevent a user from accidentally including gtest-internal-inl.h in +// his code. +#define GTEST_IMPLEMENTATION_ 1 +#include "src/gtest-internal-inl.h" +#undef GTEST_IMPLEMENTATION_ + +#if GTEST_OS_WINDOWS +# define vsnprintf _vsnprintf +#endif // GTEST_OS_WINDOWS + +namespace testing { + +using internal::CountIf; +using internal::ForEach; +using internal::GetElementOr; +using internal::Shuffle; + +// Constants. + +// A test whose test case name or test name matches this filter is +// disabled and not run. +static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; + +// A test case whose name matches this filter is considered a death +// test case and will be run before test cases whose name doesn't +// match this filter. +static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; + +// A test filter that matches everything. +static const char kUniversalFilter[] = "*"; + +// The default output file for XML output. +static const char kDefaultOutputFile[] = "test_detail.xml"; + +// The environment variable name for the test shard index. +static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; +// The environment variable name for the total number of test shards. +static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; +// The environment variable name for the test shard status file. +static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; + +namespace internal { + +// The text used in failure messages to indicate the start of the +// stack trace. +const char kStackTraceMarker[] = "\nStack trace:\n"; + +// g_help_flag is true iff the --help flag or an equivalent form is +// specified on the command line. +bool g_help_flag = false; + +} // namespace internal + +static const char* GetDefaultFilter() { +#ifdef GTEST_TEST_FILTER_ENV_VAR_ + const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_); + if (testbridge_test_only != NULL) { + return testbridge_test_only; + } +#endif // GTEST_TEST_FILTER_ENV_VAR_ + return kUniversalFilter; +} + +GTEST_DEFINE_bool_( + also_run_disabled_tests, + internal::BoolFromGTestEnv("also_run_disabled_tests", false), + "Run disabled tests too, in addition to the tests normally being run."); + +GTEST_DEFINE_bool_( + break_on_failure, + internal::BoolFromGTestEnv("break_on_failure", false), + "True iff a failed assertion should be a debugger break-point."); + +GTEST_DEFINE_bool_( + catch_exceptions, + internal::BoolFromGTestEnv("catch_exceptions", true), + "True iff " GTEST_NAME_ + " should catch exceptions and treat them as test failures."); + +GTEST_DEFINE_string_( + color, + internal::StringFromGTestEnv("color", "auto"), + "Whether to use colors in the output. Valid values: yes, no, " + "and auto. 'auto' means to use colors if the output is " + "being sent to a terminal and the TERM environment variable " + "is set to a terminal type that supports colors."); + +GTEST_DEFINE_string_( + filter, + internal::StringFromGTestEnv("filter", GetDefaultFilter()), + "A colon-separated list of glob (not regex) patterns " + "for filtering the tests to run, optionally followed by a " + "'-' and a : separated list of negative patterns (tests to " + "exclude). A test is run if it matches one of the positive " + "patterns and does not match any of the negative patterns."); + +GTEST_DEFINE_bool_(list_tests, false, + "List all tests without running them."); + +GTEST_DEFINE_string_( + output, + internal::StringFromGTestEnv("output", ""), + "A format (currently must be \"xml\"), optionally followed " + "by a colon and an output file name or directory. A directory " + "is indicated by a trailing pathname separator. " + "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " + "If a directory is specified, output files will be created " + "within that directory, with file-names based on the test " + "executable's name and, if necessary, made unique by adding " + "digits."); + +GTEST_DEFINE_bool_( + print_time, + internal::BoolFromGTestEnv("print_time", true), + "True iff " GTEST_NAME_ + " should display elapsed time in text output."); + +GTEST_DEFINE_int32_( + random_seed, + internal::Int32FromGTestEnv("random_seed", 0), + "Random number seed to use when shuffling test orders. Must be in range " + "[1, 99999], or 0 to use a seed based on the current time."); + +GTEST_DEFINE_int32_( + repeat, + internal::Int32FromGTestEnv("repeat", 1), + "How many times to repeat each test. Specify a negative number " + "for repeating forever. Useful for shaking out flaky tests."); + +GTEST_DEFINE_bool_( + show_internal_stack_frames, false, + "True iff " GTEST_NAME_ " should include internal stack frames when " + "printing test failure stack traces."); + +GTEST_DEFINE_bool_( + shuffle, + internal::BoolFromGTestEnv("shuffle", false), + "True iff " GTEST_NAME_ + " should randomize tests' order on every run."); + +GTEST_DEFINE_int32_( + stack_trace_depth, + internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + "The maximum number of stack frames to print when an " + "assertion fails. The valid range is 0 through 100, inclusive."); + +GTEST_DEFINE_string_( + stream_result_to, + internal::StringFromGTestEnv("stream_result_to", ""), + "This flag specifies the host name and the port number on which to stream " + "test results. Example: \"localhost:555\". The flag is effective only on " + "Linux."); + +GTEST_DEFINE_bool_( + throw_on_failure, + internal::BoolFromGTestEnv("throw_on_failure", false), + "When this flag is specified, a failed assertion will throw an exception " + "if exceptions are enabled or exit the program with a non-zero code " + "otherwise."); + +#if GTEST_USE_OWN_FLAGFILE_FLAG_ +GTEST_DEFINE_string_( + flagfile, + internal::StringFromGTestEnv("flagfile", ""), + "This flag specifies the flagfile to read command-line flags from."); +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + +namespace internal { + +// Generates a random number from [0, range), using a Linear +// Congruential Generator (LCG). Crashes if 'range' is 0 or greater +// than kMaxRange. +UInt32 Random::Generate(UInt32 range) { + // These constants are the same as are used in glibc's rand(3). + state_ = (1103515245U*state_ + 12345U) % kMaxRange; + + GTEST_CHECK_(range > 0) + << "Cannot generate a number in the range [0, 0)."; + GTEST_CHECK_(range <= kMaxRange) + << "Generation of a number in [0, " << range << ") was requested, " + << "but this can only generate numbers in [0, " << kMaxRange << ")."; + + // Converting via modulus introduces a bit of downward bias, but + // it's simple, and a linear congruential generator isn't too good + // to begin with. + return state_ % range; +} + +// GTestIsInitialized() returns true iff the user has initialized +// Google Test. Useful for catching the user mistake of not initializing +// Google Test before calling RUN_ALL_TESTS(). +static bool GTestIsInitialized() { return GetArgvs().size() > 0; } + +// Iterates over a vector of TestCases, keeping a running sum of the +// results of calling a given int-returning method on each. +// Returns the sum. +static int SumOverTestCaseList(const std::vector& case_list, + int (TestCase::*method)() const) { + int sum = 0; + for (size_t i = 0; i < case_list.size(); i++) { + sum += (case_list[i]->*method)(); + } + return sum; +} + +// Returns true iff the test case passed. +static bool TestCasePassed(const TestCase* test_case) { + return test_case->should_run() && test_case->Passed(); +} + +// Returns true iff the test case failed. +static bool TestCaseFailed(const TestCase* test_case) { + return test_case->should_run() && test_case->Failed(); +} + +// Returns true iff test_case contains at least one test that should +// run. +static bool ShouldRunTestCase(const TestCase* test_case) { + return test_case->should_run(); +} + +// AssertHelper constructor. +AssertHelper::AssertHelper(TestPartResult::Type type, + const char* file, + int line, + const char* message) + : data_(new AssertHelperData(type, file, line, message)) { +} + +AssertHelper::~AssertHelper() { + delete data_; +} + +// Message assignment, for assertion streaming support. +void AssertHelper::operator=(const Message& message) const { + UnitTest::GetInstance()-> + AddTestPartResult(data_->type, data_->file, data_->line, + AppendUserMessage(data_->message, message), + UnitTest::GetInstance()->impl() + ->CurrentOsStackTraceExceptTop(1) + // Skips the stack frame for this function itself. + ); // NOLINT +} + +// Mutex for linked pointers. +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); + +// A copy of all command line arguments. Set by InitGoogleTest(). +::std::vector g_argvs; + +const ::std::vector& GetArgvs() { +#if defined(GTEST_CUSTOM_GET_ARGVS_) + return GTEST_CUSTOM_GET_ARGVS_(); +#else // defined(GTEST_CUSTOM_GET_ARGVS_) + return g_argvs; +#endif // defined(GTEST_CUSTOM_GET_ARGVS_) +} + +// Returns the current application's name, removing directory path if that +// is present. +FilePath GetCurrentExecutableName() { + FilePath result; + +#if GTEST_OS_WINDOWS + result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); +#else + result.Set(FilePath(GetArgvs()[0])); +#endif // GTEST_OS_WINDOWS + + return result.RemoveDirectoryName(); +} + +// Functions for processing the gtest_output flag. + +// Returns the output format, or "" for normal printed output. +std::string UnitTestOptions::GetOutputFormat() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) return std::string(""); + + const char* const colon = strchr(gtest_output_flag, ':'); + return (colon == NULL) ? + std::string(gtest_output_flag) : + std::string(gtest_output_flag, colon - gtest_output_flag); +} + +// Returns the name of the requested output file, or the default if none +// was explicitly specified. +std::string UnitTestOptions::GetAbsolutePathToOutputFile() { + const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + if (gtest_output_flag == NULL) + return ""; + + const char* const colon = strchr(gtest_output_flag, ':'); + if (colon == NULL) + return internal::FilePath::ConcatPaths( + internal::FilePath( + UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile)).string(); + + internal::FilePath output_name(colon + 1); + if (!output_name.IsAbsolutePath()) + // TODO(wan@google.com): on Windows \some\path is not an absolute + // path (as its meaning depends on the current drive), yet the + // following logic for turning it into an absolute path is wrong. + // Fix it. + output_name = internal::FilePath::ConcatPaths( + internal::FilePath(UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(colon + 1)); + + if (!output_name.IsDirectory()) + return output_name.string(); + + internal::FilePath result(internal::FilePath::GenerateUniqueFileName( + output_name, internal::GetCurrentExecutableName(), + GetOutputFormat().c_str())); + return result.string(); +} + +// Returns true iff the wildcard pattern matches the string. The +// first ':' or '\0' character in pattern marks the end of it. +// +// This recursive algorithm isn't very efficient, but is clear and +// works well enough for matching test names, which are short. +bool UnitTestOptions::PatternMatchesString(const char *pattern, + const char *str) { + switch (*pattern) { + case '\0': + case ':': // Either ':' or '\0' marks the end of the pattern. + return *str == '\0'; + case '?': // Matches any single character. + return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); + case '*': // Matches any string (possibly empty) of characters. + return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || + PatternMatchesString(pattern + 1, str); + default: // Non-special character. Matches itself. + return *pattern == *str && + PatternMatchesString(pattern + 1, str + 1); + } +} + +bool UnitTestOptions::MatchesFilter( + const std::string& name, const char* filter) { + const char *cur_pattern = filter; + for (;;) { + if (PatternMatchesString(cur_pattern, name.c_str())) { + return true; + } + + // Finds the next pattern in the filter. + cur_pattern = strchr(cur_pattern, ':'); + + // Returns if no more pattern can be found. + if (cur_pattern == NULL) { + return false; + } + + // Skips the pattern separater (the ':' character). + cur_pattern++; + } +} + +// Returns true iff the user-specified filter matches the test case +// name and the test name. +bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, + const std::string &test_name) { + const std::string& full_name = test_case_name + "." + test_name.c_str(); + + // Split --gtest_filter at '-', if there is one, to separate into + // positive filter and negative filter portions + const char* const p = GTEST_FLAG(filter).c_str(); + const char* const dash = strchr(p, '-'); + std::string positive; + std::string negative; + if (dash == NULL) { + positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter + negative = ""; + } else { + positive = std::string(p, dash); // Everything up to the dash + negative = std::string(dash + 1); // Everything after the dash + if (positive.empty()) { + // Treat '-test1' as the same as '*-test1' + positive = kUniversalFilter; + } + } + + // A filter is a colon-separated list of patterns. It matches a + // test if any pattern in it matches the test. + return (MatchesFilter(full_name, positive.c_str()) && + !MatchesFilter(full_name, negative.c_str())); +} + +#if GTEST_HAS_SEH +// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the +// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. +// This function is useful as an __except condition. +int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { + // Google Test should handle a SEH exception if: + // 1. the user wants it to, AND + // 2. this is not a breakpoint exception, AND + // 3. this is not a C++ exception (VC++ implements them via SEH, + // apparently). + // + // SEH exception code for C++ exceptions. + // (see http://support.microsoft.com/kb/185294 for more information). + const DWORD kCxxExceptionCode = 0xe06d7363; + + bool should_handle = true; + + if (!GTEST_FLAG(catch_exceptions)) + should_handle = false; + else if (exception_code == EXCEPTION_BREAKPOINT) + should_handle = false; + else if (exception_code == kCxxExceptionCode) + should_handle = false; + + return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; +} +#endif // GTEST_HAS_SEH + +} // namespace internal + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. Intercepts only failures from the current thread. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + TestPartResultArray* result) + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), + result_(result) { + Init(); +} + +// The c'tor sets this object as the test part result reporter used by +// Google Test. The 'result' parameter specifies where to report the +// results. +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( + InterceptMode intercept_mode, TestPartResultArray* result) + : intercept_mode_(intercept_mode), + result_(result) { + Init(); +} + +void ScopedFakeTestPartResultReporter::Init() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + old_reporter_ = impl->GetGlobalTestPartResultReporter(); + impl->SetGlobalTestPartResultReporter(this); + } else { + old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); + impl->SetTestPartResultReporterForCurrentThread(this); + } +} + +// The d'tor restores the test part result reporter used by Google Test +// before. +ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + if (intercept_mode_ == INTERCEPT_ALL_THREADS) { + impl->SetGlobalTestPartResultReporter(old_reporter_); + } else { + impl->SetTestPartResultReporterForCurrentThread(old_reporter_); + } +} + +// Increments the test part result count and remembers the result. +// This method is from the TestPartResultReporterInterface interface. +void ScopedFakeTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + result_->Append(result); +} + +namespace internal { + +// Returns the type ID of ::testing::Test. We should always call this +// instead of GetTypeId< ::testing::Test>() to get the type ID of +// testing::Test. This is to work around a suspected linker bug when +// using Google Test as a framework on Mac OS X. The bug causes +// GetTypeId< ::testing::Test>() to return different values depending +// on whether the call is from the Google Test framework itself or +// from user test code. GetTestTypeId() is guaranteed to always +// return the same value, as it always calls GetTypeId<>() from the +// gtest.cc, which is within the Google Test framework. +TypeId GetTestTypeId() { + return GetTypeId(); +} + +// The value of GetTestTypeId() as seen from within the Google Test +// library. This is solely for testing GetTestTypeId(). +extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); + +// This predicate-formatter checks that 'results' contains a test part +// failure of the given type and that the failure message contains the +// given substring. +AssertionResult HasOneFailure(const char* /* results_expr */, + const char* /* type_expr */, + const char* /* substr_expr */, + const TestPartResultArray& results, + TestPartResult::Type type, + const string& substr) { + const std::string expected(type == TestPartResult::kFatalFailure ? + "1 fatal failure" : + "1 non-fatal failure"); + Message msg; + if (results.size() != 1) { + msg << "Expected: " << expected << "\n" + << " Actual: " << results.size() << " failures"; + for (int i = 0; i < results.size(); i++) { + msg << "\n" << results.GetTestPartResult(i); + } + return AssertionFailure() << msg; + } + + const TestPartResult& r = results.GetTestPartResult(0); + if (r.type() != type) { + return AssertionFailure() << "Expected: " << expected << "\n" + << " Actual:\n" + << r; + } + + if (strstr(r.message(), substr.c_str()) == NULL) { + return AssertionFailure() << "Expected: " << expected << " containing \"" + << substr << "\"\n" + << " Actual:\n" + << r; + } + + return AssertionSuccess(); +} + +// The constructor of SingleFailureChecker remembers where to look up +// test part results, what type of failure we expect, and what +// substring the failure message should contain. +SingleFailureChecker:: SingleFailureChecker( + const TestPartResultArray* results, + TestPartResult::Type type, + const string& substr) + : results_(results), + type_(type), + substr_(substr) {} + +// The destructor of SingleFailureChecker verifies that the given +// TestPartResultArray contains exactly one failure that has the given +// type and contains the given substring. If that's not the case, a +// non-fatal failure will be generated. +SingleFailureChecker::~SingleFailureChecker() { + EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); +} + +DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultGlobalTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->current_test_result()->AddTestPartResult(result); + unit_test_->listeners()->repeater()->OnTestPartResult(result); +} + +DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( + UnitTestImpl* unit_test) : unit_test_(unit_test) {} + +void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( + const TestPartResult& result) { + unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); +} + +// Returns the global test part result reporter. +TestPartResultReporterInterface* +UnitTestImpl::GetGlobalTestPartResultReporter() { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + return global_test_part_result_repoter_; +} + +// Sets the global test part result reporter. +void UnitTestImpl::SetGlobalTestPartResultReporter( + TestPartResultReporterInterface* reporter) { + internal::MutexLock lock(&global_test_part_result_reporter_mutex_); + global_test_part_result_repoter_ = reporter; +} + +// Returns the test part result reporter for the current thread. +TestPartResultReporterInterface* +UnitTestImpl::GetTestPartResultReporterForCurrentThread() { + return per_thread_test_part_result_reporter_.get(); +} + +// Sets the test part result reporter for the current thread. +void UnitTestImpl::SetTestPartResultReporterForCurrentThread( + TestPartResultReporterInterface* reporter) { + per_thread_test_part_result_reporter_.set(reporter); +} + +// Gets the number of successful test cases. +int UnitTestImpl::successful_test_case_count() const { + return CountIf(test_cases_, TestCasePassed); +} + +// Gets the number of failed test cases. +int UnitTestImpl::failed_test_case_count() const { + return CountIf(test_cases_, TestCaseFailed); +} + +// Gets the number of all test cases. +int UnitTestImpl::total_test_case_count() const { + return static_cast(test_cases_.size()); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTestImpl::test_case_to_run_count() const { + return CountIf(test_cases_, ShouldRunTestCase); +} + +// Gets the number of successful tests. +int UnitTestImpl::successful_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); +} + +// Gets the number of failed tests. +int UnitTestImpl::failed_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTestImpl::reportable_disabled_test_count() const { + return SumOverTestCaseList(test_cases_, + &TestCase::reportable_disabled_test_count); +} + +// Gets the number of disabled tests. +int UnitTestImpl::disabled_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTestImpl::reportable_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); +} + +// Gets the number of all tests. +int UnitTestImpl::total_test_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); +} + +// Gets the number of tests that should run. +int UnitTestImpl::test_to_run_count() const { + return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// CurrentOsStackTraceExceptTop(1), Foo() will be included in the +// trace but Bar() and CurrentOsStackTraceExceptTop() won't. +std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { + return os_stack_trace_getter()->CurrentStackTrace( + static_cast(GTEST_FLAG(stack_trace_depth)), + skip_count + 1 + // Skips the user-specified number of frames plus this function + // itself. + ); // NOLINT +} + +// Returns the current time in milliseconds. +TimeInMillis GetTimeInMillis() { +#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) + // Difference between 1970-01-01 and 1601-01-01 in milliseconds. + // http://analogous.blogspot.com/2005/04/epoch.html + const TimeInMillis kJavaEpochToWinFileTimeDelta = + static_cast(116444736UL) * 100000UL; + const DWORD kTenthMicrosInMilliSecond = 10000; + + SYSTEMTIME now_systime; + FILETIME now_filetime; + ULARGE_INTEGER now_int64; + // TODO(kenton@google.com): Shouldn't this just use + // GetSystemTimeAsFileTime()? + GetSystemTime(&now_systime); + if (SystemTimeToFileTime(&now_systime, &now_filetime)) { + now_int64.LowPart = now_filetime.dwLowDateTime; + now_int64.HighPart = now_filetime.dwHighDateTime; + now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - + kJavaEpochToWinFileTimeDelta; + return now_int64.QuadPart; + } + return 0; +#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ + __timeb64 now; + + // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 + // (deprecated function) there. + // TODO(kenton@google.com): Use GetTickCount()? Or use + // SystemTimeToFileTime() + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) + _ftime64(&now); + GTEST_DISABLE_MSC_WARNINGS_POP_() + + return static_cast(now.time) * 1000 + now.millitm; +#elif GTEST_HAS_GETTIMEOFDAY_ + struct timeval now; + gettimeofday(&now, NULL); + return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; +#else +# error "Don't know how to get the current time on your system." +#endif +} + +// Utilities + +// class String. + +#if GTEST_OS_WINDOWS_MOBILE +// Creates a UTF-16 wide string from the given ANSI string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the wide string, or NULL if the +// input is NULL. +LPCWSTR String::AnsiToUtf16(const char* ansi) { + if (!ansi) return NULL; + const int length = strlen(ansi); + const int unicode_length = + MultiByteToWideChar(CP_ACP, 0, ansi, length, + NULL, 0); + WCHAR* unicode = new WCHAR[unicode_length + 1]; + MultiByteToWideChar(CP_ACP, 0, ansi, length, + unicode, unicode_length); + unicode[unicode_length] = 0; + return unicode; +} + +// Creates an ANSI string from the given wide string, allocating +// memory using new. The caller is responsible for deleting the return +// value using delete[]. Returns the ANSI string, or NULL if the +// input is NULL. +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { + if (!utf16_str) return NULL; + const int ansi_length = + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + NULL, 0, NULL, NULL); + char* ansi = new char[ansi_length + 1]; + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, + ansi, ansi_length, NULL, NULL); + ansi[ansi_length] = 0; + return ansi; +} + +#endif // GTEST_OS_WINDOWS_MOBILE + +// Compares two C strings. Returns true iff they have the same content. +// +// Unlike strcmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CStringEquals(const char * lhs, const char * rhs) { + if ( lhs == NULL ) return rhs == NULL; + + if ( rhs == NULL ) return false; + + return strcmp(lhs, rhs) == 0; +} + +#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +// Converts an array of wide chars to a narrow string using the UTF-8 +// encoding, and streams the result to the given Message object. +static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, + Message* msg) { + for (size_t i = 0; i != length; ) { // NOLINT + if (wstr[i] != L'\0') { + *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); + while (i != length && wstr[i] != L'\0') + i++; + } else { + *msg << '\0'; + i++; + } + } +} + +#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING + +void SplitString(const ::std::string& str, char delimiter, + ::std::vector< ::std::string>* dest) { + ::std::vector< ::std::string> parsed; + ::std::string::size_type pos = 0; + while (::testing::internal::AlwaysTrue()) { + const ::std::string::size_type colon = str.find(delimiter, pos); + if (colon == ::std::string::npos) { + parsed.push_back(str.substr(pos)); + break; + } else { + parsed.push_back(str.substr(pos, colon - pos)); + pos = colon + 1; + } + } + dest->swap(parsed); +} + +} // namespace internal + +// Constructs an empty Message. +// We allocate the stringstream separately because otherwise each use of +// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's +// stack frame leading to huge stack frames in some cases; gcc does not reuse +// the stack space. +Message::Message() : ss_(new ::std::stringstream) { + // By default, we want there to be enough precision when printing + // a double to a Message. + *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); +} + +// These two overloads allow streaming a wide C string to a Message +// using the UTF-8 encoding. +Message& Message::operator <<(const wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} +Message& Message::operator <<(wchar_t* wide_c_str) { + return *this << internal::String::ShowWideCString(wide_c_str); +} + +#if GTEST_HAS_STD_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::std::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_STD_WSTRING + +#if GTEST_HAS_GLOBAL_WSTRING +// Converts the given wide string to a narrow string using the UTF-8 +// encoding, and streams the result to this Message object. +Message& Message::operator <<(const ::wstring& wstr) { + internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); + return *this; +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +// Gets the text streamed to this object so far as an std::string. +// Each '\0' character in the buffer is replaced with "\\0". +std::string Message::GetString() const { + return internal::StringStreamToString(ss_.get()); +} + +// AssertionResult constructors. +// Used in EXPECT_TRUE/FALSE(assertion_result). +AssertionResult::AssertionResult(const AssertionResult& other) + : success_(other.success_), + message_(other.message_.get() != NULL ? + new ::std::string(*other.message_) : + static_cast< ::std::string*>(NULL)) { +} + +// Swaps two AssertionResults. +void AssertionResult::swap(AssertionResult& other) { + using std::swap; + swap(success_, other.success_); + swap(message_, other.message_); +} + +// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. +AssertionResult AssertionResult::operator!() const { + AssertionResult negation(!success_); + if (message_.get() != NULL) + negation << *message_; + return negation; +} + +// Makes a successful assertion result. +AssertionResult AssertionSuccess() { + return AssertionResult(true); +} + +// Makes a failed assertion result. +AssertionResult AssertionFailure() { + return AssertionResult(false); +} + +// Makes a failed assertion result with the given failure message. +// Deprecated; use AssertionFailure() << message. +AssertionResult AssertionFailure(const Message& message) { + return AssertionFailure() << message; +} + +namespace internal { + +namespace edit_distance { +std::vector CalculateOptimalEdits(const std::vector& left, + const std::vector& right) { + std::vector > costs( + left.size() + 1, std::vector(right.size() + 1)); + std::vector > best_move( + left.size() + 1, std::vector(right.size() + 1)); + + // Populate for empty right. + for (size_t l_i = 0; l_i < costs.size(); ++l_i) { + costs[l_i][0] = static_cast(l_i); + best_move[l_i][0] = kRemove; + } + // Populate for empty left. + for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { + costs[0][r_i] = static_cast(r_i); + best_move[0][r_i] = kAdd; + } + + for (size_t l_i = 0; l_i < left.size(); ++l_i) { + for (size_t r_i = 0; r_i < right.size(); ++r_i) { + if (left[l_i] == right[r_i]) { + // Found a match. Consume it. + costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; + best_move[l_i + 1][r_i + 1] = kMatch; + continue; + } + + const double add = costs[l_i + 1][r_i]; + const double remove = costs[l_i][r_i + 1]; + const double replace = costs[l_i][r_i]; + if (add < remove && add < replace) { + costs[l_i + 1][r_i + 1] = add + 1; + best_move[l_i + 1][r_i + 1] = kAdd; + } else if (remove < add && remove < replace) { + costs[l_i + 1][r_i + 1] = remove + 1; + best_move[l_i + 1][r_i + 1] = kRemove; + } else { + // We make replace a little more expensive than add/remove to lower + // their priority. + costs[l_i + 1][r_i + 1] = replace + 1.00001; + best_move[l_i + 1][r_i + 1] = kReplace; + } + } + } + + // Reconstruct the best path. We do it in reverse order. + std::vector best_path; + for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { + EditType move = best_move[l_i][r_i]; + best_path.push_back(move); + l_i -= move != kAdd; + r_i -= move != kRemove; + } + std::reverse(best_path.begin(), best_path.end()); + return best_path; +} + +namespace { + +// Helper class to convert string into ids with deduplication. +class InternalStrings { + public: + size_t GetId(const std::string& str) { + IdMap::iterator it = ids_.find(str); + if (it != ids_.end()) return it->second; + size_t id = ids_.size(); + return ids_[str] = id; + } + + private: + typedef std::map IdMap; + IdMap ids_; +}; + +} // namespace + +std::vector CalculateOptimalEdits( + const std::vector& left, + const std::vector& right) { + std::vector left_ids, right_ids; + { + InternalStrings intern_table; + for (size_t i = 0; i < left.size(); ++i) { + left_ids.push_back(intern_table.GetId(left[i])); + } + for (size_t i = 0; i < right.size(); ++i) { + right_ids.push_back(intern_table.GetId(right[i])); + } + } + return CalculateOptimalEdits(left_ids, right_ids); +} + +namespace { + +// Helper class that holds the state for one hunk and prints it out to the +// stream. +// It reorders adds/removes when possible to group all removes before all +// adds. It also adds the hunk header before printint into the stream. +class Hunk { + public: + Hunk(size_t left_start, size_t right_start) + : left_start_(left_start), + right_start_(right_start), + adds_(), + removes_(), + common_() {} + + void PushLine(char edit, const char* line) { + switch (edit) { + case ' ': + ++common_; + FlushEdits(); + hunk_.push_back(std::make_pair(' ', line)); + break; + case '-': + ++removes_; + hunk_removes_.push_back(std::make_pair('-', line)); + break; + case '+': + ++adds_; + hunk_adds_.push_back(std::make_pair('+', line)); + break; + } + } + + void PrintTo(std::ostream* os) { + PrintHeader(os); + FlushEdits(); + for (std::list >::const_iterator it = + hunk_.begin(); + it != hunk_.end(); ++it) { + *os << it->first << it->second << "\n"; + } + } + + bool has_edits() const { return adds_ || removes_; } + + private: + void FlushEdits() { + hunk_.splice(hunk_.end(), hunk_removes_); + hunk_.splice(hunk_.end(), hunk_adds_); + } + + // Print a unified diff header for one hunk. + // The format is + // "@@ -, +, @@" + // where the left/right parts are ommitted if unnecessary. + void PrintHeader(std::ostream* ss) const { + *ss << "@@ "; + if (removes_) { + *ss << "-" << left_start_ << "," << (removes_ + common_); + } + if (removes_ && adds_) { + *ss << " "; + } + if (adds_) { + *ss << "+" << right_start_ << "," << (adds_ + common_); + } + *ss << " @@\n"; + } + + size_t left_start_, right_start_; + size_t adds_, removes_, common_; + std::list > hunk_, hunk_adds_, hunk_removes_; +}; + +} // namespace + +// Create a list of diff hunks in Unified diff format. +// Each hunk has a header generated by PrintHeader above plus a body with +// lines prefixed with ' ' for no change, '-' for deletion and '+' for +// addition. +// 'context' represents the desired unchanged prefix/suffix around the diff. +// If two hunks are close enough that their contexts overlap, then they are +// joined into one hunk. +std::string CreateUnifiedDiff(const std::vector& left, + const std::vector& right, + size_t context) { + const std::vector edits = CalculateOptimalEdits(left, right); + + size_t l_i = 0, r_i = 0, edit_i = 0; + std::stringstream ss; + while (edit_i < edits.size()) { + // Find first edit. + while (edit_i < edits.size() && edits[edit_i] == kMatch) { + ++l_i; + ++r_i; + ++edit_i; + } + + // Find the first line to include in the hunk. + const size_t prefix_context = std::min(l_i, context); + Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); + for (size_t i = prefix_context; i > 0; --i) { + hunk.PushLine(' ', left[l_i - i].c_str()); + } + + // Iterate the edits until we found enough suffix for the hunk or the input + // is over. + size_t n_suffix = 0; + for (; edit_i < edits.size(); ++edit_i) { + if (n_suffix >= context) { + // Continue only if the next hunk is very close. + std::vector::const_iterator it = edits.begin() + edit_i; + while (it != edits.end() && *it == kMatch) ++it; + if (it == edits.end() || (it - edits.begin()) - edit_i >= context) { + // There is no next edit or it is too far away. + break; + } + } + + EditType edit = edits[edit_i]; + // Reset count when a non match is found. + n_suffix = edit == kMatch ? n_suffix + 1 : 0; + + if (edit == kMatch || edit == kRemove || edit == kReplace) { + hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); + } + if (edit == kAdd || edit == kReplace) { + hunk.PushLine('+', right[r_i].c_str()); + } + + // Advance indices, depending on edit type. + l_i += edit != kAdd; + r_i += edit != kRemove; + } + + if (!hunk.has_edits()) { + // We are done. We don't want this hunk. + break; + } + + hunk.PrintTo(&ss); + } + return ss.str(); +} + +} // namespace edit_distance + +namespace { + +// The string representation of the values received in EqFailure() are already +// escaped. Split them on escaped '\n' boundaries. Leave all other escaped +// characters the same. +std::vector SplitEscapedString(const std::string& str) { + std::vector lines; + size_t start = 0, end = str.size(); + if (end > 2 && str[0] == '"' && str[end - 1] == '"') { + ++start; + --end; + } + bool escaped = false; + for (size_t i = start; i + 1 < end; ++i) { + if (escaped) { + escaped = false; + if (str[i] == 'n') { + lines.push_back(str.substr(start, i - start - 1)); + start = i + 1; + } + } else { + escaped = str[i] == '\\'; + } + } + lines.push_back(str.substr(start, end - start)); + return lines; +} + +} // namespace + +// Constructs and returns the message for an equality assertion +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. +// +// The first four parameters are the expressions used in the assertion +// and their values, as strings. For example, for ASSERT_EQ(foo, bar) +// where foo is 5 and bar is 6, we have: +// +// lhs_expression: "foo" +// rhs_expression: "bar" +// lhs_value: "5" +// rhs_value: "6" +// +// The ignoring_case parameter is true iff the assertion is a +// *_STRCASEEQ*. When it's true, the string "Ignoring case" will +// be inserted into the message. +AssertionResult EqFailure(const char* lhs_expression, + const char* rhs_expression, + const std::string& lhs_value, + const std::string& rhs_value, + bool ignoring_case) { + Message msg; + msg << " Expected: " << lhs_expression; + if (lhs_value != lhs_expression) { + msg << "\n Which is: " << lhs_value; + } + msg << "\nTo be equal to: " << rhs_expression; + if (rhs_value != rhs_expression) { + msg << "\n Which is: " << rhs_value; + } + + if (ignoring_case) { + msg << "\nIgnoring case"; + } + + if (!lhs_value.empty() && !rhs_value.empty()) { + const std::vector lhs_lines = + SplitEscapedString(lhs_value); + const std::vector rhs_lines = + SplitEscapedString(rhs_value); + if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { + msg << "\nWith diff:\n" + << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); + } + } + + return AssertionFailure() << msg; +} + +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. +std::string GetBoolAssertionFailureMessage( + const AssertionResult& assertion_result, + const char* expression_text, + const char* actual_predicate_value, + const char* expected_predicate_value) { + const char* actual_message = assertion_result.message(); + Message msg; + msg << "Value of: " << expression_text + << "\n Actual: " << actual_predicate_value; + if (actual_message[0] != '\0') + msg << " (" << actual_message << ")"; + msg << "\nExpected: " << expected_predicate_value; + return msg.GetString(); +} + +// Helper function for implementing ASSERT_NEAR. +AssertionResult DoubleNearPredFormat(const char* expr1, + const char* expr2, + const char* abs_error_expr, + double val1, + double val2, + double abs_error) { + const double diff = fabs(val1 - val2); + if (diff <= abs_error) return AssertionSuccess(); + + // TODO(wan): do not print the value of an expression if it's + // already a literal. + return AssertionFailure() + << "The difference between " << expr1 << " and " << expr2 + << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; +} + + +// Helper template for implementing FloatLE() and DoubleLE(). +template +AssertionResult FloatingPointLE(const char* expr1, + const char* expr2, + RawType val1, + RawType val2) { + // Returns success if val1 is less than val2, + if (val1 < val2) { + return AssertionSuccess(); + } + + // or if val1 is almost equal to val2. + const FloatingPoint lhs(val1), rhs(val2); + if (lhs.AlmostEquals(rhs)) { + return AssertionSuccess(); + } + + // Note that the above two checks will both fail if either val1 or + // val2 is NaN, as the IEEE floating-point standard requires that + // any predicate involving a NaN must return false. + + ::std::stringstream val1_ss; + val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val1; + + ::std::stringstream val2_ss; + val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) + << val2; + + return AssertionFailure() + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); +} + +} // namespace internal + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult FloatLE(const char* expr1, const char* expr2, + float val1, float val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +// Asserts that val1 is less than, or almost equal to, val2. Fails +// otherwise. In particular, it fails if either val1 or val2 is NaN. +AssertionResult DoubleLE(const char* expr1, const char* expr2, + double val1, double val2) { + return internal::FloatingPointLE(expr1, expr2, val1, val2); +} + +namespace internal { + +// The helper function for {ASSERT|EXPECT}_EQ with int or enum +// arguments. +AssertionResult CmpHelperEQ(const char* lhs_expression, + const char* rhs_expression, + BiggestInt lhs, + BiggestInt rhs) { + if (lhs == rhs) { + return AssertionSuccess(); + } + + return EqFailure(lhs_expression, + rhs_expression, + FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), + false); +} + +// A macro for implementing the helper functions needed to implement +// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here +// just to avoid copy-and-paste of similar code. +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + BiggestInt val1, BiggestInt val2) {\ + if (val1 op val2) {\ + return AssertionSuccess();\ + } else {\ + return AssertionFailure() \ + << "Expected: (" << expr1 << ") " #op " (" << expr2\ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ + << " vs " << FormatForComparisonFailureMessage(val2, val1);\ + }\ +} + +// Implements the helper function for {ASSERT|EXPECT}_NE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(NE, !=) +// Implements the helper function for {ASSERT|EXPECT}_LE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LE, <=) +// Implements the helper function for {ASSERT|EXPECT}_LT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(LT, < ) +// Implements the helper function for {ASSERT|EXPECT}_GE with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GE, >=) +// Implements the helper function for {ASSERT|EXPECT}_GT with int or +// enum arguments. +GTEST_IMPL_CMP_HELPER_(GT, > ) + +#undef GTEST_IMPL_CMP_HELPER_ + +// The helper function for {ASSERT|EXPECT}_STREQ. +AssertionResult CmpHelperSTREQ(const char* lhs_expression, + const char* rhs_expression, + const char* lhs, + const char* rhs) { + if (String::CStringEquals(lhs, rhs)) { + return AssertionSuccess(); + } + + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), + false); +} + +// The helper function for {ASSERT|EXPECT}_STRCASEEQ. +AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, + const char* rhs_expression, + const char* lhs, + const char* rhs) { + if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { + return AssertionSuccess(); + } + + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), + true); +} + +// The helper function for {ASSERT|EXPECT}_STRNE. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +// The helper function for {ASSERT|EXPECT}_STRCASENE. +AssertionResult CmpHelperSTRCASENE(const char* s1_expression, + const char* s2_expression, + const char* s1, + const char* s2) { + if (!String::CaseInsensitiveCStringEquals(s1, s2)) { + return AssertionSuccess(); + } else { + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" + << s2_expression << ") (ignoring case), actual: \"" + << s1 << "\" vs \"" << s2 << "\""; + } +} + +} // namespace internal + +namespace { + +// Helper functions for implementing IsSubString() and IsNotSubstring(). + +// This group of overloaded functions return true iff needle is a +// substring of haystack. NULL is considered a substring of itself +// only. + +bool IsSubstringPred(const char* needle, const char* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return strstr(haystack, needle) != NULL; +} + +bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { + if (needle == NULL || haystack == NULL) + return needle == haystack; + + return wcsstr(haystack, needle) != NULL; +} + +// StringType here can be either ::std::string or ::std::wstring. +template +bool IsSubstringPred(const StringType& needle, + const StringType& haystack) { + return haystack.find(needle) != StringType::npos; +} + +// This function implements either IsSubstring() or IsNotSubstring(), +// depending on the value of the expected_to_be_substring parameter. +// StringType here can be const char*, const wchar_t*, ::std::string, +// or ::std::wstring. +template +AssertionResult IsSubstringImpl( + bool expected_to_be_substring, + const char* needle_expr, const char* haystack_expr, + const StringType& needle, const StringType& haystack) { + if (IsSubstringPred(needle, haystack) == expected_to_be_substring) + return AssertionSuccess(); + + const bool is_wide_string = sizeof(needle[0]) > 1; + const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; + return AssertionFailure() + << "Value of: " << needle_expr << "\n" + << " Actual: " << begin_string_quote << needle << "\"\n" + << "Expected: " << (expected_to_be_substring ? "" : "not ") + << "a substring of " << haystack_expr << "\n" + << "Which is: " << begin_string_quote << haystack << "\""; +} + +} // namespace + +// IsSubstring() and IsNotSubstring() check whether needle is a +// substring of haystack (NULL is considered a substring of itself +// only), and return an appropriate error message when they fail. + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} + +#if GTEST_HAS_STD_WSTRING +AssertionResult IsSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); +} + +AssertionResult IsNotSubstring( + const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack) { + return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); +} +#endif // GTEST_HAS_STD_WSTRING + +namespace internal { + +#if GTEST_OS_WINDOWS + +namespace { + +// Helper function for IsHRESULT{SuccessFailure} predicates +AssertionResult HRESULTFailureHelper(const char* expr, + const char* expected, + long hr) { // NOLINT +# if GTEST_OS_WINDOWS_MOBILE + + // Windows CE doesn't support FormatMessage. + const char error_text[] = ""; + +# else + + // Looks up the human-readable system message for the HRESULT code + // and since we're not passing any params to FormatMessage, we don't + // want inserts expanded. + const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kBufSize = 4096; + // Gets the system's human readable message string for this HRESULT. + char error_text[kBufSize] = { '\0' }; + DWORD message_length = ::FormatMessageA(kFlags, + 0, // no source, we're asking system + hr, // the error + 0, // no line width restrictions + error_text, // output buffer + kBufSize, // buf size + NULL); // no arguments for inserts + // Trims tailing white space (FormatMessage leaves a trailing CR-LF) + for (; message_length && IsSpace(error_text[message_length - 1]); + --message_length) { + error_text[message_length - 1] = '\0'; + } + +# endif // GTEST_OS_WINDOWS_MOBILE + + const std::string error_hex("0x" + String::FormatHexInt(hr)); + return ::testing::AssertionFailure() + << "Expected: " << expr << " " << expected << ".\n" + << " Actual: " << error_hex << " " << error_text << "\n"; +} + +} // namespace + +AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT + if (SUCCEEDED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "succeeds", hr); +} + +AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT + if (FAILED(hr)) { + return AssertionSuccess(); + } + return HRESULTFailureHelper(expr, "fails", hr); +} + +#endif // GTEST_OS_WINDOWS + +// Utility functions for encoding Unicode text (wide strings) in +// UTF-8. + +// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 +// like this: +// +// Code-point length Encoding +// 0 - 7 bits 0xxxxxxx +// 8 - 11 bits 110xxxxx 10xxxxxx +// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx +// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + +// The maximum code-point a one-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; + +// The maximum code-point a two-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; + +// The maximum code-point a three-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; + +// The maximum code-point a four-byte UTF-8 sequence can represent. +const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; + +// Chops off the n lowest bits from a bit pattern. Returns the n +// lowest bits. As a side effect, the original bit pattern will be +// shifted to the right by n bits. +inline UInt32 ChopLowBits(UInt32* bits, int n) { + const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); + *bits >>= n; + return low_bits; +} + +// Converts a Unicode code point to a narrow string in UTF-8 encoding. +// code_point parameter is of type UInt32 because wchar_t may not be +// wide enough to contain a code point. +// If the code_point is not a valid Unicode code point +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted +// to "(Invalid Unicode 0xXXXXXXXX)". +std::string CodePointToUtf8(UInt32 code_point) { + if (code_point > kMaxCodePoint4) { + return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; + } + + char str[5]; // Big enough for the largest valid code point. + if (code_point <= kMaxCodePoint1) { + str[1] = '\0'; + str[0] = static_cast(code_point); // 0xxxxxxx + } else if (code_point <= kMaxCodePoint2) { + str[2] = '\0'; + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xC0 | code_point); // 110xxxxx + } else if (code_point <= kMaxCodePoint3) { + str[3] = '\0'; + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xE0 | code_point); // 1110xxxx + } else { // code_point <= kMaxCodePoint4 + str[4] = '\0'; + str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx + str[0] = static_cast(0xF0 | code_point); // 11110xxx + } + return str; +} + +// The following two functions only make sense if the the system +// uses UTF-16 for wide string encoding. All supported systems +// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. + +// Determines if the arguments constitute UTF-16 surrogate pair +// and thus should be combined into a single Unicode code point +// using CreateCodePointFromUtf16SurrogatePair. +inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { + return sizeof(wchar_t) == 2 && + (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; +} + +// Creates a Unicode code point from UTF16 surrogate pair. +inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, + wchar_t second) { + const UInt32 mask = (1 << 10) - 1; + return (sizeof(wchar_t) == 2) ? + (((first & mask) << 10) | (second & mask)) + 0x10000 : + // This function should not be called when the condition is + // false, but we provide a sensible default in case it is. + static_cast(first); +} + +// Converts a wide string to a narrow string in UTF-8 encoding. +// The wide string is assumed to have the following encoding: +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-32 if sizeof(wchar_t) == 4 (on Linux) +// Parameter str points to a null-terminated wide string. +// Parameter num_chars may additionally limit the number +// of wchar_t characters processed. -1 is used when the entire string +// should be processed. +// If the string contains code points that are not valid Unicode code points +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding +// and contains invalid UTF-16 surrogate pairs, values in those pairs +// will be encoded as individual Unicode characters from Basic Normal Plane. +std::string WideStringToUtf8(const wchar_t* str, int num_chars) { + if (num_chars == -1) + num_chars = static_cast(wcslen(str)); + + ::std::stringstream stream; + for (int i = 0; i < num_chars; ++i) { + UInt32 unicode_code_point; + + if (str[i] == L'\0') { + break; + } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { + unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], + str[i + 1]); + i++; + } else { + unicode_code_point = static_cast(str[i]); + } + + stream << CodePointToUtf8(unicode_code_point); + } + return StringStreamToString(&stream); +} + +// Converts a wide C string to an std::string using the UTF-8 encoding. +// NULL will be converted to "(null)". +std::string String::ShowWideCString(const wchar_t * wide_c_str) { + if (wide_c_str == NULL) return "(null)"; + + return internal::WideStringToUtf8(wide_c_str, -1); +} + +// Compares two wide C strings. Returns true iff they have the same +// content. +// +// Unlike wcscmp(), this function can handle NULL argument(s). A NULL +// C string is considered different to any non-NULL C string, +// including the empty string. +bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + + return wcscmp(lhs, rhs) == 0; +} + +// Helper function for *_STREQ on wide strings. +AssertionResult CmpHelperSTREQ(const char* lhs_expression, + const char* rhs_expression, + const wchar_t* lhs, + const wchar_t* rhs) { + if (String::WideCStringEquals(lhs, rhs)) { + return AssertionSuccess(); + } + + return EqFailure(lhs_expression, + rhs_expression, + PrintToString(lhs), + PrintToString(rhs), + false); +} + +// Helper function for *_STRNE on wide strings. +AssertionResult CmpHelperSTRNE(const char* s1_expression, + const char* s2_expression, + const wchar_t* s1, + const wchar_t* s2) { + if (!String::WideCStringEquals(s1, s2)) { + return AssertionSuccess(); + } + + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" + << s2_expression << "), actual: " + << PrintToString(s1) + << " vs " << PrintToString(s2); +} + +// Compares two C strings, ignoring case. Returns true iff they have +// the same content. +// +// Unlike strcasecmp(), this function can handle NULL argument(s). A +// NULL C string is considered different to any non-NULL C string, +// including the empty string. +bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { + if (lhs == NULL) + return rhs == NULL; + if (rhs == NULL) + return false; + return posix::StrCaseCmp(lhs, rhs) == 0; +} + + // Compares two wide C strings, ignoring case. Returns true iff they + // have the same content. + // + // Unlike wcscasecmp(), this function can handle NULL argument(s). + // A NULL C string is considered different to any non-NULL wide C string, + // including the empty string. + // NB: The implementations on different platforms slightly differ. + // On windows, this method uses _wcsicmp which compares according to LC_CTYPE + // environment variable. On GNU platform this method uses wcscasecmp + // which compares according to LC_CTYPE category of the current locale. + // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the + // current locale. +bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, + const wchar_t* rhs) { + if (lhs == NULL) return rhs == NULL; + + if (rhs == NULL) return false; + +#if GTEST_OS_WINDOWS + return _wcsicmp(lhs, rhs) == 0; +#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID + return wcscasecmp(lhs, rhs) == 0; +#else + // Android, Mac OS X and Cygwin don't define wcscasecmp. + // Other unknown OSes may not define it either. + wint_t left, right; + do { + left = towlower(*lhs++); + right = towlower(*rhs++); + } while (left && left == right); + return left == right; +#endif // OS selector +} + +// Returns true iff str ends with the given suffix, ignoring case. +// Any string is considered to end with an empty suffix. +bool String::EndsWithCaseInsensitive( + const std::string& str, const std::string& suffix) { + const size_t str_len = str.length(); + const size_t suffix_len = suffix.length(); + return (str_len >= suffix_len) && + CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, + suffix.c_str()); +} + +// Formats an int value as "%02d". +std::string String::FormatIntWidth2(int value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << value; + return ss.str(); +} + +// Formats an int value as "%X". +std::string String::FormatHexInt(int value) { + std::stringstream ss; + ss << std::hex << std::uppercase << value; + return ss.str(); +} + +// Formats a byte as "%02X". +std::string String::FormatByte(unsigned char value) { + std::stringstream ss; + ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase + << static_cast(value); + return ss.str(); +} + +// Converts the buffer in a stringstream to an std::string, converting NUL +// bytes to "\\0" along the way. +std::string StringStreamToString(::std::stringstream* ss) { + const ::std::string& str = ss->str(); + const char* const start = str.c_str(); + const char* const end = start + str.length(); + + std::string result; + result.reserve(2 * (end - start)); + for (const char* ch = start; ch != end; ++ch) { + if (*ch == '\0') { + result += "\\0"; // Replaces NUL with "\\0"; + } else { + result += *ch; + } + } + + return result; +} + +// Appends the user-supplied message to the Google-Test-generated message. +std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg) { + // Appends the user message if it's non-empty. + const std::string user_msg_string = user_msg.GetString(); + if (user_msg_string.empty()) { + return gtest_msg; + } + + return gtest_msg + "\n" + user_msg_string; +} + +} // namespace internal + +// class TestResult + +// Creates an empty TestResult. +TestResult::TestResult() + : death_test_count_(0), + elapsed_time_(0) { +} + +// D'tor. +TestResult::~TestResult() { +} + +// Returns the i-th test part result among all the results. i can +// range from 0 to total_part_count() - 1. If i is not in that range, +// aborts the program. +const TestPartResult& TestResult::GetTestPartResult(int i) const { + if (i < 0 || i >= total_part_count()) + internal::posix::Abort(); + return test_part_results_.at(i); +} + +// Returns the i-th test property. i can range from 0 to +// test_property_count() - 1. If i is not in that range, aborts the +// program. +const TestProperty& TestResult::GetTestProperty(int i) const { + if (i < 0 || i >= test_property_count()) + internal::posix::Abort(); + return test_properties_.at(i); +} + +// Clears the test part results. +void TestResult::ClearTestPartResults() { + test_part_results_.clear(); +} + +// Adds a test part result to the list. +void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { + test_part_results_.push_back(test_part_result); +} + +// Adds a test property to the list. If a property with the same key as the +// supplied property is already represented, the value of this test_property +// replaces the old value for that key. +void TestResult::RecordProperty(const std::string& xml_element, + const TestProperty& test_property) { + if (!ValidateTestProperty(xml_element, test_property)) { + return; + } + internal::MutexLock lock(&test_properites_mutex_); + const std::vector::iterator property_with_matching_key = + std::find_if(test_properties_.begin(), test_properties_.end(), + internal::TestPropertyKeyIs(test_property.key())); + if (property_with_matching_key == test_properties_.end()) { + test_properties_.push_back(test_property); + return; + } + property_with_matching_key->SetValue(test_property.value()); +} + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuitesAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "random_seed", + "tests", + "time", + "timestamp" +}; + +// The list of reserved attributes used in the element of XML +// output. +static const char* const kReservedTestSuiteAttributes[] = { + "disabled", + "errors", + "failures", + "name", + "tests", + "time" +}; + +// The list of reserved attributes used in the element of XML output. +static const char* const kReservedTestCaseAttributes[] = { + "classname", + "name", + "status", + "time", + "type_param", + "value_param" +}; + +template +std::vector ArrayAsVector(const char* const (&array)[kSize]) { + return std::vector(array, array + kSize); +} + +static std::vector GetReservedAttributesForElement( + const std::string& xml_element) { + if (xml_element == "testsuites") { + return ArrayAsVector(kReservedTestSuitesAttributes); + } else if (xml_element == "testsuite") { + return ArrayAsVector(kReservedTestSuiteAttributes); + } else if (xml_element == "testcase") { + return ArrayAsVector(kReservedTestCaseAttributes); + } else { + GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; + } + // This code is unreachable but some compilers may not realizes that. + return std::vector(); +} + +static std::string FormatWordList(const std::vector& words) { + Message word_list; + for (size_t i = 0; i < words.size(); ++i) { + if (i > 0 && words.size() > 2) { + word_list << ", "; + } + if (i == words.size() - 1) { + word_list << "and "; + } + word_list << "'" << words[i] << "'"; + } + return word_list.GetString(); +} + +bool ValidateTestPropertyName(const std::string& property_name, + const std::vector& reserved_names) { + if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != + reserved_names.end()) { + ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name + << " (" << FormatWordList(reserved_names) + << " are reserved by " << GTEST_NAME_ << ")"; + return false; + } + return true; +} + +// Adds a failure if the key is a reserved attribute of the element named +// xml_element. Returns true if the property is valid. +bool TestResult::ValidateTestProperty(const std::string& xml_element, + const TestProperty& test_property) { + return ValidateTestPropertyName(test_property.key(), + GetReservedAttributesForElement(xml_element)); +} + +// Clears the object. +void TestResult::Clear() { + test_part_results_.clear(); + test_properties_.clear(); + death_test_count_ = 0; + elapsed_time_ = 0; +} + +// Returns true iff the test failed. +bool TestResult::Failed() const { + for (int i = 0; i < total_part_count(); ++i) { + if (GetTestPartResult(i).failed()) + return true; + } + return false; +} + +// Returns true iff the test part fatally failed. +static bool TestPartFatallyFailed(const TestPartResult& result) { + return result.fatally_failed(); +} + +// Returns true iff the test fatally failed. +bool TestResult::HasFatalFailure() const { + return CountIf(test_part_results_, TestPartFatallyFailed) > 0; +} + +// Returns true iff the test part non-fatally failed. +static bool TestPartNonfatallyFailed(const TestPartResult& result) { + return result.nonfatally_failed(); +} + +// Returns true iff the test has a non-fatal failure. +bool TestResult::HasNonfatalFailure() const { + return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; +} + +// Gets the number of all test parts. This is the sum of the number +// of successful test parts and the number of failed test parts. +int TestResult::total_part_count() const { + return static_cast(test_part_results_.size()); +} + +// Returns the number of the test properties. +int TestResult::test_property_count() const { + return static_cast(test_properties_.size()); +} + +// class Test + +// Creates a Test object. + +// The c'tor saves the states of all flags. +Test::Test() + : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { +} + +// The d'tor restores the states of all flags. The actual work is +// done by the d'tor of the gtest_flag_saver_ field, and thus not +// visible here. +Test::~Test() { +} + +// Sets up the test fixture. +// +// A sub-class may override this. +void Test::SetUp() { +} + +// Tears down the test fixture. +// +// A sub-class may override this. +void Test::TearDown() { +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, const std::string& value) { + UnitTest::GetInstance()->RecordProperty(key, value); +} + +// Allows user supplied key value pairs to be recorded for later output. +void Test::RecordProperty(const std::string& key, int value) { + Message value_message; + value_message << value; + RecordProperty(key, value_message.GetString().c_str()); +} + +namespace internal { + +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, + const std::string& message) { + // This function is a friend of UnitTest and as such has access to + // AddTestPartResult. + UnitTest::GetInstance()->AddTestPartResult( + result_type, + NULL, // No info about the source file where the exception occurred. + -1, // We have no info on which line caused the exception. + message, + ""); // No stack trace, either. +} + +} // namespace internal + +// Google Test requires all tests in the same test case to use the same test +// fixture class. This function checks if the current test has the +// same fixture class as the first test in the current test case. If +// yes, it returns true; otherwise it generates a Google Test failure and +// returns false. +bool Test::HasSameFixtureClass() { + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + const TestCase* const test_case = impl->current_test_case(); + + // Info about the first test in the current test case. + const TestInfo* const first_test_info = test_case->test_info_list()[0]; + const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; + const char* const first_test_name = first_test_info->name(); + + // Info about the current test. + const TestInfo* const this_test_info = impl->current_test_info(); + const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; + const char* const this_test_name = this_test_info->name(); + + if (this_fixture_id != first_fixture_id) { + // Is the first test defined using TEST? + const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); + // Is this test defined using TEST? + const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); + + if (first_is_TEST || this_is_TEST) { + // Both TEST and TEST_F appear in same test case, which is incorrect. + // Tell the user how to fix this. + + // Gets the name of the TEST and the name of the TEST_F. Note + // that first_is_TEST and this_is_TEST cannot both be true, as + // the fixture IDs are different for the two tests. + const char* const TEST_name = + first_is_TEST ? first_test_name : this_test_name; + const char* const TEST_F_name = + first_is_TEST ? this_test_name : first_test_name; + + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class, so mixing TEST_F and TEST in the same test case is\n" + << "illegal. In test case " << this_test_info->test_case_name() + << ",\n" + << "test " << TEST_F_name << " is defined using TEST_F but\n" + << "test " << TEST_name << " is defined using TEST. You probably\n" + << "want to change the TEST to TEST_F or move it to another test\n" + << "case."; + } else { + // Two fixture classes with the same name appear in two different + // namespaces, which is not allowed. Tell the user how to fix this. + ADD_FAILURE() + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " + << this_test_info->test_case_name() << ",\n" + << "you defined test " << first_test_name + << " and test " << this_test_name << "\n" + << "using two different test fixture classes. This can happen if\n" + << "the two classes are from different namespaces or translation\n" + << "units and have the same name. You should probably rename one\n" + << "of the classes to put the tests into different test cases."; + } + return false; + } + + return true; +} + +#if GTEST_HAS_SEH + +// Adds an "exception thrown" fatal failure to the current test. This +// function returns its result via an output parameter pointer because VC++ +// prohibits creation of objects with destructors on stack in functions +// using __try (see error C2712). +static std::string* FormatSehExceptionMessage(DWORD exception_code, + const char* location) { + Message message; + message << "SEH exception with code 0x" << std::setbase(16) << + exception_code << std::setbase(10) << " thrown in " << location << "."; + + return new std::string(message.GetString()); +} + +#endif // GTEST_HAS_SEH + +namespace internal { + +#if GTEST_HAS_EXCEPTIONS + +// Adds an "exception thrown" fatal failure to the current test. +static std::string FormatCxxExceptionMessage(const char* description, + const char* location) { + Message message; + if (description != NULL) { + message << "C++ exception with description \"" << description << "\""; + } else { + message << "Unknown C++ exception"; + } + message << " thrown in " << location << "."; + + return message.GetString(); +} + +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result); + +GoogleTestFailureException::GoogleTestFailureException( + const TestPartResult& failure) + : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} + +#endif // GTEST_HAS_EXCEPTIONS + +// We put these helper functions in the internal namespace as IBM's xlC +// compiler rejects the code if they were declared static. + +// Runs the given method and handles SEH exceptions it throws, when +// SEH is supported; returns the 0-value for type Result in case of an +// SEH exception. (Microsoft compilers cannot handle SEH and C++ +// exceptions in the same function. Therefore, we provide a separate +// wrapper function for handling SEH exceptions.) +template +Result HandleSehExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { +#if GTEST_HAS_SEH + __try { + return (object->*method)(); + } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT + GetExceptionCode())) { + // We create the exception message on the heap because VC++ prohibits + // creation of objects with destructors on stack in functions using __try + // (see error C2712). + std::string* exception_message = FormatSehExceptionMessage( + GetExceptionCode(), location); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + *exception_message); + delete exception_message; + return static_cast(0); + } +#else + (void)location; + return (object->*method)(); +#endif // GTEST_HAS_SEH +} + +// Runs the given method and catches and reports C++ and/or SEH-style +// exceptions, if they are supported; returns the 0-value for type +// Result in case of an SEH exception. +template +Result HandleExceptionsInMethodIfSupported( + T* object, Result (T::*method)(), const char* location) { + // NOTE: The user code can affect the way in which Google Test handles + // exceptions by setting GTEST_FLAG(catch_exceptions), but only before + // RUN_ALL_TESTS() starts. It is technically possible to check the flag + // after the exception is caught and either report or re-throw the + // exception based on the flag's value: + // + // try { + // // Perform the test method. + // } catch (...) { + // if (GTEST_FLAG(catch_exceptions)) + // // Report the exception as failure. + // else + // throw; // Re-throws the original exception. + // } + // + // However, the purpose of this flag is to allow the program to drop into + // the debugger when the exception is thrown. On most platforms, once the + // control enters the catch block, the exception origin information is + // lost and the debugger will stop the program at the point of the + // re-throw in this function -- instead of at the point of the original + // throw statement in the code under test. For this reason, we perform + // the check early, sacrificing the ability to affect Google Test's + // exception handling in the method where the exception is thrown. + if (internal::GetUnitTestImpl()->catch_exceptions()) { +#if GTEST_HAS_EXCEPTIONS + try { + return HandleSehExceptionsInMethodIfSupported(object, method, location); + } catch (const internal::GoogleTestFailureException&) { // NOLINT + // This exception type can only be thrown by a failed Google + // Test assertion with the intention of letting another testing + // framework catch it. Therefore we just re-throw it. + throw; + } catch (const std::exception& e) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(e.what(), location)); + } catch (...) { // NOLINT + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(NULL, location)); + } + return static_cast(0); +#else + return HandleSehExceptionsInMethodIfSupported(object, method, location); +#endif // GTEST_HAS_EXCEPTIONS + } else { + return (object->*method)(); + } +} + +} // namespace internal + +// Runs the test and updates the test result. +void Test::Run() { + if (!HasSameFixtureClass()) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); + // We will run the test only if SetUp() was successful. + if (!HasFatalFailure()) { + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TestBody, "the test body"); + } + + // However, we want to clean up as much as possible. Hence we will + // always call TearDown(), even if SetUp() or the test body has + // failed. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &Test::TearDown, "TearDown()"); +} + +// Returns true iff the current test has a fatal failure. +bool Test::HasFatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); +} + +// Returns true iff the current test has a non-fatal failure. +bool Test::HasNonfatalFailure() { + return internal::GetUnitTestImpl()->current_test_result()-> + HasNonfatalFailure(); +} + +// class TestInfo + +// Constructs a TestInfo object. It assumes ownership of the test factory +// object. +TestInfo::TestInfo(const std::string& a_test_case_name, + const std::string& a_name, + const char* a_type_param, + const char* a_value_param, + internal::CodeLocation a_code_location, + internal::TypeId fixture_class_id, + internal::TestFactoryBase* factory) + : test_case_name_(a_test_case_name), + name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + value_param_(a_value_param ? new std::string(a_value_param) : NULL), + location_(a_code_location), + fixture_class_id_(fixture_class_id), + should_run_(false), + is_disabled_(false), + matches_filter_(false), + factory_(factory), + result_() {} + +// Destructs a TestInfo object. +TestInfo::~TestInfo() { delete factory_; } + +namespace internal { + +// Creates a new TestInfo object and registers it with Google Test; +// returns the created object. +// +// Arguments: +// +// test_case_name: name of the test case +// name: name of the test +// type_param: the name of the test's type parameter, or NULL if +// this is not a typed or a type-parameterized test. +// value_param: text representation of the test's value parameter, +// or NULL if this is not a value-parameterized test. +// code_location: code location where the test is defined +// fixture_class_id: ID of the test fixture class +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +// factory: pointer to the factory that creates a test object. +// The newly created TestInfo instance will assume +// ownership of the factory object. +TestInfo* MakeAndRegisterTestInfo( + const char* test_case_name, + const char* name, + const char* type_param, + const char* value_param, + CodeLocation code_location, + TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory) { + TestInfo* const test_info = + new TestInfo(test_case_name, name, type_param, value_param, + code_location, fixture_class_id, factory); + GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); + return test_info; +} + +#if GTEST_HAS_PARAM_TEST +void ReportInvalidTestCaseType(const char* test_case_name, + CodeLocation code_location) { + Message errors; + errors + << "Attempted redefinition of test case " << test_case_name << ".\n" + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " << test_case_name << ", you tried\n" + << "to define a test using a fixture class different from the one\n" + << "used earlier. This can happen if the two fixture classes are\n" + << "from different namespaces and have the same name. You should\n" + << "probably rename one of the classes to put the tests into different\n" + << "test cases."; + + fprintf(stderr, "%s %s", + FormatFileLocation(code_location.file.c_str(), + code_location.line).c_str(), + errors.GetString().c_str()); +} +#endif // GTEST_HAS_PARAM_TEST + +} // namespace internal + +namespace { + +// A predicate that checks the test name of a TestInfo against a known +// value. +// +// This is used for implementation of the TestCase class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestNameIs is copyable. +class TestNameIs { + public: + // Constructor. + // + // TestNameIs has NO default constructor. + explicit TestNameIs(const char* name) + : name_(name) {} + + // Returns true iff the test name of test_info matches name_. + bool operator()(const TestInfo * test_info) const { + return test_info && test_info->name() == name_; + } + + private: + std::string name_; +}; + +} // namespace + +namespace internal { + +// This method expands all parameterized tests registered with macros TEST_P +// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. +// This will be done just once during the program runtime. +void UnitTestImpl::RegisterParameterizedTests() { +#if GTEST_HAS_PARAM_TEST + if (!parameterized_tests_registered_) { + parameterized_test_registry_.RegisterTests(); + parameterized_tests_registered_ = true; + } +#endif +} + +} // namespace internal + +// Creates the test object, runs it, records its result, and then +// deletes it. +void TestInfo::Run() { + if (!should_run_) return; + + // Tells UnitTest where to store test result. + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_info(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + // Notifies the unit test event listeners that a test is about to start. + repeater->OnTestStart(*this); + + const TimeInMillis start = internal::GetTimeInMillis(); + + impl->os_stack_trace_getter()->UponLeavingGTest(); + + // Creates the test object. + Test* const test = internal::HandleExceptionsInMethodIfSupported( + factory_, &internal::TestFactoryBase::CreateTest, + "the test fixture's constructor"); + + // Runs the test only if the test object was created and its + // constructor didn't generate a fatal failure. + if ((test != NULL) && !Test::HasFatalFailure()) { + // This doesn't throw as all user code that can throw are wrapped into + // exception handling code. + test->Run(); + } + + // Deletes the test object. + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + test, &Test::DeleteSelf_, "the test fixture's destructor"); + + result_.set_elapsed_time(internal::GetTimeInMillis() - start); + + // Notifies the unit test event listener that a test has just finished. + repeater->OnTestEnd(*this); + + // Tells UnitTest to stop associating assertion results to this + // test. + impl->set_current_test_info(NULL); +} + +// class TestCase + +// Gets the number of successful tests in this test case. +int TestCase::successful_test_count() const { + return CountIf(test_info_list_, TestPassed); +} + +// Gets the number of failed tests in this test case. +int TestCase::failed_test_count() const { + return CountIf(test_info_list_, TestFailed); +} + +// Gets the number of disabled tests that will be reported in the XML report. +int TestCase::reportable_disabled_test_count() const { + return CountIf(test_info_list_, TestReportableDisabled); +} + +// Gets the number of disabled tests in this test case. +int TestCase::disabled_test_count() const { + return CountIf(test_info_list_, TestDisabled); +} + +// Gets the number of tests to be printed in the XML report. +int TestCase::reportable_test_count() const { + return CountIf(test_info_list_, TestReportable); +} + +// Get the number of tests in this test case that should run. +int TestCase::test_to_run_count() const { + return CountIf(test_info_list_, ShouldRunTest); +} + +// Gets the number of all tests. +int TestCase::total_test_count() const { + return static_cast(test_info_list_.size()); +} + +// Creates a TestCase with the given name. +// +// Arguments: +// +// name: name of the test case +// a_type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase::TestCase(const char* a_name, const char* a_type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) + : name_(a_name), + type_param_(a_type_param ? new std::string(a_type_param) : NULL), + set_up_tc_(set_up_tc), + tear_down_tc_(tear_down_tc), + should_run_(false), + elapsed_time_(0) { +} + +// Destructor of TestCase. +TestCase::~TestCase() { + // Deletes every Test in the collection. + ForEach(test_info_list_, internal::Delete); +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +const TestInfo* TestCase::GetTestInfo(int i) const { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Returns the i-th test among all the tests. i can range from 0 to +// total_test_count() - 1. If i is not in that range, returns NULL. +TestInfo* TestCase::GetMutableTestInfo(int i) { + const int index = GetElementOr(test_indices_, i, -1); + return index < 0 ? NULL : test_info_list_[index]; +} + +// Adds a test to this test case. Will delete the test upon +// destruction of the TestCase object. +void TestCase::AddTestInfo(TestInfo * test_info) { + test_info_list_.push_back(test_info); + test_indices_.push_back(static_cast(test_indices_.size())); +} + +// Runs every test in this TestCase. +void TestCase::Run() { + if (!should_run_) return; + + internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); + impl->set_current_test_case(this); + + TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + + repeater->OnTestCaseStart(*this); + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); + + const internal::TimeInMillis start = internal::GetTimeInMillis(); + for (int i = 0; i < total_test_count(); i++) { + GetMutableTestInfo(i)->Run(); + } + elapsed_time_ = internal::GetTimeInMillis() - start; + + impl->os_stack_trace_getter()->UponLeavingGTest(); + internal::HandleExceptionsInMethodIfSupported( + this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + + repeater->OnTestCaseEnd(*this); + impl->set_current_test_case(NULL); +} + +// Clears the results of all tests in this test case. +void TestCase::ClearResult() { + ad_hoc_test_result_.Clear(); + ForEach(test_info_list_, TestInfo::ClearTestResult); +} + +// Shuffles the tests in this test case. +void TestCase::ShuffleTests(internal::Random* random) { + Shuffle(random, &test_indices_); +} + +// Restores the test order to before the first shuffle. +void TestCase::UnshuffleTests() { + for (size_t i = 0; i < test_indices_.size(); i++) { + test_indices_[i] = static_cast(i); + } +} + +// Formats a countable noun. Depending on its quantity, either the +// singular form or the plural form is used. e.g. +// +// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". +// FormatCountableNoun(5, "book", "books") returns "5 books". +static std::string FormatCountableNoun(int count, + const char * singular_form, + const char * plural_form) { + return internal::StreamableToString(count) + " " + + (count == 1 ? singular_form : plural_form); +} + +// Formats the count of tests. +static std::string FormatTestCount(int test_count) { + return FormatCountableNoun(test_count, "test", "tests"); +} + +// Formats the count of test cases. +static std::string FormatTestCaseCount(int test_case_count) { + return FormatCountableNoun(test_case_count, "test case", "test cases"); +} + +// Converts a TestPartResult::Type enum to human-friendly string +// representation. Both kNonFatalFailure and kFatalFailure are translated +// to "Failure", as the user usually doesn't care about the difference +// between the two when viewing the test result. +static const char * TestPartResultTypeToString(TestPartResult::Type type) { + switch (type) { + case TestPartResult::kSuccess: + return "Success"; + + case TestPartResult::kNonFatalFailure: + case TestPartResult::kFatalFailure: +#ifdef _MSC_VER + return "error: "; +#else + return "Failure\n"; +#endif + default: + return "Unknown result type"; + } +} + +namespace internal { + +// Prints a TestPartResult to an std::string. +static std::string PrintTestPartResultToString( + const TestPartResult& test_part_result) { + return (Message() + << internal::FormatFileLocation(test_part_result.file_name(), + test_part_result.line_number()) + << " " << TestPartResultTypeToString(test_part_result.type()) + << test_part_result.message()).GetString(); +} + +// Prints a TestPartResult. +static void PrintTestPartResult(const TestPartResult& test_part_result) { + const std::string& result = + PrintTestPartResultToString(test_part_result); + printf("%s\n", result.c_str()); + fflush(stdout); + // If the test program runs in Visual Studio or a debugger, the + // following statements add the test part result message to the Output + // window such that the user can double-click on it to jump to the + // corresponding source code location; otherwise they do nothing. +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + // We don't call OutputDebugString*() on Windows Mobile, as printing + // to stdout is done by OutputDebugString() there already - we don't + // want the same message printed twice. + ::OutputDebugStringA(result.c_str()); + ::OutputDebugStringA("\n"); +#endif +} + +// class PrettyUnitTestResultPrinter + +enum GTestColor { + COLOR_DEFAULT, + COLOR_RED, + COLOR_GREEN, + COLOR_YELLOW +}; + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ + !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + +// Returns the character attribute for the given color. +WORD GetColorAttribute(GTestColor color) { + switch (color) { + case COLOR_RED: return FOREGROUND_RED; + case COLOR_GREEN: return FOREGROUND_GREEN; + case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; + default: return 0; + } +} + +#else + +// Returns the ANSI color code for the given color. COLOR_DEFAULT is +// an invalid input. +const char* GetAnsiColorCode(GTestColor color) { + switch (color) { + case COLOR_RED: return "1"; + case COLOR_GREEN: return "2"; + case COLOR_YELLOW: return "3"; + default: return NULL; + }; +} + +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + +// Returns true iff Google Test should use colors in the output. +bool ShouldUseColor(bool stdout_is_tty) { + const char* const gtest_color = GTEST_FLAG(color).c_str(); + + if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { +#if GTEST_OS_WINDOWS + // On Windows the TERM variable is usually not set, but the + // console there does support colors. + return stdout_is_tty; +#else + // On non-Windows platforms, we rely on the TERM variable. + const char* const term = posix::GetEnv("TERM"); + const bool term_supports_color = + String::CStringEquals(term, "xterm") || + String::CStringEquals(term, "xterm-color") || + String::CStringEquals(term, "xterm-256color") || + String::CStringEquals(term, "screen") || + String::CStringEquals(term, "screen-256color") || + String::CStringEquals(term, "tmux") || + String::CStringEquals(term, "tmux-256color") || + String::CStringEquals(term, "rxvt-unicode") || + String::CStringEquals(term, "rxvt-unicode-256color") || + String::CStringEquals(term, "linux") || + String::CStringEquals(term, "cygwin"); + return stdout_is_tty && term_supports_color; +#endif // GTEST_OS_WINDOWS + } + + return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || + String::CStringEquals(gtest_color, "1"); + // We take "yes", "true", "t", and "1" as meaning "yes". If the + // value is neither one of these nor "auto", we treat it as "no" to + // be conservative. +} + +// Helpers for printing colored strings to stdout. Note that on Windows, we +// cannot simply emit special characters and have the terminal change colors. +// This routine must actually emit the characters rather than return a string +// that would be colored when printed, as can be done on Linux. +void ColoredPrintf(GTestColor color, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ + GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT + const bool use_color = AlwaysFalse(); +#else + static const bool in_color_mode = + ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); + const bool use_color = in_color_mode && (color != COLOR_DEFAULT); +#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS + // The '!= 0' comparison is necessary to satisfy MSVC 7.1. + + if (!use_color) { + vprintf(fmt, args); + va_end(args); + return; + } + +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ + !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); + + // Gets the current text color. + CONSOLE_SCREEN_BUFFER_INFO buffer_info; + GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); + const WORD old_color_attrs = buffer_info.wAttributes; + + // We need to flush the stream buffers into the console before each + // SetConsoleTextAttribute call lest it affect the text that is already + // printed but has not yet reached the console. + fflush(stdout); + SetConsoleTextAttribute(stdout_handle, + GetColorAttribute(color) | FOREGROUND_INTENSITY); + vprintf(fmt, args); + + fflush(stdout); + // Restores the text color. + SetConsoleTextAttribute(stdout_handle, old_color_attrs); +#else + printf("\033[0;3%sm", GetAnsiColorCode(color)); + vprintf(fmt, args); + printf("\033[m"); // Resets the terminal to default. +#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE + va_end(args); +} + +// Text printed in Google Test's text output and --gunit_list_tests +// output to label the type parameter and value parameter for a test. +static const char kTypeParamLabel[] = "TypeParam"; +static const char kValueParamLabel[] = "GetParam()"; + +void PrintFullTestCommentIfPresent(const TestInfo& test_info) { + const char* const type_param = test_info.type_param(); + const char* const value_param = test_info.value_param(); + + if (type_param != NULL || value_param != NULL) { + printf(", where "); + if (type_param != NULL) { + printf("%s = %s", kTypeParamLabel, type_param); + if (value_param != NULL) + printf(" and "); + } + if (value_param != NULL) { + printf("%s = %s", kValueParamLabel, value_param); + } + } +} + +// This class implements the TestEventListener interface. +// +// Class PrettyUnitTestResultPrinter is copyable. +class PrettyUnitTestResultPrinter : public TestEventListener { + public: + PrettyUnitTestResultPrinter() {} + static void PrintTestName(const char * test_case, const char * test) { + printf("%s.%s", test_case, test); + } + + // The following methods override what's in the TestEventListener class. + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} + + private: + static void PrintFailedTests(const UnitTest& unit_test); +}; + + // Fired before each iteration of tests starts. +void PrettyUnitTestResultPrinter::OnTestIterationStart( + const UnitTest& unit_test, int iteration) { + if (GTEST_FLAG(repeat) != 1) + printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); + + const char* const filter = GTEST_FLAG(filter).c_str(); + + // Prints the filter if it's not *. This reminds the user that some + // tests may be skipped. + if (!String::CStringEquals(filter, kUniversalFilter)) { + ColoredPrintf(COLOR_YELLOW, + "Note: %s filter = %s\n", GTEST_NAME_, filter); + } + + if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { + const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); + ColoredPrintf(COLOR_YELLOW, + "Note: This is test shard %d of %s.\n", + static_cast(shard_index) + 1, + internal::posix::GetEnv(kTestTotalShards)); + } + + if (GTEST_FLAG(shuffle)) { + ColoredPrintf(COLOR_YELLOW, + "Note: Randomizing tests' orders with a seed of %d .\n", + unit_test.random_seed()); + } + + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("Running %s from %s.\n", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment set-up.\n"); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s", counts.c_str(), test_case.name()); + if (test_case.type_param() == NULL) { + printf("\n"); + } else { + printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { + ColoredPrintf(COLOR_GREEN, "[ RUN ] "); + PrintTestName(test_info.test_case_name(), test_info.name()); + printf("\n"); + fflush(stdout); +} + +// Called after an assertion failure. +void PrettyUnitTestResultPrinter::OnTestPartResult( + const TestPartResult& result) { + // If the test part succeeded, we don't need to do anything. + if (result.type() == TestPartResult::kSuccess) + return; + + // Print failure message from the assertion (e.g. expected this and got that). + PrintTestPartResult(result); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { + if (test_info.result()->Passed()) { + ColoredPrintf(COLOR_GREEN, "[ OK ] "); + } else { + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + } + PrintTestName(test_info.test_case_name(), test_info.name()); + if (test_info.result()->Failed()) + PrintFullTestCommentIfPresent(test_info); + + if (GTEST_FLAG(print_time)) { + printf(" (%s ms)\n", internal::StreamableToString( + test_info.result()->elapsed_time()).c_str()); + } else { + printf("\n"); + } + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { + if (!GTEST_FLAG(print_time)) return; + + const std::string counts = + FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("%s from %s (%s ms total)\n\n", + counts.c_str(), test_case.name(), + internal::StreamableToString(test_case.elapsed_time()).c_str()); + fflush(stdout); +} + +void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( + const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); + printf("Global test environment tear-down\n"); + fflush(stdout); +} + +// Internal helper for printing the list of failed tests. +void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { + const int failed_test_count = unit_test.failed_test_count(); + if (failed_test_count == 0) { + return; + } + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + const TestCase& test_case = *unit_test.GetTestCase(i); + if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { + continue; + } + for (int j = 0; j < test_case.total_test_count(); ++j) { + const TestInfo& test_info = *test_case.GetTestInfo(j); + if (!test_info.should_run() || test_info.result()->Passed()) { + continue; + } + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s.%s", test_case.name(), test_info.name()); + PrintFullTestCommentIfPresent(test_info); + printf("\n"); + } + } +} + +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("%s from %s ran.", + FormatTestCount(unit_test.test_to_run_count()).c_str(), + FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + if (GTEST_FLAG(print_time)) { + printf(" (%s ms total)", + internal::StreamableToString(unit_test.elapsed_time()).c_str()); + } + printf("\n"); + ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); + printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); + + int num_failures = unit_test.failed_test_count(); + if (!unit_test.Passed()) { + const int failed_test_count = unit_test.failed_test_count(); + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); + PrintFailedTests(unit_test); + printf("\n%2d FAILED %s\n", num_failures, + num_failures == 1 ? "TEST" : "TESTS"); + } + + int num_disabled = unit_test.reportable_disabled_test_count(); + if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { + if (!num_failures) { + printf("\n"); // Add a spacer if no FAILURE banner is displayed. + } + ColoredPrintf(COLOR_YELLOW, + " YOU HAVE %d DISABLED %s\n\n", + num_disabled, + num_disabled == 1 ? "TEST" : "TESTS"); + } + // Ensure that Google Test output is printed before, e.g., heapchecker output. + fflush(stdout); +} + +// End PrettyUnitTestResultPrinter + +// class TestEventRepeater +// +// This class forwards events to other event listeners. +class TestEventRepeater : public TestEventListener { + public: + TestEventRepeater() : forwarding_enabled_(true) {} + virtual ~TestEventRepeater(); + void Append(TestEventListener *listener); + TestEventListener* Release(TestEventListener* listener); + + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled() const { return forwarding_enabled_; } + void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } + + virtual void OnTestProgramStart(const UnitTest& unit_test); + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); + virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); + virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); + virtual void OnTestCaseStart(const TestCase& test_case); + virtual void OnTestStart(const TestInfo& test_info); + virtual void OnTestPartResult(const TestPartResult& result); + virtual void OnTestEnd(const TestInfo& test_info); + virtual void OnTestCaseEnd(const TestCase& test_case); + virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); + virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + virtual void OnTestProgramEnd(const UnitTest& unit_test); + + private: + // Controls whether events will be forwarded to listeners_. Set to false + // in death test child processes. + bool forwarding_enabled_; + // The list of listeners that receive events. + std::vector listeners_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); +}; + +TestEventRepeater::~TestEventRepeater() { + ForEach(listeners_, Delete); +} + +void TestEventRepeater::Append(TestEventListener *listener) { + listeners_.push_back(listener); +} + +// TODO(vladl@google.com): Factor the search functionality into Vector::Find. +TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { + for (size_t i = 0; i < listeners_.size(); ++i) { + if (listeners_[i] == listener) { + listeners_.erase(listeners_.begin() + i); + return listener; + } + } + + return NULL; +} + +// Since most methods are very similar, use macros to reduce boilerplate. +// This defines a member that forwards the call to all listeners. +#define GTEST_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} +// This defines a member that forwards the call to all listeners in reverse +// order. +#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ +void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ +} + +GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) +GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) +GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) +GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) +GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) +GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) +GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) +GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) +GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) + +#undef GTEST_REPEATER_METHOD_ +#undef GTEST_REVERSE_REPEATER_METHOD_ + +void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (size_t i = 0; i < listeners_.size(); i++) { + listeners_[i]->OnTestIterationStart(unit_test, iteration); + } + } +} + +void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, + int iteration) { + if (forwarding_enabled_) { + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { + listeners_[i]->OnTestIterationEnd(unit_test, iteration); + } + } +} + +// End TestEventRepeater + +// This class generates an XML output file. +class XmlUnitTestResultPrinter : public EmptyTestEventListener { + public: + explicit XmlUnitTestResultPrinter(const char* output_file); + + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); + + private: + // Is c a whitespace character that is normalized to a space character + // when it appears in an XML attribute value? + static bool IsNormalizableWhitespace(char c) { + return c == 0x9 || c == 0xA || c == 0xD; + } + + // May c appear in a well-formed XML document? + static bool IsValidXmlCharacter(char c) { + return IsNormalizableWhitespace(c) || c >= 0x20; + } + + // Returns an XML-escaped copy of the input string str. If + // is_attribute is true, the text is meant to appear as an attribute + // value, and normalizable whitespace is preserved by replacing it + // with character references. + static std::string EscapeXml(const std::string& str, bool is_attribute); + + // Returns the given string with all characters invalid in XML removed. + static std::string RemoveInvalidXmlCharacters(const std::string& str); + + // Convenience wrapper around EscapeXml when str is an attribute value. + static std::string EscapeXmlAttribute(const std::string& str) { + return EscapeXml(str, true); + } + + // Convenience wrapper around EscapeXml when str is not an attribute value. + static std::string EscapeXmlText(const char* str) { + return EscapeXml(str, false); + } + + // Verifies that the given attribute belongs to the given element and + // streams the attribute as XML. + static void OutputXmlAttribute(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value); + + // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. + static void OutputXmlCDataSection(::std::ostream* stream, const char* data); + + // Streams an XML representation of a TestInfo object. + static void OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info); + + // Prints an XML representation of a TestCase object + static void PrintXmlTestCase(::std::ostream* stream, + const TestCase& test_case); + + // Prints an XML summary of unit_test to output stream out. + static void PrintXmlUnitTest(::std::ostream* stream, + const UnitTest& unit_test); + + // Produces a string representing the test properties in a result as space + // delimited XML attributes based on the property key="value" pairs. + // When the std::string is not empty, it includes a space at the beginning, + // to delimit this attribute from prior attributes. + static std::string TestPropertiesAsXmlAttributes(const TestResult& result); + + // The output file. + const std::string output_file_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); +}; + +// Creates a new XmlUnitTestResultPrinter. +XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) + : output_file_(output_file) { + if (output_file_.c_str() == NULL || output_file_.empty()) { + fprintf(stderr, "XML output file may not be null\n"); + fflush(stderr); + exit(EXIT_FAILURE); + } +} + +// Called after the unit test ends. +void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, + int /*iteration*/) { + FILE* xmlout = NULL; + FilePath output_file(output_file_); + FilePath output_dir(output_file.RemoveFileName()); + + if (output_dir.CreateDirectoriesRecursively()) { + xmlout = posix::FOpen(output_file_.c_str(), "w"); + } + if (xmlout == NULL) { + // TODO(wan): report the reason of the failure. + // + // We don't do it for now as: + // + // 1. There is no urgent need for it. + // 2. It's a bit involved to make the errno variable thread-safe on + // all three operating systems (Linux, Windows, and Mac OS). + // 3. To interpret the meaning of errno in a thread-safe way, + // we need the strerror_r() function, which is not available on + // Windows. + fprintf(stderr, + "Unable to open file \"%s\"\n", + output_file_.c_str()); + fflush(stderr); + exit(EXIT_FAILURE); + } + std::stringstream stream; + PrintXmlUnitTest(&stream, unit_test); + fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); + fclose(xmlout); +} + +// Returns an XML-escaped copy of the input string str. If is_attribute +// is true, the text is meant to appear as an attribute value, and +// normalizable whitespace is preserved by replacing it with character +// references. +// +// Invalid XML characters in str, if any, are stripped from the output. +// It is expected that most, if not all, of the text processed by this +// module will consist of ordinary English text. +// If this module is ever modified to produce version 1.1 XML output, +// most invalid characters can be retained using character references. +// TODO(wan): It might be nice to have a minimally invasive, human-readable +// escaping scheme for invalid characters, rather than dropping them. +std::string XmlUnitTestResultPrinter::EscapeXml( + const std::string& str, bool is_attribute) { + Message m; + + for (size_t i = 0; i < str.size(); ++i) { + const char ch = str[i]; + switch (ch) { + case '<': + m << "<"; + break; + case '>': + m << ">"; + break; + case '&': + m << "&"; + break; + case '\'': + if (is_attribute) + m << "'"; + else + m << '\''; + break; + case '"': + if (is_attribute) + m << """; + else + m << '"'; + break; + default: + if (IsValidXmlCharacter(ch)) { + if (is_attribute && IsNormalizableWhitespace(ch)) + m << "&#x" << String::FormatByte(static_cast(ch)) + << ";"; + else + m << ch; + } + break; + } + } + + return m.GetString(); +} + +// Returns the given string with all characters invalid in XML removed. +// Currently invalid characters are dropped from the string. An +// alternative is to replace them with certain characters such as . or ?. +std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( + const std::string& str) { + std::string output; + output.reserve(str.size()); + for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) + if (IsValidXmlCharacter(*it)) + output.push_back(*it); + + return output; +} + +// The following routines generate an XML representation of a UnitTest +// object. +// +// This is how Google Test concepts map to the DTD: +// +// <-- corresponds to a UnitTest object +// <-- corresponds to a TestCase object +// <-- corresponds to a TestInfo object +// ... +// ... +// ... +// <-- individual assertion failures +// +// +// + +// Formats the given time in milliseconds as seconds. +std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { + ::std::stringstream ss; + ss << (static_cast(ms) * 1e-3); + return ss.str(); +} + +static bool PortableLocaltime(time_t seconds, struct tm* out) { +#if defined(_MSC_VER) + return localtime_s(out, &seconds) == 0; +#elif defined(__MINGW32__) || defined(__MINGW64__) + // MINGW provides neither localtime_r nor localtime_s, but uses + // Windows' localtime(), which has a thread-local tm buffer. + struct tm* tm_ptr = localtime(&seconds); // NOLINT + if (tm_ptr == NULL) + return false; + *out = *tm_ptr; + return true; +#else + return localtime_r(&seconds, out) != NULL; +#endif +} + +// Converts the given epoch time in milliseconds to a date string in the ISO +// 8601 format, without the timezone information. +std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { + struct tm time_struct; + if (!PortableLocaltime(static_cast(ms / 1000), &time_struct)) + return ""; + // YYYY-MM-DDThh:mm:ss + return StreamableToString(time_struct.tm_year + 1900) + "-" + + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec); +} + +// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. +void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, + const char* data) { + const char* segment = data; + *stream << ""); + if (next_segment != NULL) { + stream->write( + segment, static_cast(next_segment - segment)); + *stream << "]]>]]>"); + } else { + *stream << segment; + break; + } + } + *stream << "]]>"; +} + +void XmlUnitTestResultPrinter::OutputXmlAttribute( + std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value) { + const std::vector& allowed_names = + GetReservedAttributesForElement(element_name); + + GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != + allowed_names.end()) + << "Attribute " << name << " is not allowed for element <" << element_name + << ">."; + + *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; +} + +// Prints an XML representation of a TestInfo object. +// TODO(wan): There is also value in printing properties with the plain printer. +void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, + const char* test_case_name, + const TestInfo& test_info) { + const TestResult& result = *test_info.result(); + const std::string kTestcase = "testcase"; + + *stream << " \n"; + } + const string location = internal::FormatCompilerIndependentFileLocation( + part.file_name(), part.line_number()); + const string summary = location + "\n" + part.summary(); + *stream << " "; + const string detail = location + "\n" + part.message(); + OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); + *stream << "\n"; + } + } + + if (failures == 0) + *stream << " />\n"; + else + *stream << " \n"; +} + +// Prints an XML representation of a TestCase object +void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, + const TestCase& test_case) { + const std::string kTestsuite = "testsuite"; + *stream << " <" << kTestsuite; + OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); + OutputXmlAttribute(stream, kTestsuite, "tests", + StreamableToString(test_case.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuite, "failures", + StreamableToString(test_case.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuite, "disabled", + StreamableToString(test_case.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuite, "errors", "0"); + OutputXmlAttribute(stream, kTestsuite, "time", + FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) + << ">\n"; + + for (int i = 0; i < test_case.total_test_count(); ++i) { + if (test_case.GetTestInfo(i)->is_reportable()) + OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); + } + *stream << " \n"; +} + +// Prints an XML summary of unit_test to output stream out. +void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, + const UnitTest& unit_test) { + const std::string kTestsuites = "testsuites"; + + *stream << "\n"; + *stream << "<" << kTestsuites; + + OutputXmlAttribute(stream, kTestsuites, "tests", + StreamableToString(unit_test.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuites, "failures", + StreamableToString(unit_test.failed_test_count())); + OutputXmlAttribute( + stream, kTestsuites, "disabled", + StreamableToString(unit_test.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuites, "errors", "0"); + OutputXmlAttribute( + stream, kTestsuites, "timestamp", + FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); + OutputXmlAttribute(stream, kTestsuites, "time", + FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + + if (GTEST_FLAG(shuffle)) { + OutputXmlAttribute(stream, kTestsuites, "random_seed", + StreamableToString(unit_test.random_seed())); + } + + *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); + + OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); + *stream << ">\n"; + + for (int i = 0; i < unit_test.total_test_case_count(); ++i) { + if (unit_test.GetTestCase(i)->reportable_test_count() > 0) + PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); + } + *stream << "\n"; +} + +// Produces a string representing the test properties in a result as space +// delimited XML attributes based on the property key="value" pairs. +std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( + const TestResult& result) { + Message attributes; + for (int i = 0; i < result.test_property_count(); ++i) { + const TestProperty& property = result.GetTestProperty(i); + attributes << " " << property.key() << "=" + << "\"" << EscapeXmlAttribute(property.value()) << "\""; + } + return attributes.GetString(); +} + +// End XmlUnitTestResultPrinter + +#if GTEST_CAN_STREAM_RESULTS_ + +// Checks if str contains '=', '&', '%' or '\n' characters. If yes, +// replaces them by "%xx" where xx is their hexadecimal value. For +// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) +// in both time and space -- important as the input str may contain an +// arbitrarily long test failure message and stack trace. +string StreamingListener::UrlEncode(const char* str) { + string result; + result.reserve(strlen(str) + 1); + for (char ch = *str; ch != '\0'; ch = *++str) { + switch (ch) { + case '%': + case '=': + case '&': + case '\n': + result.append("%" + String::FormatByte(static_cast(ch))); + break; + default: + result.push_back(ch); + break; + } + } + return result; +} + +void StreamingListener::SocketWriter::MakeConnection() { + GTEST_CHECK_(sockfd_ == -1) + << "MakeConnection() can't be called when there is already a connection."; + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_socktype = SOCK_STREAM; + addrinfo* servinfo = NULL; + + // Use the getaddrinfo() to get a linked list of IP addresses for + // the given host name. + const int error_num = getaddrinfo( + host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + if (error_num != 0) { + GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " + << gai_strerror(error_num); + } + + // Loop through all the results and connect to the first we can. + for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; + cur_addr = cur_addr->ai_next) { + sockfd_ = socket( + cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + if (sockfd_ != -1) { + // Connect the client socket to the server socket. + if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { + close(sockfd_); + sockfd_ = -1; + } + } + } + + freeaddrinfo(servinfo); // all done with this structure + + if (sockfd_ == -1) { + GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " + << host_name_ << ":" << port_num_; + } +} + +// End of class Streaming Listener +#endif // GTEST_CAN_STREAM_RESULTS__ + +// Class ScopedTrace + +// Pushes the given source file location and message onto a per-thread +// trace stack maintained by Google Test. +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + TraceInfo trace; + trace.file = file; + trace.line = line; + trace.message = message.GetString(); + + UnitTest::GetInstance()->PushGTestTrace(trace); +} + +// Pops the info pushed by the c'tor. +ScopedTrace::~ScopedTrace() + GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { + UnitTest::GetInstance()->PopGTestTrace(); +} + + +// class OsStackTraceGetter + +const char* const OsStackTraceGetterInterface::kElidedFramesMarker = + "... " GTEST_NAME_ " internal frames ..."; + +string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, + int /*skip_count*/) { + return ""; +} + +void OsStackTraceGetter::UponLeavingGTest() {} + +// A helper class that creates the premature-exit file in its +// constructor and deletes the file in its destructor. +class ScopedPrematureExitFile { + public: + explicit ScopedPrematureExitFile(const char* premature_exit_filepath) + : premature_exit_filepath_(premature_exit_filepath) { + // If a path to the premature-exit file is specified... + if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { + // create the file with a single "0" character in it. I/O + // errors are ignored as there's nothing better we can do and we + // don't want to fail the test because of this. + FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); + fwrite("0", 1, 1, pfile); + fclose(pfile); + } + } + + ~ScopedPrematureExitFile() { + if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { + remove(premature_exit_filepath_); + } + } + + private: + const char* const premature_exit_filepath_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); +}; + +} // namespace internal + +// class TestEventListeners + +TestEventListeners::TestEventListeners() + : repeater_(new internal::TestEventRepeater()), + default_result_printer_(NULL), + default_xml_generator_(NULL) { +} + +TestEventListeners::~TestEventListeners() { delete repeater_; } + +// Returns the standard listener responsible for the default console +// output. Can be removed from the listeners list to shut down default +// console output. Note that removing this object from the listener list +// with Release transfers its ownership to the user. +void TestEventListeners::Append(TestEventListener* listener) { + repeater_->Append(listener); +} + +// Removes the given event listener from the list and returns it. It then +// becomes the caller's responsibility to delete the listener. Returns +// NULL if the listener is not found in the list. +TestEventListener* TestEventListeners::Release(TestEventListener* listener) { + if (listener == default_result_printer_) + default_result_printer_ = NULL; + else if (listener == default_xml_generator_) + default_xml_generator_ = NULL; + return repeater_->Release(listener); +} + +// Returns repeater that broadcasts the TestEventListener events to all +// subscribers. +TestEventListener* TestEventListeners::repeater() { return repeater_; } + +// Sets the default_result_printer attribute to the provided listener. +// The listener is also added to the listener list and previous +// default_result_printer is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { + if (default_result_printer_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_result_printer_); + default_result_printer_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Sets the default_xml_generator attribute to the provided listener. The +// listener is also added to the listener list and previous +// default_xml_generator is removed from it and deleted. The listener can +// also be NULL in which case it will not be added to the list. Does +// nothing if the previous and the current listener objects are the same. +void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { + if (default_xml_generator_ != listener) { + // It is an error to pass this method a listener that is already in the + // list. + delete Release(default_xml_generator_); + default_xml_generator_ = listener; + if (listener != NULL) + Append(listener); + } +} + +// Controls whether events will be forwarded by the repeater to the +// listeners in the list. +bool TestEventListeners::EventForwardingEnabled() const { + return repeater_->forwarding_enabled(); +} + +void TestEventListeners::SuppressEventForwarding() { + repeater_->set_forwarding_enabled(false); +} + +// class UnitTest + +// Gets the singleton UnitTest object. The first time this method is +// called, a UnitTest object is constructed and returned. Consecutive +// calls will return the same object. +// +// We don't protect this under mutex_ as a user is not supposed to +// call this before main() starts, from which point on the return +// value will never change. +UnitTest* UnitTest::GetInstance() { + // When compiled with MSVC 7.1 in optimized mode, destroying the + // UnitTest object upon exiting the program messes up the exit code, + // causing successful tests to appear failed. We have to use a + // different implementation in this case to bypass the compiler bug. + // This implementation makes the compiler happy, at the cost of + // leaking the UnitTest object. + + // CodeGear C++Builder insists on a public destructor for the + // default implementation. Use this implementation to keep good OO + // design with private destructor. + +#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) + static UnitTest* const instance = new UnitTest; + return instance; +#else + static UnitTest instance; + return &instance; +#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) +} + +// Gets the number of successful test cases. +int UnitTest::successful_test_case_count() const { + return impl()->successful_test_case_count(); +} + +// Gets the number of failed test cases. +int UnitTest::failed_test_case_count() const { + return impl()->failed_test_case_count(); +} + +// Gets the number of all test cases. +int UnitTest::total_test_case_count() const { + return impl()->total_test_case_count(); +} + +// Gets the number of all test cases that contain at least one test +// that should run. +int UnitTest::test_case_to_run_count() const { + return impl()->test_case_to_run_count(); +} + +// Gets the number of successful tests. +int UnitTest::successful_test_count() const { + return impl()->successful_test_count(); +} + +// Gets the number of failed tests. +int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } + +// Gets the number of disabled tests that will be reported in the XML report. +int UnitTest::reportable_disabled_test_count() const { + return impl()->reportable_disabled_test_count(); +} + +// Gets the number of disabled tests. +int UnitTest::disabled_test_count() const { + return impl()->disabled_test_count(); +} + +// Gets the number of tests to be printed in the XML report. +int UnitTest::reportable_test_count() const { + return impl()->reportable_test_count(); +} + +// Gets the number of all tests. +int UnitTest::total_test_count() const { return impl()->total_test_count(); } + +// Gets the number of tests that should run. +int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } + +// Gets the time of the test program start, in ms from the start of the +// UNIX epoch. +internal::TimeInMillis UnitTest::start_timestamp() const { + return impl()->start_timestamp(); +} + +// Gets the elapsed time, in milliseconds. +internal::TimeInMillis UnitTest::elapsed_time() const { + return impl()->elapsed_time(); +} + +// Returns true iff the unit test passed (i.e. all test cases passed). +bool UnitTest::Passed() const { return impl()->Passed(); } + +// Returns true iff the unit test failed (i.e. some test case failed +// or something outside of all tests failed). +bool UnitTest::Failed() const { return impl()->Failed(); } + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +const TestCase* UnitTest::GetTestCase(int i) const { + return impl()->GetTestCase(i); +} + +// Returns the TestResult containing information on test failures and +// properties logged outside of individual test cases. +const TestResult& UnitTest::ad_hoc_test_result() const { + return *impl()->ad_hoc_test_result(); +} + +// Gets the i-th test case among all the test cases. i can range from 0 to +// total_test_case_count() - 1. If i is not in that range, returns NULL. +TestCase* UnitTest::GetMutableTestCase(int i) { + return impl()->GetMutableTestCase(i); +} + +// Returns the list of event listeners that can be used to track events +// inside Google Test. +TestEventListeners& UnitTest::listeners() { + return *impl()->listeners(); +} + +// Registers and returns a global test environment. When a test +// program is run, all global test environments will be set-up in the +// order they were registered. After all tests in the program have +// finished, all global test environments will be torn-down in the +// *reverse* order they were registered. +// +// The UnitTest object takes ownership of the given environment. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +Environment* UnitTest::AddEnvironment(Environment* env) { + if (env == NULL) { + return NULL; + } + + impl_->environments().push_back(env); + return env; +} + +// Adds a TestPartResult to the current TestResult object. All Google Test +// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call +// this to report their results. The user code should use the +// assertion macros instead of calling this directly. +void UnitTest::AddTestPartResult( + TestPartResult::Type result_type, + const char* file_name, + int line_number, + const std::string& message, + const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { + Message msg; + msg << message; + + internal::MutexLock lock(&mutex_); + if (impl_->gtest_trace_stack().size() > 0) { + msg << "\n" << GTEST_NAME_ << " trace:"; + + for (int i = static_cast(impl_->gtest_trace_stack().size()); + i > 0; --i) { + const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; + msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) + << " " << trace.message; + } + } + + if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { + msg << internal::kStackTraceMarker << os_stack_trace; + } + + const TestPartResult result = + TestPartResult(result_type, file_name, line_number, + msg.GetString().c_str()); + impl_->GetTestPartResultReporterForCurrentThread()-> + ReportTestPartResult(result); + + if (result_type != TestPartResult::kSuccess) { + // gtest_break_on_failure takes precedence over + // gtest_throw_on_failure. This allows a user to set the latter + // in the code (perhaps in order to use Google Test assertions + // with another testing framework) and specify the former on the + // command line for debugging. + if (GTEST_FLAG(break_on_failure)) { +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + // Using DebugBreak on Windows allows gtest to still break into a debugger + // when a failure happens and both the --gtest_break_on_failure and + // the --gtest_catch_exceptions flags are specified. + DebugBreak(); +#else + // Dereference NULL through a volatile pointer to prevent the compiler + // from removing. We use this rather than abort() or __builtin_trap() for + // portability: Symbian doesn't implement abort() well, and some debuggers + // don't correctly trap abort(). + *static_cast(NULL) = 1; +#endif // GTEST_OS_WINDOWS + } else if (GTEST_FLAG(throw_on_failure)) { +#if GTEST_HAS_EXCEPTIONS + throw internal::GoogleTestFailureException(result); +#else + // We cannot call abort() as it generates a pop-up in debug mode + // that cannot be suppressed in VC 7.1 or below. + exit(1); +#endif + } + } +} + +// Adds a TestProperty to the current TestResult object when invoked from +// inside a test, to current TestCase's ad_hoc_test_result_ when invoked +// from SetUpTestCase or TearDownTestCase, or to the global property set +// when invoked elsewhere. If the result already contains a property with +// the same key, the value will be updated. +void UnitTest::RecordProperty(const std::string& key, + const std::string& value) { + impl_->RecordProperty(TestProperty(key, value)); +} + +// Runs all tests in this UnitTest object and prints the result. +// Returns 0 if successful, or 1 otherwise. +// +// We don't protect this under mutex_, as we only support calling it +// from the main thread. +int UnitTest::Run() { + const bool in_death_test_child_process = + internal::GTEST_FLAG(internal_run_death_test).length() > 0; + + // Google Test implements this protocol for catching that a test + // program exits before returning control to Google Test: + // + // 1. Upon start, Google Test creates a file whose absolute path + // is specified by the environment variable + // TEST_PREMATURE_EXIT_FILE. + // 2. When Google Test has finished its work, it deletes the file. + // + // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before + // running a Google-Test-based test program and check the existence + // of the file at the end of the test execution to see if it has + // exited prematurely. + + // If we are in the child process of a death test, don't + // create/delete the premature exit file, as doing so is unnecessary + // and will confuse the parent process. Otherwise, create/delete + // the file upon entering/leaving this function. If the program + // somehow exits before this function has a chance to return, the + // premature-exit file will be left undeleted, causing a test runner + // that understands the premature-exit-file protocol to report the + // test as having failed. + const internal::ScopedPrematureExitFile premature_exit_file( + in_death_test_child_process ? + NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); + + // Captures the value of GTEST_FLAG(catch_exceptions). This value will be + // used for the duration of the program. + impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); + +#if GTEST_HAS_SEH + // Either the user wants Google Test to catch exceptions thrown by the + // tests or this is executing in the context of death test child + // process. In either case the user does not want to see pop-up dialogs + // about crashes - they are expected. + if (impl()->catch_exceptions() || in_death_test_child_process) { +# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT + // SetErrorMode doesn't exist on CE. + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | + SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); +# endif // !GTEST_OS_WINDOWS_MOBILE + +# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE + // Death test children can be terminated with _abort(). On Windows, + // _abort() can show a dialog with a warning message. This forces the + // abort message to go to stderr instead. + _set_error_mode(_OUT_TO_STDERR); +# endif + +# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE + // In the debug version, Visual Studio pops up a separate dialog + // offering a choice to debug the aborted program. We need to suppress + // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement + // executed. Google Test will notify the user of any unexpected + // failure via stderr. + // + // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. + // Users of prior VC versions shall suffer the agony and pain of + // clicking through the countless debug dialogs. + // TODO(vladl@google.com): find a way to suppress the abort dialog() in the + // debug mode when compiled with VC 7.1 or lower. + if (!GTEST_FLAG(break_on_failure)) + _set_abort_behavior( + 0x0, // Clear the following flags: + _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. +# endif + } +#endif // GTEST_HAS_SEH + + return internal::HandleExceptionsInMethodIfSupported( + impl(), + &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") ? 0 : 1; +} + +// Returns the working directory when the first TEST() or TEST_F() was +// executed. +const char* UnitTest::original_working_dir() const { + return impl_->original_working_dir_.c_str(); +} + +// Returns the TestCase object for the test that's currently running, +// or NULL if no test is running. +const TestCase* UnitTest::current_test_case() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_case(); +} + +// Returns the TestInfo object for the test that's currently running, +// or NULL if no test is running. +const TestInfo* UnitTest::current_test_info() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_info(); +} + +// Returns the random seed used at the start of the current test run. +int UnitTest::random_seed() const { return impl_->random_seed(); } + +#if GTEST_HAS_PARAM_TEST +// Returns ParameterizedTestCaseRegistry object used to keep track of +// value-parameterized tests and instantiate and register them. +internal::ParameterizedTestCaseRegistry& + UnitTest::parameterized_test_registry() + GTEST_LOCK_EXCLUDED_(mutex_) { + return impl_->parameterized_test_registry(); +} +#endif // GTEST_HAS_PARAM_TEST + +// Creates an empty UnitTest. +UnitTest::UnitTest() { + impl_ = new internal::UnitTestImpl(this); +} + +// Destructor of UnitTest. +UnitTest::~UnitTest() { + delete impl_; +} + +// Pushes a trace defined by SCOPED_TRACE() on to the per-thread +// Google Test trace stack. +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().push_back(trace); +} + +// Pops a trace from the per-thread Google Test trace stack. +void UnitTest::PopGTestTrace() + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + impl_->gtest_trace_stack().pop_back(); +} + +namespace internal { + +UnitTestImpl::UnitTestImpl(UnitTest* parent) + : parent_(parent), + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) + default_global_test_part_result_reporter_(this), + default_per_thread_test_part_result_reporter_(this), + GTEST_DISABLE_MSC_WARNINGS_POP_() + global_test_part_result_repoter_( + &default_global_test_part_result_reporter_), + per_thread_test_part_result_reporter_( + &default_per_thread_test_part_result_reporter_), +#if GTEST_HAS_PARAM_TEST + parameterized_test_registry_(), + parameterized_tests_registered_(false), +#endif // GTEST_HAS_PARAM_TEST + last_death_test_case_(-1), + current_test_case_(NULL), + current_test_info_(NULL), + ad_hoc_test_result_(), + os_stack_trace_getter_(NULL), + post_flag_parse_init_performed_(false), + random_seed_(0), // Will be overridden by the flag before first use. + random_(0), // Will be reseeded before first use. + start_timestamp_(0), + elapsed_time_(0), +#if GTEST_HAS_DEATH_TEST + death_test_factory_(new DefaultDeathTestFactory), +#endif + // Will be overridden by the flag before first use. + catch_exceptions_(false) { + listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); +} + +UnitTestImpl::~UnitTestImpl() { + // Deletes every TestCase. + ForEach(test_cases_, internal::Delete); + + // Deletes every Environment. + ForEach(environments_, internal::Delete); + + delete os_stack_trace_getter_; +} + +// Adds a TestProperty to the current TestResult object when invoked in a +// context of a test, to current test case's ad_hoc_test_result when invoke +// from SetUpTestCase/TearDownTestCase, or to the global property set +// otherwise. If the result already contains a property with the same key, +// the value will be updated. +void UnitTestImpl::RecordProperty(const TestProperty& test_property) { + std::string xml_element; + TestResult* test_result; // TestResult appropriate for property recording. + + if (current_test_info_ != NULL) { + xml_element = "testcase"; + test_result = &(current_test_info_->result_); + } else if (current_test_case_ != NULL) { + xml_element = "testsuite"; + test_result = &(current_test_case_->ad_hoc_test_result_); + } else { + xml_element = "testsuites"; + test_result = &ad_hoc_test_result_; + } + test_result->RecordProperty(xml_element, test_property); +} + +#if GTEST_HAS_DEATH_TEST +// Disables event forwarding if the control is currently in a death test +// subprocess. Must not be called before InitGoogleTest. +void UnitTestImpl::SuppressTestEventsIfInSubprocess() { + if (internal_run_death_test_flag_.get() != NULL) + listeners()->SuppressEventForwarding(); +} +#endif // GTEST_HAS_DEATH_TEST + +// Initializes event listeners performing XML output as specified by +// UnitTestOptions. Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureXmlOutput() { + const std::string& output_format = UnitTestOptions::GetOutputFormat(); + if (output_format == "xml") { + listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( + UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); + } else if (output_format != "") { + printf("WARNING: unrecognized output format \"%s\" ignored.\n", + output_format.c_str()); + fflush(stdout); + } +} + +#if GTEST_CAN_STREAM_RESULTS_ +// Initializes event listeners for streaming test results in string form. +// Must not be called before InitGoogleTest. +void UnitTestImpl::ConfigureStreamingOutput() { + const std::string& target = GTEST_FLAG(stream_result_to); + if (!target.empty()) { + const size_t pos = target.find(':'); + if (pos != std::string::npos) { + listeners()->Append(new StreamingListener(target.substr(0, pos), + target.substr(pos+1))); + } else { + printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", + target.c_str()); + fflush(stdout); + } + } +} +#endif // GTEST_CAN_STREAM_RESULTS_ + +// Performs initialization dependent upon flag values obtained in +// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to +// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest +// this function is also called from RunAllTests. Since this function can be +// called more than once, it has to be idempotent. +void UnitTestImpl::PostFlagParsingInit() { + // Ensures that this function does not execute more than once. + if (!post_flag_parse_init_performed_) { + post_flag_parse_init_performed_ = true; + +#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) + // Register to send notifications about key process state changes. + listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); +#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) + +#if GTEST_HAS_DEATH_TEST + InitDeathTestSubprocessControlInfo(); + SuppressTestEventsIfInSubprocess(); +#endif // GTEST_HAS_DEATH_TEST + + // Registers parameterized tests. This makes parameterized tests + // available to the UnitTest reflection API without running + // RUN_ALL_TESTS. + RegisterParameterizedTests(); + + // Configures listeners for XML output. This makes it possible for users + // to shut down the default XML output before invoking RUN_ALL_TESTS. + ConfigureXmlOutput(); + +#if GTEST_CAN_STREAM_RESULTS_ + // Configures listeners for streaming test results to the specified server. + ConfigureStreamingOutput(); +#endif // GTEST_CAN_STREAM_RESULTS_ + } +} + +// A predicate that checks the name of a TestCase against a known +// value. +// +// This is used for implementation of the UnitTest class only. We put +// it in the anonymous namespace to prevent polluting the outer +// namespace. +// +// TestCaseNameIs is copyable. +class TestCaseNameIs { + public: + // Constructor. + explicit TestCaseNameIs(const std::string& name) + : name_(name) {} + + // Returns true iff the name of test_case matches name_. + bool operator()(const TestCase* test_case) const { + return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; + } + + private: + std::string name_; +}; + +// Finds and returns a TestCase with the given name. If one doesn't +// exist, creates one and returns it. It's the CALLER'S +// RESPONSIBILITY to ensure that this function is only called WHEN THE +// TESTS ARE NOT SHUFFLED. +// +// Arguments: +// +// test_case_name: name of the test case +// type_param: the name of the test case's type parameter, or NULL if +// this is not a typed or a type-parameterized test case. +// set_up_tc: pointer to the function that sets up the test case +// tear_down_tc: pointer to the function that tears down the test case +TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, + const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc) { + // Can we find a TestCase with the given name? + const std::vector::const_iterator test_case = + std::find_if(test_cases_.begin(), test_cases_.end(), + TestCaseNameIs(test_case_name)); + + if (test_case != test_cases_.end()) + return *test_case; + + // No. Let's create one. + TestCase* const new_test_case = + new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); + + // Is this a death test case? + if (internal::UnitTestOptions::MatchesFilter(test_case_name, + kDeathTestCaseFilter)) { + // Yes. Inserts the test case after the last death test case + // defined so far. This only works when the test cases haven't + // been shuffled. Otherwise we may end up running a death test + // after a non-death test. + ++last_death_test_case_; + test_cases_.insert(test_cases_.begin() + last_death_test_case_, + new_test_case); + } else { + // No. Appends to the end of the list. + test_cases_.push_back(new_test_case); + } + + test_case_indices_.push_back(static_cast(test_case_indices_.size())); + return new_test_case; +} + +// Helpers for setting up / tearing down the given environment. They +// are for use in the ForEach() function. +static void SetUpEnvironment(Environment* env) { env->SetUp(); } +static void TearDownEnvironment(Environment* env) { env->TearDown(); } + +// Runs all tests in this UnitTest object, prints the result, and +// returns true if all tests are successful. If any exception is +// thrown during a test, the test is considered to be failed, but the +// rest of the tests will still be run. +// +// When parameterized tests are enabled, it expands and registers +// parameterized tests first in RegisterParameterizedTests(). +// All other functions called from RunAllTests() may safely assume that +// parameterized tests are ready to be counted and run. +bool UnitTestImpl::RunAllTests() { + // Makes sure InitGoogleTest() was called. + if (!GTestIsInitialized()) { + printf("%s", + "\nThis test program did NOT call ::testing::InitGoogleTest " + "before calling RUN_ALL_TESTS(). Please fix it.\n"); + return false; + } + + // Do not run any test if the --help flag was specified. + if (g_help_flag) + return true; + + // Repeats the call to the post-flag parsing initialization in case the + // user didn't call InitGoogleTest. + PostFlagParsingInit(); + + // Even if sharding is not on, test runners may want to use the + // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding + // protocol. + internal::WriteToShardStatusFileIfNeeded(); + + // True iff we are in a subprocess for running a thread-safe-style + // death test. + bool in_subprocess_for_death_test = false; + +#if GTEST_HAS_DEATH_TEST + in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); +# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) + if (in_subprocess_for_death_test) { + GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); + } +# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#endif // GTEST_HAS_DEATH_TEST + + const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, + in_subprocess_for_death_test); + + // Compares the full test names with the filter to decide which + // tests to run. + const bool has_tests_to_run = FilterTests(should_shard + ? HONOR_SHARDING_PROTOCOL + : IGNORE_SHARDING_PROTOCOL) > 0; + + // Lists the tests and exits if the --gtest_list_tests flag was specified. + if (GTEST_FLAG(list_tests)) { + // This must be called *after* FilterTests() has been called. + ListTestsMatchingFilter(); + return true; + } + + random_seed_ = GTEST_FLAG(shuffle) ? + GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; + + // True iff at least one test has failed. + bool failed = false; + + TestEventListener* repeater = listeners()->repeater(); + + start_timestamp_ = GetTimeInMillis(); + repeater->OnTestProgramStart(*parent_); + + // How many times to repeat the tests? We don't want to repeat them + // when we are inside the subprocess of a death test. + const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); + // Repeats forever if the repeat count is negative. + const bool forever = repeat < 0; + for (int i = 0; forever || i != repeat; i++) { + // We want to preserve failures generated by ad-hoc test + // assertions executed before RUN_ALL_TESTS(). + ClearNonAdHocTestResult(); + + const TimeInMillis start = GetTimeInMillis(); + + // Shuffles test cases and tests if requested. + if (has_tests_to_run && GTEST_FLAG(shuffle)) { + random()->Reseed(random_seed_); + // This should be done before calling OnTestIterationStart(), + // such that a test event listener can see the actual test order + // in the event. + ShuffleTests(); + } + + // Tells the unit test event listeners that the tests are about to start. + repeater->OnTestIterationStart(*parent_, i); + + // Runs each test case if there is at least one test to run. + if (has_tests_to_run) { + // Sets up all environments beforehand. + repeater->OnEnvironmentsSetUpStart(*parent_); + ForEach(environments_, SetUpEnvironment); + repeater->OnEnvironmentsSetUpEnd(*parent_); + + // Runs the tests only if there was no fatal failure during global + // set-up. + if (!Test::HasFatalFailure()) { + for (int test_index = 0; test_index < total_test_case_count(); + test_index++) { + GetMutableTestCase(test_index)->Run(); + } + } + + // Tears down all environments in reverse order afterwards. + repeater->OnEnvironmentsTearDownStart(*parent_); + std::for_each(environments_.rbegin(), environments_.rend(), + TearDownEnvironment); + repeater->OnEnvironmentsTearDownEnd(*parent_); + } + + elapsed_time_ = GetTimeInMillis() - start; + + // Tells the unit test event listener that the tests have just finished. + repeater->OnTestIterationEnd(*parent_, i); + + // Gets the result and clears it. + if (!Passed()) { + failed = true; + } + + // Restores the original test order after the iteration. This + // allows the user to quickly repro a failure that happens in the + // N-th iteration without repeating the first (N - 1) iterations. + // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in + // case the user somehow changes the value of the flag somewhere + // (it's always safe to unshuffle the tests). + UnshuffleTests(); + + if (GTEST_FLAG(shuffle)) { + // Picks a new random seed for each iteration. + random_seed_ = GetNextRandomSeed(random_seed_); + } + } + + repeater->OnTestProgramEnd(*parent_); + + return !failed; +} + +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file +// if the variable is present. If a file already exists at this location, this +// function will write over it. If the variable is present, but the file cannot +// be created, prints an error and exits. +void WriteToShardStatusFileIfNeeded() { + const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); + if (test_shard_file != NULL) { + FILE* const file = posix::FOpen(test_shard_file, "w"); + if (file == NULL) { + ColoredPrintf(COLOR_RED, + "Could not write to the test shard status file \"%s\" " + "specified by the %s environment variable.\n", + test_shard_file, kTestShardStatusFile); + fflush(stdout); + exit(EXIT_FAILURE); + } + fclose(file); + } +} + +// Checks whether sharding is enabled by examining the relevant +// environment variable values. If the variables are present, +// but inconsistent (i.e., shard_index >= total_shards), prints +// an error and exits. If in_subprocess_for_death_test, sharding is +// disabled because it must only be applied to the original test +// process. Otherwise, we could filter out death tests we intended to execute. +bool ShouldShard(const char* total_shards_env, + const char* shard_index_env, + bool in_subprocess_for_death_test) { + if (in_subprocess_for_death_test) { + return false; + } + + const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); + const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); + + if (total_shards == -1 && shard_index == -1) { + return false; + } else if (total_shards == -1 && shard_index != -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestShardIndex << " = " << shard_index + << ", but have left " << kTestTotalShards << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (total_shards != -1 && shard_index == -1) { + const Message msg = Message() + << "Invalid environment variables: you have " + << kTestTotalShards << " = " << total_shards + << ", but have left " << kTestShardIndex << " unset.\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } else if (shard_index < 0 || shard_index >= total_shards) { + const Message msg = Message() + << "Invalid environment variables: we require 0 <= " + << kTestShardIndex << " < " << kTestTotalShards + << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + ColoredPrintf(COLOR_RED, msg.GetString().c_str()); + fflush(stdout); + exit(EXIT_FAILURE); + } + + return total_shards > 1; +} + +// Parses the environment variable var as an Int32. If it is unset, +// returns default_val. If it is not an Int32, prints an error +// and aborts. +Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { + const char* str_val = posix::GetEnv(var); + if (str_val == NULL) { + return default_val; + } + + Int32 result; + if (!ParseInt32(Message() << "The value of environment variable " << var, + str_val, &result)) { + exit(EXIT_FAILURE); + } + return result; +} + +// Given the total number of shards, the shard index, and the test id, +// returns true iff the test should be run on this shard. The test id is +// some arbitrary but unique non-negative integer assigned to each test +// method. Assumes that 0 <= shard_index < total_shards. +bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { + return (test_id % total_shards) == shard_index; +} + +// Compares the name of each test with the user-specified filter to +// decide whether the test should be run, then records the result in +// each TestCase and TestInfo object. +// If shard_tests == true, further filters tests based on sharding +// variables in the environment - see +// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. +// Returns the number of tests that should run. +int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { + const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestTotalShards, -1) : -1; + const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? + Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + + // num_runnable_tests are the number of tests that will + // run across all shards (i.e., match filter and are not disabled). + // num_selected_tests are the number of tests to be run on + // this shard. + int num_runnable_tests = 0; + int num_selected_tests = 0; + for (size_t i = 0; i < test_cases_.size(); i++) { + TestCase* const test_case = test_cases_[i]; + const std::string &test_case_name = test_case->name(); + test_case->set_should_run(false); + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + TestInfo* const test_info = test_case->test_info_list()[j]; + const std::string test_name(test_info->name()); + // A test is disabled if test case name or test name matches + // kDisableTestFilter. + const bool is_disabled = + internal::UnitTestOptions::MatchesFilter(test_case_name, + kDisableTestFilter) || + internal::UnitTestOptions::MatchesFilter(test_name, + kDisableTestFilter); + test_info->is_disabled_ = is_disabled; + + const bool matches_filter = + internal::UnitTestOptions::FilterMatchesTest(test_case_name, + test_name); + test_info->matches_filter_ = matches_filter; + + const bool is_runnable = + (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && + matches_filter; + + const bool is_selected = is_runnable && + (shard_tests == IGNORE_SHARDING_PROTOCOL || + ShouldRunTestOnShard(total_shards, shard_index, + num_runnable_tests)); + + num_runnable_tests += is_runnable; + num_selected_tests += is_selected; + + test_info->should_run_ = is_selected; + test_case->set_should_run(test_case->should_run() || is_selected); + } + } + return num_selected_tests; +} + +// Prints the given C-string on a single line by replacing all '\n' +// characters with string "\\n". If the output takes more than +// max_length characters, only prints the first max_length characters +// and "...". +static void PrintOnOneLine(const char* str, int max_length) { + if (str != NULL) { + for (int i = 0; *str != '\0'; ++str) { + if (i >= max_length) { + printf("..."); + break; + } + if (*str == '\n') { + printf("\\n"); + i += 2; + } else { + printf("%c", *str); + ++i; + } + } + } +} + +// Prints the names of the tests matching the user-specified filter flag. +void UnitTestImpl::ListTestsMatchingFilter() { + // Print at most this many characters for each type/value parameter. + const int kMaxParamLength = 250; + + for (size_t i = 0; i < test_cases_.size(); i++) { + const TestCase* const test_case = test_cases_[i]; + bool printed_test_case_name = false; + + for (size_t j = 0; j < test_case->test_info_list().size(); j++) { + const TestInfo* const test_info = + test_case->test_info_list()[j]; + if (test_info->matches_filter_) { + if (!printed_test_case_name) { + printed_test_case_name = true; + printf("%s.", test_case->name()); + if (test_case->type_param() != NULL) { + printf(" # %s = ", kTypeParamLabel); + // We print the type parameter on a single line to make + // the output easy to parse by a program. + PrintOnOneLine(test_case->type_param(), kMaxParamLength); + } + printf("\n"); + } + printf(" %s", test_info->name()); + if (test_info->value_param() != NULL) { + printf(" # %s = ", kValueParamLabel); + // We print the value parameter on a single line to make the + // output easy to parse by a program. + PrintOnOneLine(test_info->value_param(), kMaxParamLength); + } + printf("\n"); + } + } + } + fflush(stdout); +} + +// Sets the OS stack trace getter. +// +// Does nothing if the input and the current OS stack trace getter are +// the same; otherwise, deletes the old getter and makes the input the +// current getter. +void UnitTestImpl::set_os_stack_trace_getter( + OsStackTraceGetterInterface* getter) { + if (os_stack_trace_getter_ != getter) { + delete os_stack_trace_getter_; + os_stack_trace_getter_ = getter; + } +} + +// Returns the current OS stack trace getter if it is not NULL; +// otherwise, creates an OsStackTraceGetter, makes it the current +// getter, and returns it. +OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { + if (os_stack_trace_getter_ == NULL) { +#ifdef GTEST_OS_STACK_TRACE_GETTER_ + os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; +#else + os_stack_trace_getter_ = new OsStackTraceGetter; +#endif // GTEST_OS_STACK_TRACE_GETTER_ + } + + return os_stack_trace_getter_; +} + +// Returns the TestResult for the test that's currently running, or +// the TestResult for the ad hoc test if no test is running. +TestResult* UnitTestImpl::current_test_result() { + return current_test_info_ ? + &(current_test_info_->result_) : &ad_hoc_test_result_; +} + +// Shuffles all test cases, and the tests within each test case, +// making sure that death tests are still run first. +void UnitTestImpl::ShuffleTests() { + // Shuffles the death test cases. + ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); + + // Shuffles the non-death test cases. + ShuffleRange(random(), last_death_test_case_ + 1, + static_cast(test_cases_.size()), &test_case_indices_); + + // Shuffles the tests inside each test case. + for (size_t i = 0; i < test_cases_.size(); i++) { + test_cases_[i]->ShuffleTests(random()); + } +} + +// Restores the test cases and tests to their order before the first shuffle. +void UnitTestImpl::UnshuffleTests() { + for (size_t i = 0; i < test_cases_.size(); i++) { + // Unshuffles the tests in each test case. + test_cases_[i]->UnshuffleTests(); + // Resets the index of each test case. + test_case_indices_[i] = static_cast(i); + } +} + +// Returns the current OS stack trace as an std::string. +// +// The maximum number of stack frames to be included is specified by +// the gtest_stack_trace_depth flag. The skip_count parameter +// specifies the number of top frames to be skipped, which doesn't +// count against the number of frames to be included. +// +// For example, if Foo() calls Bar(), which in turn calls +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. +std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, + int skip_count) { + // We pass skip_count + 1 to skip this wrapper function in addition + // to what the user really wants to skip. + return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); +} + +// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to +// suppress unreachable code warnings. +namespace { +class ClassUniqueToAlwaysTrue {}; +} + +bool IsTrue(bool condition) { return condition; } + +bool AlwaysTrue() { +#if GTEST_HAS_EXCEPTIONS + // This condition is always false so AlwaysTrue() never actually throws, + // but it makes the compiler think that it may throw. + if (IsTrue(false)) + throw ClassUniqueToAlwaysTrue(); +#endif // GTEST_HAS_EXCEPTIONS + return true; +} + +// If *pstr starts with the given prefix, modifies *pstr to be right +// past the prefix and returns true; otherwise leaves *pstr unchanged +// and returns false. None of pstr, *pstr, and prefix can be NULL. +bool SkipPrefix(const char* prefix, const char** pstr) { + const size_t prefix_len = strlen(prefix); + if (strncmp(*pstr, prefix, prefix_len) == 0) { + *pstr += prefix_len; + return true; + } + return false; +} + +// Parses a string as a command line flag. The string should have +// the format "--flag=value". When def_optional is true, the "=value" +// part can be omitted. +// +// Returns the value of the flag, or NULL if the parsing failed. +const char* ParseFlagValue(const char* str, + const char* flag, + bool def_optional) { + // str and flag must not be NULL. + if (str == NULL || flag == NULL) return NULL; + + // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. + const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; + const size_t flag_len = flag_str.length(); + if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; + + // Skips the flag name. + const char* flag_end = str + flag_len; + + // When def_optional is true, it's OK to not have a "=value" part. + if (def_optional && (flag_end[0] == '\0')) { + return flag_end; + } + + // If def_optional is true and there are more characters after the + // flag name, or if def_optional is false, there must be a '=' after + // the flag name. + if (flag_end[0] != '=') return NULL; + + // Returns the string after "=". + return flag_end + 1; +} + +// Parses a string for a bool flag, in the form of either +// "--flag=value" or "--flag". +// +// In the former case, the value is taken as true as long as it does +// not start with '0', 'f', or 'F'. +// +// In the latter case, the value is taken as true. +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseBoolFlag(const char* str, const char* flag, bool* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, true); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Converts the string value to a bool. + *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); + return true; +} + +// Parses a string for an Int32 flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + return ParseInt32(Message() << "The value of flag --" << flag, + value_str, value); +} + +// Parses a string for a string flag, in the form of +// "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +bool ParseStringFlag(const char* str, const char* flag, std::string* value) { + // Gets the value of the flag as a string. + const char* const value_str = ParseFlagValue(str, flag, false); + + // Aborts if the parsing failed. + if (value_str == NULL) return false; + + // Sets *value to the value of the flag. + *value = value_str; + return true; +} + +// Determines whether a string has a prefix that Google Test uses for its +// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. +// If Google Test detects that a command line flag has its prefix but is not +// recognized, it will print its help message. Flags starting with +// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test +// internal flags and do not trigger the help message. +static bool HasGoogleTestFlagPrefix(const char* str) { + return (SkipPrefix("--", &str) || + SkipPrefix("-", &str) || + SkipPrefix("/", &str)) && + !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && + (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || + SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); +} + +// Prints a string containing code-encoded text. The following escape +// sequences can be used in the string to control the text color: +// +// @@ prints a single '@' character. +// @R changes the color to red. +// @G changes the color to green. +// @Y changes the color to yellow. +// @D changes to the default terminal text color. +// +// TODO(wan@google.com): Write tests for this once we add stdout +// capturing to Google Test. +static void PrintColorEncoded(const char* str) { + GTestColor color = COLOR_DEFAULT; // The current color. + + // Conceptually, we split the string into segments divided by escape + // sequences. Then we print one segment at a time. At the end of + // each iteration, the str pointer advances to the beginning of the + // next segment. + for (;;) { + const char* p = strchr(str, '@'); + if (p == NULL) { + ColoredPrintf(color, "%s", str); + return; + } + + ColoredPrintf(color, "%s", std::string(str, p).c_str()); + + const char ch = p[1]; + str = p + 2; + if (ch == '@') { + ColoredPrintf(color, "@"); + } else if (ch == 'D') { + color = COLOR_DEFAULT; + } else if (ch == 'R') { + color = COLOR_RED; + } else if (ch == 'G') { + color = COLOR_GREEN; + } else if (ch == 'Y') { + color = COLOR_YELLOW; + } else { + --str; + } + } +} + +static const char kColorEncodedHelpMessage[] = +"This program contains tests written using " GTEST_NAME_ ". You can use the\n" +"following command line flags to control its behavior:\n" +"\n" +"Test Selection:\n" +" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" +" List the names of all tests instead of running them. The name of\n" +" TEST(Foo, Bar) is \"Foo.Bar\".\n" +" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" + "[@G-@YNEGATIVE_PATTERNS]@D\n" +" Run only the tests whose name matches one of the positive patterns but\n" +" none of the negative patterns. '?' matches any single character; '*'\n" +" matches any substring; ':' separates two patterns.\n" +" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" +" Run all disabled tests too.\n" +"\n" +"Test Execution:\n" +" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" +" Run the tests repeatedly; use a negative count to repeat forever.\n" +" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" +" Randomize tests' orders on every iteration.\n" +" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" +" Random number seed to use for shuffling test orders (between 1 and\n" +" 99999, or 0 to use a seed based on the current time).\n" +"\n" +"Test Output:\n" +" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" +" Enable/disable colored output. The default is @Gauto@D.\n" +" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" +" Don't print the elapsed time of each test.\n" +" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" + GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" +" Generate an XML report in the given directory or with the given file\n" +" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" +#if GTEST_CAN_STREAM_RESULTS_ +" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" +" Stream test results to the given server.\n" +#endif // GTEST_CAN_STREAM_RESULTS_ +"\n" +"Assertion Behavior:\n" +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" +" Set the default death test style.\n" +#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" +" Turn assertion failures into debugger break-points.\n" +" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" +" Turn assertion failures into C++ exceptions.\n" +" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" +" Do not report exceptions as test failures. Instead, allow them\n" +" to crash the program or throw a pop-up (on Windows).\n" +"\n" +"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " + "the corresponding\n" +"environment variable of a flag (all letters in upper-case). For example, to\n" +"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ + "color=no@D or set\n" +"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" +"\n" +"For more information, please read the " GTEST_NAME_ " documentation at\n" +"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" +"(not one in your own code or tests), please report it to\n" +"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; + +bool ParseGoogleTestFlag(const char* const arg) { + return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, + >EST_FLAG(also_run_disabled_tests)) || + ParseBoolFlag(arg, kBreakOnFailureFlag, + >EST_FLAG(break_on_failure)) || + ParseBoolFlag(arg, kCatchExceptionsFlag, + >EST_FLAG(catch_exceptions)) || + ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || + ParseStringFlag(arg, kDeathTestStyleFlag, + >EST_FLAG(death_test_style)) || + ParseBoolFlag(arg, kDeathTestUseFork, + >EST_FLAG(death_test_use_fork)) || + ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || + ParseStringFlag(arg, kInternalRunDeathTestFlag, + >EST_FLAG(internal_run_death_test)) || + ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || + ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || + ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || + ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || + ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, + >EST_FLAG(stack_trace_depth)) || + ParseStringFlag(arg, kStreamResultToFlag, + >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, + >EST_FLAG(throw_on_failure)); +} + +#if GTEST_USE_OWN_FLAGFILE_FLAG_ +void LoadFlagsFromFile(const std::string& path) { + FILE* flagfile = posix::FOpen(path.c_str(), "r"); + if (!flagfile) { + fprintf(stderr, + "Unable to open file \"%s\"\n", + GTEST_FLAG(flagfile).c_str()); + fflush(stderr); + exit(EXIT_FAILURE); + } + std::string contents(ReadEntireFile(flagfile)); + posix::FClose(flagfile); + std::vector lines; + SplitString(contents, '\n', &lines); + for (size_t i = 0; i < lines.size(); ++i) { + if (lines[i].empty()) + continue; + if (!ParseGoogleTestFlag(lines[i].c_str())) + g_help_flag = true; + } +} +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. The type parameter CharType can be +// instantiated to either char or wchar_t. +template +void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { + for (int i = 1; i < *argc; i++) { + const std::string arg_string = StreamableToString(argv[i]); + const char* const arg = arg_string.c_str(); + + using internal::ParseBoolFlag; + using internal::ParseInt32Flag; + using internal::ParseStringFlag; + + bool remove_flag = false; + if (ParseGoogleTestFlag(arg)) { + remove_flag = true; +#if GTEST_USE_OWN_FLAGFILE_FLAG_ + } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { + LoadFlagsFromFile(GTEST_FLAG(flagfile)); + remove_flag = true; +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ + } else if (arg_string == "--help" || arg_string == "-h" || + arg_string == "-?" || arg_string == "/?" || + HasGoogleTestFlagPrefix(arg)) { + // Both help flag and unrecognized Google Test flags (excluding + // internal ones) trigger help display. + g_help_flag = true; + } + + if (remove_flag) { + // Shift the remainder of the argv list left by one. Note + // that argv has (*argc + 1) elements, the last one always being + // NULL. The following loop moves the trailing NULL element as + // well. + for (int j = i; j != *argc; j++) { + argv[j] = argv[j + 1]; + } + + // Decrements the argument count. + (*argc)--; + + // We also need to decrement the iterator as we just removed + // an element. + i--; + } + } + + if (g_help_flag) { + // We print the help here instead of in RUN_ALL_TESTS(), as the + // latter may not be called at all if the user is using Google + // Test with another testing framework. + PrintColorEncoded(kColorEncodedHelpMessage); + } +} + +// Parses the command line for Google Test flags, without initializing +// other parts of Google Test. +void ParseGoogleTestFlagsOnly(int* argc, char** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} +void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { + ParseGoogleTestFlagsOnlyImpl(argc, argv); +} + +// The internal implementation of InitGoogleTest(). +// +// The type parameter CharType can be instantiated to either char or +// wchar_t. +template +void InitGoogleTestImpl(int* argc, CharType** argv) { + // We don't want to run the initialization code twice. + if (GTestIsInitialized()) return; + + if (*argc <= 0) return; + + g_argvs.clear(); + for (int i = 0; i != *argc; i++) { + g_argvs.push_back(StreamableToString(argv[i])); + } + + ParseGoogleTestFlagsOnly(argc, argv); + GetUnitTestImpl()->PostFlagParsingInit(); +} + +} // namespace internal + +// Initializes Google Test. This must be called before calling +// RUN_ALL_TESTS(). In particular, it parses a command line for the +// flags that Google Test recognizes. Whenever a Google Test flag is +// seen, it is removed from argv, and *argc is decremented. +// +// No value is returned. Instead, the Google Test flag variables are +// updated. +// +// Calling the function for the second time has no user-visible effect. +void InitGoogleTest(int* argc, char** argv) { +#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + internal::InitGoogleTestImpl(argc, argv); +#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +} + +// This overloaded version can be used in Windows programs compiled in +// UNICODE mode. +void InitGoogleTest(int* argc, wchar_t** argv) { +#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) + internal::InitGoogleTestImpl(argc, argv); +#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +} + +} // namespace testing diff --git a/gtestsrc/gtest/src/gtest_main.cc b/gtestsrc/gtest/src/gtest_main.cc new file mode 100644 index 0000000..f302822 --- /dev/null +++ b/gtestsrc/gtest/src/gtest_main.cc @@ -0,0 +1,38 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include "gtest/gtest.h" + +GTEST_API_ int main(int argc, char **argv) { + printf("Running main() from gtest_main.cc\n"); + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/interface/VideoCommonDefs.h b/interface/VideoCommonDefs.h new file mode 100644 index 0000000..d5b3c3d --- /dev/null +++ b/interface/VideoCommonDefs.h @@ -0,0 +1,308 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_COMMON_DEFS_H_ +#define VIDEO_COMMON_DEFS_H_ +// config.h should NOT be included in header file, especially for the header file used by external + +#include +#include + +#ifdef __cplusplus + +#if __cplusplus > 199711L + #include +#else + #include + namespace std { + using std::tr1::shared_ptr; + using std::tr1::weak_ptr; + using std::tr1::enable_shared_from_this; + using std::tr1::dynamic_pointer_cast; + using std::tr1::static_pointer_cast; + } +#endif // __cplusplus > 199711L + +#define SharedPtr std::shared_ptr +#define WeakPtr std::weak_ptr +#define DynamicPointerCast std::dynamic_pointer_cast +#define StaticPointerCast std::static_pointer_cast +#define EnableSharedFromThis std::enable_shared_from_this + +#endif // __cplusplus + +#ifdef __cplusplus +extern "C" { +#endif + +#define YAMI_FOURCC(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ + ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24)) +//Y only +#define YAMI_FOURCC_Y800 YAMI_FOURCC('Y', '8', '0', '0') + +//411 +#define YAMI_FOURCC_411P YAMI_FOURCC('4', '1', '1', 'P') + +//420 +#define YAMI_FOURCC_NV12 YAMI_FOURCC('N', 'V', '1', '2') +#define YAMI_FOURCC_I420 YAMI_FOURCC('I', '4', '2', '0') +#define YAMI_FOURCC_YV12 YAMI_FOURCC('Y', 'V', '1', '2') +#define YAMI_FOURCC_IMC3 YAMI_FOURCC('I', 'M', 'C', '3') + +//422 +#define YAMI_FOURCC_422H YAMI_FOURCC('4', '2', '2', 'H') +#define YAMI_FOURCC_422V YAMI_FOURCC('4', '2', '2', 'V') +#define YAMI_FOURCC_YUY2 YAMI_FOURCC('Y', 'U', 'Y', '2') +#define YAMI_FOURCC_UYVY YAMI_FOURCC('U', 'Y', 'V', 'Y') + +//444 +#define YAMI_FOURCC_444P YAMI_FOURCC('4', '4', '4', 'P') + +//10 bits +#define YAMI_FOURCC_P010 YAMI_FOURCC('P', '0', '1', '0') + +//RGB +#define YAMI_FOURCC_RGBX YAMI_FOURCC('R', 'G', 'B', 'X') +#define YAMI_FOURCC_RGBA YAMI_FOURCC('R', 'G', 'B', 'A') +#define YAMI_FOURCC_BGRX YAMI_FOURCC('B', 'G', 'R', 'X') +#define YAMI_FOURCC_BGRA YAMI_FOURCC('B', 'G', 'R', 'A') +#define YAMI_FOURCC_XRGB YAMI_FOURCC('X', 'R', 'G', 'B') +#define YAMI_FOURCC_ARGB YAMI_FOURCC('A', 'R', 'G', 'B') +#define YAMI_FOURCC_XBGR YAMI_FOURCC('X', 'B', 'G', 'R') +#define YAMI_FOURCC_ABGR YAMI_FOURCC('A', 'B', 'G', 'R') +#define YAMI_FOURCC_RGB565 YAMI_FOURCC('R', 'G', '1', '6') +#define YAMI_FOURCC_R210 YAMI_FOURCC('R', '2', '1', '0') + +#ifndef V4L2_BUF_FLAG_NON_REF +#define V4L2_BUF_FLAG_NON_REF 0x00200000 +#endif + +typedef enum { + NATIVE_DISPLAY_AUTO, // decided by yami + NATIVE_DISPLAY_X11, + NATIVE_DISPLAY_DRM, + NATIVE_DISPLAY_WAYLAND, + NATIVE_DISPLAY_VA, /* client need init va*/ +} YamiNativeDisplayType; + +typedef struct NativeDisplay{ + intptr_t handle; + YamiNativeDisplayType type; +} NativeDisplay; + +typedef enum { + VIDEO_DATA_MEMORY_TYPE_RAW_POINTER, // pass data pointer to client + VIDEO_DATA_MEMORY_TYPE_RAW_COPY, // copy data to client provided buffer, renderDone() is not necessary + VIDEO_DATA_MEMORY_TYPE_DRM_NAME, // render output frame by egl/gles, connect with OpenCL + VIDEO_DATA_MEMORY_TYPE_DMA_BUF, // share buffer with camera device etc + VIDEO_DATA_MEMORY_TYPE_SURFACE_ID, // it can be used for surface sharing of transcoding, benefits suppressed rendering as well. + //it is discouraged to use it for video rendering. + VIDEO_DATA_MEMORY_TYPE_ANDROID_BUFFER_HANDLE, // buffer_handle_t for android + VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF, //external dma buffer, the buffer is allocate by user +} VideoDataMemoryType; + +typedef struct VideoFrameRawData{ + VideoDataMemoryType memoryType; + uint32_t width; + uint32_t height; + uint32_t pitch[3]; + uint32_t offset[3]; + uint32_t fourcc; + uint32_t size; + intptr_t handle; // planar data has one fd for now, raw data also uses one pointer (+ offset) + uint32_t internalID; // internal identification for image/surface recycle + int64_t timeStamp; + uint32_t flags; //see VIDEO_FRAME_FLAGS_XXX +}VideoFrameRawData; + +#define VIDEO_FRAME_FLAGS_KEY 1 + +typedef enum { + YAMI_FATAL_ERROR = -1024, + /* encoder fatal */ + + /* decoder fatal */ + YAMI_DECODE_PARSER_FAIL, + + /* common fatal */ + YAMI_FAIL, + YAMI_NO_CONFIG, + YAMI_DRIVER_FAIL, + /* yami unimplemented */ + YAMI_NOT_IMPLEMENT, + /* driver or yami unsupported*/ + YAMI_UNSUPPORTED, + YAMI_INVALID_PARAM, + YAMI_OUT_MEMORY, + + YAMI_SUCCESS = 0, + /* recoverable error */ + /* need more input to get output frame*/ + YAMI_MORE_DATA, + + /* decoder no fatal */ + YAMI_DECODE_INVALID_DATA, + YAMI_DECODE_FORMAT_CHANGE, + YAMI_DECODE_NO_SURFACE, + + /* encoder no fatal */ + YAMI_ENCODE_BUFFER_TOO_SMALL, // The buffer passed to encode is too small to contain encoded data + YAMI_ENCODE_BUFFER_NO_MORE, //No more output buffers. + YAMI_ENCODE_IS_BUSY, // driver is busy, there are too many buffers under encoding in parallel. + YAMI_ENCODE_NO_REQUEST_DATA, + +} YamiStatus; + +typedef YamiStatus Decode_Status; +typedef YamiStatus Encode_Status; + +/* following code just for compatible, do not use it in new code*/ +#define DECODE_INVALID_DATA YAMI_DECODE_INVALID_DATA +#define DECODE_PARSER_FAIL YAMI_DECODE_PARSER_FAIL +#define DECODE_SUCCESS YAMI_SUCCESS +#define DECODE_FORMAT_CHANGE YAMI_DECODE_FORMAT_CHANGE +#define DECODE_FAIL YAMI_FAIL +#define DECODE_NO_SURFACE YAMI_DECODE_NO_SURFACE +#define DECODE_MEMORY_FAIL YAMI_OUT_MEMORY +#define DECODE_NOT_STARTED YAMI_FAIL + +#define ENCODE_SUCCESS YAMI_SUCCESS +#define ENCODE_FAIL YAMI_FAIL +#define ENCODE_INVALID_PARAMS YAMI_INVALID_PARAM +#define ENCODE_BUFFER_TOO_SMALL YAMI_ENCODE_BUFFER_TOO_SMALL +#define ENCODE_BUFFER_NO_MORE YAMI_ENCODE_BUFFER_NO_MORE +#define ENCODE_IS_BUSY YAMI_ENCODE_IS_BUSY +#define ENCODE_NO_REQUEST_DATA YAMI_ENCODE_NO_REQUEST_DATA +#define ENCODE_NO_MEMORY YAMI_OUT_MEMORY +/*compatible code end*/ + +typedef struct _SurfaceAllocParams SurfaceAllocParams; +typedef struct _SurfaceAllocParams { + //in + uint32_t fourcc; + uint32_t width; + uint32_t height; + + //in, out, number of surfaces + //for decoder, this min surfaces size need for decoder + //you should alloc extra size for perfomance or display queue + //you have two chance to get this size + // 1. from VideoFormatInfo.surfaceNumber, after you got DECODE_FORMAT_CHANGE + // 2. in SurfaceAllocator::alloc + uint32_t size; + + //out + intptr_t* surfaces; + + /** + * yami will call this when it want new surface to put decode data + * + * it's optional + * @param user SurfaceAllocParams::user + * @param surface you want decode to + */ + YamiStatus (*getSurface)(SurfaceAllocParams* thiz, intptr_t* surface); + + /** + * yami will call this when all surface usage have been done + * + * it's optional + * @param user SurfaceAllocParams::user + * @param surface need to recycle + */ + YamiStatus (*putSurface)(SurfaceAllocParams* thiz, intptr_t surface); + + //you can set your private data for get and put surface + //yami will not touch it + void* user; + +} SurfaceAllocParams; + +typedef struct _SurfaceAllocator SurfaceAllocator; +//allocator for surfaces, yami uses this to get +// 1. decoded surface for decoder. +// 2. reconstruct surface for encoder. +typedef struct _SurfaceAllocator +{ + void* user; /* you can put your private data here, yami will not touch it */ + /* alloc and free surfaces */ + YamiStatus (*alloc) (SurfaceAllocator* thiz, SurfaceAllocParams* params); + YamiStatus (*free) (SurfaceAllocator* thiz, SurfaceAllocParams* params); + /* after this called, yami will not use the allocator */ + void (*unref) (SurfaceAllocator* thiz); +} SurfaceAllocator; + +typedef struct VideoRect +{ + uint32_t x; + uint32_t y; + uint32_t width; + uint32_t height; +} VideoRect; + +/** + * slim version of VideoFrameRawData, only useful information here + * hope we can use this for decode, encode and vpp in final. + */ +typedef struct VideoFrame { + /** + * generic id for video surface, + * for libva it's VASurfaceID + */ + intptr_t surface; + + int64_t timeStamp; + + VideoRect crop; + + /** + * VIDEO_FRAME_FLAGS_XXX + */ + uint32_t flags; + + /* android's csc need this to set VAProcColorStandardType + * see vaapipostprocess_scaler.cpp for details + */ + uint32_t fourcc; + + /** + * for frame destory, cpp should not touch here + */ + intptr_t user_data; + void (*free)(struct VideoFrame* ); +} VideoFrame; + +#define YAMI_MIME_MPEG2 "video/mpeg2" +#define YAMI_MIME_H264 "video/h264" +#define YAMI_MIME_AVC "video/avc" +#define YAMI_MIME_H265 "video/h265" +#define YAMI_MIME_HEVC "video/hevc" +#define YAMI_MIME_VP8 "video/x-vnd.on2.vp8" +#define YAMI_MIME_VP9 "video/x-vnd.on2.vp9" +#define YAMI_MIME_JPEG "image/jpeg" +#define YAMI_MIME_VC1 "video/vc1" +#define YAMI_VPP_SCALER "vpp/scaler" +#define YAMI_VPP_OCL_BLENDER "vpp/ocl_blender" +#define YAMI_VPP_OCL_OSD "vpp/ocl_osd" +#define YAMI_VPP_OCL_TRANSFORM "vpp/ocl_transform" +#define YAMI_VPP_OCL_MOSAIC "vpp/ocl_mosaic" +#define YAMI_VPP_OCL_WIREFRAME "vpp/ocl_wireframe" + +#ifdef __cplusplus +} +#endif +#endif // VIDEO_COMMON_DEFS_H_ diff --git a/interface/VideoDecoderCapi.h b/interface/VideoDecoderCapi.h new file mode 100644 index 0000000..3056a57 --- /dev/null +++ b/interface/VideoDecoderCapi.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VIDEO_DECODER_CAPI_H__ +#define __VIDEO_DECODER_CAPI_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* DecodeHandler; + +DecodeHandler createDecoder(const char *mimeType); + +void decodeSetNativeDisplay(DecodeHandler p, NativeDisplay* display); + +YamiStatus decodeStart(DecodeHandler p, VideoConfigBuffer* buffer); + +YamiStatus decodeReset(DecodeHandler p, VideoConfigBuffer* buffer); + +void decodeStop(DecodeHandler p); + +void decodeFlush(DecodeHandler p); + +YamiStatus decodeDecode(DecodeHandler p, VideoDecodeBuffer* buffer); + +VideoFrame* decodeGetOutput(DecodeHandler p); + +const VideoFormatInfo* decodeGetFormatInfo(DecodeHandler p); + +void releaseDecoder(DecodeHandler p); + +/*deprecated*/ +void releaseLock(DecodeHandler p); + +#ifdef __cplusplus +}; +#endif + +#endif diff --git a/interface/VideoDecoderDefs.h b/interface/VideoDecoderDefs.h new file mode 100644 index 0000000..81e41fe --- /dev/null +++ b/interface/VideoDecoderDefs.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_DECODER_DEFS_H_ +#define VIDEO_DECODER_DEFS_H_ +// config.h should NOT be included in header file, especially for the header file used by external + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// flags for VideoDecodeBuffer, VideoConfigBuffer and VideoRenderBuffer +typedef enum { + // indicate whether surfaceNumber field in the VideoConfigBuffer is valid + HAS_SURFACE_NUMBER = 0x04, + + // indicate whether profile field in the VideoConfigBuffer is valid + HAS_VA_PROFILE = 0x08, +} VIDEO_BUFFER_FLAG; + +typedef enum { + //this will tell decoder, we have the whole frame. + //so the decoder can do decode immediately + //else they may need to wait for next frame boundary + VIDEO_DECODE_BUFFER_FLAG_FRAME_END = 0x1, +} VIDEO_DECODE_BUFFER_FLAG; + +typedef struct { + uint8_t *data; + size_t size; + int64_t timeStamp; + uint32_t flag; +}VideoDecodeBuffer; + +typedef struct { + uint8_t *data; + int32_t size; + /// it is the actual frame size, height is 1080 for h264 1080p stream + uint32_t width; + uint32_t height; + /// surfaceWidth and surfaceHeight are the resolution to config output buffer (dirver surface size or client buffer like in sw decode mode) + /// take h264 1080p as example, it is enlarged to 1088 + int32_t surfaceWidth; + int32_t surfaceHeight; + int32_t frameRate; + int32_t surfaceNumber; + VAProfile profile; + uint32_t flag; + uint32_t fourcc; + //xxxLayer - how many layers to decode; if 0, decode all layers. + uint32_t temporalLayer; + uint32_t spacialLayer; + uint32_t qualityLayer; + + //if set this flag to true, AVC decoder will output the ready frames ASAP. + bool enableLowLatency; +}VideoConfigBuffer; + +typedef struct { + bool valid; // indicates whether format info is valid. MimeType is always valid. + char *mimeType; + //width, height, this equals to same value in VideoFrame.crop + //if your video is 1920x1080, width will be 1920,and height will be 1080 + uint32_t width; + uint32_t height; + + /* Same thing as SurfaceAllocParams.width and SurfaceAllocParams.height + * You only need pay attention surfaceXXXX only when you are: + * 1. using IVideoDecoder.setAllocator. + * and + * 2. you want pre-allocate surface before we call SurfaceAllocator.alloc + * This size is depends on codec type or decoder hardware requirements + * For h264 1920x1080 it is usually 1920x1088 since h264 need 16 aligned surface + * Other *important* thing is, we may only call SurfaceAllocator.alloc when surface resolution increased + * For example, when resolution increase from 640x480 to 1920x1080, we will call + * SurfaceAllocator.alloc for 1920x1080, but when video change from 1920x1080 to 640x480, we + * may not call SurfaceAllocator.alloc, since we have enough surface resolution for decoding. + */ + uint32_t surfaceWidth; + uint32_t surfaceHeight; + //same thing as SurfaceAllocParams.size + uint32_t surfaceNumber; + + //unused thing yet, may remove in near future + int32_t aspectX; + int32_t aspectY; + int32_t cropLeft; + int32_t cropRight; + int32_t cropTop; + int32_t cropBottom; + int32_t colorMatrix; + int32_t videoRange; + int32_t bitrate; + int32_t framerateNom; + int32_t framerateDenom; + //unused end + + uint32_t fourcc; +}VideoFormatInfo; + +#ifdef __cplusplus +} +#endif +#endif // VIDEO_DECODER_DEFS_H_ diff --git a/interface/VideoDecoderHost.h b/interface/VideoDecoderHost.h new file mode 100644 index 0000000..b579218 --- /dev/null +++ b/interface/VideoDecoderHost.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef VIDEO_DECODER_HOST_H_ +#define VIDEO_DECODER_HOST_H_ + +#include +#include +#include + +/** \file VideoDecoderHost.h +*/ + +/** \fn IVideoDecoder *createVideoDecoder(const char *mimeType) +* \brief create a decoder basing on given mimetype +*/ +YamiMediaCodec::IVideoDecoder *createVideoDecoder(const char *mimeType); +/// \brief destroy the decoder +void releaseVideoDecoder(YamiMediaCodec::IVideoDecoder * p); +/** \fn void getVideoDecoderMimeTypes() + * \brief return the MimeTypes enabled in the current build +*/ +std::vector getVideoDecoderMimeTypes(); + +typedef YamiMediaCodec::IVideoDecoder *(*YamiCreateVideoDecoderFuncPtr) (const char *mimeType); +typedef void (*YamiReleaseVideoDecoderFuncPtr)(YamiMediaCodec::IVideoDecoder * p); +#endif /* VIDEO_DECODER_HOST_H_ */ diff --git a/interface/VideoDecoderInterface.h b/interface/VideoDecoderInterface.h new file mode 100644 index 0000000..628ce12 --- /dev/null +++ b/interface/VideoDecoderInterface.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef VIDEO_DECODER_INTERFACE_H_ +#define VIDEO_DECODER_INTERFACE_H_ +// config.h should NOT be included in header file, especially for the header file used by external + +#include + +namespace YamiMediaCodec { +/** + * \class IVideoDecoder + * \brief Abstract video decoding interface of libyami + * + * it is the interface with client + */ +class IVideoDecoder { +public: + virtual ~IVideoDecoder() {} + /** \brief configure decoder before decode the first frame + * @param[in] buffer stream information to initialize decoder + * if the configuration in @param buffer doesn't match the information in coming stream, + * future #decode will return YAMI_DECODE_FORMAT_CHANGE (#VIDEO_DECODE_STATUS), it will trigger + * a reconfiguration from client. (yami will not reconfigure decoder internally to avoid mismatch between client and libyami) + */ + virtual YamiStatus start(VideoConfigBuffer* buffer) = 0; + /// \brief reset decoder with new configuration before decoding a new stream + /// @param[in] buffer new stream information to reset decoder. cached data (input data or decoded video frames) are discarded. + virtual YamiStatus reset(VideoConfigBuffer* buffer) = 0; + /// stop decoding and destroy sw/hw decoder context. + virtual void stop(void) = 0; + /// discard cached data (input data or decoded video frames), it is usually required during seek + virtual void flush(void) = 0; + /// continue decoding with new data in @param[in] buffer; send empty data (buffer.data=NULL, buffer.size=0) to indicate EOS + virtual YamiStatus decode(VideoDecodeBuffer* buffer) = 0; + + ///get decoded frame from decoder. + virtual SharedPtr getOutput() = 0; + + /** \brief retrieve updated stream information after decoder has parsed the video stream. + * client usually calls it when libyami return YAMI_DECODE_FORMAT_CHANGE in decode(). + */ + virtual const VideoFormatInfo* getFormatInfo(void) = 0; + + /// set native display + virtual void setNativeDisplay( NativeDisplay * display = NULL) = 0; + virtual void setAllocator(SurfaceAllocator* allocator) = 0; + + /*deprecated*/ + /// lockable is set to false when seek begins and reset to true after seek is done + /// EOS also set lockable to false + virtual void releaseLock(bool lockable=false) = 0; + + /*deprecated*/ + ///do not use this, we will remove this in near future + virtual VADisplay getDisplayID() = 0; +}; +} +#endif /* VIDEO_DECODER_INTERFACE_H_ */ diff --git a/interface/VideoEncoderCapi.h b/interface/VideoEncoderCapi.h new file mode 100644 index 0000000..dca656c --- /dev/null +++ b/interface/VideoEncoderCapi.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VIDEO_ENCODER_CAPI_H__ +#define __VIDEO_ENCODER_CAPI_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* EncodeHandler; + +EncodeHandler createEncoder(const char *mimeType); + +void encodeSetNativeDisplay(EncodeHandler p, NativeDisplay * display); + +YamiStatus encodeStart(EncodeHandler p); + +void encodeStop(EncodeHandler p); + +/* encoder will can frame->free, no matter it return fail or not*/ +YamiStatus encodeEncode(EncodeHandler p, VideoFrame* frame); + +YamiStatus encodeGetOutput(EncodeHandler p, VideoEncOutputBuffer* outBuffer, bool withWait); + +YamiStatus encodeGetParameters(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncParams); + +YamiStatus encodeSetParameters(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncParams); + +YamiStatus encodeGetMaxOutSize(EncodeHandler p, uint32_t* maxSize); + +void releaseEncoder(EncodeHandler p); + +/*deprecated*/ +YamiStatus encodeEncodeRawData(EncodeHandler p, VideoFrameRawData* inBuffer); + +/*deprecated*/ +YamiStatus getStatistics(EncodeHandler p, VideoStatistics* videoStat); + +/*deprecated*/ +YamiStatus getConfig(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncConfig); + +/*deprecated*/ +YamiStatus setConfig(EncodeHandler p, VideoParamConfigType type, Yami_PTR videoEncConfig); + +#ifdef __cplusplus +}; +#endif + +#endif diff --git a/interface/VideoEncoderDefs.h b/interface/VideoEncoderDefs.h new file mode 100644 index 0000000..b0db456 --- /dev/null +++ b/interface/VideoEncoderDefs.h @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VIDEO_ENCODER_DEF_H__ +#define __VIDEO_ENCODER_DEF_H__ + +// config.h should NOT be included in header file, especially for the header file used by external + +#include +#include +#include + +#define STRING_TO_FOURCC(format) ((uint32_t)(((format)[0])|((format)[1]<<8)|((format)[2]<<16)|((format)[3]<<24))) + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void * Yami_PTR; + +typedef enum { + OUTPUT_EVERYTHING = 0, //Output whatever driver generates + OUTPUT_CODEC_DATA = 1, // codec data for mp4, similar to avcc format + OUTPUT_FRAME_DATA = 2, //Equal to OUTPUT_EVERYTHING when no header along with the frame data + OUTPUT_ONE_NAL = 4, + OUTPUT_ONE_NAL_WITHOUT_STARTCODE = 8, + OUTPUT_LENGTH_PREFIXED = 16, + OUTPUT_BUFFER_LAST +}VideoOutputFormat; + +typedef enum { + RATE_CONTROL_NONE = VA_RC_NONE, + RATE_CONTROL_CBR = VA_RC_CBR, + RATE_CONTROL_VBR = VA_RC_VBR, + RATE_CONTROL_VCM = VA_RC_VCM, + RATE_CONTROL_CQP = VA_RC_CQP, + RATE_CONTROL_LAST +}VideoRateControl; + +typedef enum { + PROFILE_INVALID, + PROFILE_JPEG_BASELINE, + PROFILE_VC1_SIMPLE, + PROFILE_VC1_MAIN, + PROFILE_VC1_ADVANCED, + PROFILE_MPEG2_SIMPLE, + PROFILE_MPEG2_MAIN, + PROFILE_MPEG4_SIMPLE, + PROFILE_MPEG4_ADVANCED_SIMPLE, + PROFILE_MPEG4_MAIN, + PROFILE_H263_BASELINE, + PROFILE_H264_CONSTRAINED_BASELINE, + PROFILE_H264_MAIN, + PROFILE_H264_HIGH, + PROFILE_H264_HIGH10, + PROFILE_H264_HIGH422, + PROFILE_H264_HIGH444, + PROFILE_H265_MAIN, + PROFILE_H265_MAIN10, +} VideoProfile; + +typedef enum { + AVC_STREAM_FORMAT_AVCC, + AVC_STREAM_FORMAT_ANNEXB +}AVCStreamFormat; + +// Output buffer flag +#define ENCODE_BUFFERFLAG_ENDOFFRAME 0x00000001 +#define ENCODE_BUFFERFLAG_PARTIALFRAME 0x00000002 +#define ENCODE_BUFFERFLAG_SYNCFRAME 0x00000004 +#define ENCODE_BUFFERFLAG_CODECCONFIG 0x00000008 +#define ENCODE_BUFFERFLAG_DATACORRUPT 0x00000010 +#define ENCODE_BUFFERFLAG_DATAINVALID 0x00000020 +#define ENCODE_BUFFERFLAG_SLICEOVERFOLOW 0x00000040 + +//quality level for encoder +#define VIDEO_PARAMS_QUALITYLEVEL_NONE 0 +#define VIDEO_PARAMS_QUALITYLEVEL_MIN 1 +#define VIDEO_PARAMS_QUALITYLEVEL_MAX 7 +#define TEMPORAL_LAYER_LENGTH_MAX 32 +#define TEMPORAL_LAYERIDS_LENGTH_MAX 32 + +typedef struct VideoEncOutputBuffer { + uint8_t *data; + uint32_t bufferSize; //buffer size + uint32_t dataSize; //actuall size + uint32_t remainingSize; + uint32_t flag; //Key frame, Codec Data etc + VideoOutputFormat format; //output format + uint8_t temporalID; //output temporal id for SVCT encoder + uint64_t timeStamp; //reserved +}VideoEncOutputBuffer; + +#ifdef __BUILD_GET_MV__ + /* + * VideoEncMVBuffer is defined to store Motion vector. + * Memory size allocated to data pointer can be got by getMVBufferSize API. + * Picture is partitioned to 16*16 block, within the 16x16 block, each 4x4 subblock has the same MV. + * Access the first 4*4 subblock to get the MV of each 16*16 block, and skip the 16*16 block to + * get MV of next 16x16 Block. + * Refer to structure VAMotionVectorIntel about detailed layout for MV of 4*4 subblock. + * 16x16 block is in raster scan order, within the 16x16 block, each 4x4 block MV is ordered as below in memory. + * 16x16 Block + * ----------------------------------------- + * | 1 | 2 | 5 | 6 | + * ----------------------------------------- + * | 3 | 4 | 7 | 8 | + * ----------------------------------------- + * | 9 | 10 | 13 | 14 | + * ----------------------------------------- + * | 11 | 12 | 15 | 16 | + * ----------------------------------------- + */ +typedef struct VideoEncMVBuffer { + uint8_t *data; //memory to store the MV + uint32_t bufferSize; //buffer size + uint32_t dataSize; //actuall size +}VideoEncMVBuffer; +#endif + +typedef struct VideoEncRawBuffer { + uint8_t *data; + uint32_t fourcc; + uint32_t size; + bool bufAvailable; //To indicate whether this buffer can be reused + uint64_t timeStamp; //reserved + bool forceKeyFrame; + intptr_t id; +}VideoEncRawBuffer; + +typedef struct VideoEncSurfaceBuffer { + VASurfaceID surface; + uint8_t *usrptr; + uint32_t index; + bool bufAvailable; + struct EncSurfaceBuffer *next; +}VideoEncSurfaceBuffer; + +typedef struct VideoFrameRate { + uint32_t frameRateNum; + uint32_t frameRateDenom; +}VideoFrameRate; + +typedef struct VideoTemporalLayers { + //layer 0 bitrate is bitRate[0] + //... + //layer highest birate is VideoParamsCommon.rcParams.bitRate + uint8_t numLayersMinus1; + uint32_t bitRate[TEMPORAL_LAYER_LENGTH_MAX]; +} VideoTemporalLayers; + +typedef struct VideoTemporalLayerIDs { + uint8_t numIDs; + uint8_t ids[TEMPORAL_LAYERIDS_LENGTH_MAX]; +} VideoTemporalLayerIDs; + +typedef struct VideoResolution { + uint32_t width; + uint32_t height; +}VideoResolution; + +typedef struct VideoRateControlParams { + uint32_t bitRate; + uint32_t initQP; + uint32_t minQP; + uint32_t maxQP; + uint32_t disableFrameSkip; + uint32_t disableBitsStuffing; + int8_t diffQPIP;// P frame qp minus initQP + int8_t diffQPIB;// B frame qp minus initQP +}VideoRateControlParams; + +typedef struct SliceNum { + uint32_t iSliceNum; + uint32_t pSliceNum; +}SliceNum; + +typedef struct SamplingAspectRatio { + uint16_t SarWidth; + uint16_t SarHeight; +}SamplingAspectRatio; + +typedef enum { + VideoParamsTypeStartUnused = 0x01000000, + VideoParamsTypeCommon, + VideoParamsTypeAVC, + VideoParamsTypeH263, + VideoParamsTypeMP4, + VideoParamsTypeVP9, + VideoParamsTypeVC1, + VideoParamsTypeHRD, + VideoParamsTypeQualityLevel, + + VideoConfigTypeFrameRate, + VideoConfigTypeBitRate, + VideoConfigTypeResolution, + VideoConfigTypeNALSize, + VideoConfigTypeIDRRequest, + VideoConfigTypeSliceNum, + + //format related + VideoConfigTypeAVCStreamFormat, + + VideoParamsConfigExtension +} VideoParamConfigType; + +typedef struct VideoParamConfigSet { + uint32_t size; +}VideoParamConfigSet; + +typedef struct VideoParamsCommon { + uint32_t size; + VAProfile profile; + uint8_t level; + VideoResolution resolution; + VideoFrameRate frameRate; + VideoTemporalLayers temporalLayers; + VideoTemporalLayerIDs temporalLayerIDs; + uint32_t intraPeriod; + uint32_t ipPeriod; + uint32_t numRefFrames; + VideoRateControl rcMode; + VideoRateControlParams rcParams; + uint32_t leastInputCount; + bool enableLowPower; + uint8_t bitDepth; +}VideoParamsCommon; + +typedef struct VideoParamsAVC { + uint32_t size; + uint32_t basicUnitSize; //for rate control + uint8_t VUIFlag; + int32_t maxSliceSize; + uint32_t idrInterval; //How many Intra frames will have an IDR frame + SliceNum sliceNum; + SamplingAspectRatio SAR; + bool enableCabac; + bool enableDct8x8; + bool enableDeblockFilter; + int8_t deblockAlphaOffsetDiv2; //same as slice_alpha_c0_offset_div2 defined in h264 spec 7.4.3 + int8_t deblockBetaOffsetDiv2; //same as slice_beta_offset_div2 defined in h264 spec 7.4.3 + uint32_t priorityId; + // enable prefix NAL unit defined as h264 spec G.3.42. + // It can be used for h264 simucast or svc-t encoding. + bool enablePrefixNalUnit; +}VideoParamsAVC; + +typedef struct VideoParamsVP9 { + uint32_t referenceMode; +}VideoParamsVP9; + +typedef struct VideoParamsHRD { + uint32_t size; + uint32_t bufferSize; + uint32_t initBufferFullness; + uint32_t windowSize; // use for HRD CPB length in ms + uint32_t targetPercentage; +}VideoParamsHRD; + +typedef struct VideoParamsQualityLevel { + uint32_t size; + uint32_t level; +} VideoParamsQualityLevel; + +typedef struct VideoConfigFrameRate { + uint32_t size; + VideoFrameRate frameRate; +}VideoConfigFrameRate; + +typedef struct VideoConfigBitRate { + uint32_t size; + VideoRateControlParams rcParams; +}VideoConfigBitRate; + +typedef struct VideoConfigNALSize { + uint32_t size; + uint32_t maxSliceSize; +}VideoConfigNALSize; + +typedef struct VideoConfigResoltuion { + uint32_t size; + VideoResolution resolution; +}VideoConfigResoltuion; + +struct VideoConfigSliceNum { + uint32_t size; + SliceNum sliceNum; +}; + +typedef struct VideoConfigAVCStreamFormat { + uint32_t size; + AVCStreamFormat streamFormat; +} VideoConfigAVCStreamFormat; + +typedef struct { + uint32_t total_frames; + uint32_t skipped_frames; + uint32_t average_encode_time; + uint32_t max_encode_time; + uint32_t max_encode_frame; + uint32_t min_encode_time; + uint32_t min_encode_frame; +} VideoStatistics; + +#ifdef __cplusplus +} +#endif +#endif /* __VIDEO_ENCODER_DEF_H__ */ diff --git a/interface/VideoEncoderHost.h b/interface/VideoEncoderHost.h new file mode 100644 index 0000000..8137456 --- /dev/null +++ b/interface/VideoEncoderHost.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_ENCODER_HOST_H_ +#define VIDEO_ENCODER_HOST_H_ + +#include +#include +#include + +/** \file VideoEncoderHost.h +*/ + +/** \fn IVideoEncoder *createVideoEncoder(const char *mimeType) + * \brief create encoder basing on given mimetype +*/ +YamiMediaCodec::IVideoEncoder *createVideoEncoder(const char *mimeType); +///brief destroy encoder +void releaseVideoEncoder(YamiMediaCodec::IVideoEncoder * p); +/** \fn void getVideoEncoderMimeTypes() + * \brief return the MimeTypes enabled in the current build +*/ +std::vector getVideoEncoderMimeTypes(); + +typedef YamiMediaCodec::IVideoEncoder *(*YamiCreateVideoEncoderFuncPtr) (const char *mimeType); +typedef void (*YamiReleaseVideoEncoderFuncPtr)(YamiMediaCodec::IVideoEncoder * p); +#endif /* VIDEO_ENCODER_HOST_H_ */ diff --git a/interface/VideoEncoderInterface.h b/interface/VideoEncoderInterface.h new file mode 100644 index 0000000..622adf8 --- /dev/null +++ b/interface/VideoEncoderInterface.h @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_ENCODER_INTERFACE_H_ +#define VIDEO_ENCODER_INTERFACE_H_ +// config.h should NOT be included in header file, especially for the header file used by external + +#include +#undef None // work around for compile in chromeos + +namespace YamiMediaCodec{ +/** + * \class IVideoEncoder + * \brief Abstract video encoding interface of libyami + * it is the interface with client. they are not thread safe. + * getOutput() can be called in one (and only one) separated thread, though IVideoEncoder APIs are not fully thread safe. + */ +class IVideoEncoder { + public: + virtual ~ IVideoEncoder() {} + /// set native display + virtual void setNativeDisplay( NativeDisplay * display = NULL) = 0; + /** \brief start encode, make sure you setParameters before start, else if will use default. + */ + virtual YamiStatus start(void) = 0; + /// stop encoding and destroy encoder context. + virtual YamiStatus stop(void) = 0; + + /// continue encoding with new data in @param[in] inBuffer + virtual YamiStatus encode(VideoEncRawBuffer* inBuffer) = 0; + /// continue encoding with new data in @param[in] frame + virtual YamiStatus encode(VideoFrameRawData* frame) = 0; + + /// continue encoding with new data in @param[in] frame + /// we will hold a reference of @param[in]frame, until encode is done + virtual YamiStatus encode(const SharedPtr& frame) = 0; + +#ifndef __BUILD_GET_MV__ + /** + * \brief return one frame encoded data to client; + * when withWait is false, YAMI_ENCODE_BUFFER_NO_MORE will be returned if there is no available frame. \n + * when withWait is true, function call is block until there is one frame available. \n + * typically, getOutput() is called in a separate thread (than encoding thread), this thread sleeps when + * there is no output available when withWait is true. \n + * + * param [in/out] outBuffer a #VideoEncOutputBuffer of one frame encoded data + * param [in/out] when there is no output data available, wait or not + */ + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, bool withWait = false) = 0; +#else + /** + * \brief return one frame encoded data to client; + * when withWait is false, YAMI_ENCODE_BUFFER_NO_MORE will be returned if there is no available frame. \n + * when withWait is true, function call is block until there is one frame available. \n + * typically, getOutput() is called in a separate thread (than encoding thread), this thread sleeps when + * there is no output available when withWait is true. \n + * + * param [in/out] outBuffer a #VideoEncOutputBuffer of one frame encoded data + * param [in/out] MVBuffer a #VideoEncMVBuffer of one frame MV data + * param [in/out] when there is no output data available, wait or not + */ + virtual YamiStatus getOutput(VideoEncOutputBuffer* outBuffer, VideoEncMVBuffer* MVBuffer, bool withWait = false) = 0; +#endif + + /// get encoder params, some config parameter are updated basing on sw/hw implement limition. + /// for example, update pitches basing on hw alignment + virtual YamiStatus getParameters(VideoParamConfigType type, Yami_PTR videoEncParams) = 0; + /// set encoder params before start. \n + /// update rate controls on the fly by VideoParamsTypeRatesControl/VideoParamsRatesControl. SPS updates accordingly. + virtual YamiStatus setParameters(VideoParamConfigType type, Yami_PTR videoEncParams) = 0; + /// get max coded buffer size. + virtual YamiStatus getMaxOutSize(uint32_t* maxSize) = 0; + +#ifdef __BUILD_GET_MV__ + /// get MV buffer size. + virtual YamiStatus getMVBufferSize(uint32_t* Size) = 0; +#endif + + /// get encode statistics information, for debug use + virtual YamiStatus getStatistics(VideoStatistics* videoStat) = 0; + + ///flush cached data (input data or encoded video frames) + virtual void flush(void) = 0; + ///obsolete, what is the difference between getParameters and getConfig? + virtual YamiStatus getConfig(VideoParamConfigType type, Yami_PTR videoEncConfig) = 0; + ///obsolete, what is the difference between setParameters and setConfig? + virtual YamiStatus setConfig(VideoParamConfigType type, Yami_PTR videoEncConfig) = 0; +}; +} +#endif /* VIDEO_ENCODER_INTERFACE_H_ */ diff --git a/interface/VideoPostProcessDefs.h b/interface/VideoPostProcessDefs.h new file mode 100644 index 0000000..04f356e --- /dev/null +++ b/interface/VideoPostProcessDefs.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __VIDEO_POST_PROCESS_DEFS_H__ +#define __VIDEO_POST_PROCESS_DEFS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + VppParamTypeOsd, + VppParamTypeTransform, + VppParamTypeMosaic, + VppParamTypeDenoise, + VppParamTypeSharpening, + VppParamTypeDeinterlace, + VppParamTypeWireframe, + VppParamTypeColorBalance +} VppParamType; + +typedef struct VppParamOsd { + size_t size; + uint32_t threshold; +} VppParamOsd; + +typedef enum { + VPP_TRANSFORM_NONE = 0x0, + VPP_TRANSFORM_FLIP_H = 0x1, + VPP_TRANSFORM_FLIP_V = 0x2, + VPP_TRANSFORM_ROT_90 = 0x4, + VPP_TRANSFORM_ROT_180 = 0x8, + VPP_TRANSFORM_ROT_270 = 0x10, +} VppTransform; + +typedef struct VppParamTransform { + size_t size; + uint32_t transform; +} VppParamTransform; + +typedef struct VppParamMosaic { + size_t size; + uint32_t blockSize; +} VppParamMosaic; + +#define DENOISE_LEVEL_MIN 0 +#define DENOISE_LEVEL_MAX 100 +#define DENOISE_LEVEL_NONE (DENOISE_LEVEL_MIN - 1) + +typedef struct VPPDenoiseParameters { + size_t size; + int32_t level; +} VPPDenoiseParameters; + +#define SHARPENING_LEVEL_MIN 0 +#define SHARPENING_LEVEL_MAX 100 +#define SHARPENING_LEVEL_NONE (SHARPENING_LEVEL_MIN - 1) + +#define COLORBALANCE_LEVEL_MIN 0 +#define COLORBALANCE_LEVEL_MAX 100 +#define COLORBALANCE_LEVEL_NONE (COLORBALANCE_LEVEL_MIN - 1) + +typedef struct VPPSharpeningParameters { + size_t size; + int32_t level; +} VPPSharpeningParameters; + +typedef enum VppDeinterlaceMode { + DEINTERLACE_MODE_NONE, + DEINTERLACE_MODE_WEAVE = DEINTERLACE_MODE_NONE, + DEINTERLACE_MODE_BOB, +} VppDeinterlaceMode; + +typedef struct VPPDeinterlaceParameters { + size_t size; + VppDeinterlaceMode mode; +} VPPDeinterlaceParameters; + +typedef struct VppParamWireframe { + size_t size; + uint32_t borderWidth; + uint8_t colorY; + uint8_t colorU; + uint8_t colorV; +} VppParamWireframe; + +typedef enum VppColorBalanceMode { + COLORBALANCE_NONE = 0, + COLORBALANCE_HUE, + COLORBALANCE_SATURATION, + COLORBALANCE_BRIGHTNESS, + COLORBALANCE_CONTRAST, + COLORBALANCE_COUNT +} VppColorBalanceMode; + +typedef struct VPPColorBalanceParameter { + size_t size; + VppColorBalanceMode mode; + int32_t level; +} VPPColorBalanceParameter; + +#ifdef __cplusplus +} +#endif +#endif /* __VIDEO_POST_PROCESS_DEFS_H__ */ diff --git a/interface/VideoPostProcessHost.h b/interface/VideoPostProcessHost.h new file mode 100644 index 0000000..b0cffa6 --- /dev/null +++ b/interface/VideoPostProcessHost.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_POST_PROCESS_HOST_H_ +#define VIDEO_POST_PROCESS_HOST_H_ + +#include +#include +#include + +/** \file VideoPostProcessHost.h +*/ + +/** \fn IVideoPostProcess *createVideoPostProcess(const char *mimeType) + * \brief create encoder basing on given mimetype +*/ +YamiMediaCodec::IVideoPostProcess *createVideoPostProcess(const char *mimeType); +/** \fn void releaseVideoPostProcess(IVideoPostProcess *p) + * \brief destroy encoder +*/ +void releaseVideoPostProcess(YamiMediaCodec::IVideoPostProcess * p); +/** \fn void getVideoPostProcessMimeTypes() + * \brief return the MimeTypes enabled in the current build +*/ +std::vector getVideoPostProcessMimeTypes(); + +typedef YamiMediaCodec::IVideoPostProcess *(*YamiCreateVideoPostProcessFuncPtr) (const char *mimeType); +typedef void (*YamiReleaseVideoPostProcessFuncPtr)(YamiMediaCodec::IVideoPostProcess * p); +#endif /* VIDEO_POST_PROCESS_HOST_H_ */ diff --git a/interface/VideoPostProcessInterface.h b/interface/VideoPostProcessInterface.h new file mode 100644 index 0000000..aaad4c8 --- /dev/null +++ b/interface/VideoPostProcessInterface.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VIDEO_POST_PROCESS_INTERFACE_H_ +#define VIDEO_POST_PROCESS_INTERFACE_H_ + +#include +#include + +namespace YamiMediaCodec{ +/** + * \class IVideoPostProcess + * \brief Abstract video post process interface of libyami + * it is the interface with client. they are not thread safe. + */ +class IVideoPostProcess { + public: + // set native display + virtual YamiStatus setNativeDisplay(const NativeDisplay& display) = 0; + // it may return YAMI_MORE_DATA when output is not ready + // it's no need fill every field of VideoFrame, we can get detailed information from lower level + // VideoFrame.surface is enough for most of case + // for some type of vpp such as deinterlace, we will hold a referece of src. + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dest) = 0; + virtual YamiStatus setParameters(VppParamType type, void* vppParam) = 0; + virtual ~IVideoPostProcess() {} +}; +} +#endif /* VIDEO_POST_PROCESS_INTERFACE_H_ */ diff --git a/interface/Yami.h b/interface/Yami.h new file mode 100644 index 0000000..0bdf381 --- /dev/null +++ b/interface/Yami.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef YAMI_H_ +#define YAMI_H_ + +#include + +#include + +#include + +#include + +#endif diff --git a/interface/YamiC.h b/interface/YamiC.h new file mode 100644 index 0000000..faf8e9f --- /dev/null +++ b/interface/YamiC.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef YAMI_C_H_ +#define YAMI_C_H_ + +#include + +#include +#include + +#endif diff --git a/interface/YamiVersion.h.in b/interface/YamiVersion.h.in new file mode 100644 index 0000000..8a7ccd0 --- /dev/null +++ b/interface/YamiVersion.h.in @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef YAMI_VERSION_H +#define YAMI_VERSION_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * YAMI_API_MAJOR_VERSION + * The major version of yami api + */ +#define YAMI_API_MAJOR_VERSION @YAMI_API_MAJOR_VERSION@ + +/** + * YAMI_API_MINOR_VERSION + * The minor version of yami api + */ +#define YAMI_API_MINOR_VERSION @YAMI_API_MINOR_VERSION@ + +/** + * YAMI_API_MICRO_VERSION + * The micro version of yami api + */ +#define YAMI_API_MICRO_VERSION @YAMI_API_MICRO_VERSION@ + +/** + * YAMI_API_VERSION_STRING + * The string version of yami api + */ +#define YAMI_API_VERSION_STRING "@YAMI_API_VERSION@" + + +#define YAMI_API_VERSION_INT(major, minor, micro) ((major << 24) | (minor << 16) | (micro << 8)) + +/** + * YAMI_API_VERSION + * The int version of yami api + */ +#define YAMI_API_VERSION YAMI_API_VERSION_INT(YAMI_API_MAJOR_VERSION, YAMI_API_MINOR_VERSION, YAMI_API_MICRO_VERSION) + +/** + * YAMI_CHECK_API_VERSION + * Result is 1 if YAMI_API_VERSION is greater than + * YAMI_API_VERSION_INT(major, minor, micro) + */ +#define YAMI_CHECK_API_VERSION(major, minor, micro) (YAMI_API_VERSION >= YAMI_API_VERSION_INT(major, minor, micro)) + +/** +* yamiGetApiVersion +* return YAMI_API_VERSION; +*/ +void yamiGetApiVersion(uint32_t *apiVersion); + +#ifdef __cplusplus +}; +#endif + +#endif /* YAMI_VERSION_H */ diff --git a/interface/v4l2_wrapper.h b/interface/v4l2_wrapper.h new file mode 100644 index 0000000..dfd7b98 --- /dev/null +++ b/interface/v4l2_wrapper.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#if defined(__ENABLE_X11__) +#include +#endif +#include "VideoCommonDefs.h" + +#ifndef v4l2_wrapper_h +#define v4l2_wrapper_h +#ifndef V4L2_EVENT_RESOLUTION_CHANGE + #define V4L2_EVENT_RESOLUTION_CHANGE 5 +#endif + +#ifdef __cplusplus +extern "C" { +#endif +int32_t YamiV4L2_Open(const char* name, int32_t flags); +int32_t YamiV4L2_Close(int32_t fd); +int32_t YamiV4L2_FrameMemoryType(int32_t fd, VideoDataMemoryType memory_type); +int32_t YamiV4L2_SvcT(int32_t fd, bool enable); +int32_t YamiV4L2_Ioctl(int32_t fd, int request, void* arg); +int32_t YamiV4L2_Poll(int32_t fd, bool poll_device, bool* event_pending); +int32_t YamiV4L2_SetDevicePollInterrupt(int32_t fd); +int32_t YamiV4L2_ClearDevicePollInterrupt(int32_t fd); +void* YamiV4L2_Mmap(void* addr, size_t length, + int prot, int flags, int fd, unsigned int offset); +int32_t YamiV4L2_Munmap(void* addr, size_t length); + +#if defined(__ENABLE_WAYLAND__) +int32_t YamiV4L2_SetWaylandDisplay(int32_t fd, struct wl_display* wlDisplay); +#endif //__ENABLE_WAYLAND__ + +#if defined(__ENABLE_X11__) +/// it should be called before driver initialization (immediate after _Open()). +int32_t YamiV4L2_SetXDisplay(int32_t fd, Display* x11Display); +#endif // defined(__ENABLE_X11__) + +#if defined(__ENABLE_EGL__) +int32_t YamiV4L2_UseEglImage(int fd, /*EGLDisplay*/ void* eglDisplay, /*EGLContext*/ void* eglContext, unsigned int buffer_index, void* egl_image); +#endif //__ENABLE_EGL__ + +int32_t YamiV4L2_SetDrmFd(int32_t fd, int drm_fd); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif + diff --git a/interface/v4l2codec_device_ops.h b/interface/v4l2codec_device_ops.h new file mode 100644 index 0000000..525f4ff --- /dev/null +++ b/interface/v4l2codec_device_ops.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2015 Alibaba. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef v4l2codec_device_ops_h +#define v4l2codec_device_ops_h +#include +#include + +#ifndef V4L2_EVENT_RESOLUTION_CHANGE + #define V4L2_EVENT_RESOLUTION_CHANGE 5 +#endif +#ifndef V4L2_MEMORY_DMABUF + #define V4L2_MEMORY_DMABUF 4 +#endif +#ifndef V4L2_MEMORY_ANDROID_BUFFER_HANDLE + #define V4L2_MEMORY_ANDROID_BUFFER_HANDLE (V4L2_MEMORY_DMABUF+1) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// func pointer of v4l2 device +typedef int32_t (*V4l2OpenFunc)(const char* name, int32_t flags); +typedef int32_t (*V4l2CloseFunc)(int32_t fd); +typedef int32_t (*V4l2IoctlFunc)(int32_t fd, int32_t cmd, void* arg); +typedef int32_t (*V4l2PollFunc)(int32_t fd, bool poll_device, bool* event_pending); +typedef int32_t (*V4l2SetDevicePollInterruptFunc)(int32_t fd); +typedef int32_t (*V4l2ClearDevicePollInterruptFunc)(int32_t fd); +typedef void* (*V4l2MmapFunc)(void* addr, size_t length, int32_t prot, + int32_t flags, int32_t fd, unsigned int offset); +typedef int32_t (*V4l2MunmapFunc)(void* addr, size_t length); +typedef int32_t (*V4l2SetParameterFunc)(int32_t fd, const char* key, const char* value); +typedef int32_t (*V4l2UseEglImageFunc)(int32_t fd, /*EGLDisplay*/void* egl_display, /*EGLContext*/void* egl_context, + uint32_t buffer_index, void* egl_image); + +#define V4L2CODEC_VENDOR_STRING_SIZE 16 +#define V4L2CODEC_VERSION_MAJOR 0 +#define V4L2CODEC_VERSION_MINOR 1 +#define V4L2CODEC_VERSION_REVISION 0 +#define V4L2CODEC_VERSION_STEP 0 + +typedef union V4l2CodecVersion{ + struct { + uint8_t mMajor; + uint8_t mMinor; + uint8_t mRevision; + uint8_t mStep; + } mDetail; + uint32_t mVersion; +} V4l2CodecVersion; + +typedef struct V4l2CodecOps { + uint32_t mSize; + V4l2CodecVersion mVersion; + char mVendorString[V4L2CODEC_VENDOR_STRING_SIZE]; // for example yami-0.4.0 + V4l2OpenFunc mOpenFunc; + V4l2CloseFunc mCloseFunc; + V4l2IoctlFunc mIoctlFunc; + V4l2PollFunc mPollFunc; + V4l2SetDevicePollInterruptFunc mSetDevicePollInterruptFunc; + V4l2ClearDevicePollInterruptFunc mClearDevicePollInterruptFunc; + V4l2MmapFunc mMmapFunc; + V4l2MunmapFunc mMunmapFunc; + V4l2SetParameterFunc mSetParameterFunc; + V4l2UseEglImageFunc mUseEglImageFunc; +} V4l2CodecOps; + +#define INIT_V4L2CODEC_OPS_VERSION(version) do { \ + (version).mDetail.mMajor = V4L2CODEC_VERSION_MAJOR; \ + (version).mDetail.mMinor = V4L2CODEC_VERSION_MINOR; \ + (version).mDetail.mRevision = V4L2CODEC_VERSION_REVISION; \ + (version).mDetail.mStep = V4L2CODEC_VERSION_STEP; \ +} while(0) + +// do not cast ops to V4l2CodecOps*; assume caller use it correctly (it will not pass compile if not) +#define INIT_V4L2CODEC_OPS_SIZE_VERSION(ops) do { \ + if((ops) == NULL) break; \ + memset(ops, 0, sizeof(V4l2CodecOps)); \ + (ops)->mSize = sizeof(V4l2CodecOps); \ + INIT_V4L2CODEC_OPS_VERSION((ops)->mVersion); \ +} while(0) + +#define IS_V4L2CODEC_OPS_VERSION_MATCH(version, isMatch) do { \ + V4l2CodecVersion v; \ + INIT_V4L2CODEC_OPS_VERSION(v); \ + if (version.mVersion == v.mVersion) { \ + isMatch = 1; \ + } else { \ + isMatch = 0; \ + } \ +} while(0) + +typedef bool (*V4l2codecOperationInitFunc)(struct V4l2CodecOps *OpFuncs); +// fill all the func ptrs implemented by platform +bool v4l2codecOperationInit(V4l2CodecOps *OpFuncs); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // v4l2codec_device_ops_h + diff --git a/ocl/kernels/blend.cl b/ocl/kernels/blend.cl new file mode 100644 index 0000000..6ff8069 --- /dev/null +++ b/ocl/kernels/blend.cl @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +__kernel void blend(__write_only image2d_t dst_y, + __write_only image2d_t dst_uv, + __read_only image2d_t bg_y, + __read_only image2d_t bg_uv, + __read_only image2d_t fg, + uint crop_x, uint crop_y, uint crop_w, uint crop_h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST; + int i; + int id_x = get_global_id(0); + int id_y = get_global_id(1) * 2; + int id_z = id_x; + int id_w = id_y; + + float4 y1, y2; + float4 y1_dst, y2_dst, y_dst; + float4 uv, uv_dst; + float4 rgba[4]; + + id_x += crop_x; + id_y += crop_y; + y1 = read_imagef(bg_y, sampler, (int2)(id_x, id_y)); + y2 = read_imagef(bg_y, sampler, (int2)(id_x, id_y + 1)); + uv = read_imagef(bg_uv, sampler, (int2)(id_x, id_y / 2)); + + rgba[0] = read_imagef(fg, sampler, (int2)(2 * id_z, id_w)); + rgba[1] = read_imagef(fg, sampler, (int2)(2 * id_z + 1, id_w)); + rgba[2] = read_imagef(fg, sampler, (int2)(2 * id_z , id_w + 1)); + rgba[3] = read_imagef(fg, sampler, (int2)(2 * id_z + 1, id_w + 1)); + + y_dst = 0.299f * (float4) (rgba[0].x, rgba[1].x, rgba[2].x, rgba[3].x); + y_dst = mad(0.587f, (float4) (rgba[0].y, rgba[1].y, rgba[2].y, rgba[3].y), y_dst); + y_dst = mad(0.114f, (float4) (rgba[0].z, rgba[1].z, rgba[2].z, rgba[3].z), y_dst); + y_dst *= (float4) (rgba[0].w, rgba[1].w, rgba[2].w, rgba[3].w); + y1_dst.x = mad(1 - rgba[0].w, y1.x, y_dst.x); + y1_dst.y = mad(1 - rgba[1].w, y1.y, y_dst.y); + y2_dst.x = mad(1 - rgba[2].w, y2.x, y_dst.z); + y2_dst.y = mad(1 - rgba[3].w, y2.y, y_dst.w); + + uv_dst.x = rgba[0].w * (-0.14713f * rgba[0].x - 0.28886f * rgba[0].y + 0.43600f * rgba[0].z + 0.5f); + uv_dst.y = rgba[0].w * ( 0.61500f * rgba[0].x - 0.51499f * rgba[0].y - 0.10001f * rgba[0].z + 0.5f); + uv_dst.x = mad(1 - rgba[0].w, uv.x, uv_dst.x); + uv_dst.y = mad(1 - rgba[0].w, uv.y, uv_dst.y); + + if (id_z <= crop_w && id_w <= crop_h) { + write_imagef(dst_y, (int2)(id_x, id_y), y1_dst); + write_imagef(dst_y, (int2)(id_x, id_y + 1), y2_dst); + write_imagef(dst_uv, (int2)(id_x, id_y / 2), uv_dst); + } +} diff --git a/ocl/kernels/mosaic.cl b/ocl/kernels/mosaic.cl new file mode 100644 index 0000000..b3f59bb --- /dev/null +++ b/ocl/kernels/mosaic.cl @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +__kernel void mosaic(__write_only image2d_t img_y_dst, + __read_only image2d_t img_y, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_uv, + uint crop_x, + uint crop_y, + uint crop_w, + uint crop_h, + uint blk_size, + __local float* sum) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + size_t l_id_x = get_local_id(0); + uint imax; + + float4 Y; + sum[l_id_x] = 0; + for (uint i = 0; i < blk_size; i++) { + Y = read_imagef(img_y, (int2)(g_id_x + crop_x, g_id_y * blk_size + i + crop_y)); + sum[l_id_x] += Y.x; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (l_id_x % blk_size == 0) { + for (uint i = 1; i < blk_size; i++) { + sum[l_id_x] += sum[l_id_x + i]; + } + sum[l_id_x] /= (blk_size * blk_size); + } + barrier(CLK_LOCAL_MEM_FENCE); + Y.x = sum[l_id_x / blk_size * blk_size]; + imax = min(blk_size, crop_h - g_id_y * blk_size); + if (g_id_x < crop_w) { + for (uint i = 0; i < imax; i++) { + write_imagef(img_y_dst, (int2)(g_id_x + crop_x, g_id_y * blk_size + i + crop_y), Y); + } + } + + float4 UV; + sum[l_id_x] = 0; + for (uint i = 0; i < blk_size / 2; i++) { + UV = read_imagef(img_uv, (int2)(g_id_x + crop_x, g_id_y * blk_size / 2 + i + crop_y / 2)); + sum[l_id_x] += UV.x; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (l_id_x % blk_size == 0 || l_id_x % blk_size == 1) { + for (uint i = 2; i < blk_size; i+=2) { + sum[l_id_x] += sum[l_id_x + i]; + } + sum[l_id_x] /= (blk_size * blk_size / 4); + } + barrier(CLK_LOCAL_MEM_FENCE); + if (l_id_x % 2 == 0) { + UV.x = sum[l_id_x / blk_size * blk_size]; + } else { + UV.x = sum[l_id_x / blk_size * blk_size + 1]; + } + imax /= 2; + if (g_id_x < crop_w) { + for (uint i = 0; i < blk_size / 2; i++) { + write_imagef(img_uv_dst, (int2)(g_id_x + crop_x, g_id_y * blk_size / 2 + i + crop_y / 2), UV); + } + } +} diff --git a/ocl/kernels/osd.cl b/ocl/kernels/osd.cl new file mode 100644 index 0000000..1e96651 --- /dev/null +++ b/ocl/kernels/osd.cl @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define PIXEL_SIZE 2 +#define CELL_WIDTH 2 +#define CELL_HEIGHT 2 + +__kernel void reduce_luma(__read_only image2d_t img_y, + int crop_x, + int crop_y, + int crop_h, + __global uint* acc) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; + size_t g_id = crop_x + get_global_id(0); + uint4 Y = (uint4)(0, 0, 0, 0); + + int i; + for (i = 0; i < crop_h; i++) { + Y += read_imageui(img_y, sampler, (int2)(g_id, crop_y + i)); + } + + *((__global uint4 *)acc + get_global_id(0)) = Y; +} + +__kernel void osd(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y, + __read_only image2d_t img_uv, + __read_only image2d_t img_a, + int crop_x, + int crop_y, + int crop_w, + int crop_h, + __constant float* luma) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + size_t l_id_x = get_local_id(0); + size_t l_id_y = get_local_id(1); + + float4 Y0, Y1; + float4 UV; + float4 rgba, alpha0, alpha1; + + float bw = luma[g_id_x * PIXEL_SIZE / crop_h]; + + int id_x = g_id_x * CELL_WIDTH; + int id_y = g_id_y * CELL_HEIGHT; + rgba = read_imagef(img_a, sampler, (int2)(id_x, id_y)); + alpha0.x = rgba.w; + rgba = read_imagef(img_a, sampler, (int2)(id_x + 1, id_y)); + alpha0.y = rgba.w; + rgba = read_imagef(img_a, sampler, (int2)(id_x, id_y + 1)); + alpha1.x = rgba.w; + rgba = read_imagef(img_a, sampler, (int2)(id_x + 1, id_y + 1)); + alpha1.y = rgba.w; + + id_x = g_id_x + crop_x; + id_y = g_id_y * CELL_HEIGHT + crop_y; + Y0 = read_imagef(img_y_dst, sampler, (int2)(id_x, id_y)); + Y1 = read_imagef(img_y_dst, sampler, (int2)(id_x, id_y + 1)); + UV = read_imagef(img_uv_dst, sampler, (int2)(id_x, id_y / 2)); + + // blend BW (1.0/0.0, 0.5, 0.5) + Y0 = alpha0 * bw + (1 - alpha0) * Y0; + Y1 = alpha1 * bw + (1 - alpha1) * Y1; + UV = alpha0 * 0.5f + (1 - alpha0) * UV; + + write_imagef(img_y_dst, (int2)(id_x, id_y), Y0); + write_imagef(img_y_dst, (int2)(id_x, id_y + 1), Y1); + write_imagef(img_uv_dst, (int2)(id_x, id_y / 2), UV); +} diff --git a/ocl/kernels/transform.cl b/ocl/kernels/transform.cl new file mode 100644 index 0000000..61f5f40 --- /dev/null +++ b/ocl/kernels/transform.cl @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +__kernel void transform_flip_h(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src, dst; + + int coord_y = 2 * g_id_y; + src = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + dst = (float4)(src.w, src.z, src.y, src.x); + write_imagef(img_y_dst, (int2)(w - g_id_x, coord_y), dst); + + src = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src.w, src.z, src.y, src.x); + write_imagef(img_y_dst, (int2)(w - g_id_x, coord_y + 1), dst); + + src = read_imagef(img_uv_src, sampler, (int2)(g_id_x, g_id_y)); + dst = (float4)(src.z, src.w, src.x, src.y); + write_imagef(img_uv_dst, (int2)(w - g_id_x, g_id_y), dst); +} + +__kernel void transform_flip_v(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 data; + + int coord_y = 2 * g_id_y; + data = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + write_imagef(img_y_dst, (int2)(g_id_x, h - 1 - coord_y), data); + data = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + write_imagef(img_y_dst, (int2)(g_id_x, h - 1 - coord_y - 1), data); + + data = read_imagef(img_uv_src, sampler, (int2)(g_id_x, g_id_y)); + write_imagef(img_uv_dst, (int2)(g_id_x, h / 2 - g_id_y), data); +} + +__kernel void transform_rot_180(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src, dst; + + int coord_y = 2 * g_id_y; + src = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + dst = (float4)(src.w, src.z, src.y, src.x); + write_imagef(img_y_dst, (int2)(w - g_id_x, h - 1 - coord_y), dst); + + src = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src.w, src.z, src.y, src.x); + write_imagef(img_y_dst, (int2)(w - g_id_x, h - 1 - coord_y - 1), dst); + + src = read_imagef(img_uv_src, sampler, (int2)(g_id_x, g_id_y)); + dst = (float4)(src.z, src.w, src.x, src.y); + write_imagef(img_uv_dst, (int2)(w - g_id_x, h / 2 - g_id_y), dst); +} + +__kernel void transform_rot_90(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src0, src1, src2, src3, dst; + + int coord_x = 4 * g_id_x; + int coord_y = 4 * g_id_y; + src0 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + src2 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 2)); + src3 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 3)); + dst = (float4)(src3.x, src2.x, src1.x, src0.x); + write_imagef(img_y_dst, (int2)(h - g_id_y, coord_x), dst); + dst = (float4)(src3.y, src2.y, src1.y, src0.y); + write_imagef(img_y_dst, (int2)(h - g_id_y, coord_x + 1), dst); + dst = (float4)(src3.z, src2.z, src1.z, src0.z); + write_imagef(img_y_dst, (int2)(h - g_id_y, coord_x + 2), dst); + dst = (float4)(src3.w, src2.w, src1.w, src0.w); + write_imagef(img_y_dst, (int2)(h - g_id_y, coord_x + 3), dst); + + coord_x = 2 * g_id_x; + coord_y = 2 * g_id_y; + src0 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src1.x, src1.y, src0.x, src0.y); + write_imagef(img_uv_dst, (int2)(h - g_id_y, coord_x), dst); + dst = (float4)(src1.z, src1.w, src0.z, src0.w); + write_imagef(img_uv_dst, (int2)(h - g_id_y, coord_x + 1), dst); +} + +__kernel void transform_rot_270(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src0, src1, src2, src3, dst; + + int coord_x = 4 * g_id_x; + int coord_y = 4 * g_id_y; + src0 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + src2 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 2)); + src3 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 3)); + dst = (float4)(src0.w, src1.w, src2.w, src3.w); + write_imagef(img_y_dst, (int2)(g_id_y, w * 4 - coord_x), dst); + dst = (float4)(src0.z, src1.z, src2.z, src3.z); + write_imagef(img_y_dst, (int2)(g_id_y, w * 4 - coord_x + 1), dst); + dst = (float4)(src0.y, src1.y, src2.y, src3.y); + write_imagef(img_y_dst, (int2)(g_id_y, w * 4 - coord_x + 2), dst); + dst = (float4)(src0.x, src1.x, src2.x, src3.x); + write_imagef(img_y_dst, (int2)(g_id_y, w * 4 - coord_x + 3), dst); + + coord_x = 2 * g_id_x; + coord_y = 2 * g_id_y; + src0 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src0.z, src0.w, src1.z, src1.w); + write_imagef(img_uv_dst, (int2)(g_id_y, w * 2 - coord_x), dst); + dst = (float4)(src0.x, src0.y, src1.x, src1.y); + write_imagef(img_uv_dst, (int2)(g_id_y, w * 2 - coord_x + 1), dst); +} + +__kernel void transform_flip_h_rot_90(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src0, src1, src2, src3, dst; + + int coord_x = 4 * g_id_x; + int coord_y = 4 * g_id_y; + src0 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + src2 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 2)); + src3 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 3)); + dst = (float4)(src3.w, src2.w, src1.w, src0.w); + write_imagef(img_y_dst, (int2)(h - g_id_y, w * 4 - coord_x), dst); + dst = (float4)(src3.z, src2.z, src1.z, src0.z); + write_imagef(img_y_dst, (int2)(h - g_id_y, w * 4 - coord_x + 1), dst); + dst = (float4)(src3.y, src2.y, src1.y, src0.y); + write_imagef(img_y_dst, (int2)(h - g_id_y, w * 4 - coord_x + 2), dst); + dst = (float4)(src3.x, src2.x, src1.x, src0.x); + write_imagef(img_y_dst, (int2)(h - g_id_y, w * 4 - coord_x + 3), dst); + + coord_x = 2 * g_id_x; + coord_y = 2 * g_id_y; + src0 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src1.z, src1.w, src0.z, src0.w); + write_imagef(img_uv_dst, (int2)(h - g_id_y, w * 2 - coord_x), dst); + dst = (float4)(src1.x, src1.y, src0.x, src0.y); + write_imagef(img_uv_dst, (int2)(h - g_id_y, w * 2 - coord_x + 1), dst); +} + +__kernel void transform_flip_v_rot_90(__write_only image2d_t img_y_dst, + __write_only image2d_t img_uv_dst, + __read_only image2d_t img_y_src, + __read_only image2d_t img_uv_src, + uint w, + uint h) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | + CLK_ADDRESS_CLAMP_TO_EDGE | + CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + float4 src0, src1, src2, src3, dst; + + int coord_x = 4 * g_id_x; + int coord_y = 4 * g_id_y; + src0 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 1)); + src2 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 2)); + src3 = read_imagef(img_y_src, sampler, (int2)(g_id_x, coord_y + 3)); + dst = (float4)(src0.x, src1.x, src2.x, src3.x); + write_imagef(img_y_dst, (int2)(g_id_y, coord_x), dst); + dst = (float4)(src0.y, src1.y, src2.y, src3.y); + write_imagef(img_y_dst, (int2)(g_id_y, coord_x + 1), dst); + dst = (float4)(src0.z, src1.z, src2.z, src3.z); + write_imagef(img_y_dst, (int2)(g_id_y, coord_x + 2), dst); + dst = (float4)(src0.w, src1.w, src2.w, src3.w); + write_imagef(img_y_dst, (int2)(g_id_y, coord_x + 3), dst); + + coord_x = 2 * g_id_x; + coord_y = 2 * g_id_y; + src0 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y)); + src1 = read_imagef(img_uv_src, sampler, (int2)(g_id_x, coord_y + 1)); + dst = (float4)(src0.x, src0.y, src1.x, src1.y); + write_imagef(img_uv_dst, (int2)(g_id_y, coord_x), dst); + dst = (float4)(src0.z, src0.w, src1.z, src1.w); + write_imagef(img_uv_dst, (int2)(g_id_y, coord_x + 1), dst); +} diff --git a/ocl/kernels/wireframe.cl b/ocl/kernels/wireframe.cl new file mode 100644 index 0000000..921536b --- /dev/null +++ b/ocl/kernels/wireframe.cl @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +__kernel void wireframe(__write_only image2d_t img_y, + __write_only image2d_t img_uv, + uint crop_x, + uint crop_y, + uint crop_w, + uint crop_h, + uint border, + uchar y, + uchar u, + uchar v) +{ + sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST; + size_t g_id_x = get_global_id(0); + size_t g_id_y = get_global_id(1); + uint4 Y = (uint4)y; + uint4 UV = (uint4)(u, v, 0, 0); + + if ((g_id_x < crop_w && g_id_y < border) + || ((g_id_x < border || (g_id_x + border >= crop_w && g_id_x < crop_w)) + && (g_id_y >= border && g_id_y + border < crop_h)) + || (g_id_x < crop_w && (g_id_y + border >= crop_h && g_id_y < crop_h))) { + write_imageui(img_y, (int2)(g_id_x + crop_x, 2 * (g_id_y + crop_y)), Y); + write_imageui(img_y, (int2)(g_id_x + crop_x, 2 * (g_id_y + crop_y) + 1), Y); + write_imageui(img_uv, (int2)(g_id_x + crop_x, g_id_y + crop_y), UV); + } +} diff --git a/ocl/oclcontext.cpp b/ocl/oclcontext.cpp new file mode 100644 index 0000000..32e1386 --- /dev/null +++ b/ocl/oclcontext.cpp @@ -0,0 +1,304 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "oclcontext.h" + +#include +#include +#include + +using namespace std; + +namespace YamiMediaCodec{ + +///internal class hold device id and make sure *.cl compile in serial +class OclDevice { + +public: + static SharedPtr getInstance(); + bool createKernel(cl_context context, const char* name, OclKernelMap& kernelMap); + bool releaseKernel(OclKernelMap& kernelMap); + YamiStatus createImageFromFdIntel(cl_context context, const cl_import_image_info_intel* info, cl_mem* mem); + YamiStatus createBufferFromFdIntel(cl_context context, const cl_import_buffer_info_intel* info, cl_mem* mem); + +private: + typedef cl_mem (*OclCreateImageFromFdIntel)(cl_context, const cl_import_image_info_intel*, cl_int*); + typedef cl_mem (*OclCreateBufferFromFdIntel)(cl_context, const cl_import_buffer_info_intel*, cl_int*); + + OclDevice(); + bool init(); + bool loadKernel_l(cl_context context, const char* name, OclKernelMap& kernelMap); + bool loadFile(const char* path, vector& dest); + void* getExtensionFunctionAddress(const char* name); + + static WeakPtr m_instance; + static Lock m_lock; + + //all operations need procted by m_lock + cl_platform_id m_platform; + cl_device_id m_device; + OclCreateImageFromFdIntel m_oclCreateImageFromFdIntel; + OclCreateBufferFromFdIntel m_oclCreateBufferFromFdIntel; + friend OclContext; + + DISALLOW_COPY_AND_ASSIGN(OclDevice) + +}; + +Lock OclDevice::m_lock; +WeakPtr OclDevice::m_instance; + +SharedPtr OclContext::create() +{ + SharedPtr context(new OclContext); + if (!context->init()) + context.reset(); + return context; +} + +OclContext::OclContext() + :m_context(0), m_queue(0) +{ +} + +OclContext::~OclContext() +{ + clReleaseCommandQueue(m_queue); + clReleaseContext(m_context); +} + +bool OclContext::init() +{ + SharedPtr device = OclDevice::getInstance(); + if (!device) + return false; + m_device= device; + cl_int status; + AutoLock lock(device->m_lock); + m_context = clCreateContext(NULL, 1, &m_device->m_device, NULL,NULL,&status); + if (!checkOclStatus(status, "clCreateContext")) + return false; + + m_queue = clCreateCommandQueue(m_context, m_device->m_device, 0, &status); + if (!checkOclStatus(status, "clCreateContext")) + return false; + + return true; +} + +bool OclContext::createKernel(const char* name, OclKernelMap& kernelMap) +{ + return m_device->createKernel(m_context, name, kernelMap); +} + +bool OclContext::releaseKernel(OclKernelMap& kernelMap) +{ + return m_device->releaseKernel(kernelMap); +} + +YamiStatus +OclContext::createImageFromFdIntel(const cl_import_image_info_intel* info, cl_mem* mem) +{ + return m_device->createImageFromFdIntel(m_context, info, mem); +} + +YamiStatus +OclContext::createBufferFromFdIntel(const cl_import_buffer_info_intel* info, cl_mem* mem) +{ + return m_device->createBufferFromFdIntel(m_context, info, mem); +} + +OclDevice::OclDevice() + : m_platform(0) + , m_device(0) + , m_oclCreateImageFromFdIntel(0) + , m_oclCreateBufferFromFdIntel(0) +{ +} + +SharedPtr OclDevice::getInstance() +{ + AutoLock lock(m_lock); + SharedPtr device = m_instance.lock(); + if (device) + return device; + device.reset(new OclDevice); + if (!device->init()) { + device.reset(); + } + return device; +} + +bool OclDevice::init() +{ + cl_int status; + status = clGetPlatformIDs(1, &m_platform, NULL); + if (!checkOclStatus(status, "clGetPlatformIDs")) + return false; + + status = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_GPU, 1, &m_device, NULL); + if (!checkOclStatus(status, "clGetDeviceIDs")) + return false; + + m_oclCreateImageFromFdIntel = (OclCreateImageFromFdIntel) + getExtensionFunctionAddress("clCreateImageFromFdINTEL"); + m_oclCreateBufferFromFdIntel = (OclCreateBufferFromFdIntel) + getExtensionFunctionAddress("clCreateBufferFromFdINTEL"); + if (!m_oclCreateImageFromFdIntel || !m_oclCreateBufferFromFdIntel) { + ERROR("failed to get extension function"); + return false; + } + return true; +} + +void* OclDevice::getExtensionFunctionAddress(const char* name) +{ +#ifdef CL_VERSION_1_2 + return clGetExtensionFunctionAddressForPlatform(m_platform, name); +#else + return clGetExtensionFunctionAddress(name); +#endif +} + +bool OclDevice::loadFile(const char* path, vector& dest) +{ + FILE* fp = fopen(path, "rb"); + if (!fp) + return false; + fseek(fp,0L,SEEK_END); + size_t len = ftell(fp); + if (len > 0) { + dest.resize(len + 1); + fseek(fp,0L,SEEK_SET); + if (len == fread(&dest[0], 1, len, fp)) { + dest.back() = '\0'; + } else { + dest.clear(); + } + } + fclose(fp); + return !dest.empty(); +} + +bool OclDevice::loadKernel_l(cl_context context, const char* name, OclKernelMap& kernelMap) +{ + bool ret = true; + string path = KERNEL_DIR; + path += name; + path += ".cl"; + + vector text; + if (!loadFile(path.c_str(), text)) { + ERROR("Can't open %s", path.c_str()); + return false; + } + cl_int status; + const char* source = &text[0]; + cl_program prog = clCreateProgramWithSource(context, 1, &source, NULL, &status); + if (!checkOclStatus(status, "clCreateProgramWithSource")) + return false; + status = clBuildProgram(prog, 1, &m_device, NULL, NULL, NULL); + if (!(ret = checkOclStatus(status, "clBuildProgram"))) { + char log[1024]; + status = clGetProgramBuildInfo(prog, m_device, CL_PROGRAM_BUILD_LOG, sizeof(log), log, NULL); + if (checkOclStatus(status, "clCreateProgramWithSource")) { + //make sure null terminate + log[sizeof(log) - 1] = '\0'; + ERROR("build cl kernel failed: %s", log); + } + } else { + size_t n, num = 0; + char name[128]; + vector kernels; + status = clGetProgramInfo(prog, CL_PROGRAM_NUM_KERNELS, sizeof(num), &num, NULL); + if (!checkOclStatus(status, "clGetProgramInfo")) { + ret = false; + goto err; + } + kernels.resize(num); + status = clCreateKernelsInProgram(prog, num, kernels.data(), NULL); + if (!checkOclStatus(status, "clCreateKernelsInProgram")) { + ret = false; + goto err; + } + for (n = 0; n < num; n++) { + status = clGetKernelInfo(kernels[n], CL_KERNEL_FUNCTION_NAME, sizeof(name), name, NULL); + if (!checkOclStatus(status, "clGetKernelInfo")) { + ret = false; + goto err; + } + kernelMap[name] = kernels[n]; + } + } +err: + clReleaseProgram(prog); + return ret; +} + +bool OclDevice::createKernel(cl_context context, const char* name, OclKernelMap& kernelMap) +{ + AutoLock lock(m_lock); + return loadKernel_l(context, name, kernelMap); +} + +bool OclDevice::releaseKernel(OclKernelMap& kernelMap) +{ + AutoLock lock(m_lock); + bool ret = true; + OclKernelMap::iterator it = kernelMap.begin(); + while (it != kernelMap.end()) { + checkOclStatus(clReleaseKernel(it->second), "ReleaseKernel"); + ++it; + } + return ret; +} + +YamiStatus OclDevice::createImageFromFdIntel(cl_context context, const cl_import_image_info_intel* info, cl_mem* mem) +{ + cl_int status; + *mem = m_oclCreateImageFromFdIntel(context, info, &status); + if (checkOclStatus(status, "clCreateImageFromFdINTEL")) { + return YAMI_SUCCESS; + } + return YAMI_FAIL; +} + +YamiStatus OclDevice::createBufferFromFdIntel(cl_context context, const cl_import_buffer_info_intel* info, cl_mem* mem) +{ + cl_int status; + *mem = m_oclCreateBufferFromFdIntel(context, info, &status); + if (checkOclStatus(status, "clCreateBufferFromFdINTEL")) { + return YAMI_SUCCESS; + } + return YAMI_FAIL; +} + +bool checkOclStatus(cl_int status, const char* msg) +{ + /* todo add more description error here*/ + if (status != CL_SUCCESS) { + ERROR("%s: failed, status = %d", msg, status); + return false; + } + return true; +} + +} diff --git a/ocl/oclcontext.h b/ocl/oclcontext.h new file mode 100644 index 0000000..8747862 --- /dev/null +++ b/ocl/oclcontext.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef oclcontext_h +#define oclcontext_h + + +#include "VideoCommonDefs.h" +#include "common/lock.h" +#include +#include +#include +#include + +namespace YamiMediaCodec{ + +class OclDevice; + +typedef std::map OclKernelMap; + +class OclContext +{ +public: + static SharedPtr create(); + bool createKernel(const char* name, OclKernelMap& kernelMap); + bool releaseKernel(OclKernelMap& kernelMap); + YamiStatus createImageFromFdIntel(const cl_import_image_info_intel* info, cl_mem* mem); + YamiStatus createBufferFromFdIntel(const cl_import_buffer_info_intel* info, cl_mem* mem); + ~OclContext(); + + cl_context m_context; + cl_command_queue m_queue; +private: + OclContext(); + bool init(); + SharedPtr m_device; + DISALLOW_COPY_AND_ASSIGN(OclContext) +}; + +bool checkOclStatus(cl_int status, const char* err); + +} + +#endif //oclcontext_h diff --git a/pre-commit b/pre-commit new file mode 100755 index 0000000..e787f8f --- /dev/null +++ b/pre-commit @@ -0,0 +1,31 @@ +## strip trailing whitespace +for file in `git diff --check --cached | grep '^[^+-]' | grep -o '^.*[0-9]\+:'` ; do + file_name=`echo ${file} | grep -o '^[^:]\+'` + line_number=`echo ${file} | grep -oP '(?<=:)[0-9]+(?=:)'` + # I think the reason there are two sed commands here + # is that 'sed -i' is different on different systems. + # shoot me. + (sed -i "${line_number}s/\s*$//" "${file_name}" > /dev/null 2>&1 \ + || sed -i '' -E "${line_number}s/\s*$//" "${file_name}") + git add ${file_name} + echo "Re-wrote ${file_name} to trim whitespace." +done + +## remove 'x' bit and apply kr style for source file +for file in `git diff --cached --name-only`; do + filename=$(basename "$file") + extension="${filename##*.}" + dir_name=$(dirname "$file") + if test "$extension" = "h" || test "$extension" = "c" || test "$extension" = "cpp"; then + # remove the 'x' bit for files + echo "remove 'x' for ${file}" + chmod -x ${file} + fi +done + +echo "****************************************************" +echo "* applying coding style to the changed files, you can:" +echo "* a) [check ] it by 'git diff'" +echo "* b) [accept] it by 'git commit -a --amend'" +echo "* c) [reject] it by 'git reset --hard'" +echo "****************************************************" diff --git a/v4l2/Android.mk b/v4l2/Android.mk new file mode 100644 index 0000000..7315a2c --- /dev/null +++ b/v4l2/Android.mk @@ -0,0 +1,37 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + v4l2_codecbase.cpp \ + v4l2_decode.cpp \ + v4l2_encode.cpp \ + v4l2_wrapper.cpp + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva \ + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libc++ \ + libva \ + libhardware \ + libva-android + +LOCAL_WHOLE_STATIC_LIBRARIES := \ + libyami_common \ + libcodecparser \ + libyami_vaapi \ + libyami_vpp \ + libyami_decoder \ + libyami_encoder + +ifeq ($(ENABLE-V4L2-OPS),true) +LOCAL_CFLAGS += -D__ENABLE_V4L2_OPS__ +endif + +LOCAL_MODULE := libyami_v4l2 +include $(BUILD_SHARED_LIBRARY) diff --git a/v4l2/BufferPipe.h b/v4l2/BufferPipe.h new file mode 100644 index 0000000..d181ee1 --- /dev/null +++ b/v4l2/BufferPipe.h @@ -0,0 +1,96 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BufferPipe_h +#define BufferPipe_h + +#include "common/lock.h" +#include + +namespace YamiMediaCodec { + +template +class BufferPipe { + typedef T ValueType; + +public: + //queue to incoming + void queue(const ValueType& v) + { + queue(m_incoming, v); + } + + //deque from outgoing + bool deque(ValueType& v) + { + return peek(m_outgoing, v, true); + } + + //queue to outgoing + void put(const ValueType& v) + { + queue(m_outgoing, v); + } + + //deque from incoming + bool get(ValueType& v) + { + return peek(m_incoming, v, true); + } + + //peek from incoming + bool peek(ValueType& v) + { + return peek(m_incoming, v); + } + + //clear incoming and outgoing + void clearPipe() + { + clearQueue(m_incoming); + clearQueue(m_outgoing); + } + +private: + struct BufferQue { + std::deque m_queue; + Lock m_lock; + }; + BufferQue m_incoming; + BufferQue m_outgoing; + static void queue(BufferQue& q, const ValueType& v) + { + AutoLock l(q.m_lock); + q.m_queue.push_back(v); + } + static bool peek(BufferQue& q, ValueType& v, bool pop = false) + { + AutoLock l(q.m_lock); + if (q.m_queue.empty()) + return false; + v = q.m_queue.front(); + if (pop) + q.m_queue.pop_front(); + return true; + } + static void clearQueue(BufferQue& q) + { + AutoLock l(q.m_lock); + q.m_queue.clear(); + } +}; +} + +#endif //BufferPipe_h diff --git a/v4l2/Makefile.am b/v4l2/Makefile.am new file mode 100644 index 0000000..091ad11 --- /dev/null +++ b/v4l2/Makefile.am @@ -0,0 +1,68 @@ +libyamiv4l2_source_c = \ + v4l2_codecbase.cpp \ + v4l2_decode.cpp \ + v4l2_encode.cpp \ + v4l2_wrapper.cpp \ + $(NULL) + +if ENABLE_EGL +libyamiv4l2_source_c += ../egl/egl_util.c ../egl/egl_vaapi_image.cpp +endif + +libyamiv4l2_source_h = \ + ../interface/v4l2_wrapper.h \ + ../interface/v4l2codec_device_ops.h \ + $(NULL) + +libyamiv4l2_source_h_priv = \ + v4l2_codecbase.h \ + v4l2_encode.h \ + v4l2_decode.h \ + $(NULL) + +libyamiv4l2_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + -pthread \ + $(NULL) + +if ENABLE_EGL +libyamiv4l2_ldflags += $(LIBEGL_LIBS) +endif + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyamiv4l2_cppflags = \ + $(LIBVA_CFLAGS) \ + $(LIBV4L2_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +if ENABLE_EGL +libyamiv4l2_cppflags += $(LIBEGL_CFLAGS) +endif + +if ENABLE_DMABUF +libyamiv4l2_cppflags += $(LIBDRM_CFLAGS) +endif + + +noinst_LTLIBRARIES = libyamiv4l2.la +libyamiv4l2includedir = $(includedir)/libyami +libyamiv4l2include_HEADERS = $(libyamiv4l2_source_h) +noinst_HEADERS = $(libyamiv4l2_source_h_priv) +libyamiv4l2_la_SOURCES = $(libyamiv4l2_source_c) +libyamiv4l2_la_LDFLAGS = $(libyamiv4l2_ldflags) $(AM_LDFLAGS) +libyamiv4l2_la_CPPFLAGS = $(libyamiv4l2_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +-include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in + + diff --git a/v4l2/v4l2_codecbase.cpp b/v4l2/v4l2_codecbase.cpp new file mode 100644 index 0000000..46f75df --- /dev/null +++ b/v4l2/v4l2_codecbase.cpp @@ -0,0 +1,654 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "v4l2_encode.h" +#include "v4l2_decode.h" +#include "common/log.h" +#include "common/common_def.h" +#include "vaapi/vaapidisplay.h" +#include +#if defined(__ENABLE_WAYLAND__) +#include +#endif + +typedef SharedPtr < V4l2CodecBase > V4l2CodecPtr; +#define THREAD_NAME(thread) (thread == INPUT ? "V4L2-INPUT" : "V4L2-OUTPUT") + +#define DEBUG_FRAME_LIST(list, listType, maxSize) do { \ + std::listType::iterator it = list.begin(); \ + char buf[256]; \ + int i=0; \ + \ + buf[0] = '\0'; \ + while (it != list.end()) { \ + sprintf(&buf[i], "<%02d>", *it++); \ + i += 4; \ + } \ + DEBUG("%s size=%d, elements: %s", \ + #list, static_cast(list.size()), buf); \ + ASSERT(list.size() <= maxSize); \ +} while (0) + + V4l2CodecPtr V4l2CodecBase::createCodec(const char* name, int32_t flags) +{ + V4l2CodecPtr codec; + if (!strcmp(name, "encoder")) + codec.reset(new V4l2Encoder()); + else if (!strcmp(name, "decoder")) + codec.reset(new V4l2Decoder()); + + ASSERT(codec); + codec->open(name, flags); + + return codec; +} +V4l2CodecBase::V4l2CodecBase() + : m_memoryType(VIDEO_DATA_MEMORY_TYPE_RAW_COPY) + , m_started(false) + , m_svct(false) + , m_isThumbnailMode(false) + , m_hasEvent(false) + , m_inputThreadCond(m_frameLock[INPUT]) + , m_outputThreadCond(m_frameLock[OUTPUT]) + , m_eosState(EosStateNormal) +{ + m_maxBufferCount[INPUT] = 0; + m_maxBufferCount[OUTPUT] = 0; + m_bufferPlaneCount[INPUT] = 0; + m_bufferPlaneCount[OUTPUT] = 0; + m_memoryMode[INPUT] = 0; + m_memoryMode[OUTPUT] = 0; + m_pixelFormat[INPUT] = 0; + m_pixelFormat[OUTPUT] = 0; + m_streamOn[INPUT] = false; + m_streamOn[OUTPUT] = false; + m_threadOn[INPUT] = false; + m_threadOn[OUTPUT] = false; + m_threadCond[INPUT] = &m_inputThreadCond; + m_threadCond[OUTPUT] = &m_outputThreadCond; + + m_reqBufState[INPUT] = RBS_Normal; + m_reqBufState[OUTPUT] = RBS_Normal; + + m_fd[0] = -1; + m_fd[1] = -1; +#ifdef __ENABLE_DEBUG__ + m_frameCount[INPUT] = 0; + m_frameCount[OUTPUT] = 0; +#endif + + memset(&m_nativeDisplay, 0, sizeof(m_nativeDisplay)); +} + +V4l2CodecBase::~V4l2CodecBase() +{ + ASSERT(!m_streamOn[INPUT]); + ASSERT(!m_streamOn[OUTPUT]); + ASSERT(!m_threadOn[INPUT]); + ASSERT(!m_threadOn[OUTPUT]); + + INFO("codec is released, m_fd[0]: %d", m_fd[0]); +} + +void V4l2CodecBase::setEosState(EosState eosState) +{ + AutoLock locker(m_codecLock); + m_eosState = eosState; +} + +bool V4l2CodecBase::open(const char* name, int32_t flags) +{ + m_fd[0] = eventfd(0, EFD_SEMAPHORE | EFD_CLOEXEC); // event for codec library, block on read(), one event per read() + m_fd[1] = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); // for interrupt (escape from poll) + return true; +} + +bool V4l2CodecBase::close() +{ + bool ret = true; + int timeOut = 10; + + INFO("m_streamOn[INPUT]: %d, m_streamOn[OUTPUT]: %d, m_threadOn[INPUT]: %d, m_threadOn[OUTPUT]: %d", + m_streamOn[INPUT], m_streamOn[OUTPUT], m_threadOn[INPUT], m_threadOn[OUTPUT]); + // wait until input/output thread terminate + while ((m_threadOn[INPUT] || m_threadOn[OUTPUT]) && timeOut) { + usleep(10000); + timeOut--; + } + + for (uint32_t i=0; isignal(); + } + // wait until i/o thead has released the buffer queue + while (m_reqBufState[thread] == RBS_Acknowledge) { + m_threadCond[thread]->wait(); + } + } + { + AutoLock locker(m_frameLock[thread]); + if (m_framesTodo[thread].empty()) { + DEBUG("%s thread wait because m_framesTodo is empty", THREAD_NAME(thread)); + m_threadCond[thread]->wait(); // wait if no todo frame is available + continue; + } + index = (uint32_t)(m_framesTodo[thread].front()); + } + + + // for decode, outputPulse may update index + ret = (thread == INPUT) ? inputPulse(index) : outputPulse(index); + + { + AutoLock locker(m_frameLock[thread]); + // wait until EOS is processed on OUTPUT port + if (thread == INPUT && m_eosState == EosStateInput) { + m_threadCond[!thread]->signal(); + while (m_eosState == EosStateInput) { + m_threadCond[thread]->wait(); + } + DEBUG("flush-debug flush done, INPUT thread continue"); + setEosState(EosStateNormal); + } + + if (ret) { + if (thread == OUTPUT) { + // decoder output is in random order + // encoder output is FIFO for now since we does additional copy in v4l2_encode; it can be random order if we use a pool for coded buffer. + std::list::iterator itList = std::find(m_framesTodo[OUTPUT].begin(), m_framesTodo[OUTPUT].end(), index); + ASSERT(itList != m_framesTodo[OUTPUT].end()); + m_framesTodo[OUTPUT].erase(itList); + } else + m_framesTodo[thread].pop_front(); + + m_framesDone[thread].push_back(index); + setDeviceEvent(0); + #ifdef __ENABLE_DEBUG__ + m_frameCount[thread]++; + DEBUG("m_frameCount[%s]: %d", THREAD_NAME(thread), m_frameCount[thread]); + #endif + DEBUG("%s thread wake up %s thread after process one frame", THREAD_NAME(thread), THREAD_NAME(!thread)); + m_threadCond[!thread]->signal(); // encode/getOutput one frame success, wakeup the other thread + } else { + if (thread == OUTPUT && m_eosState == EosStateOutput) { + m_threadCond[!thread]->signal(); + DEBUG("flush-debug, wakeup INPUT thread out of EOS waiting"); + } + DEBUG("%s thread wait because operation on yami fails", THREAD_NAME(thread)); + m_threadCond[thread]->wait(); // wait if encode/getOutput fail (encode hw is busy or no available output) + } + }//protected by mLock + DEBUG("fd: %d", m_fd[0]); + } + + // VDA flush goes here, clear frames + { + AutoLock locker(m_frameLock[thread]); + m_framesTodo[thread].clear(); + m_framesDone[thread].clear(); + if (thread == INPUT) { + flush(); + } + DEBUG("%s worker thread exit", THREAD_NAME(thread)); + } + + m_threadOn[thread] = false; +} + +static void* _workerThread(void *arg) +{ + V4l2CodecBase *v4l2Codec = static_cast(arg); + pthread_detach(pthread_self()); + v4l2Codec->workerThread(); + return NULL; +} + +#if defined(__ENABLE_DEBUG__) +const char* V4l2CodecBase::IoctlCommandString(int command) +{ + static const char* unknown = "Unkonwn command"; +#define IOCTL_COMMAND_STRING_MAP(cmd) {cmd, #cmd} + static struct IoctlCommanMap{ + long unsigned int command; + const char* cmdStr; + } ioctlCommandMap[] = { + IOCTL_COMMAND_STRING_MAP(VIDIOC_QUERYCAP), + IOCTL_COMMAND_STRING_MAP(VIDIOC_STREAMON), + IOCTL_COMMAND_STRING_MAP(VIDIOC_STREAMOFF), + IOCTL_COMMAND_STRING_MAP(VIDIOC_QUERYBUF), + IOCTL_COMMAND_STRING_MAP(VIDIOC_REQBUFS), + IOCTL_COMMAND_STRING_MAP(VIDIOC_QBUF), + IOCTL_COMMAND_STRING_MAP(VIDIOC_DQBUF), + IOCTL_COMMAND_STRING_MAP(VIDIOC_S_EXT_CTRLS), + IOCTL_COMMAND_STRING_MAP(VIDIOC_S_PARM), + IOCTL_COMMAND_STRING_MAP(VIDIOC_S_FMT), + IOCTL_COMMAND_STRING_MAP(VIDIOC_S_CROP), + IOCTL_COMMAND_STRING_MAP(VIDIOC_SUBSCRIBE_EVENT), + IOCTL_COMMAND_STRING_MAP(VIDIOC_DQEVENT), + IOCTL_COMMAND_STRING_MAP(VIDIOC_G_FMT), + IOCTL_COMMAND_STRING_MAP(VIDIOC_G_CTRL) + }; + + // int --> long unsigned is different from int-->uint-->long unsigned + unsigned int u_cmd = (unsigned int)command; + long unsigned int lu_cmd = (long unsigned int) u_cmd; + size_t i; + for (i=0; i(arg); + caps->capabilities = V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING; + } + break; + case VIDIOC_STREAMON: { + // ::Enqueue + __u32 type = * ((__u32*)arg); + GET_PORT_INDEX(port, type, ret); + ASSERT(ret != -1); + if (port == INPUT) { + DEBUG("start decoding/encoding"); + boolRet = start(); + ASSERT(boolRet); + + DEBUG("INPUT port got STREAMON, escape from flushing state"); + releaseCodecLock(true); + } + + m_streamOn[port] = true; + if (pthread_create(&m_worker[port], NULL, _workerThread, this) != 0) { + ret = -1; + ERROR("fail to create input worker thread"); + } + } + break; + case VIDIOC_STREAMOFF: { + // ::StopDevicePoll + __u32 type = * ((__u32*)arg); + GET_PORT_INDEX(port, type, ret); + ASSERT(ret != -1); + m_streamOn[port] = false; + + // wait until the worker thread exit, some cleanup happend there + while (m_threadOn[port]) { + if (port == INPUT) { + DEBUG("INPUT port got STREAMOFF, release internal lock"); + setEosState(EosStateNormal); + releaseCodecLock(false); + } + DEBUG("%s port got STREAMOFF, wait until the worker thread exit/cleanup", THREAD_NAME(port)); + m_threadCond[port]->broadcast(); + usleep(5000); + } + } + break; + case VIDIOC_REQBUFS: { + struct v4l2_requestbuffers *reqbufs = static_cast(arg); + if (reqbufs->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + port = INPUT; + } else if (reqbufs->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + port = OUTPUT; + } else { + ret = -1; + ERROR("unknown request buffer type: %d", reqbufs->type); + break; + } + // ASSERT(port == INPUT || reqbufs->memory == m_memoryMode[port]); + m_memoryMode[port] = reqbufs->memory; + { + AutoLock locker(m_frameLock[port]); + + // initial status of buffers are at client side + if (reqbufs->count > 0) { + // ::CreateInputBuffers()/CreateOutputBuffers() + ASSERT(reqbufs->count <= m_maxBufferCount[port]); + reqbufs->count = m_maxBufferCount[port]; + } else { + // ::DestroyInputBuffers()/:DestroyOutputBuffers() + + } + + m_framesDone[port].clear(); //it is safe to clear m_framesDone, but race condition for clearing m_framesTodo + if (m_framesTodo[port].empty()) + break; + + // info work thread that we want to release the buffer queue + m_reqBufState[port] = RBS_Request; + // in case work thread is locked by yami codec + releaseCodecLock(false); + + //try to wakeup workthread (workthread may not be active, after EOS for example) + m_threadCond[port]->signal(); + + // wait until work thread doesn't work on current buffer queue + while (m_reqBufState[port] != RBS_Acknowledge) { + m_threadCond[port]->wait(); + } + // bring yami codec back to normal + releaseCodecLock(true); + + DEBUG("m_framesTodo[%d].size %zu, m_framesDone[%d].size %zu\n", + port, m_framesTodo[port].size(), port, m_framesDone[port].size()); + m_framesTodo[port].clear(); + m_reqBufState[port] = (reqbufs->count > 0) ? RBS_FormatChanged : RBS_Released; + m_threadCond[port]->signal(); + } + } + break; + case VIDIOC_QBUF: { + struct v4l2_buffer *qbuf = static_cast(arg); + GET_PORT_INDEX(port, qbuf->type, ret); + ASSERT(ret != -1); + + // ::EnqueueInputRecord/EnqueueOutputRecord +#ifndef __ENABLE_WAYLAND__ + ASSERT(qbuf->memory == m_memoryMode[port]); + ASSERT (qbuf->length == m_bufferPlaneCount[port]); +#endif + if (port == INPUT) { + bool _ret = acceptInputBuffer(qbuf); + ASSERT(_ret); + } else { + bool _ret = recycleOutputBuffer(qbuf->index); + ASSERT(_ret); + } + + { + AutoLock locker(m_frameLock[port]); + if (m_reqBufState[port] == RBS_Normal || + m_reqBufState[port] == RBS_FormatChanged ){ + m_framesTodo[port].push_back(qbuf->index); + m_threadCond[port]->signal(); + } else { + ret = EAGAIN; + } + } + } + break; + case VIDIOC_DQBUF: { + // ::Dequeue + struct v4l2_buffer *dqbuf = static_cast(arg); + GET_PORT_INDEX(port, dqbuf->type, ret); + ASSERT(ret != -1); + ASSERT(dqbuf->memory == m_memoryMode[port]); + + DEBUG("m_framesDone[%d].size(): %zu, m_reqBufState[port]: %d", + port, m_framesDone[port].size(), m_reqBufState[port]); + { + AutoLock locker (m_frameLock[port]); + if (m_framesDone[port].empty() || + ((m_reqBufState[port] != RBS_Normal && + m_reqBufState[port] != RBS_FormatChanged))) { + ret = -1; + errno = EAGAIN; + break; + } + } + ASSERT(dqbuf->length == m_bufferPlaneCount[port]); + dqbuf->index = m_framesDone[port].front(); + ASSERT(dqbuf->index < m_maxBufferCount[port]); + + bool _ret = true; + if (port == OUTPUT) { + _ret = giveOutputBuffer(dqbuf); + } else { + _ret = recycleInputBuffer(dqbuf); + } + + ASSERT(_ret); + { + AutoLock locker (m_frameLock[port]); + m_framesDone[port].pop_front(); + DEBUG("%s port dqbuf->index: %d", THREAD_NAME(port), dqbuf->index); + } + } + break; + default: + ERROR("unknown command type"); + ret = -1; + break; + } + + return ret; +} + +int32_t V4l2CodecBase::setDeviceEvent(int index) +{ + uint64_t buf = 1; + int32_t ret = -1; + + ASSERT(index == 0 || index == 1); + if (index == 1) + DEBUG("SetDevicePollInterrupt to unblock pool from client"); + ret = write(m_fd[index], &buf, sizeof(buf)); + if (ret != sizeof(uint64_t)) { + ERROR ("device %s setDeviceEvent(): write() failed", index ? "interrupt" : "event"); + return -1; + } + + if (index == 1) + DEBUG("SetDevicePollInterrupt OK to unblock pool from client"); + return 0; +} + +int32_t V4l2CodecBase::clearDeviceEvent(int index) +{ + uint64_t buf; + int ret = -1; + + ASSERT(index == 0 || index == 1); + if (index == 1) + DEBUG("ClearDevicePollInterrupt to block pool from client except there is event"); + ret = read(m_fd[index], &buf, sizeof(buf)); + if (ret == -1) { + if (errno == EAGAIN) { + // No interrupt flag set, and we're reading nonblocking. Not an error. + return 0; + } else { + ERROR("device %s clearDeviceEvent(): read() failed", index ? "interrupt" : "event"); + return -1; + } + } + + return 0; +} + +int32_t V4l2CodecBase::poll(bool poll_device, bool* event_pending) +{ + struct pollfd pollfds[2]; + nfds_t nfds; + + pollfds[0].fd = m_fd[1]; + pollfds[0].events = POLLIN | POLLERR; + nfds = 1; + + if (poll_device) { + DEBUG("Poll(): adding device fd to poll() set"); + pollfds[nfds].fd = m_fd[0]; + pollfds[nfds].events = POLLIN | POLLERR; + nfds++; + } + + if (::poll(pollfds, nfds, -1) == -1) { + ERROR("poll() failed"); + return -1; + } + + { + YamiMediaCodec::AutoLock locker(m_codecLock); + *event_pending = m_hasEvent; + } + + // clear event + if (pollfds[1].revents & POLLIN) + clearDeviceEvent(0); + + return 0; +} + +bool V4l2CodecBase::hasCodecEvent() +{ + YamiMediaCodec::AutoLock locker(m_codecLock); + return m_hasEvent; +} + +void V4l2CodecBase::setCodecEvent() +{ + { + YamiMediaCodec::AutoLock locker(m_codecLock); + m_hasEvent = true; + } + //notify user about this + setDeviceEvent(0); +} + +void V4l2CodecBase::clearCodecEvent() +{ + YamiMediaCodec::AutoLock locker(m_codecLock); + m_hasEvent = false; +} + +struct FormatEntry { + uint32_t format; + const char* mime; +}; + +static const FormatEntry FormatEntrys[] = { + {V4L2_PIX_FMT_H264, YAMI_MIME_H264}, + {V4L2_PIX_FMT_VP8, YAMI_MIME_VP8}, + {V4L2_PIX_FMT_VP9, YAMI_MIME_VP9}, + {V4L2_PIX_FMT_MJPEG, YAMI_MIME_JPEG}, + {V4L2_PIX_FMT_MPEG2, YAMI_MIME_MPEG2}, + {V4L2_PIX_FMT_VC1, YAMI_MIME_VC1} + +}; + +uint32_t v4l2PixelFormatFromMime(const char* mime) +{ + uint32_t format = 0; + for (uint32_t i = 0; i < N_ELEMENTS(FormatEntrys); i++) { + const FormatEntry* entry = FormatEntrys + i; + if (strcmp(mime, entry->mime) == 0) { + format = entry->format; + break; + } + } + return format; +} + +const char* mimeFromV4l2PixelFormat(uint32_t pixelFormat) +{ + const char* mime = NULL; + for (size_t i = 0; i < N_ELEMENTS(FormatEntrys); i++) { + const FormatEntry* entry = FormatEntrys + i; + if (entry->format == pixelFormat) { + mime = entry->mime; + break; + } + } + return mime; +} + +#if defined(__ENABLE_WAYLAND__) +bool V4l2CodecBase::setWaylandDisplay(struct wl_display* wlDisplay) +{ + m_nativeDisplay.type = NATIVE_DISPLAY_WAYLAND; + m_nativeDisplay.handle = (intptr_t)wlDisplay; + return true; +}; +#endif //__ENABLE_WAYLAND__ + +#if defined(__ENABLE_X11__) +bool V4l2CodecBase::setXDisplay(Display* x11Display) +{ + m_nativeDisplay.type = NATIVE_DISPLAY_X11; + m_nativeDisplay.handle = (intptr_t)x11Display; + return true; +}; +#endif //__ENABLE_X11__ + +bool V4l2CodecBase::setDrmFd(int fd) +{ + m_nativeDisplay.type = NATIVE_DISPLAY_DRM; + m_nativeDisplay.handle = (intptr_t)fd; + return true; +}; + diff --git a/v4l2/v4l2_codecbase.h b/v4l2/v4l2_codecbase.h new file mode 100644 index 0000000..9192502 --- /dev/null +++ b/v4l2/v4l2_codecbase.h @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef v4l2_codecbase_h +#define v4l2_codecbase_h + +#include +#include +#include +#include +#include "common/condition.h" +#include "VideoPostProcessHost.h" +#include "VideoDecoderInterface.h" +#if defined(__ENABLE_X11__) +#include +#endif +#if defined(__ENABLE_EGL__) +#include +#define EGL_EGLEXT_PROTOTYPES +#include "EGL/eglext.h" +#endif +#include "VideoCommonDefs.h" +#include "vaapi/vaapiptrs.h" +#include "v4l2codec_device_ops.h" + +#ifndef V4L2_EVENT_RESOLUTION_CHANGE + #define V4L2_EVENT_RESOLUTION_CHANGE 5 +#endif + +#ifndef V4L2_PIX_FMT_VP9 +#define V4L2_PIX_FMT_VP9 YAMI_FOURCC('V', 'P', '9', '0') +#endif + +#ifndef V4L2_PIX_FMT_VC1 +#define V4L2_PIX_FMT_VC1 YAMI_FOURCC('V', 'C', '1', '0') +#endif + +#if defined(INPUT) || defined(OUTPUT) + #error("conflict define for INPUT/OUTPUT") +#else + #define INPUT 0 + #define OUTPUT 1 +#endif +#define GET_PORT_INDEX(_port, _type, _ret) do { \ + if (_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { \ + _port = INPUT; \ + } else if (_type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { \ + _port = OUTPUT; \ + } else { \ + _ret = -1; \ + ERROR("unkown port, type num: %d", _type); \ + break; \ + } \ + } while (0) + +using namespace YamiMediaCodec; +class V4l2CodecBase { + public: + V4l2CodecBase(); + virtual ~V4l2CodecBase(); + + typedef SharedPtr < V4l2CodecBase > V4l2CodecPtr; + static V4l2CodecPtr createCodec(const char* name, int32_t flags); + bool close (); + virtual int32_t setFrameMemoryType(VideoDataMemoryType memory_type) {m_memoryType = memory_type; return 0;} ; + virtual int32_t setSvcT(bool enable) {m_svct = enable; return 0;}; + virtual int32_t setThumbnailMode(bool enable) {m_isThumbnailMode = enable; return 0;}; + virtual int32_t ioctl(int request, void* arg); + int32_t poll(bool poll_device, bool* event_pending); + int32_t setDeviceEvent(int index); + int32_t clearDeviceEvent(int index); + virtual void* mmap(void* addr, size_t length, + int prot, int flags, unsigned int offset) {return NULL;}; + // virtual int32_t munmap(void* addr, size_t length) {return 0;}; + virtual bool stop() = 0; + +#if defined(__ENABLE_WAYLAND__) + bool setWaylandDisplay(struct wl_display*); +#endif //__ENABLE_WAYLAND__ + +#if defined(__ENABLE_X11__) + bool setXDisplay(Display*); +#endif //__ENABLE_X11__ + +#if defined(__ENABLE_EGL__) + virtual int32_t useEglImage(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t buffer_index, void* egl_image) {return 0;}; +#endif + + bool setDrmFd(int fd); + + void workerThread(); + int32_t fd() { return m_fd[0];}; + + protected: + virtual bool start() = 0; + virtual bool acceptInputBuffer(struct v4l2_buffer *qbuf) = 0; + virtual bool giveOutputBuffer(struct v4l2_buffer *dqbuf) = 0; + virtual bool inputPulse(uint32_t index) = 0; + virtual bool outputPulse(uint32_t &index) = 0; // index of decode output is decided by libyami, not FIFO of m_framesTodo[OUTPUT] + virtual bool recycleInputBuffer(struct v4l2_buffer *qbuf) {return true; } + virtual bool recycleOutputBuffer(int32_t index) {return true;}; + virtual bool hasCodecEvent(); + virtual void setCodecEvent(); + virtual void clearCodecEvent(); + virtual void releaseCodecLock(bool lockable) {}; + virtual void flush() {} + + VideoDataMemoryType m_memoryType; + uint32_t m_maxBufferCount[2]; + uint32_t m_bufferPlaneCount[2]; + uint32_t m_memoryMode[2]; + uint32_t m_pixelFormat[2]; // (it should be a set) + bool m_streamOn[2]; + bool m_threadOn[2]; + int32_t m_fd[2]; // 0 for device event, 1 for interrupt + bool m_started; + bool m_svct; + bool m_isThumbnailMode; + + NativeDisplay m_nativeDisplay; + + enum EosState{ + EosStateNormal, + EosStateInput, + EosStateOutput, + }; + // EOS state is detected(EosStateInput) or transit to EosStateOutput in subclass (V4l2Decoder/V4l2Encoder). + // it is cleared in base class (V4l2Codec) after input thread unblock, and used for special synchronization between INPUT and OUTPUT thread + // so, we keep its operation func in base class with lock (and m_eosState private). + virtual EosState eosState() { return m_eosState; }; + virtual void setEosState(EosState eosState); + + private: + bool m_hasEvent; + + pthread_t m_worker[2]; + // to be processed by codec. + // encoder: (0:INPUT):filled with input frame data, input worker thread will send them to yami + // (1:OUTPUT): empty output buffer, output worker thread will fill it with coded data + // decoder: (0:INPUT):filled with compressed frame data, input worker thread will send them to yami + // (1:OUTPUT): frames at codec side under processing; when output worker get one frame from yami, it should be in this set + std::list m_framesTodo[2]; // INPUT port FIFO, OUTPUT port in random order + // processed by codec already, ready for dque + // (0,INPUT): ready to deque for input buffer. + // (1, OUTPUT): filled with coded data (encoder) or decoded frame (decoder). + std::deque m_framesDone[2]; // ready for deque, processed by codec already for input buffer. + YamiMediaCodec::Lock m_frameLock[2]; // lock for INPUT/OUTPUT frames respectively + + // Condition must be initialized with Lock, but array (without default construct function) doesn't work + YamiMediaCodec::Condition m_inputThreadCond; + YamiMediaCodec::Condition m_outputThreadCond; + YamiMediaCodec::Condition *m_threadCond[2]; + + enum ReqBufState { + RBS_Normal, // normal running state + RBS_Request, // receive REQBUF in I/O thread + RBS_Acknowledge, // work thread acknowledge REQBUF (pause buffer processing) + RBS_Released, //buffer released, which means cannot call Qbuf or Debuf + RBS_FormatChanged, //buffer released, which means can still call Qbuf or Debuf + }; + ReqBufState m_reqBufState[2]; + + YamiMediaCodec::Lock m_codecLock; + EosState m_eosState; + + bool open(const char* name, int32_t flags); + +#ifdef __ENABLE_DEBUG__ + protected: + const char* IoctlCommandString(int command); + + uint32_t m_frameCount[2]; +#endif +}; + +uint32_t v4l2PixelFormatFromMime(const char* mime); +const char* mimeFromV4l2PixelFormat(uint32_t pixelFormat); + +#endif diff --git a/v4l2/v4l2_decode.cpp b/v4l2/v4l2_decode.cpp new file mode 100644 index 0000000..b740950 --- /dev/null +++ b/v4l2/v4l2_decode.cpp @@ -0,0 +1,1383 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define __STDC_FORMAT_MACROS + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__ENABLE_WAYLAND__) +#include +#endif +#include "v4l2_decode.h" +#include "VideoDecoderHost.h" +#include "common/log.h" +#include "common/common_def.h" +#include "common/basesurfaceallocator.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/VaapiUtils.h" + +#define INT64_TO_TIMEVAL(i64, time_val) \ + do { \ + time_val.tv_sec = (int32_t)(i64 >> 31); \ + time_val.tv_usec = (int32_t)(i64 & 0x7fffffff); \ + } while (0) +#define TIMEVAL_TO_INT64(i64, time_val) \ + do { \ + i64 = time_val.tv_sec; \ + i64 = (i64 << 31) + time_val.tv_usec; \ + } while (0) + +//return if we have error +#define ERROR_RETURN(no) \ + do { \ + if (no) { \ + errno = no; \ + return -1; \ + } \ + } while (0) + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + ERROR("%s is false", #cond); \ + ERROR_RETURN(EINVAL); \ + } \ + } while (0) + +//check condition in post messsage. +#define PCHECK(cond) \ + do { \ + if (!(cond)) { \ + m_state = kError; \ + ERROR("%s is false", #cond); \ + return; \ + } \ + } while (0) + +#define SEND(func) \ + do { \ + int32_t ret_ = sendTask(func); \ + ERROR_RETURN(ret_); \ + } while (0) + +const static uint32_t kDefaultInputSize = 1024 * 1024; + +//#undef DEBUG +//#define DEBUG ERROR + +using namespace std; + +struct FrameInfo { + int64_t timeStamp; +}; + +class V4l2Decoder::Output { +public: + Output(V4l2Decoder* decoder) + : m_decoder(decoder) + { + memset(&m_lastFormat, 0, sizeof(m_lastFormat)); + } + virtual void setDecodeAllocator(DecoderPtr decoder) + { + /* nothing */ + } + virtual int32_t requestBuffers(uint32_t count) = 0; + virtual void output(SharedPtr& frame) = 0; + virtual bool isAllocationDone() = 0; + virtual bool isOutputReady() = 0; + virtual int32_t deque(struct v4l2_buffer* buf) = 0; + virtual int32_t queue(struct v4l2_buffer* buf) + { + m_decoder->m_out.queue(buf->index); + return 0; + } + virtual int32_t createBuffers(struct v4l2_create_buffers* createBuffers) + { + return 0; + } + virtual void streamOff() + { + //nothing for base + } + void flush() + { + //forget pending format change on flush + m_pendingFormat.reset(); + } + + bool setFormat(const VideoFormatInfo* format) + { + DEBUG("last format = %dx%dx%d@%x", + m_lastFormat.surfaceWidth, m_lastFormat.surfaceHeight, + m_lastFormat.surfaceNumber, m_lastFormat.fourcc); + if (m_pendingFormat) { + DEBUG("pending format = %dx%dx%d@%x", + m_pendingFormat->surfaceWidth, m_pendingFormat->surfaceHeight, + m_pendingFormat->surfaceNumber, m_pendingFormat->fourcc); + } + bool changed = m_lastFormat.surfaceWidth != format->surfaceWidth + || m_lastFormat.surfaceHeight != format->surfaceHeight + || m_lastFormat.surfaceNumber != format->surfaceNumber + || m_lastFormat.fourcc != format->fourcc; + if (changed) { + DEBUG("format changed to %dx%dx%d@%x", + format->surfaceWidth, format->surfaceHeight, + format->surfaceNumber, format->fourcc); + m_pendingFormat.reset(new VideoFormatInfo); + *m_pendingFormat = *format; + } + return changed; + } + +protected: + void requestFrameInfo(uint32_t count) + { + m_frameInfo.resize(count); + } + void outputFrame(uint32_t index, SharedPtr& frame) + { + setTimeStamp(index, frame->timeStamp); + m_decoder->m_out.put(index); + m_decoder->setDeviceEvent(0); + } + void getTimeStamp(uint32_t index, struct timeval& timeStamp) + { + DEBUG("index = %d, size = %d", (int)index, (int)m_frameInfo.size()); + ASSERT(index < m_frameInfo.size()); + INT64_TO_TIMEVAL(m_frameInfo[index].timeStamp, timeStamp); + } + void setTimeStamp(uint32_t index, int64_t timeStamp) + { + ASSERT(index < m_frameInfo.size()); + m_frameInfo[index].timeStamp = timeStamp; + } + + void getBufferInfo(struct v4l2_buffer* buf, uint32_t index) + { + + buf->index = index; + //chrome will use this value. + buf->m.planes[0].bytesused = 1; + buf->m.planes[1].bytesused = 1; + getTimeStamp(index, buf->timestamp); + } + + void finishFormatChangeIfNeeded() + { + DEBUG("m_pendingFormat = %d", !!m_pendingFormat); + if (m_pendingFormat) { + m_lastFormat = *m_pendingFormat; + m_pendingFormat.reset(); + } + } + + V4l2Decoder* m_decoder; + vector m_frameInfo; + Lock m_lock; + VideoFormatInfo m_lastFormat; + //format changed but caller did not allocate buffer for us. + SharedPtr m_pendingFormat; +}; + +class SurfaceGetter { + typedef map UsedMap; + const static uint32_t kHoldByRenderer = 1; + const static uint32_t kHoldByDecoder = 2; + +public: + static YamiStatus getSurface(SurfaceAllocParams* param, intptr_t* surface) + { + SurfaceGetter* p = (SurfaceGetter*)param->user; + return p->getSurface(surface); + } + + static YamiStatus putSurface(SurfaceAllocParams* param, intptr_t surface) + { + SurfaceGetter* p = (SurfaceGetter*)param->user; + return p->putSurface(surface); + } + + YamiStatus getSurface(intptr_t* surface) + { + AutoLock l(m_lock); + if (!takeOneFree(surface, kHoldByDecoder)) + return YAMI_DECODE_NO_SURFACE; + DEBUG("getSurface: %x", (uint32_t)*surface); + return YAMI_SUCCESS; + } + + YamiStatus putSurface(intptr_t surface) + { + AutoLock l(m_lock); + + clearFlag(surface, kHoldByDecoder); + DEBUG("putSurface: %x", (uint32_t)surface); + return YAMI_SUCCESS; + } + + bool holdByRenderer(intptr_t surface) + { + AutoLock l(m_lock); + return setFlag(surface, kHoldByRenderer); + } + + bool freeByRenderer(intptr_t surface) + { + AutoLock l(m_lock); + return clearFlag(surface, kHoldByRenderer); + } + + void holdAllByRenderer() + { + DEBUG("hold all by renderer"); + + AutoLock l(m_lock); + m_freed.clear(); + + UsedMap::iterator it = m_used.begin(); + while (it != m_used.end()) { + it->second = kHoldByRenderer; + ++it; + } + } + + bool takeOneFreeByRenderer(intptr_t* surface) + { + AutoLock l(m_lock); + return takeOneFree(surface, kHoldByRenderer); + } + bool addNewSurface(intptr_t surface) + { + AutoLock l(m_lock); + UsedMap::iterator it = m_used.find(surface); + if (it != m_used.end()) { + ERROR("add duplicate surface %x, it's hold by %s", (uint32_t)surface, getOwnerName(it->second)); + } + m_freed.push_back(surface); + m_used[surface] = 0; + return true; + } + + void removeAllSurfaces() + { + m_used.clear(); + m_freed.clear(); + } + +private: + bool takeOneFree(intptr_t* surface, uint32_t flag) + { + if (m_freed.empty()) { + DEBUG("no free surface"); + UsedMap::iterator it = m_used.begin(); + while (it != m_used.end()) { + DEBUG("surface %x, it's hold by %s", (uint32_t)it->first, getOwnerName(it->second)); + ++it; + } + return false; + } + *surface = m_freed.front(); + m_used[*surface] = flag; + m_freed.pop_front(); + return true; + } + + bool setFlag(intptr_t surface, uint32_t flag) + { + UsedMap::iterator it = m_used.find(surface); + DEBUG("%s takes %x", getOwnerName(flag), (uint32_t)surface); + if (it == m_used.end()) { + ERROR("set owner to %s failed for %x", getOwnerName(flag), (uint32_t)surface); + return false; + } + it->second |= flag; + return true; + } + YamiStatus clearFlag(intptr_t surface, uint32_t flag) + { + UsedMap::iterator it = m_used.find(surface); + DEBUG("return %x from %s", (uint32_t)surface, getOwnerName(flag)); + + if (it == m_used.end()) { + ERROR("clear wrong surface id = %x", (uint32_t)surface); + return YAMI_INVALID_PARAM; + } + if (!(it->second & flag)) { + ERROR("%x is not hold by %s, it hold by %s", (uint32_t)surface, getOwnerName(flag), getOwnerName(it->second)); + return YAMI_INVALID_PARAM; + } + it->second &= ~flag; + if (!it->second) { + m_freed.push_back(surface); + } + return YAMI_SUCCESS; + } + +private: + const char* getOwnerName(uint32_t flag) + { + if (flag == kHoldByRenderer) + return "renderer"; + if (flag == kHoldByDecoder) + return "decoder"; + if (flag == (kHoldByRenderer | kHoldByDecoder)) + return "decoder and render"; + if (!flag) + return "no one"; + return "unknow"; + } + Lock m_lock; + UsedMap m_used; + deque m_freed; +}; + +//the buffer resource is created from V4L2's user +class ExternalBufferOutput : public V4l2Decoder::Output, BaseSurfaceAllocator { + typedef map SurfaceMap; + +public: + ExternalBufferOutput(V4l2Decoder* decoder) + : V4l2Decoder::Output(decoder) + , m_getter(new SurfaceGetter) + { + } + virtual void setDecodeAllocator(DecoderPtr decoder) + { + decoder->setAllocator(this); + /* nothing */ + } + virtual int32_t requestBuffers(uint32_t count) + { + AutoLock l(m_lock); + m_count = count; + if (!count) { + for (size_t i = 0; i < m_surfaces.size(); i++) { + if (m_surfaces[i] != (intptr_t)VA_INVALID_SURFACE) { + destorySurface(m_surfaces[i]); + } + } + m_getter->removeAllSurfaces(); + m_surfaceMap.clear(); + } else { + finishFormatChangeIfNeeded(); + } + m_surfaces.resize(count, VA_INVALID_SURFACE); + requestFrameInfo(count); + + return 0; + } + virtual void output(SharedPtr& frame) + { + ASSERT(m_getter.get()); + m_getter->holdByRenderer(frame->surface); + + AutoLock l(m_lock); + + SurfaceMap::iterator it = m_surfaceMap.find(frame->surface); + ASSERT(it != m_surfaceMap.end()); + outputFrame(it->second, frame); + } + virtual bool isAllocationDone() + { + bool ret = !m_pendingFormat && m_surfaceMap.size() == m_count; + DEBUG("is allocation done = %d, pending format = %d, size = %d, count = %d", + ret, !!m_pendingFormat, (int)m_surfaceMap.size(), m_count); + return ret; + } + + virtual bool isOutputReady() + { + return true; + } + int32_t queue(struct v4l2_buffer* buf) + { + uint32_t index; + bool streamOn; + //create and update index + intptr_t surface; + { + //we need hold lock in freeVideoFrame, so we keep the lock in {} + AutoLock l(m_lock); + index = buf->index; + + CHECK(index < m_surfaces.size()); + streamOn = m_decoder->m_outputOn; + if (!m_decoder->m_outputOn) { + CHECK(createSurface(surface, buf)); + m_surfaces[index] = surface; + m_surfaceMap[surface] = index; + } + surface = m_surfaces[index]; + } + + ASSERT(m_getter.get()); + if (!streamOn) + m_getter->addNewSurface(surface); + else + m_getter->freeByRenderer(surface); + return 0; + } + virtual int32_t deque(struct v4l2_buffer* buf) + { + AutoLock l(m_lock); + uint32_t index; + if (m_decoder->m_outputOn) { + if (!m_decoder->m_out.deque(index)) { + ERROR_RETURN(EAGAIN); + } + } + else { + CHECK(m_getter); + intptr_t p; + //this mean we need deque the surface from free list + CHECK(m_getter->takeOneFreeByRenderer(&p)); + SurfaceMap::iterator it = m_surfaceMap.find(p); + CHECK(it != m_surfaceMap.end()); + index = it->second; + } + getBufferInfo(buf, index); + return 0; + } + virtual void streamOff() + { + m_getter->holdAllByRenderer(); + } + +protected: + virtual YamiStatus doAlloc(SurfaceAllocParams* params) + { + AutoLock l(m_lock); + if (m_surfaces.size() != m_surfaceMap.size()) { + ERROR("surfaces size did not match map size (%d != %d)", (int)m_surfaces.size(), (int)m_surfaceMap.size()); + return YAMI_FAIL; + } + if (params->size > m_surfaces.size()) { + DEBUG("ATTENTION!!! require size > surface size (%d > %d), m_isThumbnailMode = %d", (int)params->size, (int)m_surfaces.size(), m_decoder->m_isThumbnailMode); + } + + params->surfaces = &m_surfaces[0]; + params->size = m_surfaces.size(); + params->user = m_getter.get(); + params->getSurface = SurfaceGetter::getSurface; + params->putSurface = SurfaceGetter::putSurface; + return YAMI_SUCCESS; + } + virtual YamiStatus doFree(SurfaceAllocParams* params) + { + /* nothing */ + return YAMI_SUCCESS; + } + virtual void doUnref() + { + /* nothing */ + } + + virtual bool createExternalSurface(intptr_t& surface, uint32_t rtFormat, VASurfaceAttribExternalBuffers& external) + { + VASurfaceAttrib attribs[2]; + attribs[0].flags = VA_SURFACE_ATTRIB_SETTABLE; + attribs[0].type = VASurfaceAttribMemoryType; + attribs[0].value.type = VAGenericValueTypeInteger; + attribs[0].value.value.i = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME; + + attribs[1].flags = VA_SURFACE_ATTRIB_SETTABLE; + attribs[1].type = VASurfaceAttribExternalBufferDescriptor; + attribs[1].value.type = VAGenericValueTypePointer; + attribs[1].value.value.p = &external; + + VASurfaceID id; + VAStatus vaStatus = vaCreateSurfaces(m_decoder->m_display->getID(), rtFormat, external.width, external.height, + &id, 1, attribs, N_ELEMENTS(attribs)); + if (!checkVaapiStatus(vaStatus, "vaCreateSurfaces")) + return false; + surface = static_cast(id); + return true; + } + + virtual bool createSurface(intptr_t& surface, struct v4l2_buffer* buf) = 0; + virtual bool destorySurface(intptr_t& surface) = 0; + + uint32_t m_count; + vector m_surfaces; + SurfaceMap m_surfaceMap; + SharedPtr m_getter; +}; + +class ExternalDmaBufOutput : public ExternalBufferOutput { +public: + ExternalDmaBufOutput(V4l2Decoder* decoder) + : ExternalBufferOutput(decoder) + { + } + + virtual int32_t createBuffers(struct v4l2_create_buffers* createBuffers) + { + m_createBuffers.reset(new v4l2_create_buffers); + *m_createBuffers = *createBuffers; + return 0; + } + + virtual bool createSurface(intptr_t& surface, struct v4l2_buffer* buf) + { + if (!m_createBuffers) { + ERROR("you need create buffer first"); + return false; + } + + v4l2_pix_format_mplane& format = m_createBuffers->format.fmt.pix_mp; + VASurfaceAttribExternalBuffers external; + memset(&external, 0, sizeof(external)); + external.pixel_format = format.pixelformat; + uint32_t rtFormat = getRtFormat(format.pixelformat); + if (!rtFormat) { + ERROR("failed get rtformat for %.4s", (char*)&format.pixelformat); + return false; + } + external.width = format.width; + external.height = format.height; + external.num_planes = format.num_planes; + for (uint32_t i = 0; i < format.num_planes; i++) { + external.pitches[i] = format.plane_fmt[i].bytesperline; + //not really right, but we use sizeimage to deliver offset + external.offsets[i] = format.plane_fmt[i].sizeimage; + } + external.buffers = (uintptr_t *)&buf->m.userptr; + external.num_buffers = 1; + + return createExternalSurface(surface, rtFormat, external); + } + virtual bool destorySurface(intptr_t& surface) + { + VASurfaceID s = (VASurfaceID)surface; + return checkVaapiStatus(vaDestroySurfaces(m_decoder->m_display->getID(), &s, 1), "vaDestroySurfaces"); + } + SharedPtr m_createBuffers; +}; + +#ifdef __ENABLE_EGL__ +#include "egl/egl_vaapi_image.h" +class EglOutput : public V4l2Decoder::Output { +public: + EglOutput(V4l2Decoder* decoder, VideoDataMemoryType memory_type) + : V4l2Decoder::Output(decoder) + , m_memoryType(memory_type) + { + } + virtual int32_t requestBuffers(uint32_t count) + { + v4l2_pix_format_mplane& format = m_decoder->m_outputFormat.fmt.pix_mp; + DisplayPtr& display = m_decoder->m_display; + CHECK(bool(display)); + CHECK(format.width && format.height); + m_eglVaapiImages.clear(); + for (uint32_t i = 0; i < count; i++) { + SharedPtr image(new EglVaapiImage(display->getID(), format.width, format.height)); + if (!image->init()) { + ERROR("Create egl vaapi image failed"); + m_eglVaapiImages.clear(); + return EINVAL; + } + m_eglVaapiImages.push_back(image); + } + requestFrameInfo(count); + if (count) { + finishFormatChangeIfNeeded(); + } + return 0; + } + int32_t useEglImage(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t bufferIndex, void* eglImage) + { + CHECK(m_memoryType == VIDEO_DATA_MEMORY_TYPE_DRM_NAME || m_memoryType == VIDEO_DATA_MEMORY_TYPE_DMA_BUF); + CHECK(bufferIndex < m_eglVaapiImages.size()); + *(EGLImageKHR*)eglImage = m_eglVaapiImages[bufferIndex]->createEglImage(eglDisplay, eglContext, m_memoryType); + return 0; + } + void output(SharedPtr& frame) + { + uint32_t index; + if (!m_decoder->m_out.get(index)) { + ERROR("bug: can't get index"); + return; + } + if (!(index < m_eglVaapiImages.size())) { + ERROR("index = %d, size = %d", (int)index, (int)m_eglVaapiImages.size()); + ASSERT(index < m_eglVaapiImages.size()); + } + m_eglVaapiImages[index]->blt(frame); + outputFrame(index, frame); + } + bool isAllocationDone() + { + bool ret = !m_pendingFormat && !m_eglVaapiImages.empty(); + DEBUG("is allocation done = %d, pending format = %d, is empty = %d", + ret, !!m_pendingFormat, m_eglVaapiImages.empty()); + + return ret; + } + bool isOutputReady() + { + uint32_t index; + return m_decoder->m_out.peek(index); + } + + int32_t deque(struct v4l2_buffer* buf) + { + uint32_t index; + if (!m_decoder->m_out.deque(index)) { + ERROR_RETURN(EAGAIN); + } + getBufferInfo(buf, index); + return 0; + } + +private: + std::vector > m_eglVaapiImages; + VideoDataMemoryType m_memoryType; +}; +#endif + +V4l2Decoder::V4l2Decoder() + : m_inputOn(false) + , m_outputOn(false) + , m_state(kUnStarted) +{ + memset(&m_inputFormat, 0, sizeof(m_inputFormat)); + memset(&m_outputFormat, 0, sizeof(m_outputFormat)); + m_output.reset(new ExternalDmaBufOutput(this)); +} + +V4l2Decoder::~V4l2Decoder() +{ +} + +void V4l2Decoder::releaseCodecLock(bool lockable) +{ +} + +bool V4l2Decoder::start() +{ + return false; +} + +bool V4l2Decoder::stop() +{ + return true; +} + +bool V4l2Decoder::inputPulse(uint32_t index) +{ + + return true; // always return true for decode; simply ignored unsupported nal +} + +bool V4l2Decoder::outputPulse(uint32_t& index) +{ + return true; +} + +bool V4l2Decoder::recycleOutputBuffer(int32_t index) +{ + // FIXME, after we remove the extra vpp, renderDone() should come here + return true; +} + +bool V4l2Decoder::recycleInputBuffer(struct v4l2_buffer* dqbuf) +{ + + return true; +} + +bool V4l2Decoder::acceptInputBuffer(struct v4l2_buffer* qbuf) +{ + + return true; +} + +bool V4l2Decoder::giveOutputBuffer(struct v4l2_buffer* dqbuf) +{ + + return true; +} + +#ifndef V4L2_PIX_FMT_VP9 +#define V4L2_PIX_FMT_VP9 YAMI_FOURCC('V', 'P', '9', '0') +#endif + +int32_t V4l2Decoder::ioctl(int command, void* arg) +{ + DEBUG("fd: %d, ioctl command: %s", m_fd[0], IoctlCommandString(command)); + switch (command) { + case VIDIOC_QBUF: { + struct v4l2_buffer* qbuf = static_cast(arg); + return onQueueBuffer(qbuf); + } + case VIDIOC_DQBUF: { + struct v4l2_buffer* dqbuf = static_cast(arg); + return onDequeBuffer(dqbuf); + } + case VIDIOC_STREAMON: { + __u32 type = *((__u32*)arg); + return onStreamOn(type); + } + case VIDIOC_STREAMOFF: { + __u32 type = *((__u32*)arg); + return onStreamOff(type); + } + case VIDIOC_QUERYCAP: { + return V4l2CodecBase::ioctl(command, arg); + } + case VIDIOC_REQBUFS: { + struct v4l2_requestbuffers* reqbufs = static_cast(arg); + return onRequestBuffers(reqbufs); + } + case VIDIOC_S_FMT: { + struct v4l2_format* format = static_cast(arg); + return onSetFormat(format); + } + case VIDIOC_QUERYBUF: { + struct v4l2_buffer* buf = static_cast(arg); + return onQueryBuffer(buf); + } + case VIDIOC_SUBSCRIBE_EVENT: { + struct v4l2_event_subscription* sub = static_cast(arg); + return onSubscribeEvent(sub); + } + case VIDIOC_DQEVENT: { + // ::DequeueEvents + struct v4l2_event* ev = static_cast(arg); + return onDequeEvent(ev); + } + case VIDIOC_G_FMT: { + // ::GetFormatInfo + struct v4l2_format* format = static_cast(arg); + return onGetFormat(format); + } + case VIDIOC_G_CTRL: { + // ::CreateOutputBuffers + struct v4l2_control* ctrl = static_cast(arg); + return onGetCtrl(ctrl); + } + case VIDIOC_ENUM_FMT: { + struct v4l2_fmtdesc* fmtdesc = static_cast(arg); + return onEnumFormat(fmtdesc); + } + case VIDIOC_G_CROP: { + struct v4l2_crop* crop = static_cast(arg); + return onGetCrop(crop); + } + case VIDIOC_CREATE_BUFS: { + struct v4l2_create_buffers* req = static_cast(arg); + return onCreateBuffers(req); + } + default: { + ERROR("unknown ioctrl command: %d", command); + return -1; + } + } +} + +VideoDecodeBuffer* V4l2Decoder::peekInput() +{ + uint32_t index; + if (!m_in.peek(index)) + return NULL; + ASSERT(index < m_inputFrames.size()); + VideoDecodeBuffer* inputBuffer = &(m_inputFrames[index]); + return inputBuffer; +} + +void V4l2Decoder::consumeInput() +{ + PCHECK(m_thread.isCurrent()); + uint32_t index; + if (!m_in.get(index)) { + ERROR("bug: can't get from input"); + return; + } + m_in.put(index); + setDeviceEvent(0); +} + +void V4l2Decoder::getInputJob() +{ + PCHECK(m_thread.isCurrent()); + PCHECK(bool(m_decoder)); + if (m_state != kGetInput) { + DEBUG("early out, state = %d", m_state); + return; + } + VideoDecodeBuffer* inputBuffer = peekInput(); + if (!inputBuffer) { + DEBUG("early out, no input buffer"); + m_state = kWaitInput; + return; + } + YamiStatus status = m_decoder->decode(inputBuffer); + DEBUG("decode %d, return %d", (int)inputBuffer->size, (int)status); + if (status == YAMI_DECODE_FORMAT_CHANGE) { + DEBUG("decoder return format change"); + m_state = kFormatChanged; + //now we need this format in output. + const VideoFormatInfo* outFormat = m_decoder->getFormatInfo(); + PCHECK(outFormat); + m_output->setFormat(outFormat); + //drain output + getOutputJob(); + return; + } + if (status == YAMI_DECODE_NO_SURFACE) { + if (m_output->isAllocationDone()) { + m_state = kGetOutput; + getOutputJob(); + m_state = kWaitSurface; + DEBUG("early out, no surface"); + return; + } else { + DEBUG("need relocation"); + m_state = kWaitAllocation; + setCodecEvent(); + return; + } + } + consumeInput(); + if (!m_decoder->getFormatInfo()) { + DEBUG("need more data to detect output format"); + post(bind(&V4l2Decoder::getInputJob, this)); + return; + } + m_state = kGetOutput; + post(bind(&V4l2Decoder::getOutputJob, this)); +} + +void V4l2Decoder::inputReadyJob() +{ + PCHECK(m_thread.isCurrent()); + if (m_state != kWaitInput) { + DEBUG("early out, state = %d", m_state); + return; + } + m_state = kGetInput; + getInputJob(); +} + +void V4l2Decoder::getOutputJob() +{ + PCHECK(m_thread.isCurrent()); + PCHECK(bool(m_decoder)); + if (m_state != kGetOutput && m_state != kFormatChanged) { + DEBUG("early out, state = %d, change = %d", m_state, kFormatChanged); + return; + } + while (m_output->isOutputReady()) { + SharedPtr frame = m_decoder->getOutput(); + if (!frame) { + if (m_state == kFormatChanged && !m_output->isAllocationDone()) { + DEBUG("need relocation"); + m_state = kWaitAllocation; + setCodecEvent(); + return; + } else { + DEBUG("early out, no frame"); + m_state = kGetInput; + post(bind(&V4l2Decoder::getInputJob, this)); + return; + } + } + m_output->output(frame); + } + if (m_state == kGetOutput) { + m_state = kWaitOutput; + } + else { + ASSERT(m_state == kFormatChanged); + DEBUG("format change, wait more output buffers"); + } +} + +void V4l2Decoder::outputReadyJob() +{ + PCHECK(m_thread.isCurrent()); + if (m_state == kWaitOutput) { + m_state = kGetOutput; + getOutputJob(); + } else if (m_state == kFormatChanged) { + //try to drain output + getOutputJob(); + } + else if (m_state == kWaitSurface) { + m_state = kGetInput; + getInputJob(); + } +} + +void V4l2Decoder::checkAllocationJob() +{ + PCHECK(m_thread.isCurrent()); + if (m_state == kWaitAllocation) { + if (m_output->isAllocationDone()) { + m_state = kGetInput; + getInputJob(); + } + } +} + +int32_t V4l2Decoder::onQueueBuffer(v4l2_buffer* buf) +{ + CHECK(buf); + uint32_t type = buf->type; + CHECK(type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE + || type == (unsigned int)V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + CHECK(buf->memory == V4L2_MEMORY_MMAP); + CHECK(buf->length == 1); + CHECK(buf->index < m_inputFrames.size()); + DEBUG("queue input size = %d", buf->m.planes[0].bytesused); + + VideoDecodeBuffer& inputBuffer = m_inputFrames[buf->index]; + inputBuffer.size = buf->m.planes[0].bytesused; // one plane only + if (!inputBuffer.size) // EOS + inputBuffer.data = NULL; + TIMEVAL_TO_INT64(inputBuffer.timeStamp, buf->timestamp); + + m_in.queue(buf->index); + post(bind(&V4l2Decoder::inputReadyJob, this)); + return 0; + } + DEBUG("queue output index = %d", buf->index); + + m_output->queue(buf); + post(bind(&V4l2Decoder::outputReadyJob, this)); + return 0; +} + +int32_t V4l2Decoder::onDequeBuffer(v4l2_buffer* buf) +{ + CHECK(buf); + uint32_t type = buf->type; + CHECK(type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE + || type == (unsigned int)V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + CHECK(m_inputOn); + uint32_t index; + if (!m_in.deque(index)) { + ERROR_RETURN(EAGAIN); + } + buf->index = index; + DEBUG("dequeue input index = %d", buf->index); + return 0; + } + + int32_t ret = m_output->deque(buf); + if (!ret) + DEBUG("dequeue output index = %d", buf->index); + + return ret; +} +int32_t V4l2Decoder::onStreamOn(uint32_t type) +{ + CHECK(type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE + || type == (unsigned int)V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + + if (!m_display) { + m_display = VaapiDisplay::create(m_nativeDisplay); + CHECK(bool(m_display)); + } + + CHECK(!m_inputOn); + m_inputOn = true; + CHECK(m_thread.start()); + + post(bind(&V4l2Decoder::startDecoderJob, this)); + return 0; + } + CHECK(!m_outputOn); + m_outputOn = true; + post(bind(&V4l2Decoder::checkAllocationJob, this)); + return 0; +} + +void V4l2Decoder::flushDecoderJob() +{ + if (m_decoder) + m_decoder->flush(); + m_output->flush(); + m_state = kStopped; +} +int32_t V4l2Decoder::onStreamOff(uint32_t type) +{ + CHECK(type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE + || type == (unsigned int)V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + if (m_inputOn) { + post(bind(&V4l2Decoder::flushDecoderJob, this)); + m_thread.stop(); + m_in.clearPipe(); + m_inputOn = false; + m_state = kUnStarted; + } + return 0; + } + m_outputOn = false; + m_output->streamOff(); + m_out.clearPipe(); + + return 0; +} + +int32_t V4l2Decoder::requestInputBuffers(uint32_t count) +{ + CHECK(m_thread.isCurrent()); + + uint32_t size = m_inputFormat.fmt.pix_mp.plane_fmt[0].sizeimage; + + m_inputFrames.resize(count); + if (count) { + //this means we really need allocate space + if (!size) + m_inputFormat.fmt.pix_mp.plane_fmt[0].sizeimage = kDefaultInputSize; + } + m_inputSpace.resize(count * size); + m_inputFrames.resize(count); + for (uint32_t i = 0; i < count; i++) { + VideoDecodeBuffer& frame = m_inputFrames[i]; + memset(&frame, 0, sizeof(frame)); + frame.data = &m_inputSpace[i * size]; + } + return 0; +} + +int32_t V4l2Decoder::onRequestBuffers(const v4l2_requestbuffers* req) +{ + CHECK(req); + uint32_t type = req->type; + uint32_t count = req->count; + CHECK(type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE + || type == (unsigned int)V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + CHECK(req->memory == V4L2_MEMORY_MMAP); + return sendTask(bind(&V4l2Decoder::requestInputBuffers, this, count)); + } + CHECK(req->memory == V4L2_MEMORY_MMAP); + return sendTask(bind(&Output::requestBuffers, m_output, count)); +} + +int32_t V4l2Decoder::onSetFormat(v4l2_format* format) +{ + CHECK(format); + CHECK(!m_inputOn && !m_outputOn); + + if (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + uint32_t size; + memcpy(&size, format->fmt.raw_data, sizeof(uint32_t)); + + CHECK(size <= (sizeof(format->fmt.raw_data) - sizeof(uint32_t))); + + uint8_t* ptr = format->fmt.raw_data; + ptr += sizeof(uint32_t); + m_codecData.assign(ptr, ptr + size); + return 0; + } + + if (format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + CHECK(format->fmt.pix_mp.num_planes == 1); + CHECK(format->fmt.pix_mp.plane_fmt[0].sizeimage); + memcpy(&m_inputFormat, format, sizeof(*format)); + return 0; + } + + ERROR("unknow type: %d of setting format VIDIOC_S_FMT", format->type); + return -1; +} + +int32_t V4l2Decoder::onQueryBuffer(v4l2_buffer* buf) +{ + CHECK(buf); + CHECK(buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + CHECK(buf->memory == V4L2_MEMORY_MMAP); + CHECK(m_inputFormat.fmt.pix_mp.num_planes == 1); + + uint32_t idx = buf->index; + uint32_t size = m_inputFormat.fmt.pix_mp.plane_fmt[0].sizeimage; + CHECK(size); + buf->m.planes[0].length = size; + buf->m.planes[0].m.mem_offset = size * idx; + + return 0; +} + +int32_t V4l2Decoder::onSubscribeEvent(v4l2_event_subscription* sub) +{ + CHECK(sub->type == V4L2_EVENT_RESOLUTION_CHANGE); + /// resolution change event is must, we always do so + return 0; +} + +int32_t V4l2Decoder::onDequeEvent(v4l2_event* ev) +{ + CHECK(ev); + if (hasCodecEvent()) { + ev->type = V4L2_EVENT_RESOLUTION_CHANGE; + clearCodecEvent(); + return 0; + } + return -1; +} + +int32_t V4l2Decoder::onGetFormat(v4l2_format* format) +{ + CHECK(format && format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + CHECK(m_inputOn); + + SEND(bind(&V4l2Decoder::getFormatTask, this, format)); + + //save it. + m_outputFormat = *format; + return 0; +} + +int32_t V4l2Decoder::onGetCtrl(v4l2_control* ctrl) +{ + CHECK(ctrl); + CHECK(ctrl->id == V4L2_CID_MIN_BUFFERS_FOR_CAPTURE); + + SEND(bind(&V4l2Decoder::getCtrlTask, this, ctrl)); + return 0; +} + +int32_t V4l2Decoder::onEnumFormat(v4l2_fmtdesc* fmtdesc) +{ + uint32_t type = fmtdesc->type; + uint32_t index = fmtdesc->index; + if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + CHECK(!index); + fmtdesc->pixelformat = V4L2_PIX_FMT_NV12M; + return 0; + } + + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + //TODO: query from libyami when capablity api is ready. + const static uint32_t supported[] = { + V4L2_PIX_FMT_H264, + V4L2_PIX_FMT_VC1, + V4L2_PIX_FMT_MPEG2, + V4L2_PIX_FMT_JPEG, + V4L2_PIX_FMT_VP8, + V4L2_PIX_FMT_VP9, + }; + CHECK(index < N_ELEMENTS(supported)); + fmtdesc->pixelformat = supported[index]; + return 0; + } + return -1; +} + +int32_t V4l2Decoder::onGetCrop(v4l2_crop* crop) +{ + CHECK(crop->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + ASSERT(0); + return 0; + //return sendTask(m_decoderThread, std::bind(getCrop,crop))); +} + +int32_t V4l2Decoder::onCreateBuffers(v4l2_create_buffers* req) +{ + return m_output->createBuffers(req); +} + +void V4l2Decoder::startDecoderJob() +{ + PCHECK(m_state == kUnStarted); + + if (m_decoder) { + m_state = kGetInput; + getInputJob(); + return; + } + + const char* mime = mimeFromV4l2PixelFormat(m_inputFormat.fmt.pix_mp.pixelformat); + + m_decoder.reset( + createVideoDecoder(mime), releaseVideoDecoder); + if (!m_decoder) { + ERROR("create display failed"); + m_display.reset(); + return; + } + + m_output->setDecodeAllocator(m_decoder); + + YamiStatus status; + VideoConfigBuffer config; + memset(&config, 0, sizeof(config)); + config.width = m_inputFormat.fmt.pix_mp.width; + config.height = m_inputFormat.fmt.pix_mp.height; + config.data = &m_codecData[0]; + config.size = m_codecData.size(); + if (m_isThumbnailMode) { + DEBUG("enable lowlatency mode"); + config.enableLowLatency = true; + } + + status = m_decoder->start(&config); + if (status != YAMI_SUCCESS) { + ERROR("start decoder failed"); + return; + } + const VideoFormatInfo* outFormat = m_decoder->getFormatInfo(); + if (outFormat && outFormat->width && outFormat->height) { + //we got format now, we are waiting for surface allocation. + m_state = kWaitAllocation; + } + else { + m_state = kGetInput; + getInputJob(); + } +} + +void V4l2Decoder::post(Job job) +{ + m_thread.post(job); +} + +static void taskWrapper(int32_t& ret, Task& task) +{ + ret = task(); +} + +int32_t V4l2Decoder::sendTask(Task task) +{ + //if send fail, we will return EINVAL; + int32_t ret = EINVAL; + m_thread.send(bind(taskWrapper, ref(ret), ref(task))); + return ret; +} + +int32_t V4l2Decoder::getFormatTask(v4l2_format* format) +{ + CHECK(m_thread.isCurrent()); + CHECK(format); + CHECK(bool(m_decoder)); + + const VideoFormatInfo* outFormat = m_decoder->getFormatInfo(); + if (!outFormat) + return EINVAL; + + memset(format, 0, sizeof(*format)); + format->fmt.pix_mp.width = outFormat->width; + format->fmt.pix_mp.height = outFormat->height; + + //TODO: add support for P010 + format->fmt.pix_mp.num_planes = 2; //for NV12 + format->fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M; + + //we can't fill format->fmt.pix_mp.plane_fmt[0].bytesperline + //yet, since we did not creat surface. + return 0; +} + +int32_t V4l2Decoder::getCtrlTask(v4l2_control* ctrl) +{ + CHECK(m_thread.isCurrent()); + CHECK(ctrl); + CHECK(bool(m_decoder)); + + const VideoFormatInfo* outFormat = m_decoder->getFormatInfo(); + if (!outFormat) + return EINVAL; + + if (m_isThumbnailMode) { + ctrl->value = 1; + } else { + //TODO: query this from outFormat; + ctrl->value = outFormat->surfaceNumber; + } + return 0; +} + +#define MCHECK(cond) \ + do { \ + if (!(cond)) { \ + ERROR("%s is false", #cond); \ + return NULL; \ + } \ + } while (0) + +void* V4l2Decoder::mmap(void* addr, size_t length, + int prot, int flags, unsigned int offset) +{ + MCHECK(prot == (PROT_READ | PROT_WRITE)); + MCHECK(flags == MAP_SHARED); + uint32_t size = m_inputFormat.fmt.pix_mp.plane_fmt[0].sizeimage; + MCHECK(size); + MCHECK(length == size); + MCHECK(!(offset % size)); + MCHECK(offset / size < m_inputFrames.size()); + MCHECK(offset + size <= m_inputSpace.size()); + + return &m_inputSpace[offset]; +} + +#undef MCHECK + +int32_t V4l2Decoder::setFrameMemoryType(VideoDataMemoryType memory_type) +{ + if (memory_type == VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF) + m_output.reset(new ExternalDmaBufOutput(this)); +#ifdef __ENABLE_EGL__ + if (memory_type == VIDEO_DATA_MEMORY_TYPE_DRM_NAME + || memory_type == VIDEO_DATA_MEMORY_TYPE_DMA_BUF) + m_output.reset(new EglOutput(this, memory_type)); +#endif + if (!m_output) { + ERROR("unspported memory type %d", memory_type); + return -1; + } + return 0; +} + +void V4l2Decoder::flush() +{ +} + +#ifdef __ENABLE_EGL__ +int32_t V4l2Decoder::useEglImage(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t bufferIndex, void* eglImage) +{ + SharedPtr output = DynamicPointerCast(m_output); + if (!output) { + ERROR("can't cast m_output to EglOutput"); + return -1; + } + return output->useEglImage(eglDisplay, eglContext, bufferIndex, eglImage); +} +#endif diff --git a/v4l2/v4l2_decode.h b/v4l2/v4l2_decode.h new file mode 100644 index 0000000..e0cafe1 --- /dev/null +++ b/v4l2/v4l2_decode.h @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef v4l2_decode_h +#define v4l2_decode_h + +#include + +#include "v4l2_codecbase.h" +#include "VideoDecoderInterface.h" +#include "common/Thread.h" +#include "common/Functional.h" +#include + +using namespace YamiMediaCodec; +typedef SharedPtr < IVideoDecoder > DecoderPtr; +typedef std::function Task; +class V4l2Decoder : public V4l2CodecBase +{ +public: + V4l2Decoder(); + ~V4l2Decoder(); + + virtual int32_t ioctl(int request, void* arg); + virtual void* mmap(void* addr, size_t length, + int prot, int flags, unsigned int offset); +#ifdef __ENABLE_EGL__ + virtual int32_t useEglImage(EGLDisplay eglDisplay, EGLContext eglContext, uint32_t buffer_index, void* egl_image); +#endif + virtual int32_t setFrameMemoryType(VideoDataMemoryType memory_type); + + class Output; + friend class EglOutput; + friend class ExternalBufferOutput; + friend class ExternalDmaBufOutput; + +protected: + virtual bool start(); + virtual bool stop(); + virtual bool acceptInputBuffer(struct v4l2_buffer *qbuf); + virtual bool giveOutputBuffer(struct v4l2_buffer *dqbuf); + virtual bool inputPulse(uint32_t index); + virtual bool outputPulse(uint32_t &index); + virtual bool recycleOutputBuffer(int32_t index); + virtual bool recycleInputBuffer(struct v4l2_buffer *qbuf); + virtual void releaseCodecLock(bool lockable); + virtual void flush(); + +private: + int32_t onQueueBuffer(v4l2_buffer*); + int32_t onDequeBuffer(v4l2_buffer*); + int32_t onStreamOn(uint32_t type); + int32_t onStreamOff(uint32_t type); + int32_t onRequestBuffers(const v4l2_requestbuffers*); + int32_t onSetFormat(v4l2_format*); + int32_t onQueryBuffer(v4l2_buffer*); + int32_t onSubscribeEvent(v4l2_event_subscription*); + int32_t onDequeEvent(v4l2_event*); + int32_t onGetFormat(v4l2_format*); + int32_t onGetCtrl(v4l2_control*); + int32_t onEnumFormat(v4l2_fmtdesc*); + int32_t onGetCrop(v4l2_crop*); + int32_t onCreateBuffers(v4l2_create_buffers* req); + + //jobs send to decoder thread + void startDecoderJob(); + void getInputJob(); + void inputReadyJob(); + void getOutputJob(); + void outputReadyJob(); + void checkAllocationJob(); + void flushDecoderJob(); + + //tasks send to decoder thread + int32_t getFormatTask(v4l2_format*); + int32_t getCtrlTask(v4l2_control*); + int32_t requestInputBuffers(uint32_t count); + + //help functions + int32_t sendTask(Task task); + void post(Job job); + VideoDecodeBuffer* peekInput(); + void consumeInput(); + + bool m_inputOn; + v4l2_format m_inputFormat; + std::vector m_inputFrames; + std::vector m_inputSpace; + BufferPipe m_in; + + bool m_outputOn; + v4l2_format m_outputFormat; + + //decoder thread + Thread m_thread; + + enum State { + kUnStarted, //decoder thread is not started. + kWaitAllocation, //wait buffer allocation + kGetInput, + kWaitInput, + kWaitSurface, // wait for surface + kGetOutput, + kWaitOutput, + kFormatChanged, // detected format change. Waiting new surfacee. + kStopped, // stopped by use + kError, // have a error + }; + State m_state; + SharedPtr m_output; + BufferPipe m_out; + DisplayPtr m_display; + DecoderPtr m_decoder; + std::vector m_codecData; +}; +#endif diff --git a/v4l2/v4l2_encode.cpp b/v4l2/v4l2_encode.cpp new file mode 100644 index 0000000..63ccdc4 --- /dev/null +++ b/v4l2/v4l2_encode.cpp @@ -0,0 +1,423 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include +#include +#include +#include +#include + +#include "v4l2_encode.h" +#include "VideoEncoderHost.h" +#include "common/log.h" + +V4l2Encoder::V4l2Encoder() + : m_videoParamsChanged(false) + , m_maxOutputBufferSize(0) + , m_outputBufferSpace(NULL) + , m_separatedStreamHeader(false) + , m_requestStreamHeader(true) + , m_forceKeyFrame(false) +{ + m_memoryMode[INPUT] = V4L2_MEMORY_USERPTR; // dma_buf hasn't been supported yet + m_pixelFormat[INPUT] = V4L2_PIX_FMT_YUV420M; + m_bufferPlaneCount[INPUT] = 3; // decided by m_pixelFormat[INPUT] + m_memoryMode[OUTPUT] = V4L2_MEMORY_MMAP; + m_pixelFormat[OUTPUT] = V4L2_PIX_FMT_H264; + m_bufferPlaneCount[OUTPUT] = 1; + m_maxBufferCount[INPUT] = 3; + m_maxBufferCount[OUTPUT] = 3; + + m_inputFrames.resize(m_maxBufferCount[INPUT]); + m_outputFrames.resize(m_maxBufferCount[OUTPUT]); +} + +bool V4l2Encoder::start() +{ + YamiStatus status = YAMI_SUCCESS; + ASSERT(m_encoder); + + VideoConfigAVCStreamFormat streamFormat; + streamFormat.size = sizeof(VideoConfigAVCStreamFormat); + streamFormat.streamFormat = AVC_STREAM_FORMAT_ANNEXB; + m_encoder->setParameters(VideoConfigTypeAVCStreamFormat, &streamFormat); + + if (m_svct) { + VideoTemporalLayers layers; + layers.numLayersMinus1 = 1; // It is two layers actually + layers.bitRate[0] = m_videoParams.rcParams.bitRate / 2; + layers.bitRate[1] = m_videoParams.rcParams.bitRate; + + m_videoParams.temporalLayers = layers; + } + + status = m_encoder->setParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(status == YAMI_SUCCESS); + + NativeDisplay nativeDisplay; + nativeDisplay.type = NATIVE_DISPLAY_DRM; + nativeDisplay.handle = 0; + + m_encoder->setNativeDisplay(&nativeDisplay); + + status = m_encoder->start(); + ASSERT(status == YAMI_SUCCESS); + status = m_encoder->getParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(status == YAMI_SUCCESS); + + return true; +} + +bool V4l2Encoder::stop() +{ + YamiStatus encodeStatus = YAMI_SUCCESS; + if (m_encoder) + encodeStatus = m_encoder->stop(); + return encodeStatus == YAMI_SUCCESS; +} + + +bool V4l2Encoder::UpdateVideoParameters(bool isInputThread) +{ + YamiStatus status = YAMI_SUCCESS; + AutoLock locker(m_videoParamsLock); // make sure the caller has released m_videoParamsLock + + if (!m_videoParamsChanged) + return true; + + if (isInputThread || !m_streamOn[INPUT]) { + status = m_encoder->setParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(status == YAMI_SUCCESS); + m_videoParamsChanged = false; + } + + return status == YAMI_SUCCESS; +} +bool V4l2Encoder::inputPulse(uint32_t index) +{ + YamiStatus status = YAMI_SUCCESS; + + if(m_videoParamsChanged ) + UpdateVideoParameters(true); + + DEBUG_FOURCC("m_inputFrames[index].fourcc: ", m_inputFrames[index].fourcc); + status = m_encoder->encode(&m_inputFrames[index]); + ASSERT(m_inputFrames[index].bufAvailable); // check it at a later time when yami does encode in async + + if (status != YAMI_SUCCESS) + return false; + + return true; +} + +bool V4l2Encoder::outputPulse(uint32_t &index) +{ + YamiStatus status = YAMI_SUCCESS; + + VideoEncOutputBuffer *outputBuffer = &(m_outputFrames[index]); + if (m_separatedStreamHeader) { + outputBuffer->format = OUTPUT_FRAME_DATA; + if (m_requestStreamHeader) { + outputBuffer->format = OUTPUT_CODEC_DATA; + } + } else + outputBuffer->format = OUTPUT_EVERYTHING; + + status = m_encoder->getOutput(outputBuffer, false); + + if (status != YAMI_SUCCESS) + return false; + + ASSERT(m_maxOutputBufferSize > 0); // update m_maxOutputBufferSize after VIDIOC_S_FMT + ASSERT(m_outputBufferSpace); + ASSERT(outputBuffer->dataSize <= m_maxOutputBufferSize); + + if (m_separatedStreamHeader) { + if (m_requestStreamHeader) + m_requestStreamHeader = false; + } + + return true; +} + +bool V4l2Encoder::acceptInputBuffer(struct v4l2_buffer *qbuf) +{ + uint32_t i; + VideoEncRawBuffer *inputBuffer = &(m_inputFrames[qbuf->index]); + + // XXX todo: add multiple planes support for yami + inputBuffer->data = reinterpret_cast(qbuf->m.planes[0].m.userptr); + inputBuffer->size = 0; + for (i=0; ilength; i++) { + inputBuffer->size += qbuf->m.planes[i].bytesused; + } + inputBuffer->bufAvailable = false; + DEBUG("qbuf->index: %d, inputBuffer: %p, bufAvailable: %d", qbuf->index, inputBuffer, inputBuffer->bufAvailable); + inputBuffer->timeStamp = qbuf->timestamp.tv_sec * 1000000 + qbuf->timestamp.tv_usec; // XXX + if (m_forceKeyFrame) { + inputBuffer->forceKeyFrame = true; + m_forceKeyFrame = false; + } + switch(m_pixelFormat[INPUT]) { + case V4L2_PIX_FMT_NV12: + inputBuffer->fourcc = VA_FOURCC_NV12; + break; + case V4L2_PIX_FMT_YUV420M: + inputBuffer->fourcc = VA_FOURCC('I', '4', '2', '0'); + break; + case V4L2_PIX_FMT_YUYV: + inputBuffer->fourcc = VA_FOURCC_YUY2; + break; + default: + ASSERT(0); + break; + } + + return true; +} + +bool V4l2Encoder::giveOutputBuffer(struct v4l2_buffer *dqbuf) +{ + ASSERT(dqbuf->index < m_maxBufferCount[OUTPUT]); + VideoEncOutputBuffer *outputBuffer = &(m_outputFrames[dqbuf->index]); + dqbuf->m.planes[0].bytesused = outputBuffer->dataSize; + dqbuf->bytesused = m_outputFrames[dqbuf->index].dataSize; + dqbuf->m.planes[0].m.mem_offset = 0; + ASSERT(m_maxOutputBufferSize > 0); + ASSERT(m_outputBufferSpace); + if (outputBuffer->flag & ENCODE_BUFFERFLAG_SYNCFRAME) + dqbuf->flags = V4L2_BUF_FLAG_KEYFRAME; + + + if (m_svct && (m_videoParams.temporalLayers.numLayersMinus1 > 0) + && (outputBuffer->temporalID == m_videoParams.temporalLayers.numLayersMinus1)) { + dqbuf->flags |= V4L2_BUF_FLAG_NON_REF; + } + + return true; +} + +int32_t V4l2Encoder::ioctl(int command, void* arg) +{ + YamiStatus encodeStatus = YAMI_SUCCESS; + int32_t ret = 0; + + DEBUG("fd: %d, ioctl command: %s", m_fd[0], IoctlCommandString(command)); + switch (command) { + case VIDIOC_QBUF: + case VIDIOC_QUERYCAP: + case VIDIOC_STREAMON: + case VIDIOC_STREAMOFF: + case VIDIOC_REQBUFS: + case VIDIOC_DQBUF: + ret = V4l2CodecBase::ioctl(command, arg); + break; + case VIDIOC_QUERYBUF: { + struct v4l2_buffer *buffer = static_cast(arg); + ASSERT (buffer->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + ASSERT(buffer->memory == V4L2_MEMORY_MMAP); + ASSERT(buffer->index < m_maxBufferCount[OUTPUT]); + ASSERT(buffer->length == m_bufferPlaneCount[OUTPUT]); + ASSERT(m_maxOutputBufferSize > 0); + + buffer->m.planes[0].length = m_maxOutputBufferSize; + buffer->m.planes[0].m.mem_offset = m_maxOutputBufferSize * buffer->index; + } + break; + case VIDIOC_S_EXT_CTRLS: { + uint32_t i; + struct v4l2_ext_controls *control = static_cast(arg); + DEBUG("V4L2_CTRL_CLASS_MPEG: %d, control->ctrl_class: %d", V4L2_CTRL_CLASS_MPEG, control->ctrl_class); + if (control->ctrl_class == V4L2_CTRL_CLASS_MPEG) { + AutoLock locker(m_videoParamsLock); + struct v4l2_ext_control *ctrls = control->controls; + DEBUG("control->count: %d", control->count); + for (i=0; icount; i++) { + DEBUG("VIDIOC_S_EXT_CTRLS:V4L2_CTRL_CLASS_MPEG:%d", ctrls->id); + switch (ctrls->id) { + case V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE: + // ::EncodeTask + ASSERT(ctrls->value == V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME); + m_forceKeyFrame = true; + break; + case V4L2_CID_MPEG_VIDEO_BITRATE: { + // ::RequestEncodingParametersChangeTask + m_videoParams.rcParams.bitRate = ctrls->value; + m_videoParamsChanged = true; + } + break; + case V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE: + INFO("enable bitrate control"); + m_videoParams.rcMode = RATE_CONTROL_CBR; + m_videoParamsChanged = true; + break; + case V4L2_CID_MPEG_VIDEO_HEADER_MODE: + // Separate stream header so we can cache it and insert into the stream. + if (ctrls->value == V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE) + m_separatedStreamHeader = true; + INFO("use separated stream header: %d", m_separatedStreamHeader); + break; + case V4L2_CID_MPEG_VIDEO_B_FRAMES: + case V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF: + case V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT: + case V4L2_CID_MPEG_VIDEO_H264_MAX_QP: + case V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE: + case V4L2_CID_MPEG_VIDEO_H264_LEVEL: + case V4L2_CID_MPEG_VIDEO_GOP_SIZE: + default: + break; + } + ctrls++; + } + } + UpdateVideoParameters(); + } + break; + case VIDIOC_S_PARM: { + struct v4l2_streamparm *parms = static_cast(arg); + if (parms->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + AutoLock locker(m_videoParamsLock); + // ::RequestEncodingParametersChangeTask + m_videoParams.frameRate.frameRateNum = parms->parm.output.timeperframe.numerator; + m_videoParams.frameRate.frameRateDenom = parms->parm.output.timeperframe.denominator; + uint32_t framerate = m_videoParams.frameRate.frameRateNum/m_videoParams.frameRate.frameRateDenom; + if (framerate * 2 < m_videoParams.intraPeriod) { + m_videoParams.intraPeriod = framerate * 2; + } + m_videoParamsChanged = true; + } + UpdateVideoParameters(); + } + break; + case VIDIOC_S_FMT: { + struct v4l2_format *format = static_cast(arg); + ASSERT(!m_streamOn[INPUT] && !m_streamOn[OUTPUT]); + if (format->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + // ::SetOutputFormat + switch (format->fmt.pix_mp.pixelformat) { + case V4L2_PIX_FMT_H264: { + m_encoder.reset(createVideoEncoder(YAMI_MIME_H264), releaseVideoEncoder); + if (!m_encoder) { + ret = -1; + break; + } + m_videoParams.size = sizeof(m_videoParams); + encodeStatus = m_encoder->getParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(encodeStatus == YAMI_SUCCESS); + m_videoParams.profile = VAProfileH264Main; + encodeStatus = m_encoder->setParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(encodeStatus == YAMI_SUCCESS); + } + break; + case V4L2_PIX_FMT_VP8: + default: + ret = -1; + break; + } + + } else if (format->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + // ::NegotiateInputFormat + ASSERT(format->fmt.pix_mp.pixelformat == V4L2_PIX_FMT_YUV420M + || format->fmt.pix_mp.pixelformat == V4L2_PIX_FMT_YUYV + || format->fmt.pix_mp.pixelformat == V4L2_PIX_FMT_NV12); + m_pixelFormat[INPUT] = format->fmt.pix_mp.pixelformat; + switch (m_pixelFormat[INPUT]) { + case V4L2_PIX_FMT_YUV420M: + m_bufferPlaneCount[INPUT] = 3; + format->fmt.pix_mp.plane_fmt[0].bytesperline = m_videoParams.resolution.width; + format->fmt.pix_mp.plane_fmt[0].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height; + format->fmt.pix_mp.plane_fmt[1].bytesperline = m_videoParams.resolution.width/2; + format->fmt.pix_mp.plane_fmt[1].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height /4; + format->fmt.pix_mp.plane_fmt[2].bytesperline = m_videoParams.resolution.width/2; + format->fmt.pix_mp.plane_fmt[2].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height /4; + break; + case V4L2_PIX_FMT_NV12: + m_bufferPlaneCount[INPUT] = 2; + format->fmt.pix_mp.plane_fmt[0].bytesperline = m_videoParams.resolution.width; + format->fmt.pix_mp.plane_fmt[0].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height; + format->fmt.pix_mp.plane_fmt[1].bytesperline = m_videoParams.resolution.width; + format->fmt.pix_mp.plane_fmt[1].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height /2; + break; + case V4L2_PIX_FMT_YUYV: + m_bufferPlaneCount[INPUT] = 1; + format->fmt.pix_mp.plane_fmt[0].bytesperline = m_videoParams.resolution.width * 2; + format->fmt.pix_mp.plane_fmt[0].sizeimage = m_videoParams.resolution.width * m_videoParams.resolution.height * 2; + break; + default: + ASSERT(0); + break; + } + ASSERT(m_encoder); + m_videoParams.resolution.width = format->fmt.pix_mp.width; + m_videoParams.resolution.height= format->fmt.pix_mp.height; + encodeStatus = m_encoder->setParameters(VideoParamsTypeCommon, &m_videoParams); + ASSERT(encodeStatus == YAMI_SUCCESS); + encodeStatus = m_encoder->getMaxOutSize(&m_maxOutputBufferSize); + ASSERT(encodeStatus == YAMI_SUCCESS); + INFO("resolution: %d x %d, m_maxOutputBufferSize: %d", m_videoParams.resolution.width, + m_videoParams.resolution.height, m_maxOutputBufferSize); + } else { + ret = -1; + ERROR("unknow type: %d of setting format VIDIOC_S_FMT", format->type); + } + } + break; + case VIDIOC_S_CROP: { + // ::SetFormats + //struct v4l2_crop *crop = static_cast(arg); + INFO("ignore crop for now (the difference between buffer size and real size)"); + } + break; + default: + ret = -1; + ERROR("unknown ioctrl command: %d", command); + break; + } + + if (ret == -1 && errno != EAGAIN) { + ERROR("ioctl failed"); + WARNING("ioctl command: %s failed", IoctlCommandString(command)); + } + + return ret; +} + + +void* V4l2Encoder::mmap (void* addr, size_t length, + int prot, int flags, unsigned int offset) +{ + uint32_t i; + ASSERT((prot == PROT_READ) | PROT_WRITE); + ASSERT(flags == MAP_SHARED); + + ASSERT(m_maxOutputBufferSize > 0); + ASSERT(length <= m_maxOutputBufferSize); + if (!m_outputBufferSpace) { + m_outputBufferSpace = static_cast(malloc(m_maxOutputBufferSize * m_maxBufferCount[OUTPUT])); + for (i=0; i + +#include "v4l2_codecbase.h" +#include "VideoEncoderInterface.h" + +using namespace YamiMediaCodec; +typedef SharedPtr < IVideoEncoder > EncoderPtr; + +class V4l2Encoder : public V4l2CodecBase +{ + public: + V4l2Encoder(); + ~V4l2Encoder() {}; + + virtual int32_t ioctl(int request, void* arg); + virtual void* mmap(void* addr, size_t length, + int prot, int flags, unsigned int offset); + + protected: + virtual bool start(); + virtual bool stop(); + virtual bool acceptInputBuffer(struct v4l2_buffer *qbuf); + virtual bool giveOutputBuffer(struct v4l2_buffer *dqbuf); + virtual bool inputPulse(uint32_t index); + virtual bool outputPulse(uint32_t &index); + + private: + bool UpdateVideoParameters(bool isInputThread=false); + EncoderPtr m_encoder; + + VideoParamsCommon m_videoParams; + Lock m_videoParamsLock; + bool m_videoParamsChanged; + + uint32_t m_maxOutputBufferSize; + uint8_t *m_outputBufferSpace; + + std::vector m_inputFrames; + std::vector m_outputFrames; + + bool m_separatedStreamHeader; + bool m_requestStreamHeader; + bool m_forceKeyFrame; +}; +#endif diff --git a/v4l2/v4l2_wrapper.cpp b/v4l2/v4l2_wrapper.cpp new file mode 100644 index 0000000..4a884f4 --- /dev/null +++ b/v4l2/v4l2_wrapper.cpp @@ -0,0 +1,313 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "v4l2_wrapper.h" +#if defined(__ENABLE_V4L2_OPS__) +#include "v4l2codec_device_ops.h" +#endif +#include "v4l2_codecbase.h" +#include +#include "common/log.h" +#include "common/lock.h" + +#include +typedef SharedPtr < V4l2CodecBase > V4l2CodecPtr; + +/**
+v4l2_wrapper implements a wrapper library for yami encoder/decoder, it translates v4l2 ioctl to yami APIs.
+There are four threads in the wrapper library.
+Two threads for v4l2 interface: one for device pool (pool thread), one for device operation (device thread: deque, enque etc)
+Two threads are internal worker to drive data input (input thread) and output (output thread) respectively.
+   - Device thread owns yami encoder before input/output thread launch and after input/output thread exit . encoder->stop() defers to device _close() instead of STREAMOFF ioctl.
+   - Dynamic encoder parameter change (bitrate/framerate etc) are accepted in device operation thread, and executed in input thread, with mutex lock
+Input thread keeps runing until: no input buffer available (from device enque buffer) or encode() fail (yami/dirver is busy).
+Input Thread is woken up by: enqued a new input buffer, output thread run once successfully, or input stream stops.
+Output thread keeps runing until: no output buffer available (from device enque buffer) or getOutput() fail (no encoded frame available from yami/driver).
+Output Thread is woken up by: enqued a new output buffer, input thread run once successfully, or output stream stops.
+Initial buffers status are at client side.
+ 
*/ + +typedef std::map CodecPtrFdMap; +static CodecPtrFdMap s_codecMap; +static YamiMediaCodec::Lock s_codecMapLock; + +V4l2CodecPtr _findCodecFromFd(int fd) +{ + V4l2CodecPtr v4l2Codec; + YamiMediaCodec::AutoLock locker(s_codecMapLock); + CodecPtrFdMap::iterator it = s_codecMap.find(fd); + + if (it != s_codecMap.end()) { + v4l2Codec = it->second; + ASSERT(fd == v4l2Codec->fd()); + } + + return v4l2Codec; +} + +int32_t YamiV4L2_Open(const char* name, int32_t flags) +{ + V4l2CodecPtr v4l2Codec = V4l2CodecBase::createCodec(name, flags); + { + YamiMediaCodec::AutoLock locker(s_codecMapLock); + s_codecMap[v4l2Codec->fd()] = v4l2Codec; + } + INFO("add encoder(fd: %d) to list", v4l2Codec->fd()); + +#if 0 // if necessary, some pre-sandbox operation goes here + // used for chrome sandbox + // preloadDriverHandle = dlopen( preloadDriverName, RTLD_NOW| RTLD_GLOBAL | RTLD_NODELETE); // RTLD_NODELETE?? + // create VaapiDisplay to make sure vaapi driver are loaded before sandbox, the display can be reused by future request + NativeDisplay nativeDisplay; + nativeDisplay.type = NATIVE_DISPLAY_DRM; + s_display = YamiMediaCodec::VaapiDisplay::create(nativeDisplay); +#endif + return v4l2Codec->fd(); +} + +int32_t YamiV4L2_Close(int32_t fd) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + bool ret = true; + + ASSERT(v4l2Codec); + ret &= v4l2Codec->close(); + ASSERT(ret); + { + YamiMediaCodec::AutoLock locker(s_codecMapLock); + ret &= s_codecMap.erase(fd); + } + INFO("remove encoder(fd:%d) from list, ret: %d", fd, ret); + ASSERT(ret); + + return ret ? 0 : -1; +} + +// FIXME, if chromeos change to SetParameter as well, we can drop this func +int32_t YamiV4L2_FrameMemoryType(int32_t fd, VideoDataMemoryType memory_type) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->setFrameMemoryType(memory_type); +} + +int32_t YamiV4L2_SvcT(int32_t fd, bool enable) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->setSvcT(enable); +} + +int32_t YamiV4L2_SetThumbnailMode(int32_t fd, bool enable) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->setThumbnailMode(enable); +} + +int32_t YamiV4L2_Ioctl(int32_t fd, int command, void* arg) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->ioctl(command, arg); +} + +int32_t YamiV4L2_Poll(int32_t fd, bool poll_device, bool* event_pending) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->poll(poll_device, event_pending); + } + +int32_t YamiV4L2_SetDevicePollInterrupt(int32_t fd) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->setDeviceEvent(1); +} + +int32_t YamiV4L2_ClearDevicePollInterrupt(int32_t fd) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->clearDeviceEvent(1); +} + +void* YamiV4L2_Mmap(void* addr, size_t length, + int prot, int flags, int fd, unsigned int offset) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->mmap(addr, length, prot, flags, offset); +} + +int32_t YamiV4L2_Munmap(void* addr, size_t length) +{ + return 0; +} + +#if defined(__ENABLE_WAYLAND__) +int32_t YamiV4L2_SetWaylandDisplay(int32_t fd, struct wl_display* wlDisplay) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + bool ret = true; + + ASSERT(v4l2Codec); + ret &= v4l2Codec->setWaylandDisplay(wlDisplay); + + return ret; +} +#endif //__ENABLE_WAYLAND__ + +#if defined(__ENABLE_X11__) +int32_t YamiV4L2_SetXDisplay(int32_t fd, Display *x11Display) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + bool ret = true; + + ASSERT(v4l2Codec); + DEBUG("x11display: %p", x11Display); + ret &= v4l2Codec->setXDisplay(x11Display); + + return ret; +} +#endif //__ENABLE_X11__ + +#if defined(__ENABLE_EGL__) +int32_t YamiV4L2_UseEglImage(int fd, /*EGLDisplay*/void* eglDisplay, /*EGLContext*/void* eglContext, unsigned int bufferIndex, void* eglImage) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + return v4l2Codec->useEglImage(eglDisplay, eglContext, bufferIndex, eglImage); +} +#endif //__ENABLE_EGL__ + +int32_t YamiV4L2_SetDrmFd(int32_t fd, int drm_fd) +{ + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + bool ret = true; + + ASSERT(v4l2Codec); + ret &= v4l2Codec->setDrmFd(drm_fd); + + return ret; +} + +#if defined(__ENABLE_V4L2_OPS__) +extern "C" int32_t YamiV4L2_SetParameter(int32_t fd, const char* key, const char* value); +int32_t YamiV4L2_SetParameter(int32_t fd, const char* key, const char* value) +{ + int ret = -1; + + if (!key || !value) { + ERROR("invalue parameter\n"); + return -1; + } + + V4l2CodecPtr v4l2Codec = _findCodecFromFd(fd); + ASSERT(v4l2Codec); + + // FIXME, usually, it can be detected by v4l2_requestbuffers.memory + // however, chrome always set it to MMAP even for egl/texture usage + if (!strcmp(key, "frame-memory-type")) { + VideoDataMemoryType memoryType; + if (!strcmp(value, "raw-data")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_RAW_COPY; + } else if (!strcmp(value, "drm-name")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME; + } else if (!strcmp(value, "dma-buf")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_DMA_BUF; + } else if (!strcmp(value, "surface-id")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_SURFACE_ID; + } else if (!strcmp(value, "android-buffer-handle")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_ANDROID_BUFFER_HANDLE; + } + else if (!strcmp(value, "external-dma-buf")) { + memoryType = VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF; + } else { + ERROR("unknow output frame memory type: %s\n", value); + return -1; + } + ret = v4l2Codec->setFrameMemoryType(memoryType); +#ifdef __ENABLE_WAYLAND__ + } + else if (!strcmp(key, "wayland-display")) { + uintptr_t ptr = (uintptr_t)atoll(value); + struct wl_display* wlDisplay = (struct wl_display*)ptr; + DEBUG("wlDisplay: %p", wlDisplay); + ret = v4l2Codec->setWaylandDisplay(wlDisplay); +#endif //__ENABLE_WAYLAND__ +#if defined(__ENABLE_X11__) + } else if (!strcmp(key, "x11-display")) { + uintptr_t ptr = (uintptr_t)atoll(value); + Display* x11Display = (Display*)ptr; + DEBUG("x11Display: %p", x11Display); + ret = v4l2Codec->setXDisplay(x11Display); +#endif //__ENABLE_X11__ + } else if(!(strcmp(key, "encode-mode"))) { + if (!strcmp(value, "svct")) { + ret = v4l2Codec->setSvcT(true); + } + } else if (!(strcmp(key, "decode-mode"))) { + if (!strcmp(value, "thumbnail")) { + ret = v4l2Codec->setThumbnailMode(true); + } + } else { + ERROR("unsupported parameter key: %s\n", key); + } + + return ret; +} + + +bool v4l2codecOperationInit(V4l2CodecOps *opFuncs) +{ + if (!opFuncs) + return false; + + int isVersionMatch = 0; + IS_V4L2CODEC_OPS_VERSION_MATCH(opFuncs->mVersion, isVersionMatch); + if (!isVersionMatch) { + ERROR("V4l2CodecOps interface version doesn't match\n"); + return false; + } + ASSERT(opFuncs->mSize == sizeof(V4l2CodecOps)); + + memset(opFuncs->mVendorString, 0, V4L2CODEC_VENDOR_STRING_SIZE); + strncpy(opFuncs->mVendorString, "yami", V4L2CODEC_VENDOR_STRING_SIZE-1); + +#define V4L2_DLSYM_OR_RETURN_ON_ERROR(name) opFuncs->m##name##Func = YamiV4L2_##name + + V4L2_DLSYM_OR_RETURN_ON_ERROR(Open); + V4L2_DLSYM_OR_RETURN_ON_ERROR(Close); + V4L2_DLSYM_OR_RETURN_ON_ERROR(Ioctl); + V4L2_DLSYM_OR_RETURN_ON_ERROR(Poll); + V4L2_DLSYM_OR_RETURN_ON_ERROR(SetDevicePollInterrupt); + V4L2_DLSYM_OR_RETURN_ON_ERROR(ClearDevicePollInterrupt); + V4L2_DLSYM_OR_RETURN_ON_ERROR(Mmap); + V4L2_DLSYM_OR_RETURN_ON_ERROR(Munmap); + V4L2_DLSYM_OR_RETURN_ON_ERROR(SetParameter); +#if defined(__ENABLE_EGL__) + V4L2_DLSYM_OR_RETURN_ON_ERROR(UseEglImage); +#endif +#undef V4L2_DLSYM_OR_RETURN_ON_ERROR + + return true; +} +#endif // __ENABLE_V4L2_OPS__ diff --git a/vaapi/Android.mk b/vaapi/Android.mk new file mode 100644 index 0000000..34500dc --- /dev/null +++ b/vaapi/Android.mk @@ -0,0 +1,31 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + vaapipicture.cpp \ + VaapiBuffer.cpp \ + VaapiSurface.cpp\ + VaapiUtils.cpp \ + vaapidisplay.cpp \ + vaapicontext.cpp \ + vaapisurfaceallocator.cpp \ + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libva \ + libva-android \ + libc++ \ + +LOCAL_CPPFLAGS += \ + -frtti + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_vaapi +include $(BUILD_STATIC_LIBRARY) diff --git a/vaapi/Makefile.am b/vaapi/Makefile.am new file mode 100644 index 0000000..46faf1c --- /dev/null +++ b/vaapi/Makefile.am @@ -0,0 +1,57 @@ +libyami_vaapi_source_c = \ + vaapipicture.cpp \ + VaapiBuffer.cpp \ + VaapiSurface.cpp\ + VaapiUtils.cpp \ + vaapidisplay.cpp \ + vaapicontext.cpp \ + vaapisurfaceallocator.cpp \ + $(NULL) + +libyami_vaapi_source_h_priv = \ + vaapipicture.h \ + VaapiBuffer.h \ + VaapiSurface.h \ + VaapiUtils.h \ + vaapidisplay.h \ + vaapicontext.h \ + vaapistreamable.h \ + vaapisurfaceallocator.h \ + $(NULL) + +libyami_vaapi_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + $(NULL) + +if ENABLE_X11 +libyami_vaapi_ldflags += $(LIBVA_X11_LIBS) $(X11_LIBS) +endif + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_vaapi_cppflags = \ + $(LIBVA_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +noinst_LTLIBRARIES = libyami_vaapi.la +libyami_vaapiincludedir = ${includedir}/libyami +libyami_vaapiinclude_HEADERS = $(libyami_vaapi_source_h) +libyami_vaapi_la_SOURCES = $(libyami_vaapi_source_c) +libyami_vaapi_la_LDFLAGS = $(libyami_vaapi_ldflags) $(AM_LDFLAGS) +libyami_vaapi_la_CPPFLAGS = $(libyami_vaapi_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in + + diff --git a/vaapi/Makefile.unittest b/vaapi/Makefile.unittest new file mode 100644 index 0000000..c9914ef --- /dev/null +++ b/vaapi/Makefile.unittest @@ -0,0 +1,36 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + vaapidisplay_unittest.cpp \ + $(NULL) + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_vaapi.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +if ENABLE_X11 +unittest_LDADD += $(X11_LIBS) +endif + +unittest_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest + $(builddir)/unittest + diff --git a/vaapi/VaapiBuffer.cpp b/vaapi/VaapiBuffer.cpp new file mode 100644 index 0000000..9246cce --- /dev/null +++ b/vaapi/VaapiBuffer.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "VaapiBuffer.h" + +#include "VaapiUtils.h" +#include "vaapicontext.h" +#include "vaapidisplay.h" + +namespace YamiMediaCodec { + +BufObjectPtr VaapiBuffer::create(const ContextPtr& context, + VABufferType type, + uint32_t size, + const void* data, + void** mapped) +{ + BufObjectPtr buf; + if (!size || !context || !context->getDisplay()){ + ERROR("vaapibuffer: can't create buffer"); + return buf; + } + DisplayPtr display = context->getDisplay(); + VABufferID id; + VAStatus status = vaCreateBuffer(display->getID(), context->getID(), + type, size, 1, (void*)data, &id); + if (!checkVaapiStatus(status, "vaCreateBuffer")) + return buf; + buf.reset(new VaapiBuffer(display, id, size)); + if (mapped) { + *mapped = buf->map(); + if (!*mapped) + buf.reset(); + } + return buf; +} + +void* VaapiBuffer::map() +{ + if (!m_data) { + VAStatus status = vaMapBuffer(m_display->getID(), m_id, &m_data); + if (!checkVaapiStatus(status, "vaMapBuffer")) { + m_data = NULL; + } + } + return m_data; +} + +void VaapiBuffer::unmap() +{ + if (m_data) { + checkVaapiStatus(vaUnmapBuffer(m_display->getID(), m_id), "vaUnmapBuffer"); + m_data = NULL; + } +} + +uint32_t VaapiBuffer::getSize() +{ + return m_size; +} + +VABufferID VaapiBuffer::getID() +{ + return m_id; +} + +VaapiBuffer::VaapiBuffer(const DisplayPtr& display, VABufferID id, uint32_t size) + : m_display(display) + , m_id(id) + , m_data(NULL) + , m_size(size) +{ +} + +VaapiBuffer::~VaapiBuffer() +{ + unmap(); + checkVaapiStatus(vaDestroyBuffer(m_display->getID(), m_id), "vaDestroyBuffer"); +} +} diff --git a/vaapi/VaapiBuffer.h b/vaapi/VaapiBuffer.h new file mode 100644 index 0000000..326f666 --- /dev/null +++ b/vaapi/VaapiBuffer.h @@ -0,0 +1,73 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VaapiBuffer_h +#define VaapiBuffer_h + +#include "common/NonCopyable.h" +#include "vaapiptrs.h" + +#include +#include + +namespace YamiMediaCodec { + +class VaapiBuffer { +public: + static BufObjectPtr create(const ContextPtr&, + VABufferType, + uint32_t size, + const void* data = 0, + void** mapped = 0); + + template + static BufObjectPtr create(const ContextPtr&, + VABufferType, T*& mapped); + + void* map(); + void unmap(); + uint32_t getSize(); + VABufferID getID(); + ~VaapiBuffer(); + +private: + VaapiBuffer(const DisplayPtr&, VABufferID id, uint32_t size); + DisplayPtr m_display; + VABufferID m_id; + void* m_data; + uint32_t m_size; + DISALLOW_COPY_AND_ASSIGN(VaapiBuffer); +}; + +template +BufObjectPtr VaapiBuffer::create(const ContextPtr& context, + VABufferType type, T*& mapped) +{ + BufObjectPtr p = create(context, type, sizeof(T), NULL, (void**)&mapped); + if (p) { + if (mapped) { + memset(mapped, 0, sizeof(T)); + } + else { + //bug + p.reset(); + } + } + return p; +} +} + +#endif //VaapiBuffer_h diff --git a/vaapi/VaapiSurface.cpp b/vaapi/VaapiSurface.cpp new file mode 100644 index 0000000..a8143e1 --- /dev/null +++ b/vaapi/VaapiSurface.cpp @@ -0,0 +1,81 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "VaapiSurface.h" + +#include + +namespace YamiMediaCodec { + +VaapiSurface::VaapiSurface(intptr_t id, uint32_t width, uint32_t height, uint32_t fourcc) +{ + m_frame.reset(new VideoFrame); + memset(m_frame.get(), 0, sizeof(VideoFrame)); + m_frame->surface = id; + m_frame->crop.x = m_frame->crop.y = 0; + m_frame->crop.width = width; + m_frame->crop.height = height; + m_frame->fourcc = fourcc; + m_width = width; + m_height = height; +} + +VaapiSurface::VaapiSurface(const SharedPtr& frame) +{ + m_frame = frame; + + VideoRect& r = m_frame->crop; + m_width = r.x + r.width; + m_height = r.y + r.height; +} + +VASurfaceID VaapiSurface::getID() +{ + return (VASurfaceID)m_frame->surface; +} + +bool VaapiSurface::setCrop(uint32_t x, uint32_t y, uint32_t width, uint32_t height) +{ + VideoRect& r = m_frame->crop; + + if (x + width > m_width + || y + height > m_height) + return false; + r.x = x; + r.y = y; + r.width = width; + r.height = height; + return true; +} + +void VaapiSurface::getCrop(uint32_t& x, uint32_t& y, uint32_t& width, uint32_t& height) +{ + const VideoRect& r = m_frame->crop; + x = r.x; + y = r.y; + width = r.width; + height = r.height; +} + +uint32_t VaapiSurface::getFourcc() +{ + return m_frame->fourcc; +} +} diff --git a/vaapi/VaapiSurface.h b/vaapi/VaapiSurface.h new file mode 100644 index 0000000..be60320 --- /dev/null +++ b/vaapi/VaapiSurface.h @@ -0,0 +1,49 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VaapiSurface_h +#define VaapiSurface_h + +#include "common/NonCopyable.h" +#include "VideoCommonDefs.h" +#include +#include + +namespace YamiMediaCodec { + +class VaapiSurface { + friend class VaapiDecoderBase; + +public: + VaapiSurface(intptr_t id, uint32_t width, uint32_t height, uint32_t fourcc); + VaapiSurface(const SharedPtr&); + + VASurfaceID getID(); + + bool setCrop(uint32_t x, uint32_t y, uint32_t width, uint32_t height); + void getCrop(uint32_t& x, uint32_t& y, uint32_t& width, uint32_t& height); + uint32_t getFourcc(); + +private: + SharedPtr m_frame; + uint32_t m_width; + uint32_t m_height; + DISALLOW_COPY_AND_ASSIGN(VaapiSurface); +}; + +} + +#endif //VaapiSurface_h diff --git a/vaapi/VaapiUtils.cpp b/vaapi/VaapiUtils.cpp new file mode 100644 index 0000000..accbe45 --- /dev/null +++ b/vaapi/VaapiUtils.cpp @@ -0,0 +1,150 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "interface/VideoCommonDefs.h" +#include "VaapiUtils.h" + +namespace YamiMediaCodec { + +uint8_t* mapSurfaceToImage(VADisplay display, intptr_t surface, VAImage& image) +{ + uint8_t* p = NULL; + VAStatus status = vaDeriveImage(display, (VASurfaceID)surface, &image); + if (!checkVaapiStatus(status, "vaDeriveImage")) + return NULL; + status = vaMapBuffer(display, image.buf, (void**)&p); + if (!checkVaapiStatus(status, "vaMapBuffer")) { + checkVaapiStatus(vaDestroyImage(display, image.image_id), "vaDestroyImage"); + return NULL; + } + return p; +} + +void unmapImage(VADisplay display, const VAImage& image) +{ + checkVaapiStatus(vaUnmapBuffer(display, image.buf), "vaUnmapBuffer"); + checkVaapiStatus(vaDestroyImage(display, image.image_id), "vaDestroyImage"); +} + +//return rt format, 0 for unsupported +uint32_t getRtFormat(uint32_t fourcc) +{ + switch (fourcc) { + case YAMI_FOURCC_Y800: + return VA_RT_FORMAT_YUV400; + case YAMI_FOURCC_NV12: + case YAMI_FOURCC_I420: + case YAMI_FOURCC_YV12: + case YAMI_FOURCC_IMC3: + return VA_RT_FORMAT_YUV420; + case YAMI_FOURCC_422H: + case YAMI_FOURCC_422V: + case YAMI_FOURCC_YUY2: + return VA_RT_FORMAT_YUV422; + case YAMI_FOURCC_444P: + return VA_RT_FORMAT_YUV444; +#if VA_CHECK_VERSION(0, 38, 1) + case YAMI_FOURCC_P010: + return VA_RT_FORMAT_YUV420_10BPP; +#endif + case YAMI_FOURCC_RGBX: + case YAMI_FOURCC_RGBA: + case YAMI_FOURCC_BGRX: + case YAMI_FOURCC_BGRA: + case YAMI_FOURCC_XRGB: + case YAMI_FOURCC_ARGB: + case YAMI_FOURCC_XBGR: + case YAMI_FOURCC_ABGR: + return VA_RT_FORMAT_RGB32; + case YAMI_FOURCC_RGB565: + return VA_RT_FORMAT_RGB16; +#ifdef VA_RT_FORMAT_RGB32_10BPP + case YAMI_FOURCC_R210: + return VA_RT_FORMAT_RGB32_10BPP; +#endif + } + ERROR("get rt format for %.4s failed", (char*)&fourcc); + return 0; +} + +bool dumpSurface(VADisplay display, intptr_t surface) +{ + static uint32_t _frameCount = 0; + const uint8_t* p = NULL; + uint32_t fourcc = 0; + const char* ptrC = (char*)(&fourcc); + char fileName[256]; + VAImage image; + static FILE* fp = NULL; + bool useSingleFile = true; + + memset(&image, 0, sizeof(VAImage)); + p = mapSurfaceToImage(display, surface, image); + fourcc = image.format.fourcc; + + if (fourcc != VA_FOURCC_NV12) { + WARNING("format: (%c%c%c%c, 0x%x) is not support to dump surface", ptrC[0], ptrC[1], ptrC[2], ptrC[3], fourcc); + return false; + } + if (!image.width || !image.height) { + WARNING("invalid surface/image width: %d, height: %d", image.width, image.height); + return false; + } + + if (!fp) { + memset(fileName, 0, sizeof(fileName)); + if (useSingleFile) { + sprintf(fileName, "%s/%c%c%c%c_%dx%d", "/tmp/yami", ptrC[0], ptrC[1], ptrC[2], ptrC[3], image.width, image.height); + } + else { + sprintf(fileName, "%s/%04d_%c%c%c%c_%dx%d", "/tmp/yami", _frameCount, ptrC[0], ptrC[1], ptrC[2], ptrC[3], image.width, image.height); + _frameCount++; + } + fp = fopen(fileName, "w+"); + } + if (!fp) + return false; + + int widths[3], heights[3]; + widths[0] = image.width; + widths[1] = ((image.width + 1) / 2) * 2; + widths[2] = 0; + heights[0] = image.height; + heights[1] = (image.height + 1) / 2; + heights[2] = 0; + + uint32_t plane = 0; + for (plane = 0; plane < image.num_planes; plane++) { + int h = 0; + for (h = 0; h < heights[plane]; h++) { + fwrite(p + image.offsets[plane] + image.pitches[plane] * h, widths[plane], 1, fp); + } + } + + if (!useSingleFile) { + fclose(fp); + fp = NULL; + } + + unmapImage(display, image); + + return true; +} +} diff --git a/vaapi/VaapiUtils.h b/vaapi/VaapiUtils.h new file mode 100644 index 0000000..da35f8c --- /dev/null +++ b/vaapi/VaapiUtils.h @@ -0,0 +1,44 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VaapiUtils_h +#define VaapiUtils_h + +#include "common/log.h" +#include + +namespace YamiMediaCodec { + +uint8_t* mapSurfaceToImage(VADisplay display, intptr_t surface, VAImage& image); + +void unmapImage(VADisplay display, const VAImage& image); + +//return rt format, 0 for unsupported +uint32_t getRtFormat(uint32_t fourcc); +bool dumpSurface(VADisplay display, intptr_t surface); + +#define checkVaapiStatus(status, prompt) \ + ( \ + { \ + bool ret; \ + ret = (status == VA_STATUS_SUCCESS); \ + if (!ret) \ + ERROR("%s: %s", prompt, vaErrorStr(status)); \ + ret; \ + }) +} + +#endif //VaapiUtils_h diff --git a/vaapi/unittest_main.cpp b/vaapi/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/vaapi/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/vaapi/vaapicontext.cpp b/vaapi/vaapicontext.cpp new file mode 100644 index 0000000..8e1600d --- /dev/null +++ b/vaapi/vaapicontext.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapi/vaapicontext.h" + +#include "common/log.h" +#include "common/common_def.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/VaapiUtils.h" +#include "vaapi/vaapistreamable.h" +#include +#include + +namespace YamiMediaCodec{ +using std::vector; +static const VAProfile h264ProfileList[] = {VAProfileH264ConstrainedBaseline, VAProfileH264Main, VAProfileH264High}; + +//Driver may declare support higher profile but don't support lower profile. +//In this case, higher profile should be created. +//Note: creating higher va profile won't affect the detail encoding/decoding process of libva driver. +static bool checkH264Profile(VAProfile& profile, vector& profileList) +{ + vectorh264Profiles(h264ProfileList, h264ProfileList + N_ELEMENTS(h264ProfileList)); + vector::iterator start = std::find(h264Profiles.begin(), h264Profiles.end(), profile); + vector::iterator result = std::find_first_of(profileList.begin(), profileList.end(), start, h264Profiles.end()); + + if (result != profileList.end()){ + profile = *result; + return true; + } + + return false; +} + +static bool checkProfileCompatible(const DisplayPtr& display, VAProfile& profile) +{ + int maxNumProfiles, numProfiles; + VAStatus vaStatus; + + maxNumProfiles = vaMaxNumProfiles(display->getID()); + + vector profileList(maxNumProfiles); + + vaStatus = vaQueryConfigProfiles(display->getID(), &profileList[0], &numProfiles); + if (!checkVaapiStatus(vaStatus, "vaQueryConfigProfiles")) + return false; + assert((numProfiles > 0) && (numProfiles <= maxNumProfiles)); + + profileList.resize(numProfiles); + + if (profile == VAProfileH264ConstrainedBaseline || profile == VAProfileH264Main){ + if (!checkH264Profile(profile, profileList)) + return false; + } else if (!std::count(profileList.begin(), profileList.end(), profile)) + return false; + + return true; +} + +YamiStatus VaapiConfig::create(const DisplayPtr& display, + VAProfile profile, VAEntrypoint entry, + VAConfigAttrib* attribList, int numAttribs, + ConfigPtr& confg) +{ + if (!display) + return YAMI_FAIL; + VAStatus vaStatus; + VAConfigID config; + + if (!checkProfileCompatible(display, profile)){ + ERROR("Unsupported profile %s.\n", toString(profile).c_str()); + return YAMI_UNSUPPORTED; + } + + vaStatus = vaCreateConfig(display->getID(), profile, entry, attribList, numAttribs, &config); + + if (!checkVaapiStatus(vaStatus, "vaCreateConfig ")) { + ERROR("Unable to create config for profile: %s and entrypoint: %s.\n", + toString(profile).c_str(), toString(entry).c_str()); + return YAMI_FAIL; + } + confg.reset(new VaapiConfig(display, config)); + return YAMI_SUCCESS; +} + +VaapiConfig::VaapiConfig(const DisplayPtr& display, VAConfigID config) +:m_display(display), m_config(config) +{ +} + +VaapiConfig::~VaapiConfig() +{ + vaDestroyConfig(m_display->getID(), m_config); +} + +ContextPtr VaapiContext::create(const ConfigPtr& config, + int width,int height,int flag, + VASurfaceID *render_targets, + int num_render_targets) +{ + ContextPtr ret; + if (!config) { + ERROR("No display"); + return ret; + } + VAStatus vaStatus; + VAContextID context; + vaStatus = vaCreateContext(config->m_display->getID(), config->m_config, + width, height, flag, + render_targets, num_render_targets, &context); + if (!checkVaapiStatus(vaStatus, "vaCreateContext ")) + return ret; + ret.reset(new VaapiContext(config, context)); + return ret; +} + +VaapiContext::VaapiContext(const ConfigPtr& config, VAContextID context) +:m_config(config), m_context(context) +{ +} + +VaapiContext::~VaapiContext() +{ + vaDestroyContext(m_config->m_display->getID(), m_context); +} +} diff --git a/vaapi/vaapicontext.h b/vaapi/vaapicontext.h new file mode 100644 index 0000000..29644ee --- /dev/null +++ b/vaapi/vaapicontext.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapicontext_h +#define vaapicontext_h + +#include "common/NonCopyable.h" +#include "VideoCommonDefs.h" +#include "vaapi/vaapiptrs.h" +#include + +namespace YamiMediaCodec{ +class VaapiConfig +{ +friend class VaapiContext; +public: + static YamiStatus create(const DisplayPtr&, VAProfile, VAEntrypoint, + VAConfigAttrib* attribList, int numAttribs, ConfigPtr& confg); + ~VaapiConfig(); +private: + VaapiConfig(const DisplayPtr&, VAConfigID); + DisplayPtr m_display; + VAConfigID m_config; + DISALLOW_COPY_AND_ASSIGN(VaapiConfig); +}; + +class VaapiContext +{ +public: + static ContextPtr create(const ConfigPtr&, + int width,int height,int flag, + VASurfaceID *render_targets, + int num_render_targets); + VAContextID getID() const { return m_context; } + DisplayPtr getDisplay() const { return m_config->m_display; } + + ~VaapiContext(); +private: + VaapiContext(const ConfigPtr&, VAContextID); + ConfigPtr m_config; + VAContextID m_context; + DISALLOW_COPY_AND_ASSIGN(VaapiContext); +}; +} +#endif diff --git a/vaapi/vaapidisplay.cpp b/vaapi/vaapidisplay.cpp new file mode 100644 index 0000000..8974910 --- /dev/null +++ b/vaapi/vaapidisplay.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapi/vaapidisplay.h" +#include +#include +#include +#include +#include +#include "common/log.h" +#include "common/lock.h" +#include "vaapi/VaapiUtils.h" +#include + +using std::list; +/** +1. client and yami shares the same display when it provides both native + display (x11 Display or drm fd) and display type in setNativeDisplay(). + client owns the native display +2. when client set native display type only, yami will create a native + display and owns it. +3. when client doesn't set any native display, or set display type to + NATIVE_DISPLAY_AUTO; yami will try to open a x11 display first. if fail, + drm display will try next + +4. A x11 display is compatible to drm display, while not reverse. + it means, when there is a VADisplay created from x11 display already , + yami will not create a new display when drm display is requested, + simplely reuse the VADisplay. +*/ + +//helper function +namespace YamiMediaCodec{ +static bool vaInit(VADisplay vaDisplay) +{ + int majorVersion, minorVersion; + VAStatus vaStatus; + vaStatus= vaInitialize(vaDisplay, &majorVersion, &minorVersion); + return checkVaapiStatus(vaStatus, "vaInitialize"); +} + +class NativeDisplayBase { + public: + NativeDisplayBase() :m_handle(0) { }; + virtual ~NativeDisplayBase() {}; + virtual bool initialize(const NativeDisplay& display) = 0; + virtual bool isCompatible (const NativeDisplay& display) = 0; + intptr_t nativeHandle() {return m_handle;}; + + protected: + virtual bool acceptValidExternalHandle(const NativeDisplay& display) { + if (display.handle && display.handle != -1) { + m_handle = display.handle; + m_selfCreated = false; + return true; + } + return false; + } + intptr_t m_handle; + bool m_selfCreated; + + private: + DISALLOW_COPY_AND_ASSIGN(NativeDisplayBase); +}; + +bool isInvalidDrmHandle(int handle) +{ + return handle == 0 || handle == -1; +} + +#if defined(__ENABLE_X11__) +class NativeDisplayX11 : public NativeDisplayBase{ + public: + NativeDisplayX11() :NativeDisplayBase(){ }; + virtual ~NativeDisplayX11() { + if (m_selfCreated && m_handle) + XCloseDisplay((Display*)(m_handle)); + }; + + virtual bool initialize (const NativeDisplay& display) { + ASSERT(display.type == NATIVE_DISPLAY_X11 || display.type == NATIVE_DISPLAY_AUTO); + + if (acceptValidExternalHandle(display)) + return true; + + m_handle = (intptr_t)XOpenDisplay(NULL); + m_selfCreated = true; + return (Display*)m_handle != NULL; + }; + + virtual bool isCompatible(const NativeDisplay& display) { + if (display.type == NATIVE_DISPLAY_AUTO) + return true; + if (display.type == NATIVE_DISPLAY_DRM) { + //invalid drm handle means any drm display is acceptable. + if (isInvalidDrmHandle(display.handle)) + return true; + } + if (display.type == NATIVE_DISPLAY_X11 && (!display.handle || display.handle == m_handle)) + return true; + return false; + } +}; +#endif +class NativeDisplayDrm : public NativeDisplayBase{ + public: + NativeDisplayDrm() :NativeDisplayBase(){ }; + virtual ~NativeDisplayDrm() { + if (m_selfCreated && m_handle && m_handle != -1) + ::close(m_handle); + }; + virtual bool initialize (const NativeDisplay& display) { + ASSERT(display.type == NATIVE_DISPLAY_DRM || display.type == NATIVE_DISPLAY_AUTO); + + if (acceptValidExternalHandle(display)) + return true; + + m_handle = -1; + const char* device_env = getenv("VA_DRM_DEVICE"); + if (device_env) + m_handle = open(device_env, O_RDWR); + if (m_handle < 0) + m_handle = open("/dev/dri/renderD128", O_RDWR); + if (m_handle < 0) + m_handle = open("/dev/dri/card0", O_RDWR); + m_selfCreated = true; + return m_handle != -1; + }; + + bool isCompatible(const NativeDisplay& display) { + if (display.type == NATIVE_DISPLAY_AUTO) + return true; + if (display.type != NATIVE_DISPLAY_DRM) + return false; + if (isInvalidDrmHandle(display.handle) || display.handle == m_handle) + return true; + return false; + } +}; + +class NativeDisplayVADisplay : public NativeDisplayBase{ + public: + NativeDisplayVADisplay() :NativeDisplayBase(){ }; + ~NativeDisplayVADisplay() {}; + virtual bool initialize (const NativeDisplay& display) { + ASSERT(display.type == NATIVE_DISPLAY_VA); + + if (acceptValidExternalHandle(display)) + return true; + return vaDisplayIsValid((VADisplay)display.handle); + }; + + bool isCompatible(const NativeDisplay& display) { + if (display.type == NATIVE_DISPLAY_AUTO) + return true; + return display.type == NATIVE_DISPLAY_VA && display.handle == m_handle; + } +}; + +typedef SharedPtr NativeDisplayPtr; + +bool VaapiDisplay::isCompatible(const NativeDisplay& other) +{ + return m_nativeDisplay->isCompatible(other); +} + +VaapiDisplay::~VaapiDisplay() +{ + if (!DynamicPointerCast(m_nativeDisplay)) { + vaTerminate(m_vaDisplay); + } +} + +bool VaapiDisplay::setRotation(int degree) +{ + VAStatus vaStatus; + VADisplayAttribute* attrList = NULL; + VADisplayAttribute rotate; + int i, numAttributes; + rotate.type = VADisplayAttribRotation; + rotate.value = VA_ROTATION_NONE; + if (degree == 0) //no need to set rotation when degree is zero + return true; + else if (degree == 90) + rotate.value = VA_ROTATION_90; + else if (degree == 180) + rotate.value = VA_ROTATION_180; + else if (degree == 270) + rotate.value = VA_ROTATION_270; + + /* should query before set display attributres */ + vaStatus = vaQueryDisplayAttributes(m_vaDisplay, attrList, &numAttributes); + if (!checkVaapiStatus(vaStatus, "vaQueryDisplayAttributes") || !attrList) + return false; + + for (i = 0; i < numAttributes; i++) { + if (attrList[i].type == VADisplayAttribRotation) + break; + } + + if ((i == numAttributes) || !(attrList[i].flags & VA_DISPLAY_ATTRIB_SETTABLE) ) + return false; + + vaStatus = vaSetDisplayAttributes(m_vaDisplay, &rotate, 1); + if (!checkVaapiStatus(vaStatus, "vaSetDisplayAttributes")) + return false; + return true; + +} + +const VAImageFormat * +VaapiDisplay::getVaFormat(uint32_t fourcc) +{ + AutoLock locker(m_lock); + size_t i; + + if (m_vaImageFormats.empty()) { + VAStatus vaStatus; + int numImageFormats; + numImageFormats = vaMaxNumImageFormats(m_vaDisplay); + if (numImageFormats == 0) + return NULL; + + m_vaImageFormats.reserve(numImageFormats); + m_vaImageFormats.resize(numImageFormats); + + vaStatus = vaQueryImageFormats(m_vaDisplay, &m_vaImageFormats[0], &numImageFormats); + checkVaapiStatus(vaStatus, "vaQueryImageFormats()"); + for (i=0; i< m_vaImageFormats.size(); i++) + DEBUG_FOURCC("supported image format: ", m_vaImageFormats[i].fourcc); + } + + for (i = 0; i < m_vaImageFormats.size(); i++) { + VAImageFormat vaImageFormat = m_vaImageFormats[i]; + if (vaImageFormat.fourcc == fourcc) + return &m_vaImageFormats[i]; + } + return NULL; +} + +//display cache +class DisplayCache +{ +public: + static SharedPtr getInstance(); + DisplayPtr createDisplay(const NativeDisplay& nativeDisplay); + + ~DisplayCache() {} +private: + DisplayCache() {} + + list > m_cache; + YamiMediaCodec::Lock m_lock; +}; + +SharedPtr DisplayCache::getInstance() +{ + static SharedPtr cache; + if (!cache) { + SharedPtr temp(new DisplayCache); + cache = temp; + } + return cache; +} + +bool expired(const WeakPtr& weak) +{ + return !weak.lock(); +} + +DisplayPtr DisplayCache::createDisplay(const NativeDisplay& nativeDisplay) +{ + NativeDisplayPtr nativeDisplayObj; + VADisplay vaDisplay = NULL; + DisplayPtr vaapiDisplay; + YamiMediaCodec::AutoLock locker(m_lock); + + m_cache.remove_if(expired); + + //lockup first + list >::iterator it; + for (it = m_cache.begin(); it != m_cache.end(); ++it) { + vaapiDisplay = (*it).lock(); + if (vaapiDisplay->isCompatible(nativeDisplay)) { + return vaapiDisplay; + } + } + vaapiDisplay.reset(); + + //crate new one + DEBUG("nativeDisplay: (type : %d), (handle : %" PRIxPTR ")", nativeDisplay.type, nativeDisplay.handle); + + switch (nativeDisplay.type) { + case NATIVE_DISPLAY_AUTO: +#if defined(__ENABLE_X11__) + case NATIVE_DISPLAY_X11: + nativeDisplayObj.reset (new NativeDisplayX11()); + if (nativeDisplayObj && nativeDisplayObj->initialize(nativeDisplay)) + vaDisplay = vaGetDisplay((Display*)(nativeDisplayObj->nativeHandle())); + if (vaDisplay) + INFO("use vaapi x11 backend"); + if(vaDisplay || nativeDisplay.type == NATIVE_DISPLAY_X11) + break; + INFO("try to init va with x11 display (%p) but failed", (Display*)(nativeDisplayObj->nativeHandle())); + // NATIVE_DISPLAY_AUTO continue, no break +#endif + case NATIVE_DISPLAY_DRM: + nativeDisplayObj.reset (new NativeDisplayDrm()); + if (nativeDisplayObj && nativeDisplayObj->initialize(nativeDisplay)) +#ifndef ANDROID + vaDisplay = vaGetDisplayDRM(nativeDisplayObj->nativeHandle()); +#endif + INFO("use vaapi drm backend"); + break; + case NATIVE_DISPLAY_VA: + nativeDisplayObj.reset (new NativeDisplayVADisplay()); + if (nativeDisplayObj && nativeDisplayObj->initialize(nativeDisplay)) + vaDisplay = (VADisplay)nativeDisplayObj->nativeHandle(); + INFO("use vaapi va backend"); + break; + default: + break; + } + + if (vaDisplay == NULL) { + ERROR("vaGetDisplay failed."); + return vaapiDisplay; + } + + if (nativeDisplay.type == NATIVE_DISPLAY_VA || vaInit(vaDisplay)) { + DisplayPtr temp(new VaapiDisplay(nativeDisplayObj, vaDisplay)); + vaapiDisplay = temp; + } + if (vaapiDisplay) { + WeakPtr weak(vaapiDisplay); + m_cache.push_back(weak); + } + return vaapiDisplay; +} + +DisplayPtr VaapiDisplay::create(const NativeDisplay& display) +{ + return DisplayCache::getInstance()->createDisplay(display); +} +} //YamiMediaCodec diff --git a/vaapi/vaapidisplay.h b/vaapi/vaapidisplay.h new file mode 100644 index 0000000..cde397e --- /dev/null +++ b/vaapi/vaapidisplay.h @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapidisplay_h +#define vaapidisplay_h + +#include "vaapi/vaapiptrs.h" +#include +#include +#ifdef HAVE_VA_X11 +#include +#endif +#ifndef ANDROID +#include +#endif +#include +#include "common/lock.h" +#include "common/NonCopyable.h" + +///abstract for all display, x11, wayland, ozone, android etc. +namespace YamiMediaCodec{ +#ifndef VA_FOURCC_I420 +#define VA_FOURCC_I420 VA_FOURCC('I','4','2','0') +#endif +class NativeDisplayBase; +class VaapiDisplay +{ + typedef SharedPtr NativeDisplayPtr; + friend class DisplayCache; + friend class VaapiDisplayTest; + +public: + virtual ~VaapiDisplay(); + //FIXME: add more create functions. + static DisplayPtr create(const NativeDisplay& display); + virtual bool setRotation(int degree); + VADisplay getID() const { return m_vaDisplay; } + const VAImageFormat* getVaFormat(uint32_t fourcc); + +protected: + /// for display cache management. + virtual bool isCompatible(const NativeDisplay& other); + +private: + VaapiDisplay(const NativeDisplayPtr& nativeDisplay, VADisplay vaDisplay) + :m_vaDisplay(vaDisplay), m_nativeDisplay(nativeDisplay) { }; + + Lock m_lock; + VADisplay m_vaDisplay; + NativeDisplayPtr m_nativeDisplay; + std::vector m_vaImageFormats; + +DISALLOW_COPY_AND_ASSIGN(VaapiDisplay); +}; +} +#endif + diff --git a/vaapi/vaapidisplay_unittest.cpp b/vaapi/vaapidisplay_unittest.cpp new file mode 100644 index 0000000..b491720 --- /dev/null +++ b/vaapi/vaapidisplay_unittest.cpp @@ -0,0 +1,396 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// The unittest header must be included before vaapidisplay.h. +// In vaapidisplay.h we include va_x11.h which includes Xlib.h and X.h. +// The X headers define 'Bool' and 'None' preprocessor types. Gtest +// uses the same names to define some struct placeholders. Thus, this +// creates a compile conflict if X defines them before gtest. Hence, the +// include order requirement here is the only fix for this right now. +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +#include "common/unittest.h" + +// primary header +#include "vaapidisplay.h" + +// system headers +#include +#include +#include + +namespace YamiMediaCodec { + +class VaapiDisplayTest : public ::testing::Test { + typedef std::set DrmHandles; + +protected: + bool isCompatible(const DisplayPtr display, const NativeDisplay& native) { + return display->isCompatible(native); + } + + virtual void SetUp() { +#if defined(__ENABLE_X11__) + m_x11_handle = 0; +#endif + } + + intptr_t openDrmHandle() { + intptr_t handle = -1; + handle = open("/dev/dri/renderD128", O_RDWR); + if (handle < 0) + handle = open("/dev/dri/card0", O_RDWR); + if (handle != -1) + m_drm_handles.insert(handle); + return handle; + } + + void closeDrmHandle(intptr_t handle) { + if (handle == -1) + return; + close(handle); + const DrmHandles::const_iterator match(m_drm_handles.find(handle)); + if (match != m_drm_handles.end()) + m_drm_handles.erase(match); + } + +#if defined(__ENABLE_X11__) + intptr_t openX11Handle() { + m_x11_handle = (intptr_t)XOpenDisplay(NULL); + return m_x11_handle; + } +#endif + + virtual void TearDown() { + const DrmHandles::const_iterator endIt(m_drm_handles.end()); + DrmHandles::const_iterator it; + for (it = m_drm_handles.begin(); it != endIt; ++it) + close(*it); + m_drm_handles.clear(); + +#if defined(__ENABLE_X11__) + if (m_x11_handle) + XCloseDisplay((Display*)(m_x11_handle)); +#endif + } + + DrmHandles m_drm_handles; + +#if defined(__ENABLE_X11__) + intptr_t m_x11_handle; +#endif +}; + +#if defined(__ENABLE_X11__) +bool haveX11Display() +{ + Display* display = XOpenDisplay(NULL); + if (display) { + XCloseDisplay(display); + return true; + } + return false; +} +#endif + +const std::string getFullTestName() +{ + const ::testing::TestInfo* const info = ::testing::UnitTest::GetInstance()->current_test_info(); + return std::string(info->test_case_name()) + + std::string(".") + + std::string(info->name()); +} + +#define VAAPI_DISPLAY_TEST(name) \ + TEST_F(VaapiDisplayTest, name) + +#if defined(__ENABLE_X11__) +VAAPI_DISPLAY_TEST(CreateInvalidHandleX11) { + //this turn off gest warning about multithread + //you can check details at + //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + + NativeDisplay native = {1, NATIVE_DISPLAY_X11}; + //this will crash vaGetDisplay + ASSERT_DEATH({ DisplayPtr display = VaapiDisplay::create(native); }, ""); +} +#endif + +VAAPI_DISPLAY_TEST(CreateInvalidHandleDRM) { + NativeDisplay native = {1, NATIVE_DISPLAY_DRM}; + DisplayPtr display = VaapiDisplay::create(native); + + EXPECT_FALSE(display.get()); + + intptr_t handle = openDrmHandle(); + + ASSERT_NE(handle, -1); + + // DRM handle is invalidated once it's closed. + closeDrmHandle(handle); + + native.handle = handle; + native.type = NATIVE_DISPLAY_DRM; + display = VaapiDisplay::create(native); + + EXPECT_FALSE(display.get()); +} + +VAAPI_DISPLAY_TEST(CreateInvalidHandleVA) { + NativeDisplay native = {0, NATIVE_DISPLAY_VA}; + DisplayPtr display = VaapiDisplay::create(native); + + EXPECT_FALSE(display.get()); + + //this turn off gest warning about multithread + //you can check details at + //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + + native.handle = -1; + native.type = NATIVE_DISPLAY_VA; + + //This will crash in vaDisplayIsValid + ASSERT_DEATH({ display = VaapiDisplay::create(native); }, ""); +} + +#if defined(__ENABLE_X11__) +VAAPI_DISPLAY_TEST(CreateX11) { + + if (!haveX11Display()) { + RecordProperty("skipped", true); + std::cout << "[ SKIPPED ] " << getFullTestName() + << " We can't test this in terminal, we need a X11 window for this" << std::endl; + return; + } + + // Let yami create the native display + NativeDisplay native = {0, NATIVE_DISPLAY_X11}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_TRUE(display.get()); + EXPECT_TRUE(display->getID() > 0); + + // Test the display caching + DisplayPtr display2 = VaapiDisplay::create(native); + + ASSERT_TRUE(display2.get()); + EXPECT_TRUE(display.get() == display2.get()); + EXPECT_EQ(display->getID(), display2->getID()); + + // DRM native type returns cached X11 display + // TODO: Is this really supposed to be allowed? + native.handle = 0; + native.type = NATIVE_DISPLAY_DRM; + display2 = VaapiDisplay::create(native); + ASSERT_TRUE(display2.get()); + EXPECT_TRUE(display.get() == display2.get()); + EXPECT_EQ(display->getID(), display2->getID()); + + // FIXME: If client created the DRM handle, it seems + // that we should not get the cached X11 display, but we do. + intptr_t handle = openDrmHandle(); + native.handle = handle; + native.type = NATIVE_DISPLAY_DRM; + display2 = VaapiDisplay::create(native); + ASSERT_NE(handle, -1); + ASSERT_TRUE(display2.get()); + EXPECT_FALSE(display.get() == display2.get()); + EXPECT_NE(display->getID(), display2->getID()); + + // Let client create the native display + native.handle = openX11Handle(); + native.type = NATIVE_DISPLAY_X11; + display = VaapiDisplay::create(native); + + ASSERT_NE(m_x11_handle, -1); + ASSERT_TRUE(display.get()); + EXPECT_TRUE(display->getID() > 0); + + // Ensure we didn't get the yami cached display + EXPECT_FALSE(display.get() == display2.get()); + EXPECT_NE(display->getID(), display2->getID()); +} +#endif + +VAAPI_DISPLAY_TEST(CreateDRM) { + // Let yami create the native display + NativeDisplay native = {0, NATIVE_DISPLAY_DRM}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_TRUE(display.get()); + EXPECT_TRUE(display->getID() > 0); + + // Test the display caching + DisplayPtr display2 = VaapiDisplay::create(native); + + ASSERT_TRUE(display2.get()); + EXPECT_TRUE(display.get() == display2.get()); + EXPECT_EQ(display->getID(), display2->getID()); + + // Let client create the native display + intptr_t handle = openDrmHandle(); + native.handle = handle; + native.type = NATIVE_DISPLAY_DRM; + display = VaapiDisplay::create(native); + + ASSERT_NE(handle, -1); + ASSERT_TRUE(display.get()); + EXPECT_TRUE(display->getID() > 0); + + // Ensure we didn't get the yami cached display + EXPECT_FALSE(display.get() == display2.get()); + EXPECT_NE(display->getID(), display2->getID()); +} + +VAAPI_DISPLAY_TEST(CreateVA) { + NativeDisplay native = {1, NATIVE_DISPLAY_VA}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_TRUE(display.get()); + EXPECT_TRUE(display->getID() > 0); + + // Test the display caching + DisplayPtr display2 = VaapiDisplay::create(native); + + ASSERT_TRUE(display2.get()); + EXPECT_TRUE(display.get() == display2.get()); + EXPECT_EQ(display->getID(), display2->getID()); +} + +#if defined(__ENABLE_X11__) +VAAPI_DISPLAY_TEST(CompatibleX11) { + + if (!haveX11Display()) { + RecordProperty("skipped", true); + std::cout << "[ SKIPPED ] " << getFullTestName() + << " We can't test this in terminal, we need a X11 window for this" << std::endl; + return; + } + + NativeDisplay native = {openX11Handle(), NATIVE_DISPLAY_X11}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_TRUE((Display*)m_x11_handle != NULL); + ASSERT_TRUE(display.get()); + + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = m_x11_handle + 1; + native.type = NATIVE_DISPLAY_X11; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_X11; + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_VA; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_DRM; + EXPECT_TRUE(isCompatible(display, native)); + + // FIXME: If client created the DRM handle, it seems + // that we should not get the cached X11 display + intptr_t handle = openDrmHandle(); + native.handle = handle; + native.type = NATIVE_DISPLAY_DRM; + ASSERT_NE(handle, -1); + ASSERT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_AUTO; + EXPECT_TRUE(isCompatible(display, native)); +} +#endif + +VAAPI_DISPLAY_TEST(CompatibleDRM) { + intptr_t handle = openDrmHandle(); + intptr_t handle2 = openDrmHandle(); + NativeDisplay native = {handle, NATIVE_DISPLAY_DRM}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_NE(handle, -1); + ASSERT_NE(handle2, -1); + ASSERT_NE(handle, handle2); + ASSERT_TRUE(display.get()); + + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = handle2; + native.type = NATIVE_DISPLAY_DRM; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_DRM; + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = -1; + native.type = NATIVE_DISPLAY_DRM; + EXPECT_TRUE(isCompatible(display, native)); + + native.type = NATIVE_DISPLAY_AUTO; + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_VA; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_X11; + EXPECT_FALSE(isCompatible(display, native)); +} + +VAAPI_DISPLAY_TEST(CompatibleVA) { + NativeDisplay native = {1, NATIVE_DISPLAY_VA}; + DisplayPtr display = VaapiDisplay::create(native); + + ASSERT_TRUE(display.get()); + + EXPECT_TRUE(isCompatible(display, native)); + + native.handle = 2; + native.type = NATIVE_DISPLAY_VA; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 0; + native.type = NATIVE_DISPLAY_VA; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = -1; + native.type = NATIVE_DISPLAY_VA; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 1; + native.type = NATIVE_DISPLAY_DRM; + EXPECT_FALSE(isCompatible(display, native)); + + native.handle = 1; + native.type = NATIVE_DISPLAY_X11; + EXPECT_FALSE(isCompatible(display, native)); + + native.type = NATIVE_DISPLAY_AUTO; + EXPECT_TRUE(isCompatible(display, native)); +} + +} //namespace YamiMediaCodec diff --git a/vaapi/vaapipicture.cpp b/vaapi/vaapipicture.cpp new file mode 100644 index 0000000..1851808 --- /dev/null +++ b/vaapi/vaapipicture.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapipicture.h" + +#include "common/log.h" +#include "VaapiBuffer.h" +#include "vaapidisplay.h" +#include "vaapicontext.h" +#include "VaapiSurface.h" +#include "VaapiUtils.h" + +namespace YamiMediaCodec{ +VaapiPicture::VaapiPicture(const ContextPtr& context, + const SurfacePtr& surface, int64_t timeStamp) + : m_display(context->getDisplay()) + , m_context(context) + , m_surface(surface) + , m_timeStamp(timeStamp) +{ + +} + +VaapiPicture::VaapiPicture() + : m_timeStamp(0) +{ +} + +bool VaapiPicture::render() +{ + if (m_surface->getID() == VA_INVALID_SURFACE) { + ERROR("bug: no surface to encode"); + return false; + } + + VAStatus status; + status = vaBeginPicture(m_display->getID(), m_context->getID(), m_surface->getID()); + if (!checkVaapiStatus(status, "vaBeginPicture()")) + return false; + + bool ret = doRender(); + + status = vaEndPicture(m_display->getID(), m_context->getID()); + if (!checkVaapiStatus(status, "vaEndPicture()")) + return false; + return ret; +} + +bool VaapiPicture::render(BufObjectPtr& buffer) +{ + VAStatus status = VA_STATUS_SUCCESS; + VABufferID bufferID = VA_INVALID_ID; + + if (!buffer) + return true; + + buffer->unmap(); + + bufferID = buffer->getID(); + if (bufferID == VA_INVALID_ID) + return false; + + status = vaRenderPicture(m_display->getID(), m_context->getID(), &bufferID, 1); + if (!checkVaapiStatus(status, "vaRenderPicture failed")) + return false; + + buffer.reset(); // silently work arouond for psb + return true; +} + +bool VaapiPicture::render(std::pair ¶mAndData) +{ + return render(paramAndData.first) && render(paramAndData.second); +} + +bool VaapiPicture::addObject(std::vector >& objects, + const BufObjectPtr & param, + const BufObjectPtr & data) +{ + if (!param || !data) + return false; + objects.push_back(std::make_pair(param, data)); + return true; +} + +bool VaapiPicture::addObject(std::vector < BufObjectPtr >& objects, + const BufObjectPtr& object) +{ + if (!object) + return false; + objects.push_back(object); + return true; +} + +bool VaapiPicture::sync() +{ + return vaSyncSurface(m_display->getID(), getSurfaceID()) == VA_STATUS_SUCCESS; +} +} diff --git a/vaapi/vaapipicture.h b/vaapi/vaapipicture.h new file mode 100644 index 0000000..3d03eae --- /dev/null +++ b/vaapi/vaapipicture.h @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapipicture_h +#define vaapipicture_h + +#include "VideoCommonDefs.h" +#include "VaapiBuffer.h" +#include "vaapiptrs.h" +#include "VaapiSurface.h" +#include +#include +#include +#include + +namespace YamiMediaCodec{ + +typedef enum +{ + VAAPI_PICTURE_INVALID = 0x0000, + VAAPI_PICTURE_TOP_FIELD = 0x0001, + VAAPI_PICTURE_BOTTOM_FIELD = 0x0002, + VAAPI_PICTURE_FRAME = 0x0003, + VAAPI_PICTURE_I = 0x0100, + VAAPI_PICTURE_B = 0x0200, + VAAPI_PICTURE_P = 0x0400 +} VaapiPictureType; + +class VaapiPicture +{ +protected: + DisplayPtr m_display; + ContextPtr m_context; + SurfacePtr m_surface; + +public: + VaapiPicture(const ContextPtr&, const SurfacePtr&, int64_t timeStamp); + virtual ~VaapiPicture() {}; + + inline VASurfaceID getSurfaceID() const; + inline SurfacePtr getSurface() const; + inline void setSurface(const SurfacePtr&); + bool sync(); + + int64_t m_timeStamp; + VaapiPictureType m_type; + +protected: + virtual bool doRender() = 0; + + bool render(); + bool render(BufObjectPtr& buffer); + bool render(std::pair& paramAndData); + + template + bool render(std::vector& objects); + + template + bool editObject(BufObjectPtr& object , VABufferType, T*& bufPtr); + bool addObject(std::vector >& objects, + const BufObjectPtr& param, const BufObjectPtr& data); + bool addObject(std::vector& objects, const BufObjectPtr& object); + + template + BufObjectPtr createBufferObject(VABufferType, T*& bufPtr); + inline BufObjectPtr createBufferObject(VABufferType bufType, + uint32_t size, const void* data, void** mapped); + VaapiPicture(); +}; + +template +BufObjectPtr VaapiPicture::createBufferObject(VABufferType bufType, T*& bufPtr) +{ + return VaapiBuffer::create(m_context, bufType, bufPtr); +} + +BufObjectPtr VaapiPicture::createBufferObject(VABufferType bufType, + uint32_t size, const void* data, void** mapped) +{ + return VaapiBuffer::create(m_context, bufType, size, data, mapped); +} + +template +bool VaapiPicture::editObject(BufObjectPtr& object , VABufferType bufType, T*& bufPtr) +{ + /* already set? It's only one time offer*/ + if (object) + return false; + object = createBufferObject(bufType, bufPtr); + + if (!bufPtr) + return false; + + return bool(object); +} + +#define RENDER_OBJECT(obj) \ +do { if (!VaapiPicture::render(obj)) { ERROR("render " #obj " failed"); return false;} } while(0) + +template +bool VaapiPicture::render(std::vector& objects) +{ + bool ret = true; + + for (uint32_t i = 0; i < objects.size(); i++) + ret &= render(objects[i]); + + objects.clear(); // slient work around for psb drv to delete VABuffer + return ret; +} + + +VASurfaceID VaapiPicture::getSurfaceID() const +{ + return m_surface->getID(); +} + +SurfacePtr VaapiPicture::getSurface() const +{ + return m_surface; +} + +void VaapiPicture::setSurface(const SurfacePtr& surface) +{ + m_surface = surface; +} + +} + +#endif //vaapipicture_h + diff --git a/vaapi/vaapiptrs.h b/vaapi/vaapiptrs.h new file mode 100644 index 0000000..4e48daf --- /dev/null +++ b/vaapi/vaapiptrs.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapiptrs_h +#define vaapiptrs_h + +#include "VideoCommonDefs.h" + +namespace YamiMediaCodec{ +class VaapiSurface; +typedef SharedPtr < VaapiSurface > SurfacePtr; + +class VaapiCodedBuffer; +typedef SharedPtr < VaapiCodedBuffer > CodedBufferPtr; + +class VaapiBuffer; +typedef SharedPtr BufObjectPtr; + +class VaapiDisplay; +typedef SharedPtr < VaapiDisplay > DisplayPtr; + +class VaapiConfig; +typedef SharedPtr < VaapiConfig > ConfigPtr; + +class VaapiContext; +typedef SharedPtr < VaapiContext > ContextPtr; + +class VaapiDecSurfacePool; +typedef SharedPtr < VaapiDecSurfacePool > DecSurfacePoolPtr; + +} //namespace YamiMediaCodec + +#endif /* vaapiptr_h */ diff --git a/vaapi/vaapistreamable.h b/vaapi/vaapistreamable.h new file mode 100644 index 0000000..b47d689 --- /dev/null +++ b/vaapi/vaapistreamable.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2017 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapistreamable_h +#define vaapistreamable_h +#include +#include + +template +const std::string toString(const T& t) +{ + std::ostringstream os; + os << t; + return os.str(); +} + + +inline std::ostream& +operator<<(std::ostream& os, const VAProfile& profile) +{ + switch(profile) { + case VAProfileNone: + return os << "VAProfileNone"; + case VAProfileMPEG2Simple: + return os << "VAProfileMPEG2Simple"; + case VAProfileMPEG2Main: + return os << "VAProfileMPEG2Main"; + case VAProfileMPEG4Simple: + return os << "VAProfileMPEG4Simple"; + case VAProfileMPEG4AdvancedSimple: + return os << "VAProfileMPEG4AdvancedSimple"; + case VAProfileMPEG4Main: + return os << "VAProfileMPEG4Main"; + case VAProfileVC1Simple: + return os << "VAProfileVC1Simple"; + case VAProfileVC1Main: + return os << "VAProfileVC1Main"; + case VAProfileVC1Advanced: + return os << "VAProfileVC1Advanced"; + case VAProfileH263Baseline: + return os << "VAProfileH263Baseline"; + case VAProfileJPEGBaseline: + return os << "VAProfileJPEGBaseline"; + case VAProfileVP8Version0_3: + return os << "VAProfileVP8Version0_3"; + case VAProfileHEVCMain: + return os << "VAProfileHEVCMain"; + case VAProfileHEVCMain10: + return os << "VAProfileHEVCMain10"; + case VAProfileVP9Profile0: + return os << "VAProfileVP9Profile0"; + case VAProfileVP9Profile1: + return os << "VAProfileVP9Profile1"; + case VAProfileVP9Profile2: + return os << "VAProfileVP9Profile2"; + case VAProfileVP9Profile3: + return os << "VAProfileVP9Profile3"; + case VAProfileH264ConstrainedBaseline: + return os << "VAProfileH264ConstrainedBaseline"; + case VAProfileH264High: + return os << "VAProfileH264High"; + case VAProfileH264Main: + return os << "VAProfileH264Main"; + case VAProfileH264MultiviewHigh: + return os << "VAProfileH264MultiviewHigh"; + case VAProfileH264StereoHigh: + return os << "VAProfileH264StereoHigh"; + default: + return os << "Unknown VAProfile: " << static_cast(profile); + } +} + +inline std::ostream& +operator<<(std::ostream& os, const VAEntrypoint& entrypoint) +{ + switch(entrypoint) { + case VAEntrypointVLD: + return os << "VAEntrypointVLD"; + case VAEntrypointIZZ: + return os << "VAEntrypointIZZ"; + case VAEntrypointIDCT: + return os << "VAEntrypointIDCT"; + case VAEntrypointMoComp: + return os << "VAEntrypointMoComp"; + case VAEntrypointDeblocking: + return os << "VAEntrypointDeblocking"; + case VAEntrypointVideoProc: + return os << "VAEntrypointVideoProc"; + case VAEntrypointEncSlice: + return os << "VAEntrypointEncSlice"; + case VAEntrypointEncSliceLP: + return os << "VAEntrypointEncSliceLP"; + case VAEntrypointEncPicture: + return os << "VAEntrypointEncPicture"; +#if VA_CHECK_VERSION(1, 0, 0) + case VAEntrypointFEI: + return os << "VAEntrypointFEI"; +#endif + default: + return os << "Unknown VAEntrypoint: " << static_cast(entrypoint); + } +} + +#endif // vaapistreamable_h diff --git a/vaapi/vaapisurfaceallocator.cpp b/vaapi/vaapisurfaceallocator.cpp new file mode 100644 index 0000000..164559b --- /dev/null +++ b/vaapi/vaapisurfaceallocator.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "vaapi/vaapisurfaceallocator.h" +#include "vaapi/VaapiUtils.h" +#include + +namespace YamiMediaCodec{ + +VaapiSurfaceAllocator::VaapiSurfaceAllocator(VADisplay display, uint32_t extraSize) + :m_display(display), + m_extraSize(extraSize) +{ +} + +YamiStatus VaapiSurfaceAllocator::doAlloc(SurfaceAllocParams* params) +{ + if (!params) + return YAMI_INVALID_PARAM; + uint32_t size = params->size; + uint32_t width = params->width; + uint32_t height = params->height; + if (!width || !height || !size) + return YAMI_INVALID_PARAM; + uint32_t rtFormat = getRtFormat(params->fourcc); + if (!rtFormat) { + ERROR("unsupported format %x", params->fourcc); + return YAMI_UNSUPPORTED; + } + + size += m_extraSize; + + std::vector v(size); + VASurfaceAttrib attrib; + attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; + attrib.type = VASurfaceAttribPixelFormat; + attrib.value.type = VAGenericValueTypeInteger; + attrib.value.value.i = params->fourcc; + VAStatus status = vaCreateSurfaces(m_display, + rtFormat, width, height, + &v[0], size, &attrib, 1); + if (!checkVaapiStatus(status, "vaCreateSurfaces")) + return YAMI_OUT_MEMORY; + params->surfaces = new intptr_t[size]; + for (uint32_t i = 0; i < size; i++) { + params->surfaces[i] = (intptr_t)v[i]; + } + params->size = size; + return YAMI_SUCCESS; +} + +YamiStatus VaapiSurfaceAllocator::doFree(SurfaceAllocParams* params) +{ + if (!params || !params->size || !params->surfaces) + return YAMI_INVALID_PARAM; + uint32_t size = params->size; + std::vector v(size); + for (uint32_t i = 0; i < size; i++) { + v[i] = (VASurfaceID)params->surfaces[i]; + } + checkVaapiStatus(vaDestroySurfaces(m_display, &v[0], size), "vaDestroySurfaces"); + delete[] params->surfaces; + return YAMI_SUCCESS; +} + +void VaapiSurfaceAllocator::doUnref() +{ + delete this; +} + +} //YamiMediaCodec diff --git a/vaapi/vaapisurfaceallocator.h b/vaapi/vaapisurfaceallocator.h new file mode 100644 index 0000000..9e66bee --- /dev/null +++ b/vaapi/vaapisurfaceallocator.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapisurfaceallocator_h +#define vaapisurfaceallocator_h +#include "common/basesurfaceallocator.h" +#include "common/NonCopyable.h" +#include + +namespace YamiMediaCodec{ + +class VaapiSurfaceAllocator : public BaseSurfaceAllocator +{ + //extra buffer size for performance + static const uint32_t EXTRA_BUFFER_SIZE = 5; +public: + //we do not use DisplayPtr here since we may give this to user someday. + //@extraSize[in] extra size add to SurfaceAllocParams.size + VaapiSurfaceAllocator(VADisplay display, uint32_t extraSize = EXTRA_BUFFER_SIZE); +protected: + virtual YamiStatus doAlloc(SurfaceAllocParams* params); + virtual YamiStatus doFree(SurfaceAllocParams* params); + virtual void doUnref(); +private: + VADisplay m_display; + uint32_t m_extraSize; + DISALLOW_COPY_AND_ASSIGN(VaapiSurfaceAllocator); +}; + +} +#endif //vaapisurfaceallocator_h diff --git a/vpp/Android.mk b/vpp/Android.mk new file mode 100755 index 0000000..9d8c44e --- /dev/null +++ b/vpp/Android.mk @@ -0,0 +1,29 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +include $(LOCAL_PATH)/../common.mk + +LOCAL_SRC_FILES := \ + vaapipostprocess_base.cpp \ + vaapipostprocess_host.cpp \ + vaapipostprocess_scaler.cpp \ + vaapivpppicture.cpp + +LOCAL_C_INCLUDES:= \ + $(LOCAL_PATH)/.. \ + $(LOCAL_PATH)/../interface \ + external/libcxx/include \ + $(TARGET_OUT_HEADERS)/libva + +LOCAL_SHARED_LIBRARIES := \ + liblog \ + libva \ + libc++ + +LOCAL_CPPFLAGS += \ + -frtti + +LOCAL_ALLOW_UNDEFINED_SYMBOLS := true + +LOCAL_PROPRIETARY_MODULE := true +LOCAL_MODULE := libyami_vpp +include $(BUILD_STATIC_LIBRARY) diff --git a/vpp/Makefile.am b/vpp/Makefile.am new file mode 100644 index 0000000..a227ada --- /dev/null +++ b/vpp/Makefile.am @@ -0,0 +1,98 @@ +libyami_vpp_source_c = \ + vaapipostprocess_base.cpp \ + vaapipostprocess_host.cpp \ + vaapipostprocess_scaler.cpp \ + vaapivpppicture.cpp \ + $(NULL) + +if BUILD_OCL_FILTERS +libyami_vpp_source_c += ../ocl/oclcontext.cpp +libyami_vpp_source_c += oclpostprocess_base.cpp +libyami_vpp_source_c += oclvppimage.cpp +endif + +if BUILD_OCL_FILTERS +libyami_vpp_source_c += oclpostprocess_blender.cpp +libyami_vpp_source_c += oclpostprocess_osd.cpp +libyami_vpp_source_c += oclpostprocess_transform.cpp +libyami_vpp_source_c += oclpostprocess_mosaic.cpp +libyami_vpp_source_c += oclpostprocess_wireframe.cpp +endif + +libyami_vpp_source_h = \ + ../interface/VideoCommonDefs.h \ + ../interface/VideoPostProcessDefs.h \ + ../interface/VideoPostProcessHost.h \ + ../interface/VideoPostProcessInterface.h \ + $(NULL) + +libyami_vpp_source_h_priv = \ + vaapipostprocess_base.h \ + vaapipostprocess_scaler.h \ + vaapivpppicture.h \ + $(NULL) + +if BUILD_OCL_FILTERS +libyami_vpp_source_h_priv += ../ocl/oclcontext.h +libyami_vpp_source_h_priv += oclpostprocess_base.h +libyami_vpp_source_h_priv += oclvppimage.h +endif + +if BUILD_OCL_FILTERS +libyami_vpp_source_h_priv += oclpostprocess_blender.h +libyami_vpp_source_h_priv += oclpostprocess_osd.h +libyami_vpp_source_h_priv += oclpostprocess_transform.h +libyami_vpp_source_h_priv += oclpostprocess_mosaic.h +libyami_vpp_source_h_priv += oclpostprocess_wireframe.h +endif + +libyami_vpp_ldflags = \ + $(LIBYAMI_LT_LDFLAGS) \ + $(LIBVA_LIBS) \ + $(LIBVA_DRM_LIBS) \ + -ldl \ + $(NULL) + +#to compile within yocto +extra_includes = \ + -I$(top_srcdir) \ + $(NULL) + +libyami_vpp_cppflags = \ + $(LIBVA_CFLAGS) \ + $(LIBVA_DRM_CFLAGS) \ + -I$(top_srcdir)/interface \ + $(extra_includes) \ + $(NULL) + +if BUILD_OCL_FILTERS +libyami_vpp_ocl_kernel = \ + ../ocl/kernels/blend.cl \ + ../ocl/kernels/osd.cl \ + ../ocl/kernels/transform.cl \ + ../ocl/kernels/mosaic.cl \ + ../ocl/kernels/wireframe.cl \ + $(NULL) +kerneldir = $(datadir)/libyami/kernel +kernel_DATA = $(libyami_vpp_ocl_kernel) +libyami_vpp_cppflags += -DKERNEL_DIR=\"$(kerneldir)/\" +endif + +if BUILD_OCL_FILTERS +libyami_vpp_ldflags += -lOpenCL +endif + +noinst_LTLIBRARIES = libyami_vpp.la +libyami_vppincludedir = $(includedir)/libyami +libyami_vppinclude_HEADERS = $(libyami_vpp_source_h) +noinst_HEADERS = $(libyami_vpp_source_h_priv) +libyami_vpp_la_SOURCES = $(libyami_vpp_source_c) +libyami_vpp_la_LDFLAGS = $(libyami_vpp_ldflags) $(AM_LDFLAGS) +libyami_vpp_la_CPPFLAGS = $(libyami_vpp_cppflags) $(AM_CPPFLAGS) + +if ENABLE_TESTS +include Makefile.unittest +endif + +DISTCLEANFILES = \ + Makefile.in diff --git a/vpp/Makefile.unittest b/vpp/Makefile.unittest new file mode 100644 index 0000000..2bbc8c7 --- /dev/null +++ b/vpp/Makefile.unittest @@ -0,0 +1,78 @@ +noinst_PROGRAMS = unittest + +unittest_SOURCES = \ + unittest_main.cpp \ + $(NULL) + +unittest_SOURCES += vaapipostprocess_scaler_unittest.cpp + +if BUILD_OCL_FILTERS +unittest_SOURCES += \ + oclpostprocess_blender_unittest.cpp \ + oclpostprocess_mosaic_unittest.cpp \ + oclpostprocess_osd_unittest.cpp \ + oclpostprocess_transform_unittest.cpp \ + oclpostprocess_wireframe_unittest.cpp \ + $(NULL) +endif + +unittest_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_LDADD = \ + libyami_vpp.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +# Separate the vaapipostprocess_host_unittest so that we can detect static +# initialization bugs with the vpp factory. Separation is required +# since any derived vpp that is explicitly constructed in another test +# would hide such bugs. +noinst_PROGRAMS += unittest_host +unittest_host_SOURCES = \ + unittest_main.cpp \ + vaapipostprocess_host_unittest.cpp \ + $(NULL) + +unittest_host_LDFLAGS = \ + $(AM_LDFLAGS) \ + -pthread \ + $(NULL) + +unittest_host_LDADD = \ + libyami_vpp.la \ + $(top_builddir)/vaapi/libyami_vaapi.la \ + $(top_builddir)/common/libyami_common.la \ + $(top_srcdir)/gtestsrc/libgtest.la \ + $(NULL) + +unittest_host_CPPFLAGS = \ + $(LIBVA_CFLAGS) \ + $(AM_CPPFLAGS) \ + -I$(top_srcdir)/interface \ + -I$(top_srcdir)/gtestsrc/gtest/include \ + $(NULL) + +unittest_host_CXXFLAGS = \ + $(AM_CXXFLAGS) \ + $(NULL) + +check-local: unittest unittest_host + $(builddir)/unittest + $(builddir)/unittest_host + diff --git a/vpp/oclpostprocess_base.cpp b/vpp/oclpostprocess_base.cpp new file mode 100644 index 0000000..f93eabe --- /dev/null +++ b/vpp/oclpostprocess_base.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "oclpostprocess_base.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "vaapi/VaapiUtils.h" +#include + +namespace YamiMediaCodec{ + +OclPostProcessBase::OclPostProcessBase() +{ +} + +YamiStatus OclPostProcessBase::setNativeDisplay(const NativeDisplay& display) +{ + if (display.type != NATIVE_DISPLAY_VA + || !display.handle) { + ERROR("vpp only support va display as NativeDisplay"); + return YAMI_INVALID_PARAM; + } + m_display = (VADisplay)display.handle; + return YAMI_SUCCESS; +} + +YamiStatus OclPostProcessBase::ensureContext(const char* name) +{ + if (m_kernels.size()) + return YAMI_SUCCESS; + m_context = OclContext::create(); + if (!m_context + || !m_context->createKernel(name, m_kernels) + || !prepareKernels()) + return YAMI_DRIVER_FAIL; + return YAMI_SUCCESS; +} + +uint32_t OclPostProcessBase::getPixelSize(const cl_image_format& fmt) +{ + uint32_t size = 0; + + switch (fmt.image_channel_order) { + case CL_R: + case CL_A: + case CL_Rx: + size = 1; + break; + case CL_RG: + case CL_RA: + case CL_RGx: + size = 2; + break; + case CL_RGB: + case CL_RGBx: + size = 3; + break; + case CL_RGBA: + case CL_BGRA: + case CL_ARGB: + size = 4; + break; + case CL_INTENSITY: + case CL_LUMINANCE: + size = 1; + break; + default: + ERROR("invalid image channel order: %u", fmt.image_channel_order); + return 0; + } + + switch (fmt.image_channel_data_type) { + case CL_UNORM_INT8: + case CL_SNORM_INT8: + case CL_SIGNED_INT8: + case CL_UNSIGNED_INT8: + size *= 1; + break; + case CL_SNORM_INT16: + case CL_UNORM_INT16: + case CL_UNORM_SHORT_565: + case CL_UNORM_SHORT_555: + case CL_SIGNED_INT16: + case CL_UNSIGNED_INT16: + case CL_HALF_FLOAT: + size *= 2; + break; + case CL_UNORM_INT24: + size *= 3; + break; + case CL_SIGNED_INT32: + case CL_UNSIGNED_INT32: + case CL_UNORM_INT_101010: + case CL_FLOAT: + size *= 4; + break; + default: + ERROR("invalid image channel data type: %d", fmt.image_channel_data_type); + return 0; + } + + return size; +} + +cl_kernel OclPostProcessBase::prepareKernel(const char* name) +{ + OclKernelMap::iterator it = m_kernels.find(name); + if (it == m_kernels.end()) + return NULL; + else + return it->second; +} + +OclPostProcessBase::~OclPostProcessBase() +{ + if (m_context) + m_context->releaseKernel(m_kernels); +} +} diff --git a/vpp/oclpostprocess_base.h b/vpp/oclpostprocess_base.h new file mode 100644 index 0000000..d68e534 --- /dev/null +++ b/vpp/oclpostprocess_base.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef oclpostprocess_base_h +#define oclpostprocess_base_h + +#include "VideoPostProcessInterface.h" +#include +#include +#include + +template +class FactoryTest; + +namespace YamiMediaCodec{ +class OclContext; +/** + * \class OclPostProcessBase + * \brief Abstract video post process base on opencl + * + */ +class OclPostProcessBase : public IVideoPostProcess { +public: + // set native display + virtual YamiStatus setNativeDisplay(const NativeDisplay& display); + + YamiStatus ensureContext(const char* name); + // + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dest) = 0; + virtual YamiStatus setParameters(VppParamType type, void* vppParam) + { + return YAMI_SUCCESS; + } + OclPostProcessBase(); + virtual ~OclPostProcessBase(); + +protected: + class VideoFrameDeleter { + public: + VideoFrameDeleter(VADisplay display) + : m_display(display) + { + } + void operator()(VideoFrame* frame) + { + VASurfaceID id = (VASurfaceID)frame->surface; + vaDestroySurfaces(m_display, &id, 1); + delete frame; + } + + private: + VADisplay m_display; + }; + + uint32_t getPixelSize(const cl_image_format& fmt); + cl_kernel prepareKernel(const char* name); + + VADisplay m_display; + SharedPtr m_context; + OclKernelMap m_kernels; + +private: + virtual bool prepareKernels() = 0; +}; +} +#endif /* vaapipostprocess_base_h */ + diff --git a/vpp/oclpostprocess_blender.cpp b/vpp/oclpostprocess_blender.cpp new file mode 100644 index 0000000..0513ff3 --- /dev/null +++ b/vpp/oclpostprocess_blender.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2015-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/common_def.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "oclpostprocess_blender.h" +#include "oclvppimage.h" + +namespace YamiMediaCodec{ + +YamiStatus +OclPostProcessBlender::blend(const SharedPtr& src, + const SharedPtr& dst) +{ + YamiStatus ret = YAMI_SUCCESS; + SharedPtr srcImagePtr, dstImagePtr; + cl_image_format srcFormat, dstFormat; + + srcFormat.image_channel_order = CL_RGBA; + srcFormat.image_channel_data_type = CL_UNORM_INT8; + srcImagePtr = OclVppCLImage::create(m_display, src, m_context, srcFormat); + if (!srcImagePtr) { + ERROR("failed to create cl image from src frame"); + return YAMI_FAIL; + } + + dstFormat.image_channel_order = CL_RG; + dstFormat.image_channel_data_type = CL_UNORM_INT8; + dstImagePtr = OclVppCLImage::create(m_display, dst, m_context, dstFormat); + if (!dstImagePtr) { + ERROR("failed to create cl image from dst frame"); + return YAMI_FAIL; + } + + cl_mem bgImageMem[3]; + for (uint32_t n = 0; n < dstImagePtr->numPlanes(); n++) { + bgImageMem[n] = dstImagePtr->plane(n); + } + + uint32_t pixelSize = getPixelSize(dstFormat); + VideoRect crop; + crop.x = dst->crop.x / pixelSize; + crop.y = dst->crop.y & ~1; + crop.width = dst->crop.width / pixelSize; + crop.height = dst->crop.height; + if ((CL_SUCCESS != clSetKernelArg(m_kernelBlend, 0, sizeof(cl_mem), &dstImagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 1, sizeof(cl_mem), &dstImagePtr->plane(1))) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 2, sizeof(cl_mem), &bgImageMem[0])) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 3, sizeof(cl_mem), &bgImageMem[1])) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 4, sizeof(cl_mem), &srcImagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 5, sizeof(uint32_t), &crop.x)) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 6, sizeof(uint32_t), &crop.y)) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 7, sizeof(uint32_t), &crop.width)) + || (CL_SUCCESS != clSetKernelArg(m_kernelBlend, 8, sizeof(uint32_t), &crop.height))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + // each work group has 8x8 work items; each work item handles 2x2 pixels + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = ALIGN16(dst.get()->crop.width) / pixelSize; + globalWorkSize[1] = ALIGN16(dst.get()->crop.height) / 2; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, m_kernelBlend, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + + return ret; +} + +YamiStatus +OclPostProcessBlender::process(const SharedPtr& src, + const SharedPtr& dest) +{ + YamiStatus status = ensureContext("blend"); + if (status != YAMI_SUCCESS) + return status; + + if (src->fourcc != YAMI_FOURCC_RGBA || dest->fourcc != YAMI_FOURCC_NV12) { + ERROR("only support RGBA blending on NV12 video frame"); + return YAMI_INVALID_PARAM; + } + + return blend(src, dest); +} + +bool OclPostProcessBlender::prepareKernels() +{ + m_kernelBlend = prepareKernel("blend"); + + return m_kernelBlend != NULL; +} + +} + diff --git a/vpp/oclpostprocess_blender.h b/vpp/oclpostprocess_blender.h new file mode 100644 index 0000000..f2d4ee0 --- /dev/null +++ b/vpp/oclpostprocess_blender.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2015-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef oclpostprocess_blender_h +#define oclpostprocess_blender_h + + +#include "VideoCommonDefs.h" +#include "oclpostprocess_base.h" + +namespace YamiMediaCodec{ + +/** + * \class OclPostProcessBlend + * \brief alpha blending base on opencl + */ +class OclPostProcessBlender : public OclPostProcessBase { +public: + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dest); + explicit OclPostProcessBlender() + : m_kernelBlend(NULL) + { + ensureContext("blend"); + } + +private: + friend class FactoryTest; + friend class OclPostProcessBlenderTest; + + virtual bool prepareKernels(); + YamiStatus blend(const SharedPtr& src, + const SharedPtr& dst); + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; + + cl_kernel m_kernelBlend; +}; + +} +#endif //oclpostprocess_blend_h diff --git a/vpp/oclpostprocess_blender_unittest.cpp b/vpp/oclpostprocess_blender_unittest.cpp new file mode 100644 index 0000000..16efc5b --- /dev/null +++ b/vpp/oclpostprocess_blender_unittest.cpp @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "oclpostprocess_blender.h" + +namespace YamiMediaCodec { + +class OclPostProcessBlenderTest + : public FactoryTest +{ }; + +#define OCLPOSTPROCESS_BLENDER_TEST(name) \ + TEST_F(OclPostProcessBlenderTest, name) + +OCLPOSTPROCESS_BLENDER_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_OCL_BLENDER); + doFactoryTest(mimeTypes); +} + +} diff --git a/vpp/oclpostprocess_mosaic.cpp b/vpp/oclpostprocess_mosaic.cpp new file mode 100644 index 0000000..9809640 --- /dev/null +++ b/vpp/oclpostprocess_mosaic.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "oclpostprocess_mosaic.h" +#include "common/common_def.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "vpp/oclvppimage.h" + +namespace YamiMediaCodec { + +YamiStatus +OclPostProcessMosaic::process(const SharedPtr& src, + const SharedPtr& dst) +{ + YamiStatus status = ensureContext("mosaic"); + if (status != YAMI_SUCCESS) + return status; + + if (src != dst) { + ERROR("src and dst must be the same for mosaic filter"); + return YAMI_INVALID_PARAM; + } + + if (dst->fourcc != YAMI_FOURCC_NV12) { + ERROR("only support mosaic filter on NV12 video frame"); + return YAMI_INVALID_PARAM; + } + + cl_image_format format; + format.image_channel_order = CL_R; + format.image_channel_data_type = CL_UNORM_INT8; + SharedPtr imagePtr = OclVppCLImage::create(m_display, dst, m_context, format); + if (!imagePtr->numPlanes()) { + ERROR("failed to create cl image from dst frame"); + return YAMI_FAIL; + } + + cl_mem bgImageMem[3]; + for (uint32_t n = 0; n < imagePtr->numPlanes(); n++) { + bgImageMem[n] = imagePtr->plane(n); + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 256 / m_blockSize * m_blockSize; + localWorkSize[1] = 1; + globalWorkSize[0] = (dst->crop.width / localWorkSize[0] + 1) * localWorkSize[0]; + globalWorkSize[1] = dst->crop.height / m_blockSize + 1; + size_t localMemSize = localWorkSize[0] * sizeof(float); + + if ((CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 0, sizeof(cl_mem), &imagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 1, sizeof(cl_mem), &bgImageMem[0])) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 2, sizeof(cl_mem), &imagePtr->plane(1))) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 3, sizeof(cl_mem), &bgImageMem[1])) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 4, sizeof(uint32_t), &dst->crop.x)) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 5, sizeof(uint32_t), &dst->crop.y)) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 6, sizeof(uint32_t), &dst->crop.width)) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 7, sizeof(uint32_t), &dst->crop.height)) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 8, sizeof(uint32_t), &m_blockSize)) + || (CL_SUCCESS != clSetKernelArg(m_kernelMosaic, 9, localMemSize, NULL))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, m_kernelMosaic, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + + return status; +} + +YamiStatus OclPostProcessMosaic::setParameters(VppParamType type, void* vppParam) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + switch (type) { + case VppParamTypeMosaic: { + VppParamMosaic* mosaic = (VppParamMosaic*)vppParam; + if (mosaic->size == sizeof(VppParamMosaic)) { + if (mosaic->blockSize > 0 && mosaic->blockSize <= 256) { + m_blockSize = mosaic->blockSize; + status = YAMI_SUCCESS; + } + } + } break; + default: + status = OclPostProcessBase::setParameters(type, vppParam); + break; + } + return status; +} + +bool OclPostProcessMosaic::prepareKernels() +{ + m_kernelMosaic = prepareKernel("mosaic"); + + return m_kernelMosaic != NULL; +} + +} diff --git a/vpp/oclpostprocess_mosaic.h b/vpp/oclpostprocess_mosaic.h new file mode 100644 index 0000000..c432fe0 --- /dev/null +++ b/vpp/oclpostprocess_mosaic.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef oclpostprocess_mosaic_h +#define oclpostprocess_mosaic_h + +#include "VideoCommonDefs.h" +#include "oclpostprocess_base.h" + +namespace YamiMediaCodec { + +/** + * \class OclPostProcessMosaic + * \brief OpenCL based mosaic filter + */ +class OclPostProcessMosaic : public OclPostProcessBase { +public: + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dst); + + virtual YamiStatus setParameters(VppParamType type, void* vppParam); + + explicit OclPostProcessMosaic() + : m_blockSize(32) + , m_kernelMosaic(NULL) + { + ensureContext("mosaic"); + } + +private: + friend class FactoryTest; + friend class OclPostProcessMosaicTest; + + virtual bool prepareKernels(); + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; + + int m_blockSize; + cl_kernel m_kernelMosaic; +}; +} +#endif //oclpostprocess_mosaic_h diff --git a/vpp/oclpostprocess_mosaic_unittest.cpp b/vpp/oclpostprocess_mosaic_unittest.cpp new file mode 100644 index 0000000..7966fd8 --- /dev/null +++ b/vpp/oclpostprocess_mosaic_unittest.cpp @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "oclpostprocess_mosaic.h" + +namespace YamiMediaCodec { + +class OclPostProcessMosaicTest + : public FactoryTest +{ }; + +#define OCLPOSTPROCESS_MOSAIC_TEST(name) \ + TEST_F(OclPostProcessMosaicTest, name) + +OCLPOSTPROCESS_MOSAIC_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_OCL_MOSAIC); + doFactoryTest(mimeTypes); +} + +} diff --git a/vpp/oclpostprocess_osd.cpp b/vpp/oclpostprocess_osd.cpp new file mode 100644 index 0000000..fb6633b --- /dev/null +++ b/vpp/oclpostprocess_osd.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "oclpostprocess_osd.h" +#include "common/common_def.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "vpp/oclvppimage.h" + +namespace YamiMediaCodec { + +YamiStatus +OclPostProcessOsd::process(const SharedPtr& src, + const SharedPtr& dst) +{ + YamiStatus status = ensureContext("osd"); + if (status != YAMI_SUCCESS) + return status; + + if (src->fourcc != YAMI_FOURCC_RGBA || dst->fourcc != YAMI_FOURCC_NV12) { + ERROR("only support RGBA OSD on NV12 video frame"); + return YAMI_INVALID_PARAM; + } + + status = computeBlockLuma(dst); + if (status != YAMI_SUCCESS) + return status; + + cl_int clStatus; + cl_mem clBuf = clCreateBuffer(m_context->m_context, + CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY, + m_osdLuma.size() * sizeof(float), + NULL, + &clStatus); + SharedPtr osdLuma(new cl_mem(clBuf), OclMemDeleter()); + if (!checkOclStatus(clStatus, "CreateBuffer") + || !checkOclStatus(clEnqueueWriteBuffer(m_context->m_queue, *osdLuma, CL_TRUE, 0, + m_osdLuma.size() * sizeof(float), + m_osdLuma.data(), 0, NULL, NULL), + "EnqueueWriteBuffer")) { + return YAMI_FAIL; + } + + SharedPtr srcImagePtr, dstImagePtr; + cl_image_format srcFormat, dstFormat; + + srcFormat.image_channel_order = CL_RGBA; + srcFormat.image_channel_data_type = CL_UNORM_INT8; + srcImagePtr = OclVppCLImage::create(m_display, src, m_context, srcFormat); + if (!srcImagePtr) { + ERROR("failed to create cl image from src frame"); + return YAMI_FAIL; + } + + dstFormat.image_channel_order = CL_RG; + dstFormat.image_channel_data_type = CL_UNORM_INT8; + dstImagePtr = OclVppCLImage::create(m_display, dst, m_context, dstFormat); + if (!dstImagePtr) { + ERROR("failed to create cl image from dst frame"); + return YAMI_FAIL; + } + + cl_mem bgImageMem[3]; + for (uint32_t n = 0; n < dstImagePtr->numPlanes(); n++) { + bgImageMem[n] = dstImagePtr->plane(n); + } + + uint32_t pixelSize = getPixelSize(dstFormat); + VideoRect crop; + crop.x = dst->crop.x / pixelSize; + crop.y = dst->crop.y & ~1; + crop.width = dst->crop.width / pixelSize; + crop.height = dst->crop.height; + if ((CL_SUCCESS != clSetKernelArg(m_kernelOsd, 0, sizeof(cl_mem), &dstImagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 1, sizeof(cl_mem), &dstImagePtr->plane(1))) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 2, sizeof(cl_mem), &bgImageMem[0])) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 3, sizeof(cl_mem), &bgImageMem[1])) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 4, sizeof(cl_mem), &srcImagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 5, sizeof(uint32_t), &crop.x)) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 6, sizeof(uint32_t), &crop.y)) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 7, sizeof(uint32_t), &crop.width)) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 8, sizeof(uint32_t), &crop.height)) + || (CL_SUCCESS != clSetKernelArg(m_kernelOsd, 9, sizeof(cl_mem), osdLuma.get()))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = ALIGN_POW2(dst->crop.width, localWorkSize[0] * pixelSize) / pixelSize; + globalWorkSize[1] = ALIGN_POW2(dst->crop.height, localWorkSize[1] * 2) / 2; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, m_kernelOsd, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + + return status; +} + +YamiStatus OclPostProcessOsd::setParameters(VppParamType type, void* vppParam) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + switch (type) { + case VppParamTypeOsd: { + VppParamOsd* osd = (VppParamOsd*)vppParam; + if (osd->size == sizeof(VppParamOsd)) { + m_threshold = osd->threshold; + status = YAMI_SUCCESS; + } + } break; + default: + status = OclPostProcessBase::setParameters(type, vppParam); + break; + } + return status; +} + +YamiStatus OclPostProcessOsd::computeBlockLuma(const SharedPtr frame) +{ + uint32_t blockWidth = frame->crop.height; + cl_image_format format; + format.image_channel_order = CL_RGBA; + format.image_channel_data_type = CL_UNSIGNED_INT8; + uint32_t pixelSize = getPixelSize(format); + + if (m_blockCount < (int)(frame->crop.width / blockWidth)) { + m_blockCount = frame->crop.width / blockWidth; + m_osdLuma.resize(m_blockCount); + } + + uint32_t padding = frame->crop.x % pixelSize; + uint32_t alignedWidth = frame->crop.width + padding; + if (m_lineBuf.size() < alignedWidth) + m_lineBuf.resize(alignedWidth); + + cl_int clStatus; + cl_mem clBuf = clCreateBuffer(m_context->m_context, + CL_MEM_WRITE_ONLY | CL_MEM_HOST_READ_ONLY, + m_lineBuf.size() * sizeof(uint32_t), + NULL, + &clStatus); + if (!checkOclStatus(clStatus, "CreateBuffer")) + return YAMI_FAIL; + SharedPtr lineBuf(new cl_mem(clBuf), OclMemDeleter()); + + SharedPtr imagePtr; + imagePtr = OclVppCLImage::create(m_display, frame, m_context, format); + if (!imagePtr) { + ERROR("failed to create cl image from src frame"); + return YAMI_FAIL; + } + + VideoRect crop; + crop.x = frame->crop.x / pixelSize; + crop.y = frame->crop.y; + crop.width = alignedWidth / pixelSize; + crop.height = frame->crop.height; + if ((CL_SUCCESS != clSetKernelArg(m_kernelReduceLuma, 0, sizeof(cl_mem), &imagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelReduceLuma, 1, sizeof(uint32_t), &crop.x)) + || (CL_SUCCESS != clSetKernelArg(m_kernelReduceLuma, 2, sizeof(uint32_t), &crop.y)) + || (CL_SUCCESS != clSetKernelArg(m_kernelReduceLuma, 3, sizeof(uint32_t), &crop.height)) + || (CL_SUCCESS != clSetKernelArg(m_kernelReduceLuma, 4, sizeof(cl_mem), lineBuf.get()))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + size_t localWorkSize = 16; + size_t globalWorkSize = ALIGN_POW2(alignedWidth, pixelSize * localWorkSize) / pixelSize; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, m_kernelReduceLuma, 1, NULL, + &globalWorkSize, &localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + if (!checkOclStatus(clEnqueueReadBuffer(m_context->m_queue, + *lineBuf, + CL_TRUE, + 0, + m_lineBuf.size() * sizeof(uint32_t), + m_lineBuf.data(), + 0, NULL, NULL), + "EnqueueReadBuffer")) { + return YAMI_FAIL; + } + + uint32_t acc; + int offset; + uint32_t blockThreshold = m_threshold * blockWidth * frame->crop.height; + for (int i = 0; i < m_blockCount; i++) { + acc = 0; + offset = i * blockWidth + padding; + for (uint32_t j = 0; j < blockWidth; j++) { + acc += m_lineBuf[offset + j]; + } + if (acc <= blockThreshold) + m_osdLuma[i] = 1.0; + else + m_osdLuma[i] = 0.0; + } + + return YAMI_SUCCESS; +} + +bool OclPostProcessOsd::prepareKernels() +{ + m_kernelOsd = prepareKernel("osd"); + m_kernelReduceLuma = prepareKernel("reduce_luma"); + + return (m_kernelOsd != NULL) + && (m_kernelReduceLuma != NULL); +} + +} diff --git a/vpp/oclpostprocess_osd.h b/vpp/oclpostprocess_osd.h new file mode 100644 index 0000000..b41300e --- /dev/null +++ b/vpp/oclpostprocess_osd.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef oclpostprocess_osd_h +#define oclpostprocess_osd_h + +#include +#include "VideoCommonDefs.h" +#include "oclpostprocess_base.h" + +using std::vector; + +namespace YamiMediaCodec { + +/** + * \class OclPostProcessOsd + * \brief OpenCL based OSD of contrastive font color + */ +class OclPostProcessOsd : public OclPostProcessBase { +public: + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dst); + + virtual YamiStatus setParameters(VppParamType type, void* vppParam); + + explicit OclPostProcessOsd() + : m_blockCount(0) + , m_threshold(128) + , m_kernelOsd(NULL) + , m_kernelReduceLuma(NULL) + { + ensureContext("osd"); + } + +private: + friend class FactoryTest; + friend class OclPostProcessOsdTest; + + virtual bool prepareKernels(); + YamiStatus computeBlockLuma(const SharedPtr frame); + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; + + vector m_osdLuma; + vector m_lineBuf; + int m_blockCount; + uint32_t m_threshold; + cl_kernel m_kernelOsd; + cl_kernel m_kernelReduceLuma; +}; +} +#endif //oclpostprocess_osd_h diff --git a/vpp/oclpostprocess_osd_unittest.cpp b/vpp/oclpostprocess_osd_unittest.cpp new file mode 100644 index 0000000..5394b7d --- /dev/null +++ b/vpp/oclpostprocess_osd_unittest.cpp @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "oclpostprocess_osd.h" + +namespace YamiMediaCodec { + +class OclPostProcessOsdTest + : public FactoryTest +{ }; + +#define OCLPOSTPROCESS_OSD_TEST(name) \ + TEST_F(OclPostProcessOsdTest, name) + +OCLPOSTPROCESS_OSD_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_OCL_OSD); + doFactoryTest(mimeTypes); +} + +} diff --git a/vpp/oclpostprocess_transform.cpp b/vpp/oclpostprocess_transform.cpp new file mode 100644 index 0000000..e290e52 --- /dev/null +++ b/vpp/oclpostprocess_transform.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "oclpostprocess_transform.h" +#include "common/common_def.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "vaapi/VaapiUtils.h" +#include "vpp/oclvppimage.h" + +namespace YamiMediaCodec { + +YamiStatus +OclPostProcessTransform::process(const SharedPtr& src, + const SharedPtr& dst) +{ + YamiStatus status = ensureContext("transform"); + if (status != YAMI_SUCCESS) + return status; + + if (src->fourcc != YAMI_FOURCC_NV12 || dst->fourcc != YAMI_FOURCC_NV12) { + ERROR("only support transform of NV12 video frame"); + return YAMI_INVALID_PARAM; + } + + cl_image_format format; + format.image_channel_order = CL_RGBA; + format.image_channel_data_type = CL_UNORM_INT8; + SharedPtr srcImage = OclVppCLImage::create(m_display, src, m_context, format); + if (!srcImage) { + ERROR("failed to create cl image from src video frame"); + return YAMI_FAIL; + } + SharedPtr dstImage = OclVppCLImage::create(m_display, dst, m_context, format); + if (!dstImage) { + ERROR("failed to create cl image from dst video frame"); + return YAMI_FAIL; + } + + if (m_transform & VPP_TRANSFORM_FLIP_H && m_transform & VPP_TRANSFORM_FLIP_V) { + // flip both v and h is effectively rotate 180 + m_transform &= ~(VPP_TRANSFORM_FLIP_H | VPP_TRANSFORM_FLIP_V); + switch (m_transform) { + case VPP_TRANSFORM_NONE: + m_transform = VPP_TRANSFORM_ROT_180; + case VPP_TRANSFORM_ROT_90: + m_transform = VPP_TRANSFORM_ROT_270; + break; + case VPP_TRANSFORM_ROT_180: + m_transform = VPP_TRANSFORM_NONE; + break; + case VPP_TRANSFORM_ROT_270: + m_transform = VPP_TRANSFORM_ROT_90; + break; + default: + ERROR("unsupported transform type"); + return YAMI_INVALID_PARAM; + } + } + + status = YAMI_INVALID_PARAM; + switch (m_transform) { + case VPP_TRANSFORM_FLIP_H | VPP_TRANSFORM_ROT_90: + case VPP_TRANSFORM_FLIP_V | VPP_TRANSFORM_ROT_270: + status = flipAndRotate(srcImage, dstImage, m_kernelFlipHRot90); + break; + case VPP_TRANSFORM_FLIP_V | VPP_TRANSFORM_ROT_90: + case VPP_TRANSFORM_FLIP_H | VPP_TRANSFORM_ROT_270: + status = flipAndRotate(srcImage, dstImage, m_kernelFlipVRot90); + break; + case VPP_TRANSFORM_FLIP_H | VPP_TRANSFORM_ROT_180: + case VPP_TRANSFORM_FLIP_V: + m_transform = VPP_TRANSFORM_FLIP_V; + status = flip(srcImage, dstImage); + break; + case VPP_TRANSFORM_FLIP_V | VPP_TRANSFORM_ROT_180: + case VPP_TRANSFORM_FLIP_H: + m_transform = VPP_TRANSFORM_FLIP_H; + status = flip(srcImage, dstImage); + break; + case VPP_TRANSFORM_ROT_90: + case VPP_TRANSFORM_ROT_180: + case VPP_TRANSFORM_ROT_270: + status = rotate(srcImage, dstImage); + break; + default: + ERROR("unsupported transform type"); + break; + } + + return status; +} + +YamiStatus OclPostProcessTransform::setParameters(VppParamType type, void* vppParam) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + switch (type) { + case VppParamTypeTransform: { + VppParamTransform* param = (VppParamTransform*)vppParam; + if (param->size == sizeof(VppParamTransform)) { + m_transform = param->transform; + status = YAMI_SUCCESS; + } + } break; + default: + status = OclPostProcessBase::setParameters(type, vppParam); + break; + } + return status; +} + +YamiStatus OclPostProcessTransform::flip(const SharedPtr& src, + const SharedPtr& dst) +{ + uint32_t width = src->getWidth(); + uint32_t height = src->getHeight(); + if (width != dst->getWidth() || height != dst->getHeight()) { + ERROR("flip failed due to unmatched resolution"); + return YAMI_INVALID_PARAM; + } + + uint32_t size; + cl_kernel kernel = NULL; + if (m_transform & VPP_TRANSFORM_FLIP_H) { + size = width / 4 - 1; + kernel = m_kernelFlipH; + } + else if (m_transform & VPP_TRANSFORM_FLIP_V) { + size = height; + kernel = m_kernelFlipV; + } + if (!kernel) { + ERROR("failed to get cl kernel"); + return YAMI_FAIL; + } + if ((CL_SUCCESS != clSetKernelArg(kernel, 0, sizeof(cl_mem), &dst->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 2, sizeof(cl_mem), &src->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 3, sizeof(cl_mem), &src->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 4, sizeof(uint32_t), &size))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = ALIGN_POW2(width, localWorkSize[0] * 4) / 4; + globalWorkSize[1] = ALIGN_POW2(height, localWorkSize[1] * 2) / 2; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, kernel, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + return YAMI_SUCCESS; +} + +YamiStatus OclPostProcessTransform::rotate(const SharedPtr& src, + const SharedPtr& dst) +{ + uint32_t width = src->getWidth(); + uint32_t height = src->getHeight(); + + uint32_t size, w, h; + cl_kernel kernel = NULL; + if (m_transform & VPP_TRANSFORM_ROT_90) { + if (width != dst->getHeight() || height != dst->getWidth()) { + ERROR("rotate failed due to unmatched resolution"); + return YAMI_INVALID_PARAM; + } + size = 4; + w = width / 4 - 1; + h = height / 4 - 1; + kernel = m_kernelRot90; + } + else if (m_transform & VPP_TRANSFORM_ROT_180) { + if (width != dst->getWidth() || height != dst->getHeight()) { + ERROR("rotate failed due to unmatched resolution"); + return YAMI_INVALID_PARAM; + } + size = 2; + w = width / 4 - 1; + h = height; + kernel = m_kernelRot180; + } + else if (m_transform & VPP_TRANSFORM_ROT_270) { + if (width != dst->getHeight() || height != dst->getWidth()) { + ERROR("rotate failed due to unmatched resolution"); + return YAMI_INVALID_PARAM; + } + size = 4; + w = width / 4 - 1; + h = height / 4 - 1; + kernel = m_kernelRot270; + } + if (!kernel) { + ERROR("failed to get cl kernel"); + return YAMI_FAIL; + } + if ((CL_SUCCESS != clSetKernelArg(kernel, 0, sizeof(cl_mem), &dst->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 2, sizeof(cl_mem), &src->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 3, sizeof(cl_mem), &src->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 4, sizeof(uint32_t), &w)) + || (CL_SUCCESS != clSetKernelArg(kernel, 5, sizeof(uint32_t), &h))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = ALIGN_POW2(width, localWorkSize[0] * 4) / 4; + globalWorkSize[1] = ALIGN_POW2(height, localWorkSize[1] * size) / size; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, kernel, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + return YAMI_SUCCESS; +} + +YamiStatus OclPostProcessTransform::flipAndRotate(const SharedPtr& src, + const SharedPtr& dst, + const cl_kernel& kernel) +{ + uint32_t width = src->getWidth(); + uint32_t height = src->getHeight(); + if (width != dst->getHeight() || height != dst->getWidth()) { + ERROR("flipAndRotate failed due to unmatched resolution"); + return YAMI_INVALID_PARAM; + } + + uint32_t size = 4; + uint32_t w = width / 4 - 1; + uint32_t h = height / 4 - 1; + if (!kernel) { + ERROR("failed to get cl kernel"); + return YAMI_FAIL; + } + if ((CL_SUCCESS != clSetKernelArg(kernel, 0, sizeof(cl_mem), &dst->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 2, sizeof(cl_mem), &src->plane(0))) + || (CL_SUCCESS != clSetKernelArg(kernel, 3, sizeof(cl_mem), &src->plane(1))) + || (CL_SUCCESS != clSetKernelArg(kernel, 4, sizeof(uint32_t), &w)) + || (CL_SUCCESS != clSetKernelArg(kernel, 5, sizeof(uint32_t), &h))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = ALIGN_POW2(width, localWorkSize[0] * 4) / 4; + globalWorkSize[1] = ALIGN_POW2(height, localWorkSize[1] * size) / size; + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, kernel, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + return YAMI_SUCCESS; +} + +bool OclPostProcessTransform::prepareKernels() +{ + m_kernelFlipH = prepareKernel("transform_flip_h"); + m_kernelFlipV = prepareKernel("transform_flip_v"); + m_kernelRot180 = prepareKernel("transform_rot_180"); + m_kernelRot90 = prepareKernel("transform_rot_90"); + m_kernelRot270 = prepareKernel("transform_rot_270"); + m_kernelFlipHRot90 = prepareKernel("transform_flip_h_rot_90"); + m_kernelFlipVRot90 = prepareKernel("transform_flip_v_rot_90"); + + return (m_kernelFlipH != NULL) + && (m_kernelFlipV != NULL) + && (m_kernelRot180 != NULL) + && (m_kernelRot90 != NULL) + && (m_kernelRot270 != NULL) + && (m_kernelFlipHRot90 != NULL) + && (m_kernelFlipVRot90 != NULL); +} + +} diff --git a/vpp/oclpostprocess_transform.h b/vpp/oclpostprocess_transform.h new file mode 100644 index 0000000..21ffcb8 --- /dev/null +++ b/vpp/oclpostprocess_transform.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef oclpostprocess_transform_h +#define oclpostprocess_transform_h + +#include +#include "VideoCommonDefs.h" +#include "oclpostprocess_base.h" + +using std::vector; + +namespace YamiMediaCodec { +class OclVppCLImage; +/** + * \class OclPostProcessTransform + * \brief OpenCL based flip and rotate + */ +class OclPostProcessTransform : public OclPostProcessBase { +public: + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dst); + + virtual YamiStatus setParameters(VppParamType type, void* vppParam); + + explicit OclPostProcessTransform() + : m_transform(0) + , m_kernelFlipH(NULL) + , m_kernelFlipV(NULL) + , m_kernelRot180(NULL) + , m_kernelRot90(NULL) + , m_kernelRot270(NULL) + , m_kernelFlipHRot90(NULL) + , m_kernelFlipVRot90(NULL) + { + ensureContext("transform"); + } + +private: + friend class FactoryTest; + friend class OclPostProcessTransformTest; + + virtual bool prepareKernels(); + YamiStatus flip(const SharedPtr& src, + const SharedPtr& dst); + YamiStatus rotate(const SharedPtr& src, + const SharedPtr& dst); + YamiStatus flipAndRotate(const SharedPtr& src, + const SharedPtr& dst, + const cl_kernel& kernel); + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; + + uint32_t m_transform; + cl_kernel m_kernelFlipH; + cl_kernel m_kernelFlipV; + cl_kernel m_kernelRot180; + cl_kernel m_kernelRot90; + cl_kernel m_kernelRot270; + cl_kernel m_kernelFlipHRot90; + cl_kernel m_kernelFlipVRot90; +}; +} +#endif //oclpostprocess_transform_h diff --git a/vpp/oclpostprocess_transform_unittest.cpp b/vpp/oclpostprocess_transform_unittest.cpp new file mode 100644 index 0000000..4a214e3 --- /dev/null +++ b/vpp/oclpostprocess_transform_unittest.cpp @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "oclpostprocess_transform.h" + +namespace YamiMediaCodec { + +class OclPostProcessTransformTest + : public FactoryTest +{ }; + +#define OCLPOSTPROCESS_TRANSFORM_TEST(name) \ + TEST_F(OclPostProcessTransformTest, name) + +OCLPOSTPROCESS_TRANSFORM_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_OCL_TRANSFORM); + doFactoryTest(mimeTypes); +} + +} diff --git a/vpp/oclpostprocess_wireframe.cpp b/vpp/oclpostprocess_wireframe.cpp new file mode 100644 index 0000000..b04e796 --- /dev/null +++ b/vpp/oclpostprocess_wireframe.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "oclpostprocess_wireframe.h" +#include "common/common_def.h" +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "vpp/oclvppimage.h" + +namespace YamiMediaCodec { + +YamiStatus +OclPostProcessWireframe::process(const SharedPtr& src, + const SharedPtr& dst) +{ + YamiStatus status = ensureContext("wireframe"); + if (status != YAMI_SUCCESS) + return status; + + if (src != dst) { + ERROR("src and dst must be the same for wireframe"); + return YAMI_INVALID_PARAM; + } + + if (dst->fourcc != YAMI_FOURCC_NV12) { + ERROR("only support wireframe on NV12 video frame"); + return YAMI_INVALID_PARAM; + } + + if (m_borderWidth == 0 + || dst->crop.width < 2 * m_borderWidth + || dst->crop.height < 2 * m_borderWidth) { + ERROR("wireframe invalid param"); + return YAMI_INVALID_PARAM; + } + + cl_image_format format; + format.image_channel_order = CL_RG; + format.image_channel_data_type = CL_UNSIGNED_INT8; + uint32_t pixelSize = getPixelSize(format); + uint32_t x = ALIGN_POW2(dst->crop.x, pixelSize) / pixelSize; + uint32_t y = ALIGN_POW2(dst->crop.y, pixelSize) / pixelSize; + uint32_t w = ALIGN_POW2(dst->crop.width, pixelSize) / pixelSize; + uint32_t h = ALIGN_POW2(dst->crop.height, pixelSize) / pixelSize; + uint32_t b = ALIGN_POW2(m_borderWidth, pixelSize) / pixelSize; + SharedPtr imagePtr = OclVppCLImage::create(m_display, dst, m_context, format); + if (!imagePtr->numPlanes()) { + ERROR("failed to create cl image from dst frame"); + return YAMI_FAIL; + } + + size_t globalWorkSize[2], localWorkSize[2]; + localWorkSize[0] = 8; + localWorkSize[1] = 8; + globalWorkSize[0] = (w / localWorkSize[0] + 1) * localWorkSize[0]; + globalWorkSize[1] = (h / localWorkSize[1] + 1) * localWorkSize[1]; + + if ((CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 0, sizeof(cl_mem), &imagePtr->plane(0))) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 1, sizeof(cl_mem), &imagePtr->plane(1))) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 2, sizeof(uint32_t), &x)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 3, sizeof(uint32_t), &y)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 4, sizeof(uint32_t), &w)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 5, sizeof(uint32_t), &h)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 6, sizeof(uint32_t), &b)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 7, sizeof(uint8_t), &m_colorY)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 8, sizeof(uint8_t), &m_colorU)) + || (CL_SUCCESS != clSetKernelArg(m_kernelWireframe, 9, sizeof(uint8_t), &m_colorV))) { + ERROR("clSetKernelArg failed"); + return YAMI_FAIL; + } + + if (!checkOclStatus(clEnqueueNDRangeKernel(m_context->m_queue, m_kernelWireframe, 2, NULL, + globalWorkSize, localWorkSize, 0, NULL, NULL), + "EnqueueNDRangeKernel")) { + return YAMI_FAIL; + } + + return status; +} + +YamiStatus OclPostProcessWireframe::setParameters(VppParamType type, void* vppParam) +{ + YamiStatus status = YAMI_INVALID_PARAM; + + switch (type) { + case VppParamTypeWireframe: { + VppParamWireframe* wireframe = (VppParamWireframe*)vppParam; + if (wireframe->size == sizeof(VppParamWireframe)) { + m_borderWidth = ALIGN2(wireframe->borderWidth); + if (m_borderWidth == 0 || m_borderWidth != wireframe->borderWidth) + ERROR("wireframe border width must be non-zero and 2-pixel aligned"); + m_colorY = wireframe->colorY; + m_colorU = wireframe->colorU; + m_colorV = wireframe->colorV; + status = YAMI_SUCCESS; + } + } break; + default: + status = OclPostProcessBase::setParameters(type, vppParam); + break; + } + return status; +} + +bool OclPostProcessWireframe::prepareKernels() +{ + m_kernelWireframe = prepareKernel("wireframe"); + + return m_kernelWireframe != NULL; +} + +} diff --git a/vpp/oclpostprocess_wireframe.h b/vpp/oclpostprocess_wireframe.h new file mode 100644 index 0000000..1d23b6c --- /dev/null +++ b/vpp/oclpostprocess_wireframe.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef oclpostprocess_wireframe_h +#define oclpostprocess_wireframe_h + +#include "interface/VideoCommonDefs.h" +#include "oclpostprocess_base.h" + +namespace YamiMediaCodec { + +/** + * \class OclPostProcessWireframe + * \brief OpenCL based wireframe filter + */ +class OclPostProcessWireframe : public OclPostProcessBase { +public: + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dst); + + virtual YamiStatus setParameters(VppParamType type, void* vppParam); + + explicit OclPostProcessWireframe() + : m_borderWidth(4) + , m_colorY(0xFF) + , m_colorU(0) + , m_colorV(0) + , m_kernelWireframe(NULL) + { + ensureContext("wireframe"); + } + +private: + friend class FactoryTest; + friend class OclPostProcessWireframeTest; + + virtual bool prepareKernels(); + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; + + uint32_t m_borderWidth; + uint8_t m_colorY; + uint8_t m_colorU; + uint8_t m_colorV; + cl_kernel m_kernelWireframe; +}; +} +#endif //oclpostprocess_wireframe_h diff --git a/vpp/oclpostprocess_wireframe_unittest.cpp b/vpp/oclpostprocess_wireframe_unittest.cpp new file mode 100644 index 0000000..0118385 --- /dev/null +++ b/vpp/oclpostprocess_wireframe_unittest.cpp @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "oclpostprocess_wireframe.h" + +namespace YamiMediaCodec { + +class OclPostProcessWireframeTest + : public FactoryTest +{ }; + +#define OCLPOSTPROCESS_WIREFRAME_TEST(name) \ + TEST_F(OclPostProcessWireframeTest, name) + +OCLPOSTPROCESS_WIREFRAME_TEST(Factory) { + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_OCL_WIREFRAME); + doFactoryTest(mimeTypes); +} + +} diff --git a/vpp/oclvppimage.cpp b/vpp/oclvppimage.cpp new file mode 100644 index 0000000..53e39ec --- /dev/null +++ b/vpp/oclvppimage.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "ocl/oclcontext.h" +#include "oclvppimage.h" +#include "vaapi/VaapiUtils.h" +#include + +namespace YamiMediaCodec { + +SharedPtr OclVppRawImage::create( + VADisplay d, + const SharedPtr& f) +{ + SharedPtr image(new OclVppRawImage(d, f)); + if (image->init()) + return image; + ERROR("Failed to create OclVppRawImage"); + image.reset(); + return image; +} + +bool OclVppRawImage::init() +{ + VASurfaceID surfaceId = (VASurfaceID)m_frame->surface; + if (!checkVaapiStatus(vaDeriveImage(m_display, surfaceId, &m_image), "DeriveImage")) + return false; + + uint8_t* buf = 0; + if (!checkVaapiStatus(vaMapBuffer(m_display, m_image.buf, (void**)&buf), "vaMapBuffer")) + return false; + + for (uint32_t n = 0; n < m_image.num_planes; n++) { + m_mem[n] = buf + m_image.offsets[n]; + } + return true; +} + +OclVppRawImage::~OclVppRawImage() +{ + checkVaapiStatus(vaUnmapBuffer(m_display, m_image.buf), "ReleaseBufferHandle"); + checkVaapiStatus(vaDestroyImage(m_display, m_image.image_id), "DestroyImage"); +} + +SharedPtr OclVppCLImage::create( + VADisplay d, + const SharedPtr& f, + const SharedPtr ctx, + const cl_image_format& fmt) +{ + SharedPtr image(new OclVppCLImage(d, f, ctx, fmt)); + if (image->init()) + return image; + ERROR("Failed to create OclVppCLImage"); + image.reset(); + return image; +} + +bool OclVppCLImage::init() +{ + VASurfaceID surfaceId = (VASurfaceID)m_frame->surface; + if (!checkVaapiStatus(vaDeriveImage(m_display, surfaceId, &m_image), "DeriveImage")) + return false; + + VABufferInfo bufferInfo; + bufferInfo.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME; + if (!checkVaapiStatus(vaAcquireBufferHandle(m_display, m_image.buf, &bufferInfo), + "AcquireBufferHandle")) + return false; + + cl_import_image_info_intel importInfo; + uint32_t height[3] = {0}; + switch (m_image.format.fourcc) { + case VA_FOURCC_RGBA: + height[0] = m_image.height; + break; + case VA_FOURCC_NV12: + height[0] = m_image.height; + height[1] = m_image.height / 2; + break; + default: + ERROR("unsupported format"); + return false; + } + + for (uint32_t n = 0; n < m_image.num_planes; n++) { + importInfo.fd = bufferInfo.handle; + importInfo.type = CL_MEM_OBJECT_IMAGE2D; + importInfo.fmt.image_channel_order = m_fmt.image_channel_order; + importInfo.fmt.image_channel_data_type = m_fmt.image_channel_data_type; + importInfo.row_pitch = m_image.pitches[n]; + importInfo.offset = m_image.offsets[n]; + importInfo.width = m_image.width; + importInfo.height = height[n]; + importInfo.size = importInfo.row_pitch * importInfo.height; + if (YAMI_SUCCESS != m_context->createImageFromFdIntel(&importInfo, &m_mem[n])) { + ERROR("createImageFromFdIntel failed"); + return false; + } + } + + return true; +} + +OclVppCLImage::~OclVppCLImage() +{ + for (uint32_t n = 0; n < m_image.num_planes; n++) + checkOclStatus(clReleaseMemObject(m_mem[n]), "ReleaseMemObject"); + + checkVaapiStatus(vaReleaseBufferHandle(m_display, m_image.buf), "ReleaseBufferHandle"); + checkVaapiStatus(vaDestroyImage(m_display, m_image.image_id), "DestroyImage"); +} +} diff --git a/vpp/oclvppimage.h b/vpp/oclvppimage.h new file mode 100644 index 0000000..3af4830 --- /dev/null +++ b/vpp/oclvppimage.h @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef oclvppimage_h +#define oclvppimage_h + +#include "VideoCommonDefs.h" +#include +#include + +namespace YamiMediaCodec { +/** + * \class OclVppImage + * \brief Image wrappers used by opencl vpp modules + * + */ +template +class OclVppImage { +public: + const MemType& plane(int n) { return m_mem[n]; } + uint32_t pitch(int n) { return m_image.pitches[n]; } + uint32_t numPlanes() { return m_image.num_planes; } + uint32_t getWidth() { return m_image.width; } + uint32_t getHeight() { return m_image.height; } + uint32_t getFourcc() { return m_frame->fourcc; } + +protected: + OclVppImage(VADisplay d, const SharedPtr& f) + : m_display(d) + , m_frame(f) + { + memset(&m_image, 0, sizeof(m_image)); + m_image.image_id = VA_INVALID_ID; + m_image.buf = VA_INVALID_ID; + } + virtual bool init() = 0; + + virtual ~OclVppImage() {} + VADisplay m_display; + SharedPtr m_frame; + VAImage m_image; + MemType m_mem[3]; +}; + +class OclVppRawImage : public OclVppImage { +public: + static SharedPtr create(VADisplay d, const SharedPtr& f); + ~OclVppRawImage(); + uint8_t pixel(uint32_t x, uint32_t y, int n) { return m_mem[n][y * pitch(n) + x]; } + +private: + OclVppRawImage(VADisplay d, const SharedPtr& f) + : OclVppImage(d, f) + { + } + virtual bool init(); +}; + +class OclVppCLImage : public OclVppImage { +public: + static SharedPtr create(VADisplay d, + const SharedPtr& f, + const SharedPtr ctx, + const cl_image_format& fmt); + ~OclVppCLImage(); + +private: + OclVppCLImage(VADisplay d, + const SharedPtr& f, + const SharedPtr ctx, + const cl_image_format& fmt) + : OclVppImage(d, f) + , m_context(ctx) + , m_fmt(fmt) + { + } + virtual bool init(); + + SharedPtr m_context; + const cl_image_format& m_fmt; +}; + +class OclMemDeleter { +public: + void operator()(cl_mem* mem) + { + checkOclStatus(clReleaseMemObject(*mem), "ReleaseMemObject"); + delete mem; + } +}; +} +#endif /* oclvppimage_h */ diff --git a/vpp/unittest_main.cpp b/vpp/unittest_main.cpp new file mode 100644 index 0000000..48fec41 --- /dev/null +++ b/vpp/unittest_main.cpp @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// library headers +#include "common/unittest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/vpp/vaapipostprocess_base.cpp b/vpp/vaapipostprocess_base.cpp new file mode 100644 index 0000000..1eb6412 --- /dev/null +++ b/vpp/vaapipostprocess_base.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapipostprocess_base.h" +#include "common/log.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/vaapicontext.h" +#include "vaapi/VaapiUtils.h" + +namespace YamiMediaCodec{ + +YamiStatus VaapiPostProcessBase::setNativeDisplay(const NativeDisplay& display) +{ + return initVA(display); +} + +YamiStatus VaapiPostProcessBase::initVA(const NativeDisplay& display) +{ + if (m_context) { + ERROR("do not init va more than one time"); + return YAMI_FAIL; + } + m_display = VaapiDisplay::create(display); + if (!m_display) { + ERROR("failed to create display"); + return YAMI_DRIVER_FAIL; + } + + ConfigPtr config; + YamiStatus status = VaapiConfig::create(m_display, VAProfileNone, VAEntrypointVideoProc, NULL, 0, config); + if (YAMI_SUCCESS != status) { + ERROR("failed to create config"); + return YAMI_NO_CONFIG; + } + + //register WxH as 1x1 to make configure creation not fail. + m_context = VaapiContext::create(config,1, 1, + 0, NULL, 0); + if (!m_context) { + ERROR("failed to create context"); + return YAMI_FAIL; + } + return YAMI_SUCCESS; +} + +void VaapiPostProcessBase::cleanupVA() +{ + m_context.reset(); + m_display.reset(); +} + +YamiStatus VaapiPostProcessBase::queryVideoProcFilterCaps( + VAProcFilterType filterType, void* filterCaps, uint32_t* numFilterCaps) +{ + if (!filterCaps) + return YAMI_INVALID_PARAM; + + if (!m_context) { + ERROR("no va context"); + return YAMI_FAIL; + } + + uint32_t tmp = 1; + if (!numFilterCaps) + numFilterCaps = &tmp; + VAStatus status = vaQueryVideoProcFilterCaps(m_display->getID(), m_context->getID(), + filterType, filterCaps, numFilterCaps); + if (!checkVaapiStatus(status, "vaQueryVideoProcFilterCaps") || !*numFilterCaps) { + return YAMI_UNSUPPORTED; + } + return YAMI_SUCCESS; +} + +VaapiPostProcessBase::~VaapiPostProcessBase() +{ + cleanupVA(); +} + +} diff --git a/vpp/vaapipostprocess_base.h b/vpp/vaapipostprocess_base.h new file mode 100644 index 0000000..c076ba7 --- /dev/null +++ b/vpp/vaapipostprocess_base.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapipostprocess_base_h +#define vaapipostprocess_base_h + +#include "VideoPostProcessInterface.h" +#include "vaapi/vaapiptrs.h" +#include +#include + +template +class FactoryTest; + +namespace YamiMediaCodec{ +/** + * \class IVideoPostProcess + * \brief Abstract video post process interface of libyami + * it is the interface with client. they are not thread safe. + */ +class VaapiPostProcessBase : public IVideoPostProcess { +public: + // set native display + virtual YamiStatus setNativeDisplay(const NativeDisplay& display); + // it may return YAMI_MORE_DATA when output is not ready + // it's no need fill every field of VideoFrame, we can get detailed information from lower level + // VideoFrame.surface is enough for most of case + // for some type of vpp such as deinterlace, we will hold a referece of src. + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dest) = 0; + virtual YamiStatus setParameters(VppParamType type, void* vppParam) { return YAMI_INVALID_PARAM; } + virtual ~VaapiPostProcessBase(); +protected: + //NativeDisplay m_externalDisplay; + YamiStatus initVA(const NativeDisplay& display); + void cleanupVA(); + + YamiStatus queryVideoProcFilterCaps(VAProcFilterType filterType, void* filterCaps, uint32_t* numFilterCaps = NULL); + + DisplayPtr m_display; + ContextPtr m_context; +}; +} +#endif /* vaapipostprocess_base_h */ diff --git a/vpp/vaapipostprocess_factory.h b/vpp/vaapipostprocess_factory.h new file mode 100644 index 0000000..4fa6c81 --- /dev/null +++ b/vpp/vaapipostprocess_factory.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapipostprocess_factory_h +#define vaapipostprocess_factory_h + +#include "common/factory.h" +#include "VideoPostProcessInterface.h" + +namespace YamiMediaCodec { + +typedef Factory VaapiPostProcessFactory; + +} // namespace YamiMediaCodec +#endif // vaapipostprocess_factory_h diff --git a/vpp/vaapipostprocess_host.cpp b/vpp/vaapipostprocess_host.cpp new file mode 100644 index 0000000..3febe00 --- /dev/null +++ b/vpp/vaapipostprocess_host.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "common/log.h" +#include "VideoPostProcessHost.h" +#include "vaapipostprocess_factory.h" + +#if __BUILD_OCL_FILTERS__ +#include "oclpostprocess_blender.h" +#include "oclpostprocess_mosaic.h" +#include "oclpostprocess_osd.h" +#include "oclpostprocess_transform.h" +#include "oclpostprocess_wireframe.h" + +namespace YamiMediaCodec { +const bool OclPostProcessBlender::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_OCL_BLENDER); +const bool OclPostProcessMosaic::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_OCL_MOSAIC); +const bool OclPostProcessOsd::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_OCL_OSD); +const bool OclPostProcessTransform::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_OCL_TRANSFORM); +const bool OclPostProcessWireframe::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_OCL_WIREFRAME); +} +#endif + +#include "vaapipostprocess_scaler.h" +namespace YamiMediaCodec { +const bool VaapiPostProcessScaler::s_registered = + VaapiPostProcessFactory::register_(YAMI_VPP_SCALER); +} + +using namespace YamiMediaCodec; + +IVideoPostProcess *createVideoPostProcess(const char *mimeType) +{ + if (!mimeType) { + ERROR("NULL mime type."); + return NULL; + } + + VaapiPostProcessFactory::Type vpp = + VaapiPostProcessFactory::create(mimeType); + + if (!vpp) + ERROR("Failed to create vpp for mimeType: '%s'", mimeType); + else + INFO("Created vpp for mimeType: '%s'", mimeType); + + return vpp; +} + +void releaseVideoPostProcess(IVideoPostProcess * p) +{ + delete p; +} + +std::vector getVideoPostProcessMimeTypes() +{ + return VaapiPostProcessFactory::keys(); +} diff --git a/vpp/vaapipostprocess_host_unittest.cpp b/vpp/vaapipostprocess_host_unittest.cpp new file mode 100644 index 0000000..fb28ab1 --- /dev/null +++ b/vpp/vaapipostprocess_host_unittest.cpp @@ -0,0 +1,95 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/unittest.h" + +// primary header +#include "VideoPostProcessHost.h" + +// system headers +#include +#include +#include + +namespace YamiMediaCodec { + +std::set& expectations() +{ + static std::set e; + +#if __BUILD_OCL_FILTERS__ + e.insert(YAMI_VPP_OCL_BLENDER); + e.insert(YAMI_VPP_OCL_OSD); + e.insert(YAMI_VPP_OCL_TRANSFORM); + e.insert(YAMI_VPP_OCL_MOSAIC); + e.insert(YAMI_VPP_OCL_WIREFRAME); +#endif + + e.insert(YAMI_VPP_SCALER); + + return e; +} + +class VaapiPostProcessHostTest + : public ::testing::TestWithParam +{ }; + +TEST_P(VaapiPostProcessHostTest, createVideoPostProcess) +{ + std::string mime = GetParam(); + IVideoPostProcess *vpp = createVideoPostProcess(mime.c_str()); + bool expect = expectations().count(mime) != 0; + + EXPECT_EQ(expect, (vpp != NULL)) + << "createVideoPostProcess(" << mime << "): " + << "did not " << (expect ? "SUCCEED" : "FAIL") + << " as it should have."; + + releaseVideoPostProcess(vpp); +} + +TEST_P(VaapiPostProcessHostTest, getVideoPostProcessMimeTypesContains) +{ + std::string mime = GetParam(); + std::vector avail = getVideoPostProcessMimeTypes(); + + bool expect = expectations().count(mime) != 0; + bool actual = std::find(avail.begin(), avail.end(), mime) != avail.end(); + + EXPECT_EQ( expect, actual ); +} + +INSTANTIATE_TEST_CASE_P( + MimeType, VaapiPostProcessHostTest, + ::testing::Values( + YAMI_VPP_SCALER, YAMI_VPP_OCL_BLENDER, YAMI_VPP_OCL_OSD, + YAMI_VPP_OCL_TRANSFORM, YAMI_VPP_OCL_MOSAIC, YAMI_VPP_OCL_WIREFRAME)); +} diff --git a/vpp/vaapipostprocess_scaler.cpp b/vpp/vaapipostprocess_scaler.cpp new file mode 100644 index 0000000..bfb60c2 --- /dev/null +++ b/vpp/vaapipostprocess_scaler.cpp @@ -0,0 +1,429 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "vaapipostprocess_scaler.h" + +#include "vaapi/vaapidisplay.h" +#include "vaapi/vaapicontext.h" +#include "vaapivpppicture.h" +#include "common/log.h" +#include + +namespace YamiMediaCodec { + +static bool fillRect(VARectangle& vaRect, const VideoRect& rect) +{ + vaRect.x = rect.x; + vaRect.y = rect.y; + vaRect.width = rect.width; + vaRect.height = rect.height; + return rect.x || rect.y || rect.width || rect.height; +} + +static void copyVideoFrameMeta(const SharedPtr& src, const SharedPtr& dest) +{ + dest->timeStamp = src->timeStamp; + dest->flags = src->flags; +} + +//android csc need us set color standard +VAProcColorStandardType fourccToColorStandard(uint32_t fourcc) +{ + if (fourcc == YAMI_FOURCC_RGBX + || fourcc == YAMI_FOURCC_RGBA + || fourcc == YAMI_FOURCC_BGRX + || fourcc == YAMI_FOURCC_BGRA) { + //we should return VAProcColorStandardSRGB here + //but it only exist on libva staging. so we return None + //side effect is android libva will print error info when we convert it to RGB + //we will change this after staing merged to master + //return VAProcColorStandardSRGB; + return VAProcColorStandardNone; + } + if (fourcc == YAMI_FOURCC_NV12) + return VAProcColorStandardBT601; + return VAProcColorStandardBT601; +} + +VaapiPostProcessScaler::VaapiPostProcessScaler() +{ + m_denoise.level = DENOISE_LEVEL_NONE; + m_sharpening.level = SHARPENING_LEVEL_NONE; + m_transform = VPP_TRANSFORM_NONE; +} + +bool VaapiPostProcessScaler::getFilters(std::vector& filters) +{ + if (m_denoise.filter) { + filters.push_back(m_denoise.filter->getID()); + } + if (m_sharpening.filter) { + filters.push_back(m_sharpening.filter->getID()); + } + if (m_deinterlace.filter) { + filters.push_back(m_deinterlace.filter->getID()); + } + + for (ColorBalanceMapItr itr = m_colorBalance.begin(); itr != m_colorBalance.end(); itr++) { + if (itr->second.filter) { + filters.push_back(itr->second.filter->getID()); + } + } + return !filters.empty(); +} + +YamiStatus +VaapiPostProcessScaler::process(const SharedPtr& src, + const SharedPtr& dest) +{ + if (!m_context) { + ERROR("NO context for scaler"); + return YAMI_FAIL; + } + if (!src || !dest) { + return YAMI_INVALID_PARAM; + } + if(src->crop.width & 0x01 || src->crop.height & 0x01){ + ERROR("unsupported odd resolution"); + return YAMI_FAIL; + } + + copyVideoFrameMeta(src, dest); + SurfacePtr surface(new VaapiSurface(dest)); + VaapiVppPicture picture(m_context, surface); + VAProcPipelineParameterBuffer* vppParam; + if (!picture.editVppParam(vppParam)) { + return YAMI_OUT_MEMORY; + } + VARectangle srcCrop, destCrop; + if (fillRect(srcCrop, src->crop)) + vppParam->surface_region = &srcCrop; + vppParam->surface = (VASurfaceID)src->surface; + vppParam->surface_color_standard = fourccToColorStandard(src->fourcc); + + if (fillRect(destCrop, dest->crop)) + vppParam->output_region = &destCrop; + vppParam->output_color_standard = fourccToColorStandard(dest->fourcc); + + std::vector filters; + if (getFilters(filters)) { + vppParam->filters = &filters[0]; + vppParam->num_filters = (unsigned int)filters.size(); + } +#if VA_CHECK_VERSION(1, 1, 0) + vppParam->rotation_state = mapToVARotationState(m_transform); +#endif + + return picture.process() ? YAMI_SUCCESS : YAMI_FAIL; +} + +uint32_t VaapiPostProcessScaler::mapToVARotationState(VppTransform vppTransform) +{ + switch (vppTransform) { + case VPP_TRANSFORM_ROT_90: + return VA_ROTATION_90; + case VPP_TRANSFORM_ROT_180: + return VA_ROTATION_180; + case VPP_TRANSFORM_ROT_270: + return VA_ROTATION_270; + default: + return VA_ROTATION_NONE; + } +} + +bool VaapiPostProcessScaler::mapToRange( + float& value, float min, float max, + int32_t level, int32_t minLevel, int32_t maxLevel) +{ + if (minLevel >= maxLevel) { + ERROR("minLevel(%d) >= maxLevel(%d)", minLevel, maxLevel); + return false; + } + if (level > maxLevel || level < minLevel) { + ERROR("level(%d) not in the range[minLevel(%d), maxLevel(%d)]", level, minLevel, maxLevel); + return false; + } + if (min >= max) { + ERROR("min(%f) >= max(%f)", min, max); + return false; + } + + value = min + (max - min) / (maxLevel - minLevel) * level; + + return true; +} + +bool VaapiPostProcessScaler::mapToRange(float& value, int32_t level, + int32_t minLevel, int32_t maxLevel, + VAProcFilterType filterType, SharedPtr& caps) +{ + if (!caps) { + //query from libva + YamiStatus status; + caps.reset(new VAProcFilterCap); + status = queryVideoProcFilterCaps(filterType, caps.get()); + if (status != YAMI_SUCCESS) { + caps.reset(); + return false; + } + } + return mapToRange(value, caps->range.min_value, caps->range.max_value, level, minLevel, maxLevel); +} + +YamiStatus +VaapiPostProcessScaler::setParamToNone(ProcParams& params, int32_t none) +{ + params.level = none; + params.filter.reset(); + return YAMI_SUCCESS; +} + +YamiStatus +VaapiPostProcessScaler::createFilter(BufObjectPtr& filter, VAProcFilterType type, float value) +{ + VAProcFilterParameterBuffer* f; + filter = VaapiBuffer::create(m_context, VAProcFilterParameterBufferType, f); + if (filter) { + f->type = type; + f->value = value; + //unmap for va use. + filter->unmap(); + return YAMI_SUCCESS; + } + return YAMI_FAIL; +} + +YamiStatus +VaapiPostProcessScaler::setProcParams(ProcParams& params, int32_t level, + int32_t min, int32_t max, int32_t none, VAProcFilterType type) +{ + if (params.level == level) + return YAMI_SUCCESS; + if (level == none) + return setParamToNone(params, none); + float value; + if (!mapToRange(value, level, min, max, type, params.caps)) { + setParamToNone(params, none); + return YAMI_INVALID_PARAM; + } + return createFilter(params.filter, type, value); +} + +static VAProcDeinterlacingType getDeinterlaceMode(VppDeinterlaceMode mode) +{ + switch (mode) { + case DEINTERLACE_MODE_BOB: + return VAProcDeinterlacingBob; + default: + break; + } + return VAProcDeinterlacingNone; +} + +YamiStatus +VaapiPostProcessScaler::createDeinterlaceFilter(const VPPDeinterlaceParameters& deinterlace) +{ + VAProcFilterParameterBufferDeinterlacing* d; + m_deinterlace.filter = VaapiBuffer::create(m_context, VAProcFilterParameterBufferType, d); + if (!m_deinterlace.filter) + return YAMI_DRIVER_FAIL; + d->type = VAProcFilterDeinterlacing; + d->algorithm = getDeinterlaceMode(deinterlace.mode); + //unmap for va usage + m_deinterlace.filter->unmap(); + return YAMI_SUCCESS; +} + +static bool mapToVppColorBalanceMode(VppColorBalanceMode& vppMode, VAProcColorBalanceType vaMode) +{ + switch (vaMode) { + case VAProcColorBalanceNone: + vppMode = COLORBALANCE_NONE; + break; + case VAProcColorBalanceHue: + vppMode = COLORBALANCE_HUE; + break; + case VAProcColorBalanceSaturation: + vppMode = COLORBALANCE_SATURATION; + break; + case VAProcColorBalanceBrightness: + vppMode = COLORBALANCE_BRIGHTNESS; + break; + case VAProcColorBalanceContrast: + vppMode = COLORBALANCE_CONTRAST; + break; + default: + return false; + } + return true; +} + +YamiStatus +VaapiPostProcessScaler::createColorBalanceFilters(ColorBalanceParam& clrBalance, const VPPColorBalanceParameter& vppClrBalance) +{ + float value; + + if (!mapToRange(value, clrBalance.range.min_value, clrBalance.range.max_value, vppClrBalance.level, COLORBALANCE_LEVEL_MIN, COLORBALANCE_LEVEL_MAX)) { + return YAMI_DRIVER_FAIL; + } + + VAProcFilterParameterBufferColorBalance* d; + clrBalance.filter = VaapiBuffer::create(m_context, VAProcFilterParameterBufferType, d); + if (!clrBalance.filter) + return YAMI_DRIVER_FAIL; + d->type = VAProcFilterColorBalance; + d->attrib = clrBalance.type; + d->value = value; + + //unmap for va usage + clrBalance.filter->unmap(); + clrBalance.level = vppClrBalance.level; + return YAMI_SUCCESS; +} + +YamiStatus VaapiPostProcessScaler::setDeinterlaceParam(const VPPDeinterlaceParameters& deinterlace) +{ + std::set& supported = m_deinterlace.supportedModes; + if (supported.empty()) { + //query from libva. + VAProcFilterCapDeinterlacing caps[VAProcDeinterlacingCount]; + uint32_t num = VAProcDeinterlacingCount; + YamiStatus status = queryVideoProcFilterCaps(VAProcFilterDeinterlacing, caps, &num); + if (status != YAMI_SUCCESS) + return status; + for (uint32_t i = 0; i < num; i++) { + //only support bob yet + if (caps[i].type == VAProcDeinterlacingBob) { + supported.insert(DEINTERLACE_MODE_BOB); + } + } + } + VppDeinterlaceMode mode = deinterlace.mode; + if (mode == DEINTERLACE_MODE_NONE) { + m_deinterlace.filter.reset(); + return YAMI_SUCCESS; + } + if (supported.find(mode) == supported.end()) { + m_deinterlace.filter.reset(); + return YAMI_UNSUPPORTED; + } + m_deinterlace.mode = mode; + return createDeinterlaceFilter(deinterlace); +} + +YamiStatus VaapiPostProcessScaler::setColorBalanceParam(const VPPColorBalanceParameter& colorbalance) +{ + VAProcFilterCapColorBalance caps[VAProcColorBalanceCount]; + VppColorBalanceMode vppClrBalanceMode; + if (m_colorBalance.empty()) { + uint32_t num = VAProcColorBalanceCount; + //query from libva. + YamiStatus status = queryVideoProcFilterCaps(VAProcFilterColorBalance, caps, &num); + if (status != YAMI_SUCCESS) + return status; + for (uint32_t i = 0; i < num; i++) { + if (mapToVppColorBalanceMode(vppClrBalanceMode, caps[i].type)) { + m_colorBalance[vppClrBalanceMode].range = caps[i].range; + m_colorBalance[vppClrBalanceMode].type = caps[i].type; + m_colorBalance[vppClrBalanceMode].level = COLORBALANCE_LEVEL_NONE; + } + } + } + + if(COLORBALANCE_NONE == colorbalance.mode){ + for (ColorBalanceMapItr itr = m_colorBalance.begin(); itr != m_colorBalance.end(); itr++) { + if (itr->second.filter) { + itr->second.filter.reset(); + itr->second.level = COLORBALANCE_LEVEL_NONE; + } + } + return YAMI_SUCCESS; + } + + ColorBalanceMapItr iteratorClrBalance = m_colorBalance.find(colorbalance.mode); + if (iteratorClrBalance == m_colorBalance.end()) { + ERROR("unsupported VppColorBalanceMode: %d", colorbalance.mode); + return YAMI_UNSUPPORTED; + } + + if (colorbalance.level == COLORBALANCE_LEVEL_NONE) { + if (iteratorClrBalance->second.filter) + iteratorClrBalance->second.filter.reset(); + iteratorClrBalance->second.level = colorbalance.level; + return YAMI_SUCCESS; + } + + if (colorbalance.level == iteratorClrBalance->second.level) { + return YAMI_SUCCESS; + } + + return createColorBalanceFilters(iteratorClrBalance->second, colorbalance); +} + +YamiStatus +VaapiPostProcessScaler::setParameters(VppParamType type, void* vppParam) +{ + if (!vppParam) + return YAMI_INVALID_PARAM; + if (!m_context) { + ERROR("no context"); + return YAMI_FAIL; + } + if (type == VppParamTypeDenoise) { + VPPDenoiseParameters* denoise = (VPPDenoiseParameters*)vppParam; + if (denoise->size != sizeof(VPPDenoiseParameters)) + return YAMI_INVALID_PARAM; + return setProcParams(m_denoise, denoise->level, + DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_NONE, VAProcFilterNoiseReduction); + } + else if (type == VppParamTypeSharpening) { + VPPSharpeningParameters* sharpening = (VPPSharpeningParameters*)vppParam; + if (sharpening->size != sizeof(VPPSharpeningParameters)) + return YAMI_INVALID_PARAM; + return setProcParams(m_sharpening, sharpening->level, + SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_NONE, VAProcFilterSharpening); + } + else if (type == VppParamTypeDeinterlace) { + VPPDeinterlaceParameters* deinterlace = (VPPDeinterlaceParameters*)vppParam; + if (deinterlace->size != sizeof(VPPDeinterlaceParameters)) + return YAMI_INVALID_PARAM; + return setDeinterlaceParam(*deinterlace); + } + else if (type == VppParamTypeColorBalance) { + VPPColorBalanceParameter* colorbalance = (VPPColorBalanceParameter*)vppParam; + if (colorbalance->size != sizeof(VPPColorBalanceParameter)) + return YAMI_INVALID_PARAM; + + return setColorBalanceParam(*colorbalance); + } + else if (type == VppParamTypeTransform) { +#if VA_CHECK_VERSION(1, 1, 0) + VppParamTransform* param = (VppParamTransform*)vppParam; + if (param->size != sizeof(VppParamTransform)) { + return YAMI_INVALID_PARAM; + } + m_transform = (VppTransform)param->transform; + return YAMI_SUCCESS; +#else + return YAMI_INVALID_PARAM; +#endif + } + return VaapiPostProcessBase::setParameters(type, vppParam); +} +} diff --git a/vpp/vaapipostprocess_scaler.h b/vpp/vaapipostprocess_scaler.h new file mode 100644 index 0000000..e9889c2 --- /dev/null +++ b/vpp/vaapipostprocess_scaler.h @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2013-2016 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapipostprocess_scaler_h +#define vaapipostprocess_scaler_h + +#include "vaapipostprocess_base.h" +#include +#include +#include + +namespace YamiMediaCodec{ + +/* class for video scale and color space conversion */ +class VaapiPostProcessScaler : public VaapiPostProcessBase { +public: + VaapiPostProcessScaler(); + virtual YamiStatus process(const SharedPtr& src, + const SharedPtr& dest); + + virtual YamiStatus setParameters(VppParamType type, void* vppParam); + +private: + friend class FactoryTest; + friend class VaapiPostProcessScalerTest; + + struct ProcParams { + int32_t level; //set by user + SharedPtr caps; //query from va; + BufObjectPtr filter; //send to va; + }; + + struct DeinterlaceParams { + VppDeinterlaceMode mode; //set by user + std::set supportedModes; //query from va + BufObjectPtr filter; //send to va; + }; + + struct ColorBalanceParam { + BufObjectPtr filter; //send to va; + int32_t level; //send to va + VAProcColorBalanceType type; //query from va + VAProcFilterValueRange range; //query from va + }; + + typedef std::map ColorBalanceMap; + typedef ColorBalanceMap::iterator ColorBalanceMapItr; + uint32_t mapToVARotationState(VppTransform vppTransform); + + bool mapToRange(float& value, float min, float max, + int32_t level, int32_t minLevel, int32_t maxLevel); + + //map to driver's range + bool mapToRange(float& value, int32_t level, int32_t minLevel, int32_t maxLevel, + VAProcFilterType filterType, SharedPtr& caps); + + YamiStatus setParamToNone(ProcParams& params, int32_t none); + + bool getFilters(std::vector& filters); + YamiStatus createFilter(BufObjectPtr& filter, VAProcFilterType, float value); + + YamiStatus setProcParams(ProcParams& params, int32_t level, + int32_t min, int32_t max, int32_t none, VAProcFilterType type); + + YamiStatus setDeinterlaceParam(const VPPDeinterlaceParameters&); + YamiStatus createDeinterlaceFilter(const VPPDeinterlaceParameters&); + YamiStatus setColorBalanceParam(const VPPColorBalanceParameter&); + YamiStatus createColorBalanceFilters(ColorBalanceParam& clrBalance, const VPPColorBalanceParameter& vppClrBalance); + + ProcParams m_denoise; + ProcParams m_sharpening; + DeinterlaceParams m_deinterlace; + ColorBalanceMap m_colorBalance; + VppTransform m_transform; + + /** + * VaapiPostProcessFactory registration result. This postprocess is + * registered in vaapipostprocess_host.cpp + */ + static const bool s_registered; +}; +} +#endif /* vaapipostprocess_scaler_h */ diff --git a/vpp/vaapipostprocess_scaler_unittest.cpp b/vpp/vaapipostprocess_scaler_unittest.cpp new file mode 100644 index 0000000..e841424 --- /dev/null +++ b/vpp/vaapipostprocess_scaler_unittest.cpp @@ -0,0 +1,334 @@ +/* + * Copyright 2016 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +// +// The unittest header must be included before va_x11.h (which might be included +// indirectly). The va_x11.h includes Xlib.h and X.h. And the X headers +// define 'Bool' and 'None' preprocessor types. Gtest uses the same names +// to define some struct placeholders. Thus, this creates a compile conflict +// if X defines them before gtest. Hence, the include order requirement here +// is the only fix for this right now. +// +// See bug filed on gtest at https://github.com/google/googletest/issues/371 +// for more details. +// +#include "common/factory_unittest.h" + +// primary header +#include "vaapipostprocess_scaler.h" + +#include "common/log.h" +#include "vaapi/vaapidisplay.h" +#include "vaapi/VaapiUtils.h" + +namespace YamiMediaCodec { + +typedef void (*VppTestFunction)(VaapiPostProcessScaler& scaler, + const SharedPtr& src, const SharedPtr& dest); + +struct FrameDestroyer { + FrameDestroyer(DisplayPtr display) + : m_display(display) + { + } + void operator()(VideoFrame* frame) + { + VASurfaceID id = (VASurfaceID)frame->surface; + checkVaapiStatus(vaDestroySurfaces(m_display->getID(), &id, 1), + "vaDestroySurfaces"); + delete frame; + } + +private: + DisplayPtr m_display; +}; + +//TODO: refact it with decoder base +SharedPtr createVideoFrame(const DisplayPtr& display, uint32_t width, uint32_t height, uint32_t fourcc) +{ + SharedPtr frame; + VASurfaceAttrib attrib; + attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; + attrib.type = VASurfaceAttribPixelFormat; + attrib.value.type = VAGenericValueTypeInteger; + attrib.value.value.i = fourcc; + uint32_t rtformat; + if (fourcc == VA_FOURCC_BGRX + || fourcc == VA_FOURCC_BGRA) { + rtformat = VA_RT_FORMAT_RGB32; + ERROR("rgb32"); + } + else { + rtformat = VA_RT_FORMAT_YUV420; + } + + VASurfaceID id; + VAStatus status = vaCreateSurfaces(display->getID(), rtformat, width, height, + &id, 1, &attrib, 1); + if (status != VA_STATUS_SUCCESS) { + ERROR("create surface failed fourcc = %d", fourcc); + return frame; + } + frame.reset(new VideoFrame, FrameDestroyer(display)); + memset(frame.get(), 0, sizeof(VideoFrame)); + frame->surface = (intptr_t)id; + return frame; +} + +class VaapiPostProcessScalerTest + : public FactoryTest { +public: + static void checkFilter(const VaapiPostProcessScaler& scaler, VppParamType type) + { + if (type == VppParamTypeDenoise) { + EXPECT_TRUE(bool(scaler.m_denoise.filter)); + } + else if (type == VppParamTypeSharpening) { + EXPECT_TRUE(bool(scaler.m_sharpening.filter)); + } + } + + static void checkColorBalanceFilter(VaapiPostProcessScaler& scaler, VppColorBalanceMode mode) + { + if (COLORBALANCE_NONE != mode) { + EXPECT_TRUE(bool(scaler.m_colorBalance[mode].filter)); + } + } + +protected: + /* invoked by gtest before the test */ + virtual void SetUp() + { + return; + } + + /* invoked by gtest after the test */ + virtual void TearDown() + { + return; + } + + static void checkFilterCaps(VaapiPostProcessScaler& scaler, + VAProcFilterType filterType, + int32_t minLevel, int32_t maxLevel, int32_t level) + { + + SharedPtr caps; + float value; + + EXPECT_TRUE(scaler.mapToRange(value, level, minLevel, maxLevel, filterType, caps)); + ASSERT_TRUE(bool(caps)); + EXPECT_LT(caps->range.min_value, caps->range.max_value); + EXPECT_LE(caps->range.min_value, value); + EXPECT_LE(value, caps->range.max_value); + } + + static void checkMapToRange() + { + float value; + VaapiPostProcessScaler scaler; + EXPECT_TRUE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); + EXPECT_FLOAT_EQ(0, value); + EXPECT_TRUE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); + EXPECT_FLOAT_EQ(64, value); + EXPECT_FALSE(scaler.mapToRange(value, 0, 64, DENOISE_LEVEL_NONE, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX)); + + NativeDisplay nDisplay; + memset(&nDisplay, 0, sizeof(nDisplay)); + ASSERT_EQ(YAMI_SUCCESS, scaler.setNativeDisplay(nDisplay)); + + checkFilterCaps(scaler, VAProcFilterNoiseReduction, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MIN); + checkFilterCaps(scaler, VAProcFilterNoiseReduction, DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_MAX); + + checkFilterCaps(scaler, VAProcFilterSharpening, SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_MIN); + checkFilterCaps(scaler, VAProcFilterSharpening, SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_MAX); + } + + static void vppTest(VppTestFunction func) + { + NativeDisplay nDisplay; + memset(&nDisplay, 0, sizeof(nDisplay)); + + VaapiPostProcessScaler scaler; + ASSERT_EQ(YAMI_SUCCESS, scaler.setNativeDisplay(nDisplay)); + + SharedPtr src = createVideoFrame(scaler.m_display, 320, 240, YAMI_FOURCC_NV12); + SharedPtr dest = createVideoFrame(scaler.m_display, 480, 272, YAMI_FOURCC_NV12); + ASSERT_TRUE(src && dest); + func(scaler, src, dest); + } +}; + +#define VAAPIPOSTPROCESS_SCALER_TEST(name) \ + TEST_F(VaapiPostProcessScalerTest, name) + +VAAPIPOSTPROCESS_SCALER_TEST(Factory) +{ + FactoryKeys mimeTypes; + mimeTypes.push_back(YAMI_VPP_SCALER); + doFactoryTest(mimeTypes); +} + +VAAPIPOSTPROCESS_SCALER_TEST(mapToRange) +{ + checkMapToRange(); +} + +template +void VppSetParams(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest, + P& params, int32_t& value, int32_t min, int32_t max, int32_t none, VppParamType type) +{ + memset(¶ms, 0, sizeof(P)); + params.size = sizeof(P); + value = min; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + value = max; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + value = none; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + value = (min + max) / 2; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(type, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + VaapiPostProcessScalerTest::checkFilter(scaler, type); +} + +void VppColorBalanceSetParams(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest, + VppColorBalanceMode mode) +{ + VPPColorBalanceParameter params; + memset(¶ms, 0, sizeof(params)); + params.size = sizeof(params); + + if (COLORBALANCE_COUNT == mode) { + params.mode = mode; + EXPECT_EQ(YAMI_UNSUPPORTED, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + return; + } + + if (COLORBALANCE_NONE == mode) { + params.mode = mode; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + return; + } + + params.mode = mode; + params.level = COLORBALANCE_LEVEL_MIN; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + params.mode = mode; + params.level = COLORBALANCE_LEVEL_MAX; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + params.mode = mode; + params.level = COLORBALANCE_LEVEL_NONE; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + params.mode = mode; + params.level = COLORBALANCE_LEVEL_MIN - 10; + EXPECT_EQ(YAMI_DRIVER_FAIL, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + + params.mode = mode; + params.level = COLORBALANCE_LEVEL_MAX + 10; + EXPECT_EQ(YAMI_DRIVER_FAIL, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + + params.mode = mode; + params.level = (COLORBALANCE_LEVEL_MIN + COLORBALANCE_LEVEL_MAX) / 2; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeColorBalance, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + VaapiPostProcessScalerTest::checkColorBalanceFilter(scaler, mode); +} + +void VppDenoise(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest) +{ + VPPDenoiseParameters params; + VppSetParams(scaler, src, dest, params, params.level, + DENOISE_LEVEL_MIN, DENOISE_LEVEL_MAX, DENOISE_LEVEL_NONE, VppParamTypeDenoise); +} + +VAAPIPOSTPROCESS_SCALER_TEST(Denoise) +{ + vppTest(VppDenoise); +} + +void VppSharpening(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest) +{ + VPPSharpeningParameters params; + VppSetParams(scaler, src, dest, params, params.level, + SHARPENING_LEVEL_MIN, SHARPENING_LEVEL_MAX, SHARPENING_LEVEL_NONE, VppParamTypeSharpening); +} + +VAAPIPOSTPROCESS_SCALER_TEST(Sharpening) +{ + vppTest(VppSharpening); +} + +void VppDeinterlace(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest) +{ + VPPDeinterlaceParameters params; + memset(¶ms, 0, sizeof(params)); + params.size = sizeof(params); + + params.mode = DEINTERLACE_MODE_BOB; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + params.mode = DEINTERLACE_MODE_NONE; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); + + params.mode = DEINTERLACE_MODE_WEAVE; + EXPECT_EQ(YAMI_SUCCESS, scaler.setParameters(VppParamTypeDeinterlace, ¶ms)); + EXPECT_EQ(YAMI_SUCCESS, scaler.process(src, dest)); +} + +VAAPIPOSTPROCESS_SCALER_TEST(Deinterlace) +{ + vppTest(VppDeinterlace); +} + +void VppColorBalance(VaapiPostProcessScaler& scaler, const SharedPtr& src, const SharedPtr& dest) +{ + VppParamWireframe wireFrameParams; + EXPECT_EQ(YAMI_INVALID_PARAM, scaler.setParameters(VppParamTypeColorBalance, &wireFrameParams)); + + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_NONE); + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_HUE); + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_SATURATION); + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_BRIGHTNESS); + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_CONTRAST); + VppColorBalanceSetParams(scaler, src, dest, COLORBALANCE_COUNT); +} + +VAAPIPOSTPROCESS_SCALER_TEST(Colorbalance) +{ + vppTest(VppColorBalance); +} +} diff --git a/vpp/vaapivpppicture.cpp b/vpp/vaapivpppicture.cpp new file mode 100644 index 0000000..c083fc2 --- /dev/null +++ b/vpp/vaapivpppicture.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "vaapivpppicture.h" +#include "common/log.h" + +namespace YamiMediaCodec{ +VaapiVppPicture::VaapiVppPicture(const ContextPtr& context, + const SurfacePtr & surface) +:VaapiPicture(context, surface, 0) +{ +} + +bool VaapiVppPicture::editVppParam(VAProcPipelineParameterBuffer*& vppParm) +{ + return editObject(m_vppParam, VAProcPipelineParameterBufferType, vppParm); +} + +bool VaapiVppPicture::process() +{ + return render(); +} + +bool VaapiVppPicture::doRender() +{ + RENDER_OBJECT(m_vppParam); + return true; +} + +} diff --git a/vpp/vaapivpppicture.h b/vpp/vaapivpppicture.h new file mode 100644 index 0000000..cc4d543 --- /dev/null +++ b/vpp/vaapivpppicture.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef vaapivpppicture_h +#define vaapivpppicture_h + +#include "vaapi/vaapipicture.h" +#include + +namespace YamiMediaCodec{ + +class VaapiVppPicture:public VaapiPicture { +public: + VaapiVppPicture(const ContextPtr& context, + const SurfacePtr & surface); + virtual ~VaapiVppPicture() { } + + bool editVppParam(VAProcPipelineParameterBuffer*&); + + bool process(); + +protected: + bool doRender(); +private: + BufObjectPtr m_vppParam; + DISALLOW_COPY_AND_ASSIGN(VaapiVppPicture); +}; + +} + +#endif /* vaapivpppicture_h */