From 8f7ba03ed29284d86c68831996ec826692ba7bd6 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Fri, 14 Jun 2013 11:53:54 +0400
Subject: [PATCH 01/75] Some fixes for incorrectly documented parameters
 identified by rst_parser.py (Bug #1205)

---
 modules/core/doc/basic_structures.rst         | 31 +++++++++++++++++--
 modules/core/doc/clustering.rst               |  8 +++++
 modules/core/doc/drawing_functions.rst        |  8 +++++
 modules/core/doc/operations_on_arrays.rst     |  2 ++
 ...tility_and_system_functions_and_macros.rst |  9 ++++++
 modules/core/doc/xml_yaml_persistence.rst     | 11 +++++++
 modules/core/include/opencv2/core/core.hpp    |  2 --
 7 files changed, 67 insertions(+), 4 deletions(-)

diff --git a/modules/core/doc/basic_structures.rst b/modules/core/doc/basic_structures.rst
index acfbb911d..370587922 100644
--- a/modules/core/doc/basic_structures.rst
+++ b/modules/core/doc/basic_structures.rst
@@ -489,6 +489,9 @@ Various Ptr constructors.
 .. ocv:function:: Ptr::Ptr(_Tp* _obj)
 .. ocv:function:: Ptr::Ptr(const Ptr& ptr)
 
+    :param _obj: Object for copy.
+    :param ptr: Object for copy.
+
 Ptr::~Ptr
 ---------
 The Ptr destructor.
@@ -501,6 +504,8 @@ Assignment operator.
 
 .. ocv:function:: Ptr& Ptr::operator = (const Ptr& ptr)
 
+    :param ptr: Object for assignment.
+
 Decrements own reference counter (with ``release()``) and increments ptr's reference counter.
 
 Ptr::addref
@@ -1465,6 +1470,7 @@ Adds elements to the bottom of the matrix.
 .. ocv:function:: void Mat::push_back( const Mat& m )
 
     :param elem: Added element(s).
+    :param m: Added line(s).
 
 The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of the STL vector class. When ``elem`` is ``Mat`` , its type and the number of columns must be the same as in the container matrix.
 
@@ -2160,7 +2166,6 @@ Various SparseMat constructors.
     :param dims: Array dimensionality.
     :param _sizes: Sparce matrix size on all dementions.
     :param _type: Sparse matrix data type.
-    :param try1d: if try1d is true and matrix is a single-column matrix (Nx1), then the sparse matrix will be 1-dimensional.
 
 SparseMat::~SparseMat
 ---------------------
@@ -2175,6 +2180,8 @@ Provides sparse matrix assignment operators.
 .. ocv:function:: SparseMat& SparseMat::operator = (const SparseMat& m)
 .. ocv:function:: SparseMat& SparseMat::operator = (const Mat& m)
 
+    :param m: Matrix for assignment.
+
 The last variant is equivalent to the corresponding constructor with try1d=false.
 
 
@@ -2202,6 +2209,10 @@ Convert sparse matrix with possible type change and scaling.
 .. ocv:function:: void SparseMat::convertTo( SparseMat& m, int rtype, double alpha=1 ) const
 .. ocv:function:: void SparseMat::convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const
 
+    :param m: Destination matrix.
+    :param rtype: Destination matrix type.
+    :param alpha: Conversion multiplier.
+
 The first version converts arbitrary sparse matrix to dense matrix and multiplies all the matrix elements by the specified scalar.
 The second versiob converts sparse matrix to dense matrix with optional type conversion and scaling.
 When rtype=-1, the destination element type will be the same as the sparse matrix element type.
@@ -2294,7 +2305,7 @@ The method returns the number of matrix channels.
 
 SparseMat::size
 ---------------
-Returns the array of sizes or matrix size by i dimention and 0 if the matrix is not allocated.
+Returns the array of sizes or matrix size by i dimension and 0 if the matrix is not allocated.
 
 .. ocv:function:: const int* SparseMat::size() const
 .. ocv:function:: int SparseMat::size(int i) const
@@ -2322,6 +2333,11 @@ Compute element hash value from the element indices.
 .. ocv:function:: size_t SparseMat::hash(int i0, int i1, int i2) const
 .. ocv:function:: size_t SparseMat::hash(const int* idx) const
 
+    :param i0: The first dimension index.
+    :param i1: The second dimension index.
+    :param i2: The third dimension index.
+    :param idx: Array of element indices for multidimensional matices.
+
 SparseMat::ptr
 --------------
 Low-level element-access functions, special variants for 1D, 2D, 3D cases, and the generic one for n-D case.
@@ -2331,6 +2347,12 @@ Low-level element-access functions, special variants for 1D, 2D, 3D cases, and t
 .. ocv:function:: uchar* SparseMat::ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0)
 .. ocv:function:: uchar* SparseMat::ptr(const int* idx, bool createMissing, size_t* hashval=0)
 
+    :param i0: The first dimension index.
+    :param i1: The second dimension index.
+    :param i2: The third dimension index.
+    :param idx: Array of element indices for multidimensional matices.
+    :param createMissing: Create new element with 0 value if it does not exist in SparseMat.
+
 Return pointer to the matrix element. If the element is there (it is non-zero), the pointer to it is returned.
 If it is not there and ``createMissing=false``, NULL pointer is returned. If it is not there and ``createMissing=true``,
 the new elementis created and initialized with 0. Pointer to it is returned. If the optional hashval pointer is not ``NULL``,
@@ -2344,6 +2366,11 @@ Erase the specified matrix element. When there is no such an element, the method
 .. ocv:function:: void SparseMat::erase(int i0, int i1, int i2, size_t* hashval=0)
 .. ocv:function:: void SparseMat::erase(const int* idx, size_t* hashval=0)
 
+    :param i0: The first dimension index.
+    :param i1: The second dimension index.
+    :param i2: The third dimension index.
+    :param idx: Array of element indices for multidimensional matices.
+
 SparseMat\_
 -----------
 .. ocv:class:: SparseMat_
diff --git a/modules/core/doc/clustering.rst b/modules/core/doc/clustering.rst
index 46130bc8f..f58e99ce2 100644
--- a/modules/core/doc/clustering.rst
+++ b/modules/core/doc/clustering.rst
@@ -17,12 +17,18 @@ Finds centers of clusters and groups input samples around the clusters.
 
     :param samples: Floating-point matrix of input samples, one row per sample.
 
+    :param data: Data for clustering.
+
     :param cluster_count: Number of clusters to split the set by.
 
+    :param K: Number of clusters to split the set by.
+
     :param labels: Input/output integer array that stores the cluster indices for every sample.
 
     :param criteria: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``criteria.epsilon``. As soon as each of the cluster centers moves by less than ``criteria.epsilon`` on some iteration, the algorithm stops.
 
+    :param termcrit: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy.
+
     :param attempts: Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
 
     :param rng: CvRNG state initialized by RNG().
@@ -37,6 +43,8 @@ Finds centers of clusters and groups input samples around the clusters.
 
     :param centers: Output matrix of the cluster centers, one row per each cluster center.
 
+    :param _centers: Output matrix of the cluster centers, one row per each cluster center.
+
     :param compactness: The returned value that is described below.
 
 The function ``kmeans`` implements a k-means algorithm that finds the
diff --git a/modules/core/doc/drawing_functions.rst b/modules/core/doc/drawing_functions.rst
index 24328f9a5..342301db9 100644
--- a/modules/core/doc/drawing_functions.rst
+++ b/modules/core/doc/drawing_functions.rst
@@ -234,6 +234,8 @@ Calculates the width and height of a text string.
 
     :param text: Input text string.
 
+    :param text_string: Input text string in C format.
+
     :param fontFace: Font to use. See the  :ocv:func:`putText` for details.
 
     :param fontScale: Font scale. See the  :ocv:func:`putText`  for details.
@@ -242,6 +244,12 @@ Calculates the width and height of a text string.
 
     :param baseLine: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
 
+    :param baseline: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
+
+    :param font: Font description in terms of old C API.
+
+    :param text_size: Output parameter - The size of a box that contains the specified text.
+
 The function ``getTextSize`` calculates and returns the size of a box that contains the specified text.
 That is, the following code renders some text, the tight box surrounding it, and the baseline: ::
 
diff --git a/modules/core/doc/operations_on_arrays.rst b/modules/core/doc/operations_on_arrays.rst
index d33844476..bd55993af 100644
--- a/modules/core/doc/operations_on_arrays.rst
+++ b/modules/core/doc/operations_on_arrays.rst
@@ -1062,6 +1062,8 @@ Returns the determinant of a square floating-point matrix.
 
     :param mtx: input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type and square size.
 
+    :param mat: input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type and square size.
+
 The function ``determinant`` calculates and returns the determinant of the specified matrix. For small matrices ( ``mtx.cols=mtx.rows<=3`` ),
 the direct method is used. For larger matrices, the function uses LU factorization with partial pivoting.
 
diff --git a/modules/core/doc/utility_and_system_functions_and_macros.rst b/modules/core/doc/utility_and_system_functions_and_macros.rst
index 54198b058..41cf7e1b7 100644
--- a/modules/core/doc/utility_and_system_functions_and_macros.rst
+++ b/modules/core/doc/utility_and_system_functions_and_macros.rst
@@ -173,6 +173,8 @@ Checks a condition at runtime and throws exception if it fails
 
 .. ocv:function:: CV_Assert(expr)
 
+    :param expr: Expression for check.
+
 The macros ``CV_Assert`` (and ``CV_DbgAssert``) evaluate the specified expression. If it is 0, the macros raise an error (see :ocv:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations while ``CV_DbgAssert`` is only retained in the Debug configuration.
 
 
@@ -188,8 +190,14 @@ Signals an error and raises an exception.
 
     :param status: Error code. Normally, it is a negative value. The list of pre-defined error codes can be found in  ``cxerror.h`` .
 
+    :param func_name: The function name where error occurs.
+
     :param err_msg: Text of the error message.
 
+    :param file_name: The file name where error occurs.
+
+    :param line: The line number where error occurs.
+
     :param args: ``printf`` -like formatted error message in parentheses.
 
 The function and the helper macros ``CV_Error`` and ``CV_Error_``: ::
@@ -249,6 +257,7 @@ Allocates an aligned memory buffer.
 .. ocv:cfunction:: void* cvAlloc( size_t size )
 
     :param size: Allocated buffer size.
+    :param bufSize: Allocated buffer size.
 
 The function allocates the buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned to 16 bytes.
 
diff --git a/modules/core/doc/xml_yaml_persistence.rst b/modules/core/doc/xml_yaml_persistence.rst
index c7d55d01f..28bae2450 100644
--- a/modules/core/doc/xml_yaml_persistence.rst
+++ b/modules/core/doc/xml_yaml_persistence.rst
@@ -181,6 +181,17 @@ Opens a file.
 
 .. ocv:function:: bool FileStorage::open(const string& filename, int flags, const string& encoding=string())
 
+    :param filename: Name of the file to open or the text string to read the data from.
+                     Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively).
+                     Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``.
+                     If both ``FileStorage::WRITE`` and ``FileStorage::MEMORY`` flags are specified, ``source``
+                     is used just to specify the output file format (e.g. ``mydata.xml``, ``.yml`` etc.).
+
+    :param flags: Mode of operation. See FileStorage constructor for more details.
+
+    :param encoding: Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it.
+
+
 See description of parameters in :ocv:func:`FileStorage::FileStorage`. The method calls :ocv:func:`FileStorage::release` before opening the file.
 
 
diff --git a/modules/core/include/opencv2/core/core.hpp b/modules/core/include/opencv2/core/core.hpp
index 2b7791958..10210c511 100644
--- a/modules/core/include/opencv2/core/core.hpp
+++ b/modules/core/include/opencv2/core/core.hpp
@@ -3409,8 +3409,6 @@ public:
     //! converts dense 2d matrix to the sparse form
     /*!
      \param m the input matrix
-     \param try1d if true and m is a single-column matrix (Nx1),
-            then the sparse matrix will be 1-dimensional.
     */
     explicit SparseMat(const Mat& m);
     //! converts old-style sparse matrix to the new-style. All the data is copied

From 371a9cd8338e15f89b1c0ab6e46fe34fe377a553 Mon Sep 17 00:00:00 2001
From: Vladislav Vinogradov <vlad.vinogradov@itseez.com>
Date: Tue, 18 Jun 2013 17:46:57 +0400
Subject: [PATCH 02/75] fixed build with CUDA 5.5 on arm platforms

---
 cmake/OpenCVDetectCUDA.cmake | 40 ++++++++++++++++++++++++++++++++----
 modules/gpu/CMakeLists.txt   | 16 +++++++--------
 2 files changed, 44 insertions(+), 12 deletions(-)

diff --git a/cmake/OpenCVDetectCUDA.cmake b/cmake/OpenCVDetectCUDA.cmake
index 8db667762..3b93f2932 100644
--- a/cmake/OpenCVDetectCUDA.cmake
+++ b/cmake/OpenCVDetectCUDA.cmake
@@ -29,10 +29,42 @@ if(CUDA_FOUND)
   if(${CUDA_VERSION} VERSION_LESS "5.5")
     find_cuda_helper_libs(npp)
   else()
-    find_cuda_helper_libs(nppc)
-    find_cuda_helper_libs(nppi)
-    find_cuda_helper_libs(npps)
-    set(CUDA_npp_LIBRARY ${CUDA_nppc_LIBRARY} ${CUDA_nppi_LIBRARY} ${CUDA_npps_LIBRARY})
+    # hack for CUDA 5.5
+    if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "arm")
+      unset(CUDA_TOOLKIT_INCLUDE CACHE)
+      unset(CUDA_CUDART_LIBRARY CACHE)
+      unset(CUDA_cublas_LIBRARY CACHE)
+      unset(CUDA_cufft_LIBRARY CACHE)
+      unset(CUDA_npp_LIBRARY CACHE)
+
+      if(SOFTFP)
+        set(cuda_arm_path "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-gnueabi")
+      else()
+        set(cuda_arm_path "${CUDA_TOOLKIT_ROOT_DIR}/targets/armv7-linux-gnueabihf")
+      endif()
+
+      set(CUDA_TOOLKIT_INCLUDE "${cuda_arm_path}/include" CACHE PATH "include path")
+      set(CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_INCLUDE})
+
+      set(cuda_arm_library_path "${cuda_arm_path}/lib")
+
+      set(CUDA_CUDART_LIBRARY "${cuda_arm_library_path}/libcudart.so" CACHE FILEPATH "cudart library")
+      set(CUDA_LIBRARIES ${CUDA_CUDART_LIBRARY})
+      set(CUDA_cublas_LIBRARY "${cuda_arm_library_path}/libcublas.so" CACHE FILEPATH "cublas library")
+      set(CUDA_cufft_LIBRARY "${cuda_arm_library_path}/libcufft.so" CACHE FILEPATH "cufft library")
+      set(CUDA_nppc_LIBRARY "${cuda_arm_library_path}/libnppc.so" CACHE FILEPATH "nppc library")
+      set(CUDA_nppi_LIBRARY "${cuda_arm_library_path}/libnppi.so" CACHE FILEPATH "nppi library")
+      set(CUDA_npps_LIBRARY "${cuda_arm_library_path}/libnpps.so" CACHE FILEPATH "npps library")
+      set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppi_LIBRARY};${CUDA_npps_LIBRARY}" CACHE STRING "npp library")
+    else()
+      unset(CUDA_npp_LIBRARY CACHE)
+
+      find_cuda_helper_libs(nppc)
+      find_cuda_helper_libs(nppi)
+      find_cuda_helper_libs(npps)
+
+      set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppi_LIBRARY};${CUDA_npps_LIBRARY}" CACHE STRING "npp library")
+    endif()
   endif()
 
   if(WITH_NVCUVID)
diff --git a/modules/gpu/CMakeLists.txt b/modules/gpu/CMakeLists.txt
index 0062944ba..44b507268 100644
--- a/modules/gpu/CMakeLists.txt
+++ b/modules/gpu/CMakeLists.txt
@@ -43,6 +43,14 @@ if(HAVE_CUDA)
   ocv_cuda_compile(cuda_objs ${lib_cuda} ${ncv_cuda})
 
   set(cuda_link_libs ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
+  
+  if(HAVE_CUFFT)
+      set(cuda_link_libs ${cuda_link_libs} ${CUDA_cufft_LIBRARY})
+  endif()
+
+  if(HAVE_CUBLAS)
+      set(cuda_link_libs ${cuda_link_libs} ${CUDA_cublas_LIBRARY})
+  endif()
 
   if(WITH_NVCUVID)
     set(cuda_link_libs ${cuda_link_libs} ${CUDA_CUDA_LIBRARY} ${CUDA_nvcuvid_LIBRARY})
@@ -71,14 +79,6 @@ ocv_set_module_sources(
 ocv_create_module(${cuda_link_libs})
 
 if(HAVE_CUDA)
-  if(HAVE_CUFFT)
-    CUDA_ADD_CUFFT_TO_TARGET(${the_module})
-  endif()
-
-  if(HAVE_CUBLAS)
-    CUDA_ADD_CUBLAS_TO_TARGET(${the_module})
-  endif()
-
   install(FILES src/nvidia/NPP_staging/NPP_staging.hpp  src/nvidia/core/NCV.hpp
     DESTINATION ${OPENCV_INCLUDE_INSTALL_PATH}/opencv2/${name}
     COMPONENT main)

From 68741bf8a010913991fc43252c052d2519bdf301 Mon Sep 17 00:00:00 2001
From: Alexander Shishkov <alexander.shishkov@itseez.com>
Date: Wed, 19 Jun 2013 00:20:21 +0400
Subject: [PATCH 03/75] moved iOS part to platforms folder

---
 .../introduction/ios_install/ios_install.rst      |  2 +-
 ios/configure-device_xcode.sh                     |  1 -
 ios/configure-simulator_xcode.sh                  |  1 -
 ios/readme.txt                                    | 15 ---------------
 {ios => platforms/ios}/Info.plist.in              |  2 +-
 {ios => platforms/ios}/build_framework.py         |  9 +++------
 .../ios}/cmake/Modules/Platform/iOS.cmake         |  0
 .../Toolchains/Toolchain-iPhoneOS_Xcode.cmake     |  8 ++++----
 .../Toolchain-iPhoneSimulator_Xcode.cmake         |  8 ++++----
 platforms/ios/readme.txt                          |  7 +++++++
 10 files changed, 20 insertions(+), 33 deletions(-)
 delete mode 100755 ios/configure-device_xcode.sh
 delete mode 100755 ios/configure-simulator_xcode.sh
 delete mode 100644 ios/readme.txt
 rename {ios => platforms/ios}/Info.plist.in (93%)
 rename {ios => platforms/ios}/build_framework.py (95%)
 rename {ios => platforms/ios}/cmake/Modules/Platform/iOS.cmake (100%)
 rename {ios => platforms/ios}/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake (84%)
 rename {ios => platforms/ios}/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake (85%)
 create mode 100644 platforms/ios/readme.txt

diff --git a/doc/tutorials/introduction/ios_install/ios_install.rst b/doc/tutorials/introduction/ios_install/ios_install.rst
index ace657b21..8d117a0b4 100644
--- a/doc/tutorials/introduction/ios_install/ios_install.rst
+++ b/doc/tutorials/introduction/ios_install/ios_install.rst
@@ -37,7 +37,7 @@ Building OpenCV from Source, using CMake and Command Line
     .. code-block:: bash
 
        cd ~/<my_working_directory>
-       python opencv/ios/build_framework.py ios
+       python opencv/platforms/ios/build_framework.py ios
 
 If everything's fine, a few minutes later you will get ~/<my_working_directory>/ios/opencv2.framework. You can add this framework to your Xcode projects.
 
diff --git a/ios/configure-device_xcode.sh b/ios/configure-device_xcode.sh
deleted file mode 100755
index 8c28a3e90..000000000
--- a/ios/configure-device_xcode.sh
+++ /dev/null
@@ -1 +0,0 @@
-cmake -GXcode -DCMAKE_TOOLCHAIN_FILE=../opencv/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake -DCMAKE_INSTALL_PREFIX=../OpenCV_iPhoneOS ../opencv 
diff --git a/ios/configure-simulator_xcode.sh b/ios/configure-simulator_xcode.sh
deleted file mode 100755
index 50e00261d..000000000
--- a/ios/configure-simulator_xcode.sh
+++ /dev/null
@@ -1 +0,0 @@
-cmake -GXcode -DCMAKE_TOOLCHAIN_FILE=../opencv/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake -DCMAKE_INSTALL_PREFIX=../OpenCV_iPhoneSimulator ../opencv 
diff --git a/ios/readme.txt b/ios/readme.txt
deleted file mode 100644
index 1441b241b..000000000
--- a/ios/readme.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Assuming that your build directory is on the same level that opencv source,
-From the build directory run
-  ../opencv/ios/configure-device_xcode.sh
-or
-  ../opencv/ios/configure-simulator_xcode.sh
-
-Then from the same folder invoke
-
-xcodebuild -sdk iphoneos -configuration Release -target ALL_BUILD
-xcodebuild -sdk iphoneos -configuration Release -target install install
-
-or
-
-xcodebuild -sdk iphonesimulator -configuration Release -target ALL_BUILD
-xcodebuild -sdk iphonesimulator -configuration Release -target install install
\ No newline at end of file
diff --git a/ios/Info.plist.in b/platforms/ios/Info.plist.in
similarity index 93%
rename from ios/Info.plist.in
rename to platforms/ios/Info.plist.in
index 89ef38625..012de8856 100644
--- a/ios/Info.plist.in
+++ b/platforms/ios/Info.plist.in
@@ -5,7 +5,7 @@
     <key>CFBundleName</key>
     <string>OpenCV</string>
     <key>CFBundleIdentifier</key>
-    <string>com.itseez.opencv</string>
+    <string>opencv.org</string>
     <key>CFBundleVersion</key>
     <string>${VERSION}</string>
     <key>CFBundleShortVersionString</key>
diff --git a/ios/build_framework.py b/platforms/ios/build_framework.py
similarity index 95%
rename from ios/build_framework.py
rename to platforms/ios/build_framework.py
index ceef4b71d..bc385bb1b 100755
--- a/ios/build_framework.py
+++ b/platforms/ios/build_framework.py
@@ -38,7 +38,7 @@ def build_opencv(srcroot, buildroot, target, arch):
     # for some reason, if you do not specify CMAKE_BUILD_TYPE, it puts libs to "RELEASE" rather than "Release"
     cmakeargs = ("-GXcode " +
                 "-DCMAKE_BUILD_TYPE=Release " +
-                "-DCMAKE_TOOLCHAIN_FILE=%s/ios/cmake/Toolchains/Toolchain-%s_Xcode.cmake " +
+                "-DCMAKE_TOOLCHAIN_FILE=%s/platforms/ios/cmake/Toolchains/Toolchain-%s_Xcode.cmake " +
                 "-DBUILD_opencv_world=ON " +
                 "-DCMAKE_INSTALL_PREFIX=install") % (srcroot, target)
     # if cmake cache exists, just rerun cmake to update OpenCV.xproj if necessary
@@ -92,16 +92,13 @@ def put_framework_together(srcroot, dstroot):
     os.system("lipo -create " + wlist + " -o " + dstdir + "/opencv2")
 
     # form Info.plist
-    srcfile = open(srcroot + "/ios/Info.plist.in", "rt")
+    srcfile = open(srcroot + "/platforms/ios/Info.plist.in", "rt")
     dstfile = open(dstdir + "/Resources/Info.plist", "wt")
     for l in srcfile.readlines():
         dstfile.write(l.replace("${VERSION}", opencv_version))
     srcfile.close()
     dstfile.close()
 
-    # copy cascades
-    # TODO ...
-
     # make symbolic links
     os.symlink("A", "Versions/Current")
     os.symlink("Versions/Current/Headers", "Headers")
@@ -125,4 +122,4 @@ if __name__ == "__main__":
         print "Usage:\n\t./build_framework.py <outputdir>\n\n"
         sys.exit(0)
 
-    build_framework(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..")), os.path.abspath(sys.argv[1]))
\ No newline at end of file
+    build_framework(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "../..")), os.path.abspath(sys.argv[1]))
\ No newline at end of file
diff --git a/ios/cmake/Modules/Platform/iOS.cmake b/platforms/ios/cmake/Modules/Platform/iOS.cmake
similarity index 100%
rename from ios/cmake/Modules/Platform/iOS.cmake
rename to platforms/ios/cmake/Modules/Platform/iOS.cmake
diff --git a/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake b/platforms/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake
similarity index 84%
rename from ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake
rename to platforms/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake
index 67343253b..6493deb45 100644
--- a/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake
+++ b/platforms/ios/cmake/Toolchains/Toolchain-iPhoneOS_Xcode.cmake
@@ -4,12 +4,12 @@ set (IPHONEOS TRUE)
 # Standard settings
 set (CMAKE_SYSTEM_NAME iOS)
 # Include extra modules for the iOS platform files
-set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/ios/cmake/Modules")
+set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/cmake/Modules")
 
-# Force the compilers to gcc for iOS
+# Force the compilers to clang for iOS
 include (CMakeForceCompiler)
-#CMAKE_FORCE_C_COMPILER (gcc gcc)
-#CMAKE_FORCE_CXX_COMPILER (g++ g++)
+#CMAKE_FORCE_C_COMPILER (clang GNU)
+#CMAKE_FORCE_CXX_COMPILER (clang++ GNU)
 
 set (CMAKE_C_SIZEOF_DATA_PTR 4)
 set (CMAKE_C_HAS_ISYSROOT 1)
diff --git a/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake b/platforms/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake
similarity index 85%
rename from ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake
rename to platforms/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake
index 7ef8113ed..0056c8dbd 100644
--- a/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake
+++ b/platforms/ios/cmake/Toolchains/Toolchain-iPhoneSimulator_Xcode.cmake
@@ -4,12 +4,12 @@ set (IPHONESIMULATOR TRUE)
 # Standard settings
 set (CMAKE_SYSTEM_NAME iOS)
 # Include extra modules for the iOS platform files
-set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/ios/cmake/Modules")
+set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/cmake/Modules")
 
-# Force the compilers to gcc for iOS
+# Force the compilers to clang for iOS
 include (CMakeForceCompiler)
-#CMAKE_FORCE_C_COMPILER (gcc gcc)
-#CMAKE_FORCE_CXX_COMPILER (g++ g++)
+#CMAKE_FORCE_C_COMPILER (clang GNU)
+#CMAKE_FORCE_CXX_COMPILER (clang++ GNU)
 
 set (CMAKE_C_SIZEOF_DATA_PTR 4)
 set (CMAKE_C_HAS_ISYSROOT 1)
diff --git a/platforms/ios/readme.txt b/platforms/ios/readme.txt
new file mode 100644
index 000000000..8f1f206b0
--- /dev/null
+++ b/platforms/ios/readme.txt
@@ -0,0 +1,7 @@
+Building OpenCV from Source, using CMake and Command Line
+=========================================================
+
+cd ~/<my_working_directory>
+python opencv/platforms/ios/build_framework.py ios
+
+If everything's fine, a few minutes later you will get ~/<my_working_directory>/ios/opencv2.framework. You can add this framework to your Xcode projects.
\ No newline at end of file

From 37d19b9c46ebfc4be922237b11913cf838959b49 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Wed, 19 Jun 2013 17:44:12 +0400
Subject: [PATCH 04/75] Pass the HAVE_QT* flags through the config header, like
 all others.

I don't know why it didn't work for the original author, but it definitely
works now.
---
 cmake/OpenCVFindLibsGUI.cmake     | 3 ---
 cmake/templates/cvconfig.h.cmake  | 6 ++++++
 modules/highgui/src/window_QT.cpp | 1 +
 3 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/cmake/OpenCVFindLibsGUI.cmake b/cmake/OpenCVFindLibsGUI.cmake
index 59ce1cd05..d685d23fe 100644
--- a/cmake/OpenCVFindLibsGUI.cmake
+++ b/cmake/OpenCVFindLibsGUI.cmake
@@ -24,7 +24,6 @@ if(WITH_QT)
     if(Qt5Core_FOUND AND Qt5Gui_FOUND AND Qt5Widgets_FOUND AND Qt5Test_FOUND AND Qt5Concurrent_FOUND)
       set(HAVE_QT5 ON)
       set(HAVE_QT  ON)
-      add_definitions(-DHAVE_QT)
       find_package(Qt5OpenGL)
       if(Qt5OpenGL_FOUND)
         set(QT_QTOPENGL_FOUND ON)
@@ -36,7 +35,6 @@ if(WITH_QT)
     find_package(Qt4 REQUIRED QtCore QtGui QtTest)
     if(QT4_FOUND)
       set(HAVE_QT TRUE)
-      add_definitions(-DHAVE_QT) # We need to define the macro this way, using cvconfig.h does not work
     endif()
   endif()
 endif()
@@ -61,7 +59,6 @@ if(WITH_OPENGL)
       list(APPEND OPENCV_LINKER_LIBS ${OPENGL_LIBRARIES})
       if(QT_QTOPENGL_FOUND)
         set(HAVE_QT_OPENGL TRUE)
-        add_definitions(-DHAVE_QT_OPENGL)
       else()
         ocv_include_directories(${OPENGL_INCLUDE_DIR})
       endif()
diff --git a/cmake/templates/cvconfig.h.cmake b/cmake/templates/cvconfig.h.cmake
index db46af4b6..f12730988 100644
--- a/cmake/templates/cvconfig.h.cmake
+++ b/cmake/templates/cvconfig.h.cmake
@@ -228,3 +228,9 @@
 
 /* Clp support */
 #cmakedefine HAVE_CLP
+
+/* Qt support */
+#cmakedefine HAVE_QT
+
+/* Qt OpenGL support */
+#cmakedefine HAVE_QT_OPENGL
diff --git a/modules/highgui/src/window_QT.cpp b/modules/highgui/src/window_QT.cpp
index 0c50c7070..64d57ab26 100644
--- a/modules/highgui/src/window_QT.cpp
+++ b/modules/highgui/src/window_QT.cpp
@@ -38,6 +38,7 @@
 
 //--------------------Google Code 2010 -- Yannick Verdie--------------------//
 
+#include "precomp.hpp"
 
 #if defined(HAVE_QT)
 

From 936236e4b1b190d7bc33a33df982fac8ab6cfc76 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Tue, 11 Jun 2013 16:06:51 +0400
Subject: [PATCH 05/75] Extended the CPU/GPU selection mechanism in performance
 tests.

Now it allows choosing between arbitrary implementation variants.
---
 modules/gpu/perf/perf_main.cpp            |   2 +-
 modules/nonfree/perf/perf_main.cpp        |   2 +-
 modules/superres/perf/perf_main.cpp       |   2 +-
 modules/ts/include/opencv2/ts/ts_perf.hpp |  20 +++--
 modules/ts/src/ts_perf.cpp                | 101 ++++++++++++++--------
 5 files changed, 81 insertions(+), 46 deletions(-)

diff --git a/modules/gpu/perf/perf_main.cpp b/modules/gpu/perf/perf_main.cpp
index a7ac1ccce..f9f3a6854 100644
--- a/modules/gpu/perf/perf_main.cpp
+++ b/modules/gpu/perf/perf_main.cpp
@@ -44,4 +44,4 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN(gpu, printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(gpu, ("cuda", "plain"), printCudaInfo())
diff --git a/modules/nonfree/perf/perf_main.cpp b/modules/nonfree/perf/perf_main.cpp
index de1242149..373e08aed 100644
--- a/modules/nonfree/perf/perf_main.cpp
+++ b/modules/nonfree/perf/perf_main.cpp
@@ -1,4 +1,4 @@
 #include "perf_precomp.hpp"
 #include "opencv2/ts/gpu_perf.hpp"
 
-CV_PERF_TEST_MAIN(nonfree, perf::printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(nonfree, ("cuda", "plain"), perf::printCudaInfo())
diff --git a/modules/superres/perf/perf_main.cpp b/modules/superres/perf/perf_main.cpp
index adc69e6e8..90a7f5125 100644
--- a/modules/superres/perf/perf_main.cpp
+++ b/modules/superres/perf/perf_main.cpp
@@ -44,4 +44,4 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN(superres, printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(superres, ("cuda", "plain"), printCudaInfo())
diff --git a/modules/ts/include/opencv2/ts/ts_perf.hpp b/modules/ts/include/opencv2/ts/ts_perf.hpp
index fe5765515..eb5e3e554 100644
--- a/modules/ts/include/opencv2/ts/ts_perf.hpp
+++ b/modules/ts/include/opencv2/ts/ts_perf.hpp
@@ -210,18 +210,13 @@ private:
 #define SANITY_CHECK_KEYPOINTS(array, ...) ::perf::Regression::addKeypoints(this, #array, array , ## __VA_ARGS__)
 #define SANITY_CHECK_MATCHES(array, ...) ::perf::Regression::addMatches(this, #array, array , ## __VA_ARGS__)
 
-#ifdef HAVE_CUDA
 class CV_EXPORTS GpuPerf
 {
 public:
   static bool targetDevice();
 };
 
-# define PERF_RUN_GPU()  ::perf::GpuPerf::targetDevice()
-#else
-# define PERF_RUN_GPU()  false
-#endif
-
+#define PERF_RUN_GPU()  ::perf::GpuPerf::targetDevice()
 
 /*****************************************************************************************\
 *                            Container for performance metrics                            *
@@ -263,7 +258,10 @@ public:
     TestBase();
 
     static void Init(int argc, const char* const argv[]);
+    static void Init(const std::vector<std::string> & availableImpls,
+                     int argc, const char* const argv[]);
     static std::string getDataPath(const std::string& relativePath);
+    static std::string getSelectedImpl();
 
 protected:
     virtual void PerfTestBody() = 0;
@@ -476,18 +474,24 @@ CV_EXPORTS void PrintTo(const Size& sz, ::std::ostream* os);
     INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\
     void fixture##_##name::PerfTestBody()
 
+#define CV_PERF_UNWRAP_IMPLS(...) __VA_ARGS__
 
-#define CV_PERF_TEST_MAIN(testsuitname, ...) \
+// "plain" should always be one of the implementations
+#define CV_PERF_TEST_MAIN_WITH_IMPLS(testsuitname, impls, ...) \
 int main(int argc, char **argv)\
 {\
     while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/\
+    std::string impls_[] = { CV_PERF_UNWRAP_IMPLS impls };\
     ::perf::Regression::Init(#testsuitname);\
-    ::perf::TestBase::Init(argc, argv);\
+    ::perf::TestBase::Init(std::vector<std::string>(impls_, impls_ + sizeof impls_ / sizeof *impls_),\
+                           argc, argv);\
     ::testing::InitGoogleTest(&argc, argv);\
     cvtest::printVersionInfo();\
     return RUN_ALL_TESTS();\
 }
 
+#define CV_PERF_TEST_MAIN(testsuitname, ...) CV_PERF_TEST_MAIN_WITH_IMPLS(testsuitname, ("plain"), __VA_ARGS__)
+
 #define TEST_CYCLE_N(n) for(declare.iterations(n); startTimer(), next(); stopTimer())
 #define TEST_CYCLE() for(; startTimer(), next(); stopTimer())
 #define TEST_CYCLE_MULTIRUN(runsNum) for(declare.runs(runsNum); startTimer(), next(); stopTimer()) for(int r = 0; r < runsNum; ++r)
diff --git a/modules/ts/src/ts_perf.cpp b/modules/ts/src/ts_perf.cpp
index c375e7c38..3b73ddcf7 100644
--- a/modules/ts/src/ts_perf.cpp
+++ b/modules/ts/src/ts_perf.cpp
@@ -14,30 +14,10 @@ int64 TestBase::timeLimitDefault = 0;
 unsigned int TestBase::iterationsLimitDefault = (unsigned int)(-1);
 int64 TestBase::_timeadjustment = 0;
 
-const std::string command_line_keys =
-    "{   |perf_max_outliers   |8        |percent of allowed outliers}"
-    "{   |perf_min_samples    |10       |minimal required numer of samples}"
-    "{   |perf_force_samples  |100      |force set maximum number of samples for all tests}"
-    "{   |perf_seed           |809564   |seed for random numbers generator}"
-    "{   |perf_threads        |-1       |the number of worker threads, if parallel execution is enabled}"
-    "{   |perf_write_sanity   |false    |create new records for sanity checks}"
-    "{   |perf_verify_sanity  |false    |fail tests having no regression data for sanity checks}"
-#ifdef ANDROID
-    "{   |perf_time_limit     |6.0      |default time limit for a single test (in seconds)}"
-    "{   |perf_affinity_mask  |0        |set affinity mask for the main thread}"
-    "{   |perf_log_power_checkpoints  | |additional xml logging for power measurement}"
-#else
-    "{   |perf_time_limit     |3.0      |default time limit for a single test (in seconds)}"
-#endif
-    "{   |perf_max_deviation  |1.0      |}"
-    "{h  |help                |false    |print help info}"
-#ifdef HAVE_CUDA
-    "{   |perf_run_cpu        |false    |run GPU performance tests for analogical CPU functions}"
-    "{   |perf_cuda_device    |0        |run GPU test suite onto specific CUDA capable device}"
-    "{   |perf_cuda_info_only |false    |print an information about system and an available CUDA devices and then exit.}"
-#endif
-;
+// Item [0] will be considered the default implementation.
+static std::vector<std::string> available_impls;
 
+static std::string  param_impl;
 static double       param_max_outliers;
 static double       param_max_deviation;
 static unsigned int param_min_samples;
@@ -48,7 +28,6 @@ static int          param_threads;
 static bool         param_write_sanity;
 static bool         param_verify_sanity;
 #ifdef HAVE_CUDA
-static bool         param_run_cpu;
 static int          param_cuda_device;
 #endif
 
@@ -577,11 +556,12 @@ Regression& Regression::operator() (const std::string& name, cv::InputArray arra
 
     std::string nodename = getCurrentTestNodeName();
 
-#ifdef HAVE_CUDA
-    static const std::string prefix = (param_run_cpu)? "CPU_" : "GPU_";
+    // This is a hack for compatibility and it should eventually get removed.
+    // gpu's tests don't even have CPU sanity data anymore.
     if(suiteName == "gpu")
-        nodename = prefix + nodename;
-#endif
+    {
+        nodename = (PERF_RUN_GPU() ? "GPU_" : "CPU_") + nodename;
+    }
 
     cv::FileNode n = rootIn[nodename];
     if(n.isNone())
@@ -646,6 +626,42 @@ performance_metrics::performance_metrics()
 
 void TestBase::Init(int argc, const char* const argv[])
 {
+    std::vector<std::string> plain_only;
+    plain_only.push_back("plain");
+    TestBase::Init(plain_only, argc, argv);
+}
+
+void TestBase::Init(const std::vector<std::string> & availableImpls,
+                 int argc, const char* const argv[])
+{
+    available_impls = availableImpls;
+
+    const std::string command_line_keys =
+        "{   |perf_max_outliers           |8        |percent of allowed outliers}"
+        "{   |perf_min_samples            |10       |minimal required numer of samples}"
+        "{   |perf_force_samples          |100      |force set maximum number of samples for all tests}"
+        "{   |perf_seed                   |809564   |seed for random numbers generator}"
+        "{   |perf_threads                |-1       |the number of worker threads, if parallel execution is enabled}"
+        "{   |perf_write_sanity           |false    |create new records for sanity checks}"
+        "{   |perf_verify_sanity          |false    |fail tests having no regression data for sanity checks}"
+        "{   |perf_impl                   |" + available_impls[0] +
+                                                   "|the implementation variant of functions under test}"
+        "{   |perf_run_cpu                |false    |deprecated, equivalent to --perf_impl=plain}"
+#ifdef ANDROID
+        "{   |perf_time_limit             |6.0      |default time limit for a single test (in seconds)}"
+        "{   |perf_affinity_mask          |0        |set affinity mask for the main thread}"
+        "{   |perf_log_power_checkpoints  |         |additional xml logging for power measurement}"
+#else
+        "{   |perf_time_limit             |3.0      |default time limit for a single test (in seconds)}"
+#endif
+        "{   |perf_max_deviation          |1.0      |}"
+        "{h  |help                        |false    |print help info}"
+#ifdef HAVE_CUDA
+        "{   |perf_cuda_device            |0        |run GPU test suite onto specific CUDA capable device}"
+        "{   |perf_cuda_info_only         |false    |print an information about system and an available CUDA devices and then exit.}"
+#endif
+    ;
+
     cv::CommandLineParser args(argc, argv, command_line_keys.c_str());
     if (args.get<bool>("help"))
     {
@@ -656,6 +672,7 @@ void TestBase::Init(int argc, const char* const argv[])
 
     ::testing::AddGlobalTestEnvironment(new PerfEnvironment);
 
+    param_impl          = args.get<bool>("perf_run_cpu") ? "plain" : args.get<std::string>("perf_impl");
     param_max_outliers  = std::min(100., std::max(0., args.get<double>("perf_max_outliers")));
     param_min_samples   = std::max(1u, args.get<unsigned int>("perf_min_samples"));
     param_max_deviation = std::max(0., args.get<double>("perf_max_deviation"));
@@ -670,19 +687,28 @@ void TestBase::Init(int argc, const char* const argv[])
     log_power_checkpoints = args.get<bool>("perf_log_power_checkpoints");
 #endif
 
+    if (std::find(available_impls.begin(), available_impls.end(), param_impl) == available_impls.end())
+    {
+        printf("No such implementation: %s\n", param_impl.c_str());
+        exit(1);
+    }
+
 #ifdef HAVE_CUDA
 
     bool printOnly        = args.get<bool>("perf_cuda_info_only");
 
     if (printOnly)
         exit(0);
+#endif
+
+    if (available_impls.size() > 1)
+        printf("[----------]\n[   INFO   ] \tImplementation variant: %s.\n[----------]\n", param_impl.c_str()), fflush(stdout);
+
+#ifdef HAVE_CUDA
 
-    param_run_cpu         = args.get<bool>("perf_run_cpu");
     param_cuda_device      = std::max(0, std::min(cv::gpu::getCudaEnabledDeviceCount(), args.get<int>("perf_cuda_device")));
 
-    if (param_run_cpu)
-        printf("[----------]\n[ GPU INFO ] \tRun test suite on CPU.\n[----------]\n"), fflush(stdout);
-    else
+    if (param_impl == "cuda")
     {
         cv::gpu::DeviceInfo info(param_cuda_device);
         if (!info.isCompatible())
@@ -708,6 +734,13 @@ void TestBase::Init(int argc, const char* const argv[])
     _timeadjustment = _calibrate();
 }
 
+
+std::string TestBase::getSelectedImpl()
+{
+    return param_impl;
+}
+
+
 int64 TestBase::_calibrate()
 {
     class _helper : public ::perf::TestBase
@@ -1325,12 +1358,10 @@ void perf::sort(std::vector<cv::KeyPoint>& pts, cv::InputOutputArray descriptors
 /*****************************************************************************************\
 *                                  ::perf::GpuPerf
 \*****************************************************************************************/
-#ifdef HAVE_CUDA
 bool perf::GpuPerf::targetDevice()
 {
-    return !param_run_cpu;
+    return param_impl == "cuda";
 }
-#endif
 
 /*****************************************************************************************\
 *                                  ::perf::PrintTo

From b581f27249250fa7454be0e56e1dfe0bbf264ab6 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Tue, 18 Jun 2013 18:40:55 +0400
Subject: [PATCH 06/75] Made perf tests record module name, selected
 implementation and number of threads.

---
 modules/ts/include/opencv2/ts/ts_perf.hpp | 9 ++++++---
 modules/ts/src/ts_perf.cpp                | 5 +++++
 2 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/modules/ts/include/opencv2/ts/ts_perf.hpp b/modules/ts/include/opencv2/ts/ts_perf.hpp
index eb5e3e554..ba0996403 100644
--- a/modules/ts/include/opencv2/ts/ts_perf.hpp
+++ b/modules/ts/include/opencv2/ts/ts_perf.hpp
@@ -260,6 +260,7 @@ public:
     static void Init(int argc, const char* const argv[]);
     static void Init(const std::vector<std::string> & availableImpls,
                      int argc, const char* const argv[]);
+    static void RecordRunParameters();
     static std::string getDataPath(const std::string& relativePath);
     static std::string getSelectedImpl();
 
@@ -477,20 +478,22 @@ CV_EXPORTS void PrintTo(const Size& sz, ::std::ostream* os);
 #define CV_PERF_UNWRAP_IMPLS(...) __VA_ARGS__
 
 // "plain" should always be one of the implementations
-#define CV_PERF_TEST_MAIN_WITH_IMPLS(testsuitname, impls, ...) \
+#define CV_PERF_TEST_MAIN_WITH_IMPLS(modulename, impls, ...) \
 int main(int argc, char **argv)\
 {\
     while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/\
     std::string impls_[] = { CV_PERF_UNWRAP_IMPLS impls };\
-    ::perf::Regression::Init(#testsuitname);\
+    ::perf::Regression::Init(#modulename);\
     ::perf::TestBase::Init(std::vector<std::string>(impls_, impls_ + sizeof impls_ / sizeof *impls_),\
                            argc, argv);\
     ::testing::InitGoogleTest(&argc, argv);\
     cvtest::printVersionInfo();\
+    ::testing::Test::RecordProperty("cv_module_name", #modulename);\
+    ::perf::TestBase::RecordRunParameters();\
     return RUN_ALL_TESTS();\
 }
 
-#define CV_PERF_TEST_MAIN(testsuitname, ...) CV_PERF_TEST_MAIN_WITH_IMPLS(testsuitname, ("plain"), __VA_ARGS__)
+#define CV_PERF_TEST_MAIN(modulename, ...) CV_PERF_TEST_MAIN_WITH_IMPLS(modulename, ("plain"), __VA_ARGS__)
 
 #define TEST_CYCLE_N(n) for(declare.iterations(n); startTimer(), next(); stopTimer())
 #define TEST_CYCLE() for(; startTimer(), next(); stopTimer())
diff --git a/modules/ts/src/ts_perf.cpp b/modules/ts/src/ts_perf.cpp
index 3b73ddcf7..e61878e19 100644
--- a/modules/ts/src/ts_perf.cpp
+++ b/modules/ts/src/ts_perf.cpp
@@ -734,6 +734,11 @@ void TestBase::Init(const std::vector<std::string> & availableImpls,
     _timeadjustment = _calibrate();
 }
 
+void TestBase::RecordRunParameters()
+{
+    ::testing::Test::RecordProperty("cv_implementation", param_impl);
+    ::testing::Test::RecordProperty("cv_num_threads", param_threads);
+}
 
 std::string TestBase::getSelectedImpl()
 {

From 7a104d2793ed0fde70b2ce3185823912d2455075 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Wed, 19 Jun 2013 18:47:15 +0400
Subject: [PATCH 07/75] Added an option to print available implementation
 variants.

---
 modules/ts/src/ts_perf.cpp | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/modules/ts/src/ts_perf.cpp b/modules/ts/src/ts_perf.cpp
index e61878e19..c2c1ee6bd 100644
--- a/modules/ts/src/ts_perf.cpp
+++ b/modules/ts/src/ts_perf.cpp
@@ -646,6 +646,7 @@ void TestBase::Init(const std::vector<std::string> & availableImpls,
         "{   |perf_verify_sanity          |false    |fail tests having no regression data for sanity checks}"
         "{   |perf_impl                   |" + available_impls[0] +
                                                    "|the implementation variant of functions under test}"
+        "{   |perf_list_impls             |false    |list available implementation variants and exit}"
         "{   |perf_run_cpu                |false    |deprecated, equivalent to --perf_impl=plain}"
 #ifdef ANDROID
         "{   |perf_time_limit             |6.0      |default time limit for a single test (in seconds)}"
@@ -687,6 +688,19 @@ void TestBase::Init(const std::vector<std::string> & availableImpls,
     log_power_checkpoints = args.get<bool>("perf_log_power_checkpoints");
 #endif
 
+    bool param_list_impls = args.get<bool>("perf_list_impls");
+
+    if (param_list_impls)
+    {
+        fputs("Available implementation variants:", stdout);
+        for (size_t i = 0; i < available_impls.size(); ++i) {
+            putchar(' ');
+            fputs(available_impls[i].c_str(), stdout);
+        }
+        putchar('\n');
+        exit(0);
+    }
+
     if (std::find(available_impls.begin(), available_impls.end(), param_impl) == available_impls.end())
     {
         printf("No such implementation: %s\n", param_impl.c_str());

From 51a672ec40d7637888fa6aae07247e4e737c64ce Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Wed, 19 Jun 2013 19:16:18 +0400
Subject: [PATCH 08/75] Disabled the cuda variant when CUDA is not available.

---
 modules/gpu/perf/perf_main.cpp      | 6 +++++-
 modules/nonfree/perf/perf_main.cpp  | 6 +++++-
 modules/superres/perf/perf_main.cpp | 6 +++++-
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/modules/gpu/perf/perf_main.cpp b/modules/gpu/perf/perf_main.cpp
index f9f3a6854..db362af8f 100644
--- a/modules/gpu/perf/perf_main.cpp
+++ b/modules/gpu/perf/perf_main.cpp
@@ -44,4 +44,8 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(gpu, ("cuda", "plain"), printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(gpu, (
+#ifdef HAVE_CUDA
+                                   "cuda",
+#endif
+                                   "plain"), printCudaInfo())
diff --git a/modules/nonfree/perf/perf_main.cpp b/modules/nonfree/perf/perf_main.cpp
index 373e08aed..a3245186a 100644
--- a/modules/nonfree/perf/perf_main.cpp
+++ b/modules/nonfree/perf/perf_main.cpp
@@ -1,4 +1,8 @@
 #include "perf_precomp.hpp"
 #include "opencv2/ts/gpu_perf.hpp"
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(nonfree, ("cuda", "plain"), perf::printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(nonfree, (
+#ifdef HAVE_CUDA
+                                       "cuda",
+#endif
+                                       "plain"), perf::printCudaInfo())
diff --git a/modules/superres/perf/perf_main.cpp b/modules/superres/perf/perf_main.cpp
index 90a7f5125..8bf217e30 100644
--- a/modules/superres/perf/perf_main.cpp
+++ b/modules/superres/perf/perf_main.cpp
@@ -44,4 +44,8 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(superres, ("cuda", "plain"), printCudaInfo())
+CV_PERF_TEST_MAIN_WITH_IMPLS(superres, (
+#ifdef HAVE_CUDA
+                                        "cuda",
+#endif
+                                        "plain"), printCudaInfo())

From 3ea4836a0a7e20455e6199d5bd32f0a462d286c6 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Thu, 20 Jun 2013 15:16:22 +0400
Subject: [PATCH 09/75] Changed the impls argument to be an array name.

Turns out, you can't use preprocessor directives inside macro arguments.
Who'd have thought?
---
 modules/gpu/perf/perf_main.cpp            |  9 ++++++---
 modules/nonfree/perf/perf_main.cpp        |  9 ++++++---
 modules/superres/perf/perf_main.cpp       |  9 ++++++---
 modules/ts/include/opencv2/ts/ts_perf.hpp | 24 ++++++++++++++---------
 4 files changed, 33 insertions(+), 18 deletions(-)

diff --git a/modules/gpu/perf/perf_main.cpp b/modules/gpu/perf/perf_main.cpp
index db362af8f..53a19ca41 100644
--- a/modules/gpu/perf/perf_main.cpp
+++ b/modules/gpu/perf/perf_main.cpp
@@ -44,8 +44,11 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(gpu, (
+static const char * impls[] = {
 #ifdef HAVE_CUDA
-                                   "cuda",
+    "cuda",
 #endif
-                                   "plain"), printCudaInfo())
+    "plain"
+};
+
+CV_PERF_TEST_MAIN_WITH_IMPLS(gpu, impls, printCudaInfo())
diff --git a/modules/nonfree/perf/perf_main.cpp b/modules/nonfree/perf/perf_main.cpp
index a3245186a..d5f4a1a51 100644
--- a/modules/nonfree/perf/perf_main.cpp
+++ b/modules/nonfree/perf/perf_main.cpp
@@ -1,8 +1,11 @@
 #include "perf_precomp.hpp"
 #include "opencv2/ts/gpu_perf.hpp"
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(nonfree, (
+static const char * impls[] = {
 #ifdef HAVE_CUDA
-                                       "cuda",
+    "cuda",
 #endif
-                                       "plain"), perf::printCudaInfo())
+    "plain"
+};
+
+CV_PERF_TEST_MAIN_WITH_IMPLS(nonfree, impls, perf::printCudaInfo())
diff --git a/modules/superres/perf/perf_main.cpp b/modules/superres/perf/perf_main.cpp
index 8bf217e30..0a8ab5dea 100644
--- a/modules/superres/perf/perf_main.cpp
+++ b/modules/superres/perf/perf_main.cpp
@@ -44,8 +44,11 @@
 
 using namespace perf;
 
-CV_PERF_TEST_MAIN_WITH_IMPLS(superres, (
+static const char * impls[] = {
 #ifdef HAVE_CUDA
-                                        "cuda",
+    "cuda",
 #endif
-                                        "plain"), printCudaInfo())
+    "plain"
+};
+
+CV_PERF_TEST_MAIN_WITH_IMPLS(superres, impls, printCudaInfo())
diff --git a/modules/ts/include/opencv2/ts/ts_perf.hpp b/modules/ts/include/opencv2/ts/ts_perf.hpp
index ba0996403..1e68cd49b 100644
--- a/modules/ts/include/opencv2/ts/ts_perf.hpp
+++ b/modules/ts/include/opencv2/ts/ts_perf.hpp
@@ -475,25 +475,31 @@ CV_EXPORTS void PrintTo(const Size& sz, ::std::ostream* os);
     INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\
     void fixture##_##name::PerfTestBody()
 
-#define CV_PERF_UNWRAP_IMPLS(...) __VA_ARGS__
 
-// "plain" should always be one of the implementations
-#define CV_PERF_TEST_MAIN_WITH_IMPLS(modulename, impls, ...) \
-int main(int argc, char **argv)\
-{\
+#define CV_PERF_TEST_MAIN_INTERNALS(modulename, impls, ...) \
     while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/\
-    std::string impls_[] = { CV_PERF_UNWRAP_IMPLS impls };\
     ::perf::Regression::Init(#modulename);\
-    ::perf::TestBase::Init(std::vector<std::string>(impls_, impls_ + sizeof impls_ / sizeof *impls_),\
+    ::perf::TestBase::Init(std::vector<std::string>(impls, impls + sizeof impls / sizeof *impls),\
                            argc, argv);\
     ::testing::InitGoogleTest(&argc, argv);\
     cvtest::printVersionInfo();\
     ::testing::Test::RecordProperty("cv_module_name", #modulename);\
     ::perf::TestBase::RecordRunParameters();\
-    return RUN_ALL_TESTS();\
+    return RUN_ALL_TESTS();
+
+// impls must be an array, not a pointer; "plain" should always be one of the implementations
+#define CV_PERF_TEST_MAIN_WITH_IMPLS(modulename, impls, ...) \
+int main(int argc, char **argv)\
+{\
+    CV_PERF_TEST_MAIN_INTERNALS(modulename, impls, __VA_ARGS__)\
 }
 
-#define CV_PERF_TEST_MAIN(modulename, ...) CV_PERF_TEST_MAIN_WITH_IMPLS(modulename, ("plain"), __VA_ARGS__)
+#define CV_PERF_TEST_MAIN(modulename, ...) \
+int main(int argc, char **argv)\
+{\
+    const char * plain_only[] = { "plain" };\
+    CV_PERF_TEST_MAIN_INTERNALS(modulename, plain_only, __VA_ARGS__)\
+}
 
 #define TEST_CYCLE_N(n) for(declare.iterations(n); startTimer(), next(); stopTimer())
 #define TEST_CYCLE() for(; startTimer(), next(); stopTimer())

From 2688e22cb595c6b652538c36dacf2bb35cc58ac3 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Thu, 20 Jun 2013 19:34:32 +0400
Subject: [PATCH 10/75] Made xls-report.py use global properties in XML files.

Now it can determine, without looking at the file name, both the module
name and the configuration name (the latter with a little help from the
configuration file).
---
 modules/ts/misc/testlog_parser.py | 48 +++++++++++++++----
 modules/ts/misc/xls-report.py     | 79 ++++++++++++++++++++++---------
 2 files changed, 96 insertions(+), 31 deletions(-)

diff --git a/modules/ts/misc/testlog_parser.py b/modules/ts/misc/testlog_parser.py
index 8ab21417c..5d478645b 100755
--- a/modules/ts/misc/testlog_parser.py
+++ b/modules/ts/misc/testlog_parser.py
@@ -1,6 +1,9 @@
 #!/usr/bin/env python
 
-import sys, re, os.path
+import collections
+import re
+import os.path
+import sys
 from xml.dom.minidom import parse
 
 class TestInfo(object):
@@ -159,12 +162,31 @@ class TestInfo(object):
                 return 1
         return 0
 
+# This is a Sequence for compatibility with old scripts,
+# which treat parseLogFile's return value as a list.
+class TestRunInfo(collections.Sequence):
+    def __init__(self, properties, tests):
+        self.properties = properties
+        self.tests = tests
+
+    def __len__(self):
+        return len(self.tests)
+
+    def __getitem__(self, key):
+        return self.tests[key]
+
 def parseLogFile(filename):
-    tests = []
     log = parse(filename)
-    for case in log.getElementsByTagName("testcase"):
-        tests.append(TestInfo(case))
-    return tests
+
+    properties = {
+        attr_name[3:]: attr_value
+        for (attr_name, attr_value) in log.documentElement.attributes.items()
+        if attr_name.startswith('cv_')
+    }
+
+    tests = map(TestInfo, log.getElementsByTagName("testcase"))
+
+    return TestRunInfo(properties, tests)
 
 
 if __name__ == "__main__":
@@ -173,8 +195,18 @@ if __name__ == "__main__":
         exit(0)
 
     for arg in sys.argv[1:]:
-        print "Tests found in", arg
-        tests = parseLogFile(arg)
-        for t in sorted(tests):
+        print "Processing {}...".format(arg)
+
+        run = parseLogFile(arg)
+
+        print "Properties:"
+
+        for (prop_name, prop_value) in run.properties.items():
+          print "\t{} = {}".format(prop_name, prop_value)
+
+        print "Tests:"
+
+        for t in sorted(run.tests):
             t.dump()
+
         print
diff --git a/modules/ts/misc/xls-report.py b/modules/ts/misc/xls-report.py
index e79bb123d..a3cf8daca 100755
--- a/modules/ts/misc/xls-report.py
+++ b/modules/ts/misc/xls-report.py
@@ -3,6 +3,7 @@
 from __future__ import division
 
 import ast
+import fnmatch
 import logging
 import numbers
 import os, os.path
@@ -45,15 +46,55 @@ no_speedup_style = no_time_style
 error_speedup_style = xlwt.easyxf('pattern: pattern solid, fore_color orange')
 header_style = xlwt.easyxf('font: bold true; alignment: horizontal centre, vertical top, wrap True')
 
-def collect_xml(collection, configuration, xml_fullname):
-    xml_fname = os.path.split(xml_fullname)[1]
-    module = xml_fname[:xml_fname.index('_')]
+class Collector(object):
+    def __init__(self, config_match_func):
+        self.__config_cache = {}
+        self.config_match_func = config_match_func
+        self.tests = {}
 
-    module_tests = collection.setdefault(module, OrderedDict())
+    def collect_from(self, xml_path):
+        run = parseLogFile(xml_path)
 
-    for test in sorted(parseLogFile(xml_fullname)):
-        test_results = module_tests.setdefault((test.shortName(), test.param()), {})
-        test_results[configuration] = test.get("gmean") if test.status == 'run' else test.status
+        module = run.properties['module_name']
+
+        properties = run.properties.copy()
+        del properties['module_name']
+
+        props_key = tuple(sorted(properties.iteritems())) # dicts can't be keys
+
+        if props_key in self.__config_cache:
+            configuration = self.__config_cache[props_key]
+        else:
+            configuration = self.config_match_func(properties)
+
+            if configuration is None:
+                logging.warning('failed to match properties to a configuration: %r', props_key)
+            else:
+                same_config_props = [it[0] for it in self.__config_cache.iteritems() if it[1] == configuration]
+                if len(same_config_props) > 0:
+                    logging.warning('property set %r matches the same configuration %r as property set %r',
+                        props_key, configuration, same_config_props[0])
+
+            self.__config_cache[props_key] = configuration
+
+        if configuration is None: return
+
+        module_tests = self.tests.setdefault(module, OrderedDict())
+
+        for test in run.tests:
+            test_results = module_tests.setdefault((test.shortName(), test.param()), {})
+            test_results[configuration] = test.get("gmean") if test.status == 'run' else test.status
+
+def make_match_func(matchers):
+    def match_func(properties):
+        for matcher in matchers:
+            if all(properties.get(name) == value
+                   for (name, value) in matcher['properties'].iteritems()):
+                return matcher['name']
+
+        return None
+
+    return match_func
 
 def main():
     arg_parser = ArgumentParser(description='Build an XLS performance report.')
@@ -83,23 +124,15 @@ def main():
 
         sheet_conf = dict(global_conf.items() + sheet_conf.items())
 
-        if 'configurations' in sheet_conf:
-            config_names = sheet_conf['configurations']
-        else:
-            try:
-                config_names = [p for p in os.listdir(sheet_path)
-                    if os.path.isdir(os.path.join(sheet_path, p))]
-            except Exception as e:
-                logging.warning('error while determining configuration names for %s: %s', sheet_path, e)
-                continue
+        config_names = sheet_conf.get('configurations', [])
+        config_matchers = sheet_conf.get('configuration_matchers', [])
 
-        collection = {}
+        collector = Collector(make_match_func(config_matchers))
 
-        for configuration, configuration_path in \
-                [(c, os.path.join(sheet_path, c))  for c in config_names]:
-            logging.info('processing %s', configuration_path)
-            for xml_fullname in glob(os.path.join(configuration_path, '*.xml')):
-                collect_xml(collection, configuration, xml_fullname)
+        for root, _, filenames in os.walk(sheet_path):
+            logging.info('looking in %s', root)
+            for filename in fnmatch.filter(filenames, '*.xml'):
+                collector.collect_from(os.path.join(root, filename))
 
         sheet = wb.add_sheet(sheet_conf.get('sheet_name', os.path.basename(os.path.abspath(sheet_path))))
 
@@ -126,7 +159,7 @@ def main():
         module_styles = {module: xlwt.easyxf('pattern: pattern solid, fore_color {}'.format(color))
                          for module, color in module_colors.iteritems()}
 
-        for module, tests in sorted(collection.iteritems()):
+        for module, tests in sorted(collector.tests.iteritems()):
             for ((test, param), configs) in tests.iteritems():
                 sheet.write(row, 0, module, module_styles.get(module, xlwt.Style.default_style))
                 sheet.write(row, 1, test)

From 0e3a9eaf980b484a9d5f56c0f38c92164e9c5910 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Fri, 21 Jun 2013 13:43:16 +0400
Subject: [PATCH 11/75] Made Collector render property sets as dicts instead of
 tuples of pairs.

---
 modules/ts/misc/xls-report.py | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/modules/ts/misc/xls-report.py b/modules/ts/misc/xls-report.py
index a3cf8daca..2dcbf89cf 100755
--- a/modules/ts/misc/xls-report.py
+++ b/modules/ts/misc/xls-report.py
@@ -52,6 +52,12 @@ class Collector(object):
         self.config_match_func = config_match_func
         self.tests = {}
 
+    # Format a sorted sequence of pairs as if it was a dictionary.
+    # We can't just use a dictionary instead, since we want to preserve the sorted order of the keys.
+    @staticmethod
+    def __format_config_cache_key(pairs):
+        return '{' + ', '.join(repr(k) + ': ' + repr(v) for (k, v) in pairs) + '}'
+
     def collect_from(self, xml_path):
         run = parseLogFile(xml_path)
 
@@ -68,12 +74,15 @@ class Collector(object):
             configuration = self.config_match_func(properties)
 
             if configuration is None:
-                logging.warning('failed to match properties to a configuration: %r', props_key)
+                logging.warning('failed to match properties to a configuration: %s',
+                    Collector.__format_config_cache_key(props_key))
             else:
                 same_config_props = [it[0] for it in self.__config_cache.iteritems() if it[1] == configuration]
                 if len(same_config_props) > 0:
-                    logging.warning('property set %r matches the same configuration %r as property set %r',
-                        props_key, configuration, same_config_props[0])
+                    logging.warning('property set %s matches the same configuration %r as property set %s',
+                        Collector.__format_config_cache_key(props_key),
+                        configuration,
+                        Collector.__format_config_cache_key(same_config_props[0]))
 
             self.__config_cache[props_key] = configuration
 

From d4a8b87645f6df2ee5a61c8b0c52a4248d2c600a Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Fri, 21 Jun 2013 16:45:17 +0400
Subject: [PATCH 12/75] Wrote relevant docs.

---
 modules/ts/misc/xls-report.py | 79 ++++++++++++++++++++++++++++-------
 1 file changed, 64 insertions(+), 15 deletions(-)

diff --git a/modules/ts/misc/xls-report.py b/modules/ts/misc/xls-report.py
index 2dcbf89cf..e911314e9 100755
--- a/modules/ts/misc/xls-report.py
+++ b/modules/ts/misc/xls-report.py
@@ -1,5 +1,69 @@
 #!/usr/bin/env python
 
+"""
+    This script can generate XLS reports from OpenCV tests' XML output files.
+
+    To use it, first, create a directory for each machine you ran tests on.
+    Each such directory will become a sheet in the report. Put each XML file
+    into the corresponding directory.
+
+    Then, create your configuration file(s). You can have a global configuration
+    file (specified with the -c option), and per-sheet configuration files, which
+    must be called sheet.conf and placed in the directory corresponding to the sheet.
+    The settings in the per-sheet configuration file will override those in the
+    global configuration file, if both are present.
+
+    A configuration file must consist of a Python dictionary. The following keys
+    will be recognized:
+
+    * 'comparisons': [{'from': string, 'to': string}]
+        List of configurations to compare performance between. For each item,
+        the sheet will have a column showing speedup from configuration named
+        'from' to configuration named "to".
+
+    * 'configuration_matchers': [{'properties': {string: object}, 'name': string}]
+        Instructions for matching test run property sets to configuration names.
+
+        For each found XML file:
+
+        1) All attributes of the root element starting with the prefix 'cv_' are
+           placed in a dictionary, with the cv_ prefix stripped and the cv_module_name
+           element deleted.
+
+        2) The first matcher for which the XML's file property set contains the same
+           keys with equal values as its 'properties' dictionary is searched for.
+           A missing property can be matched by using None as the value.
+
+           Corollary 1: you should place more specific matchers before less specific
+           ones.
+
+           Corollary 2: an empty 'properties' dictionary matches every property set.
+
+        3) If a matching matcher is found, its 'name' string is presumed to be the name
+           of the configuration the XML file corresponds to. Otherwise, a warning is
+           printed. A warning is also printed if two different property sets match to the
+           same configuration name.
+
+    * 'configurations': [string]
+        List of names for compile-time and runtime configurations of OpenCV.
+        Each item will correspond to a column of the sheet.
+
+    * 'module_colors': {string: string}
+        Mapping from module name to color name. In the sheet, cells containing module
+        names from this mapping will be colored with the corresponding color. You can
+        find the list of available colors here:
+        <http://www.simplistix.co.uk/presentations/python-excel.pdf>.
+
+    * 'sheet_name': string
+        Name for the sheet. If this parameter is missing, the name of sheet's directory
+        will be used.
+
+    Note that all keys are optional, although to get useful results, you'll want to
+    specify at least 'configurations' and 'configuration_matchers'.
+
+    Finally, run the script. Use the --help option for usage information.
+"""
+
 from __future__ import division
 
 import ast
@@ -18,21 +82,6 @@ import xlwt
 
 from testlog_parser import parseLogFile
 
-# To build XLS report you neet to put your xmls (OpenCV tests output) in the
-# following way:
-#
-# "root" --- folder, representing the whole XLS document. It contains several
-# subfolders --- sheet-paths of the XLS document. Each sheet-path contains it's
-# subfolders --- config-paths. Config-paths are columns of the sheet and
-# they contains xmls files --- output of OpenCV modules testing.
-# Config-path means OpenCV build configuration, including different
-# options such as NEON, TBB, GPU enabling/disabling.
-#
-# root
-# root\sheet_path
-# root\sheet_path\configuration1 (column 1)
-# root\sheet_path\configuration2 (column 2)
-
 re_image_size = re.compile(r'^ \d+ x \d+$', re.VERBOSE)
 re_data_type = re.compile(r'^ (?: 8 | 16 | 32 | 64 ) [USF] C [1234] $', re.VERBOSE)
 

From c16316c4b49fe73b768210d43db46405f177e9fe Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Fri, 21 Jun 2013 12:43:16 +0400
Subject: [PATCH 13/75] Replaced the semi-public CV_PARALLEL_FRAMEWORK macro
 with a function.

That way, core/internal.hpp doesn't have to depend on cvconfig.h, which we
don't ship.
---
 .../core/include/opencv2/core/internal.hpp    | 31 ++++---------------
 modules/core/src/parallel.cpp                 | 31 +++++++++++++++++++
 modules/ts/src/precomp.hpp                    |  1 -
 modules/ts/src/ts_func.cpp                    | 11 +++----
 4 files changed, 42 insertions(+), 32 deletions(-)

diff --git a/modules/core/include/opencv2/core/internal.hpp b/modules/core/include/opencv2/core/internal.hpp
index 10cd2caf9..606c62f8f 100644
--- a/modules/core/include/opencv2/core/internal.hpp
+++ b/modules/core/include/opencv2/core/internal.hpp
@@ -50,7 +50,8 @@
 
 #include <vector>
 
-#include "cvconfig.h"
+#include "opencv2/core/core.hpp"
+#include "opencv2/core/types_c.h"
 
 #if defined WIN32 || defined _WIN32
 #  ifndef WIN32
@@ -186,30 +187,6 @@ CV_INLINE IppiSize ippiSize(int width, int height)
 #  include "opencv2/core/eigen.hpp"
 #endif
 
-#ifdef _OPENMP
-#  define HAVE_OPENMP
-#endif
-
-#ifdef __APPLE__
-#  define HAVE_GCD
-#endif
-
-#if defined _MSC_VER && _MSC_VER >= 1600
-#  define HAVE_CONCURRENCY
-#endif
-
-#if defined HAVE_TBB && TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202
-#  define CV_PARALLEL_FRAMEWORK "tbb"
-#elif defined HAVE_CSTRIPES
-#  define CV_PARALLEL_FRAMEWORK "cstripes"
-#elif defined HAVE_OPENMP
-#  define CV_PARALLEL_FRAMEWORK "openmp"
-#elif defined HAVE_GCD
-#  define CV_PARALLEL_FRAMEWORK "gcd"
-#elif defined HAVE_CONCURRENCY
-#  define CV_PARALLEL_FRAMEWORK "ms-concurrency"
-#endif
-
 #ifdef __cplusplus
 
 namespace cv
@@ -277,6 +254,10 @@ namespace cv
         body(range);
     }
 #endif
+
+    // Returns a static string if there is a parallel framework,
+    // NULL otherwise.
+    CV_EXPORTS const char* currentParallelFramework();
 } //namespace cv
 
 #define CV_INIT_ALGORITHM(classname, algname, memberinit) \
diff --git a/modules/core/src/parallel.cpp b/modules/core/src/parallel.cpp
index 51b165275..0a9ed0987 100644
--- a/modules/core/src/parallel.cpp
+++ b/modules/core/src/parallel.cpp
@@ -61,6 +61,17 @@
     #endif
 #endif
 
+#ifdef _OPENMP
+    #define HAVE_OPENMP
+#endif
+
+#ifdef __APPLE__
+    #define HAVE_GCD
+#endif
+
+#if defined _MSC_VER && _MSC_VER >= 1600
+    #define HAVE_CONCURRENCY
+#endif
 
 /* IMPORTANT: always use the same order of defines
    1. HAVE_TBB         - 3rdparty library, should be explicitly enabled
@@ -99,6 +110,18 @@
     #endif
 #endif
 
+#if defined HAVE_TBB && TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202
+#  define CV_PARALLEL_FRAMEWORK "tbb"
+#elif defined HAVE_CSTRIPES
+#  define CV_PARALLEL_FRAMEWORK "cstripes"
+#elif defined HAVE_OPENMP
+#  define CV_PARALLEL_FRAMEWORK "openmp"
+#elif defined HAVE_GCD
+#  define CV_PARALLEL_FRAMEWORK "gcd"
+#elif defined HAVE_CONCURRENCY
+#  define CV_PARALLEL_FRAMEWORK "ms-concurrency"
+#endif
+
 namespace cv
 {
     ParallelLoopBody::~ParallelLoopBody() {}
@@ -465,6 +488,14 @@ int cv::getNumberOfCPUs(void)
 #endif
 }
 
+const char* cv::currentParallelFramework() {
+#ifdef CV_PARALLEL_FRAMEWORK
+    return CV_PARALLEL_FRAMEWORK;
+#else
+    return NULL;
+#endif
+}
+
 CV_IMPL void cvSetNumThreads(int nt)
 {
     cv::setNumThreads(nt);
diff --git a/modules/ts/src/precomp.hpp b/modules/ts/src/precomp.hpp
index 0b2adacc4..a74417da4 100644
--- a/modules/ts/src/precomp.hpp
+++ b/modules/ts/src/precomp.hpp
@@ -1,4 +1,3 @@
-#include "opencv2/core/core.hpp"
 #include "opencv2/core/core_c.h"
 #include "opencv2/core/internal.hpp"
 #include "opencv2/ts/ts.hpp"
diff --git a/modules/ts/src/ts_func.cpp b/modules/ts/src/ts_func.cpp
index e2998149d..0186e9c8f 100644
--- a/modules/ts/src/ts_func.cpp
+++ b/modules/ts/src/ts_func.cpp
@@ -2963,13 +2963,12 @@ void printVersionInfo(bool useStdOut)
         if(useStdOut) std::cout << ver << std::endl;
     }
 
-#ifdef CV_PARALLEL_FRAMEWORK
-    ::testing::Test::RecordProperty("cv_parallel_framework", CV_PARALLEL_FRAMEWORK);
-    if (useStdOut)
-    {
-        std::cout << "Parallel framework: " << CV_PARALLEL_FRAMEWORK << std::endl;
+    const char* parallel_framework = currentParallelFramework();
+
+    if (parallel_framework) {
+        ::testing::Test::RecordProperty("cv_parallel_framework", parallel_framework);
+        if (useStdOut) std::cout << "Parallel framework: " << parallel_framework << std::endl;
     }
-#endif
 
     std::string cpu_features;
 

From e3577c2f586aaa83c858139d67c1317259416454 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 8 Apr 2013 18:13:49 -0700
Subject: [PATCH 14/75] Build with dev release of TBB enabled.

---
 3rdparty/tbb/CMakeLists.txt | 47 ++++++++++++++++++++++++++++---------
 1 file changed, 36 insertions(+), 11 deletions(-)

diff --git a/3rdparty/tbb/CMakeLists.txt b/3rdparty/tbb/CMakeLists.txt
index af1581349..9dcb63b7f 100644
--- a/3rdparty/tbb/CMakeLists.txt
+++ b/3rdparty/tbb/CMakeLists.txt
@@ -1,13 +1,20 @@
 #Cross compile TBB from source
 project(tbb)
 
-# 4.1 update 2 - works fine
-set(tbb_ver "tbb41_20130116oss")
-set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130116oss_src.tgz")
-set(tbb_md5 "3809790e1001a1b32d59c9fee590ee85")
+# 4.1 update 3 dev - works fine
+set(tbb_ver "tbb41_20130401oss")
+set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130401oss_src.tgz")
+set(tbb_md5 "f2f591a0d2ca8f801e221ce7d9ea84bb")
 set(tbb_version_file "version_string.ver")
 ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow)
 
+# 4.1 update 2 - works fine
+#set(tbb_ver "tbb41_20130116oss")
+#set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130116oss_src.tgz")
+#set(tbb_md5 "3809790e1001a1b32d59c9fee590ee85")
+#set(tbb_version_file "version_string.ver")
+#ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow)
+
 # 4.1 update 1 - works fine
 #set(tbb_ver "tbb41_20121003oss")
 #set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20121003oss_src.tgz")
@@ -107,7 +114,8 @@ if(NOT EXISTS "${tbb_src_dir}")
               RESULT_VARIABLE tbb_untar_RESULT)
 
   if(NOT tbb_untar_RESULT EQUAL 0 OR NOT EXISTS "${tbb_src_dir}")
-    message(FATAL_ERROR "Failed to unpack TBB sources")
+    message(FATAL_ERROR "Failed to unpack TBB sources (${tbb_untar_RESULT} ${tbb_src_dir})")
+
   endif()
 endif()
 
@@ -124,11 +132,12 @@ list(APPEND lib_srcs "${tbb_src_dir}/src/rml/client/rml_tbb.cpp")
 
 if (WIN32)
   add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0
-                -D__TBB_BUILD=1
-                -D_UNICODE
-                -DUNICODE
-                -DWINAPI_FAMILY=WINAPI_FAMILY_APP
-                -DDO_ITT_NOTIFY=0
+                /D__TBB_BUILD=1
+                /D_UNICODE
+                /DUNICODE
+                /DWINAPI_FAMILY=WINAPI_FAMILY_APP
+                /DDO_ITT_NOTIFY=0
+                /DUSE_WINTHREAD
                ) # defines were copied from windows.cl.inc
 set(CMAKE_LINKER_FLAGS "${CMAKE_LINKER_FLAGS} /APPCONTAINER")
 else()
@@ -173,7 +182,23 @@ endif()
 set(TBB_SOURCE_FILES ${TBB_SOURCE_FILES} "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_version_file}")
 
 add_library(tbb ${TBB_SOURCE_FILES})
-target_link_libraries(tbb c m dl)
+
+if (WIN32)
+  add_custom_command(TARGET tbb
+                     PRE_BUILD
+                     COMMAND ${CMAKE_C_COMPILER} /nologo /TC /EP ${tbb_src_dir}\\src\\tbb\\win32-tbb-export.def /DTBB_NO_LEGACY /DUSE_WINTHREAD /D_CRT_SECURE_NO_DEPRECATE /D_WIN32_WINNT=0x0400 /D__TBB_BUILD=1 /I${tbb_src_dir}\\src /I${tbb_src_dir}\\include > "${tbb_src_dir}\\src\\tbb\\tbb.def"
+                     WORKING_DIRECTORY ${tbb_src_dir}\\src\\tbb
+                     COMMENT "Generating tbb.def file" VERBATIM
+                    )
+endif()
+
+if (WIN32)
+  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEF:${tbb_src_dir}/src/tbb/tbb.def /DLL /MAP /fixed:no /INCREMENTAL:NO")
+endif()
+
+if (NOT WIN32)
+  target_link_libraries(tbb c m dl)
+endif()
 
 ocv_warnings_disable(CMAKE_CXX_FLAGS -Wundef -Wmissing-declarations)
 string(REPLACE "-Werror=non-virtual-dtor" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")

From 033e3092a3297d8cb3e49eeff825cb706dd01f95 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Tue, 16 Apr 2013 06:25:10 -0700
Subject: [PATCH 15/75] Media Foundation based VideoCapture improved

Code formating fixed;
GrabFrame method implemented correclty.
---
 modules/highgui/src/cap.cpp      |   5 ++
 modules/highgui/src/cap_msmf.cpp | 146 +++++++++++++++++++++++++++++--
 2 files changed, 144 insertions(+), 7 deletions(-)

diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp
index 2c3b3a94c..3750d1d66 100644
--- a/modules/highgui/src/cap.cpp
+++ b/modules/highgui/src/cap.cpp
@@ -117,6 +117,9 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index)
 #ifdef HAVE_DSHOW
         CV_CAP_DSHOW,
 #endif
+#ifdef HAVE_MSMF
+        CV_CAP_MSMF,
+#endif
 #if 1
         CV_CAP_IEEE1394,   // identical to CV_CAP_DC1394
 #endif
@@ -198,7 +201,9 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index)
         {
 #ifdef HAVE_MSMF
         case CV_CAP_MSMF:
+             printf("Creating Media foundation capture\n");
              capture = cvCreateCameraCapture_MSMF (index);
+             printf("Capture address %p\n", capture);
              if (capture)
                  return capture;
             break;
diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 52b780463..28d92c361 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -61,18 +61,22 @@
 #include <stdio.h>
 #include <stdarg.h>
 #include <string.h>
+
 #pragma warning(disable:4503)
 #pragma comment(lib, "mfplat")
 #pragma comment(lib, "mf")
 #pragma comment(lib, "mfuuid")
 #pragma comment(lib, "Strmiids")
 #pragma comment(lib, "MinCore_Downlevel")
+
 struct IMFMediaType;
 struct IMFActivate;
 struct IMFMediaSource;
 struct IMFAttributes;
+
 namespace
 {
+
 template <class T> void SafeRelease(T **ppT)
 {
     if (*ppT)
@@ -81,7 +85,8 @@ template <class T> void SafeRelease(T **ppT)
         *ppT = NULL;
     }
 }
- /// Class for printing info into consol
+
+/// Class for printing info into consol
 class DebugPrintOut
 {
 public:
@@ -93,6 +98,7 @@ public:
 private:
     DebugPrintOut(void);
 };
+
 // Structure for collecting info about types of video, which are supported by current video device
 struct MediaType
 {
@@ -127,6 +133,7 @@ struct MediaType
     ~MediaType();
     void Clear();
 };
+
 /// Class for parsing info from IMFMediaType into the local MediaType
 class FormatReader
 {
@@ -136,9 +143,11 @@ public:
 private:
     FormatReader(void);
 };
+
 DWORD WINAPI MainThreadFunction( LPVOID lpParam );
 typedef void(*emergensyStopEventCallback)(int, void *);
 typedef unsigned char BYTE;
+
 class RawImage
 {
 public:
@@ -156,6 +165,7 @@ private:
     unsigned char *ri_pixels;
     RawImage(unsigned int size);
 };
+
 // Class for grabbing image from video stream
 class ImageGrabber : public IMFSampleGrabberSinkCallback
 {
@@ -836,10 +846,13 @@ MediaType FormatReader::Read(IMFMediaType *pType)
 FormatReader::~FormatReader(void)
 {
 }
-#define CHECK_HR(x) if (FAILED(x)) { goto done; }
+
+#define CHECK_HR(x) if (FAILED(x)) { printf("Checking failed !!!\n"); goto done; }
+
 ImageGrabber::ImageGrabber(unsigned int deviceID): m_cRef(1), ig_DeviceID(deviceID), ig_pSource(NULL), ig_pSession(NULL), ig_pTopology(NULL), ig_RIE(true), ig_Close(false)
 {
 }
+
 ImageGrabber::~ImageGrabber(void)
 {
     if (ig_pSession)
@@ -851,6 +864,7 @@ ImageGrabber::~ImageGrabber(void)
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Destroing instance of the ImageGrabber class \n", ig_DeviceID);
 }
+
 HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat)
 {
     IMFActivate *pSinkActivate = NULL;
@@ -871,23 +885,34 @@ HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat
     ig_pSource = pSource;
     hr = pSource->CreatePresentationDescriptor(&pPD);
     if (FAILED(hr))
+    {
+        printf("Error creating CreatePresentationDescriptor()\n");
         goto err;
+    }
     BOOL fSelected;
     hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
-    if (FAILED(hr))
+    if (FAILED(hr)) {
+        printf("Error GetStreamDescriptorByIndex()\n");
         goto err;
+    }
     hr = pSD->GetMediaTypeHandler(&pHandler);
-    if (FAILED(hr))
+    if (FAILED(hr)) {
+        printf("Error GetMediaTypeHandler()\n");
         goto err;
+    }
     DWORD cTypes = 0;
     hr = pHandler->GetMediaTypeCount(&cTypes);
-    if (FAILED(hr))
+    if (FAILED(hr)) {
+        printf("Error GetMediaTypeCount()\n");
         goto err;
+    }
     if(cTypes > 0)
     {
         hr = pHandler->GetCurrentMediaType(&pCurrentType);
-        if (FAILED(hr))
+        if (FAILED(hr)) {
+            printf("Error GetCurrentMediaType()\n");
             goto err;
+        }
         MT = FormatReader::Read(pCurrentType);
     }
 err:
@@ -904,6 +929,10 @@ err:
     {
         sizeRawImage = MT.MF_MT_FRAME_SIZE * 4;
     }
+    else
+    {
+        printf("Video format is not RBG 24/32!\n");
+    }
     CHECK_HR(hr = RawImage::CreateInstance(&ig_RIFirst, sizeRawImage));
     CHECK_HR(hr = RawImage::CreateInstance(&ig_RISecond, sizeRawImage));
     ig_RIOut = ig_RISecond;
@@ -936,6 +965,7 @@ done:
     SafeRelease(&pType);
     return hr;
 }
+
 void ImageGrabber::stopGrabbing()
 {
     if(ig_pSession)
@@ -943,6 +973,7 @@ void ImageGrabber::stopGrabbing()
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Stopping of of grabbing of images\n", ig_DeviceID);
 }
+
 HRESULT ImageGrabber::startGrabbing(void)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -995,12 +1026,15 @@ HRESULT ImageGrabber::startGrabbing(void)
         SafeRelease(&pEvent);
     }
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
+
 done:
     SafeRelease(&pEvent);
     SafeRelease(&ig_pSession);
     SafeRelease(&ig_pTopology);
+    
     return hr;
 }
+
 HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo)
 {
     IMFTopology *pTopology = NULL;
@@ -1038,6 +1072,7 @@ HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSink
     }
     *ppTopo = pTopology;
     (*ppTopo)->AddRef();
+
 done:
     SafeRelease(&pTopology);
     SafeRelease(&pNode1);
@@ -1045,8 +1080,10 @@ done:
     SafeRelease(&pPD);
     SafeRelease(&pSD);
     SafeRelease(&pHandler);
+    
     return hr;
 }
+
 HRESULT ImageGrabber::AddSourceNode(
     IMFTopology *pTopology,           // Topology.
     IMFMediaSource *pSource,          // Media source.
@@ -1064,10 +1101,13 @@ HRESULT ImageGrabber::AddSourceNode(
     // Return the pointer to the caller.
     *ppNode = pNode;
     (*ppNode)->AddRef();
+
 done:
     SafeRelease(&pNode);
+
     return hr;
 }
+
 HRESULT ImageGrabber::AddOutputNode(
     IMFTopology *pTopology,     // Topology.
     IMFActivate *pActivate,     // Media sink activation object.
@@ -1084,10 +1124,13 @@ HRESULT ImageGrabber::AddOutputNode(
     // Return the pointer to the caller.
     *ppNode = pNode;
     (*ppNode)->AddRef();
+
 done:
     SafeRelease(&pNode);
+
     return hr;
 }
+
 HRESULT ImageGrabber::CreateInstance(ImageGrabber **ppIG, unsigned int deviceID)
 {
     *ppIG = new (std::nothrow) ImageGrabber(deviceID);
@@ -1099,6 +1142,7 @@ HRESULT ImageGrabber::CreateInstance(ImageGrabber **ppIG, unsigned int deviceID)
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Creating instance of ImageGrabber\n", deviceID);
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::QueryInterface(REFIID riid, void** ppv)
 {
     HRESULT hr = E_NOINTERFACE;
@@ -1119,10 +1163,12 @@ STDMETHODIMP ImageGrabber::QueryInterface(REFIID riid, void** ppv)
     }
     return hr;
 }
+
 STDMETHODIMP_(ULONG) ImageGrabber::AddRef()
 {
     return InterlockedIncrement(&m_cRef);
 }
+
 STDMETHODIMP_(ULONG) ImageGrabber::Release()
 {
     ULONG cRef = InterlockedDecrement(&m_cRef);
@@ -1132,38 +1178,45 @@ STDMETHODIMP_(ULONG) ImageGrabber::Release()
     }
     return cRef;
 }
+
 STDMETHODIMP ImageGrabber::OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset)
 {
     (void)hnsSystemTime;
     (void)llClockStartOffset;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnClockStop(MFTIME hnsSystemTime)
 {
     (void)hnsSystemTime;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnClockPause(MFTIME hnsSystemTime)
 {
     (void)hnsSystemTime;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnClockRestart(MFTIME hnsSystemTime)
 {
     (void)hnsSystemTime;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnClockSetRate(MFTIME hnsSystemTime, float flRate)
 {
     (void)flRate;
     (void)hnsSystemTime;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnSetPresentationClock(IMFPresentationClock* pClock)
 {
     (void)pClock;
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwSampleFlags,
     LONGLONG llSampleTime, LONGLONG llSampleDuration, const BYTE * pSampleBuffer,
     DWORD dwSampleSize)
@@ -1173,6 +1226,9 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
     (void)dwSampleFlags;
     (void)llSampleDuration;
     (void)dwSampleSize;
+
+    printf("ImageGrabber::OnProcessSample() -- begin\n");
+
     if(ig_RIE)
     {
         ig_RIFirst->fastCopy(pSampleBuffer);
@@ -1184,22 +1240,29 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
         ig_RIOut = ig_RISecond;
     }
     ig_RIE = !ig_RIE;
+
+    printf("ImageGrabber::OnProcessSample() -- end\n");
+
     return S_OK;
 }
+
 STDMETHODIMP ImageGrabber::OnShutdown()
 {
     return S_OK;
 }
+
 RawImage *ImageGrabber::getRawImage()
 {
     return ig_RIOut;
 }
+
 DWORD WINAPI MainThreadFunction( LPVOID lpParam )
 {
     ImageGrabberThread *pIGT = (ImageGrabberThread *)lpParam;
     pIGT->run();
     return 0;
 }
+
 HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaSource *pSource, unsigned int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -1213,6 +1276,7 @@ HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaS
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Creating of the instance of ImageGrabberThread\n", deviceID);
     return S_OK;
 }
+
 ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID): igt_Handle(NULL), igt_stop(false)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -1235,6 +1299,7 @@ ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int dev
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i There is a problem with creation of the instance of the ImageGrabber class\n", deviceID);
     }
 }
+
 void ImageGrabberThread::setEmergencyStopEvent(void *userData, void(*func)(int, void *))
 {
     if(func)
@@ -1243,12 +1308,14 @@ void ImageGrabberThread::setEmergencyStopEvent(void *userData, void(*func)(int,
         igt_userData = userData;
     }
 }
+
 ImageGrabberThread::~ImageGrabberThread(void)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Destroing ImageGrabberThread\n", igt_DeviceID);
     delete igt_pImageGrabber;
 }
+
 void ImageGrabberThread::stop()
 {
     igt_stop = true;
@@ -1257,6 +1324,7 @@ void ImageGrabberThread::stop()
         igt_pImageGrabber->stopGrabbing();
     }
 }
+
 void ImageGrabberThread::start()
 {
     igt_Handle = CreateThread(
@@ -1267,6 +1335,7 @@ void ImageGrabberThread::start()
             0,                      // use default creation flags
             &igt_ThreadIdArray);   // returns the thread identifier
 }
+
 void ImageGrabberThread::run()
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -1294,10 +1363,12 @@ void ImageGrabberThread::run()
     else
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Finish thread\n", igt_DeviceID);
 }
+
 ImageGrabber *ImageGrabberThread::getImageGrabber()
 {
     return igt_pImageGrabber;
 }
+
 Media_Foundation::Media_Foundation(void)
 {
     HRESULT hr = MFStartup(MF_VERSION);
@@ -1307,6 +1378,7 @@ Media_Foundation::Media_Foundation(void)
         DPO->printOut(L"MEDIA FOUNDATION: It cannot be created!!!\n");
     }
 }
+
 Media_Foundation::~Media_Foundation(void)
 {
     HRESULT hr = MFShutdown();
@@ -1316,6 +1388,7 @@ Media_Foundation::~Media_Foundation(void)
         DPO->printOut(L"MEDIA FOUNDATION: Resources cannot be released\n");
     }
 }
+
 bool Media_Foundation::buildListOfDevices()
 {
     HRESULT hr = S_OK;
@@ -1342,30 +1415,36 @@ bool Media_Foundation::buildListOfDevices()
     SafeRelease(&pAttributes);
     return (SUCCEEDED(hr));
 }
+
 Media_Foundation& Media_Foundation::getInstance()
 {
     static Media_Foundation instance;
     return instance;
 }
+
 RawImage::RawImage(unsigned int size): ri_new(false), ri_pixels(NULL)
 {
     ri_size = size;
     ri_pixels = new unsigned char[size];
     memset((void *)ri_pixels,0,ri_size);
 }
+
 bool RawImage::isNew()
 {
     return ri_new;
 }
+
 unsigned int RawImage::getSize()
 {
     return ri_size;
 }
+
 RawImage::~RawImage(void)
 {
     delete []ri_pixels;
     ri_pixels = NULL;
 }
+
 long RawImage::CreateInstance(RawImage **ppRImage,unsigned int size)
 {
     *ppRImage = new (std::nothrow) RawImage(size);
@@ -1375,25 +1454,30 @@ long RawImage::CreateInstance(RawImage **ppRImage,unsigned int size)
     }
     return S_OK;
 }
+
 void RawImage::setCopy(const BYTE * pSampleBuffer)
 {
     memcpy(ri_pixels, pSampleBuffer, ri_size);
     ri_new = true;
 }
+
 void RawImage::fastCopy(const BYTE * pSampleBuffer)
 {
     memcpy(ri_pixels, pSampleBuffer, ri_size);
     ri_new = true;
 }
+
 unsigned char * RawImage::getpPixels()
 {
     ri_new = false;
     return ri_pixels;
 }
+
 videoDevice::videoDevice(void): vd_IsSetuped(false), vd_LockOut(OpenLock), vd_pFriendlyName(NULL),
     vd_Width(0), vd_Height(0), vd_pSource(NULL), vd_func(NULL), vd_userData(NULL)
 {
 }
+
 void videoDevice::setParametrs(CamParametrs parametrs)
 {
     if(vd_IsSetuped)
@@ -1428,6 +1512,7 @@ void videoDevice::setParametrs(CamParametrs parametrs)
         }
     }
 }
+
 CamParametrs videoDevice::getParametrs()
 {
     CamParametrs out;
@@ -1472,6 +1557,7 @@ CamParametrs videoDevice::getParametrs()
     }
     return out;
 }
+
 long videoDevice::resetDevice(IMFActivate *pActivate)
 {
     HRESULT hr = -1;
@@ -1503,6 +1589,7 @@ long videoDevice::resetDevice(IMFActivate *pActivate)
     }
     return hr;
 }
+
 long videoDevice::readInfoOfDevice(IMFActivate *pActivate, unsigned int Num)
 {
     HRESULT hr = -1;
@@ -1510,6 +1597,7 @@ long videoDevice::readInfoOfDevice(IMFActivate *pActivate, unsigned int Num)
     hr = resetDevice(pActivate);
     return hr;
 }
+
 long videoDevice::checkDevice(IMFAttributes *pAttributes, IMFActivate **pDevice)
 {
     HRESULT hr = S_OK;
@@ -1911,8 +1999,10 @@ done:
     SafeRelease(&pType);
     return hr;
 }
+
 videoDevices::videoDevices(void): count(0)
 {}
+
 void videoDevices::clearDevices()
 {
     std::vector<videoDevice *>::iterator i = vds_Devices.begin();
@@ -1920,10 +2010,12 @@ void videoDevices::clearDevices()
         delete (*i);
     vds_Devices.clear();
 }
+
 videoDevices::~videoDevices(void)
 {
     clearDevices();
 }
+
 videoDevice * videoDevices::getDevice(unsigned int i)
 {
     if(i >= vds_Devices.size())
@@ -1936,6 +2028,7 @@ videoDevice * videoDevices::getDevice(unsigned int i)
     }
     return vds_Devices[i];
 }
+
 long videoDevices::initDevices(IMFAttributes *pAttributes)
 {
     HRESULT hr = S_OK;
@@ -1965,15 +2058,18 @@ long videoDevices::initDevices(IMFAttributes *pAttributes)
     }
     return hr;
 }
+
 size_t videoDevices::getCount()
 {
     return vds_Devices.size();
 }
+
 videoDevices& videoDevices::getInstance()
 {
     static videoDevices instance;
     return instance;
 }
+
 Parametr::Parametr()
 {
     CurrentValue = 0;
@@ -1983,6 +2079,7 @@ Parametr::Parametr()
     Default = 0;
     Flag = 0;
 }
+
 MediaType::MediaType()
 {
     pMF_MT_AM_FORMAT_TYPEName = NULL;
@@ -1990,10 +2087,12 @@ MediaType::MediaType()
     pMF_MT_SUBTYPEName = NULL;
     Clear();
 }
+
 MediaType::~MediaType()
 {
     Clear();
 }
+
 void MediaType::Clear()
 {
     MF_MT_FRAME_SIZE = 0;
@@ -2021,6 +2120,7 @@ void MediaType::Clear()
     memset(&MF_MT_AM_FORMAT_TYPE, 0, sizeof(GUID));
     memset(&MF_MT_SUBTYPE, 0, sizeof(GUID));
 }
+
 videoInput::videoInput(void): accessToDevices(false)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2029,6 +2129,7 @@ videoInput::videoInput(void): accessToDevices(false)
     if(!accessToDevices)
         DPO->printOut(L"INITIALIZATION: Ther is not any suitable video device\n");
 }
+
 void videoInput::updateListOfDevices()
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2037,11 +2138,13 @@ void videoInput::updateListOfDevices()
     if(!accessToDevices)
         DPO->printOut(L"UPDATING: Ther is not any suitable video device\n");
 }
+
 videoInput::~videoInput(void)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->printOut(L"\n***** CLOSE VIDEOINPUT LIBRARY - 2013 *****\n\n");
 }
+
 IMFMediaSource *videoInput::getMediaSource(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2063,6 +2166,7 @@ IMFMediaSource *videoInput::getMediaSource(int deviceID)
     }
     return NULL;
 }
+
 bool videoInput::setupDevice(int deviceID, unsigned int id)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2089,6 +2193,7 @@ bool videoInput::setupDevice(int deviceID, unsigned int id)
     }
     return false;
 }
+
 bool videoInput::setupDevice(int deviceID, unsigned int w, unsigned int h, unsigned int idealFramerate)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2115,6 +2220,7 @@ bool videoInput::setupDevice(int deviceID, unsigned int w, unsigned int h, unsig
     }
     return false;
 }
+
 MediaType videoInput::getFormat(int deviceID, unsigned int id)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2136,6 +2242,7 @@ MediaType videoInput::getFormat(int deviceID, unsigned int id)
     }
     return MediaType();
 }
+
 bool videoInput::isDeviceSetup(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2157,6 +2264,7 @@ bool videoInput::isDeviceSetup(int deviceID)
     }
     return false;
 }
+
 bool videoInput::isDeviceMediaSource(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2178,6 +2286,7 @@ bool videoInput::isDeviceMediaSource(int deviceID)
     }
     return false;
 }
+
 bool videoInput::isDeviceRawDataSource(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2202,6 +2311,7 @@ bool videoInput::isDeviceRawDataSource(int deviceID)
     }
     return false;
 }
+
 bool videoInput::isFrameNew(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2230,6 +2340,7 @@ bool videoInput::isFrameNew(int deviceID)
     }
     return false;
 }
+
 unsigned int videoInput::getCountFormats(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2251,12 +2362,14 @@ unsigned int videoInput::getCountFormats(int deviceID)
     }
     return 0;
 }
+
 void videoInput::closeAllDevices()
 {
     videoDevices *VDS = &videoDevices::getInstance();
     for(unsigned int i = 0; i < VDS->getCount(); i++)
         closeDevice(i);
 }
+
 void videoInput::setParametrs(int deviceID, CamParametrs parametrs)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2277,6 +2390,7 @@ void videoInput::setParametrs(int deviceID, CamParametrs parametrs)
         DPO->printOut(L"VIDEODEVICE(s): There is not any suitable video device\n");
     }
 }
+
 CamParametrs videoInput::getParametrs(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2299,6 +2413,7 @@ CamParametrs videoInput::getParametrs(int deviceID)
     }
     return out;
 }
+
 void videoInput::closeDevice(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2319,6 +2434,7 @@ void videoInput::closeDevice(int deviceID)
         DPO->printOut(L"VIDEODEVICE(s): There is not any suitable video device\n");
     }
 }
+
 unsigned int videoInput::getWidth(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2340,6 +2456,7 @@ unsigned int videoInput::getWidth(int deviceID)
     }
     return 0;
 }
+
 unsigned int videoInput::getHeight(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2361,6 +2478,7 @@ unsigned int videoInput::getHeight(int deviceID)
     }
     return 0;
 }
+
 wchar_t *videoInput::getNameVideoDevice(int deviceID)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2382,6 +2500,7 @@ wchar_t *videoInput::getNameVideoDevice(int deviceID)
     }
     return L"Empty";
 }
+
 unsigned int videoInput::listDevices(bool silent)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2405,20 +2524,24 @@ unsigned int videoInput::listDevices(bool silent)
     }
     return out;
 }
+
 videoInput& videoInput::getInstance()
 {
     static videoInput instance;
     return instance;
 }
+
 bool videoInput::isDevicesAcceable()
 {
     return accessToDevices;
 }
+
 void videoInput::setVerbose(bool state)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->setVerbose(state);
 }
+
 void videoInput::setEmergencyStopEvent(int deviceID, void *userData, void(*func)(int, void *))
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2442,6 +2565,7 @@ void videoInput::setEmergencyStopEvent(int deviceID, void *userData, void(*func)
         DPO->printOut(L"VIDEODEVICE(s): There is not any suitable video device\n");
     }
 }
+
 bool videoInput::getPixels(int deviceID, unsigned char * dstBuffer, bool flipRedAndBlue, bool flipImage)
 {
     bool success = false;
@@ -2491,6 +2615,7 @@ bool videoInput::getPixels(int deviceID, unsigned char * dstBuffer, bool flipRed
     }
     return success;
 }
+
 void videoInput::processPixels(unsigned char * src, unsigned char * dst, unsigned int width,
                                 unsigned int height, unsigned int bpp, bool bRGB, bool bFlip)
 {
@@ -2553,6 +2678,7 @@ void videoInput::processPixels(unsigned char * src, unsigned char * dst, unsigne
     }
 }
 }
+
 /******* Capturing video from camera via Microsoft Media Foundation **********/
 class CvCaptureCAM_MSMF : public CvCapture
 {
@@ -2605,6 +2731,7 @@ void CvCaptureCAM_MSMF::close()
     }
     widthSet = heightSet = width = height = -1;
 }
+
 // Initialize camera input
 bool CvCaptureCAM_MSMF::open( int _index )
 {
@@ -2621,10 +2748,14 @@ bool CvCaptureCAM_MSMF::open( int _index )
     index = try_index;
     return true;
 }
+
 bool CvCaptureCAM_MSMF::grabFrame()
 {
-    return true;
+    while (VI.isDeviceSetup(index) && !VI.isFrameNew(index))
+        Sleep(1);
+    return VI.isDeviceSetup(index);
 }
+
 IplImage* CvCaptureCAM_MSMF::retrieveFrame(int)
 {
     if( !frame || (int)VI.getWidth(index) != frame->width || (int)VI.getHeight(index) != frame->height )
@@ -2637,6 +2768,7 @@ IplImage* CvCaptureCAM_MSMF::retrieveFrame(int)
     VI.getPixels( index, (uchar*)frame->imageData, false, true );
     return frame;
 }
+
 double CvCaptureCAM_MSMF::getProperty( int property_id )
 {
     // image format proprrties

From ccb8292e8ec245944d71fe38c32a70ecb0428feb Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 6 May 2013 03:36:51 -0700
Subject: [PATCH 16/75] Media Foundation-based VideoWriter added

---
 modules/highgui/src/cap.cpp        |  12 +
 modules/highgui/src/cap_ffmpeg.cpp |   4 -
 modules/highgui/src/cap_msmf.cpp   | 356 ++++++++++++++++++++++++++++-
 modules/highgui/src/precomp.hpp    |   2 +
 4 files changed, 367 insertions(+), 7 deletions(-)

diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp
index 3750d1d66..afab8d4b5 100644
--- a/modules/highgui/src/cap.cpp
+++ b/modules/highgui/src/cap.cpp
@@ -408,8 +408,20 @@ CV_IMPL CvVideoWriter* cvCreateVideoWriter( const char* filename, int fourcc,
     if(!fourcc || !fps)
         result = cvCreateVideoWriter_Images(filename);
 
+#ifdef HAVE_FFMPEG
     if(!result)
         result = cvCreateVideoWriter_FFMPEG_proxy (filename, fourcc, fps, frameSize, is_color);
+#endif
+
+#ifdef HAVE_VFW
+    if(!result)
+     return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, isColor);
+#endif
+
+#ifdef HAVE_MSMF
+    if (!result)
+        result = cvCreateVideoWriter_MSMF(filename, fourcc, fps, frameSize, is_color);
+#endif
 
 /*  #ifdef HAVE_XINE
     if(!result)
diff --git a/modules/highgui/src/cap_ffmpeg.cpp b/modules/highgui/src/cap_ffmpeg.cpp
index 669ebda12..7d4d6af38 100644
--- a/modules/highgui/src/cap_ffmpeg.cpp
+++ b/modules/highgui/src/cap_ffmpeg.cpp
@@ -263,9 +263,5 @@ CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourc
     if( result->open( filename, fourcc, fps, frameSize, isColor != 0 ))
         return result;
     delete result;
-#ifdef HAVE_VFW
-     return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, isColor);
- #else
     return 0;
-#endif
 }
diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 28d92c361..1d6bb597b 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -54,6 +54,8 @@
 #include <mfplay.h>
 #include <mfobjects.h>
 #include "Strsafe.h"
+#include <wrl/client.h>
+#include <Mfreadwrite.h>
 #include <new>
 #include <map>
 #include <vector>
@@ -67,6 +69,7 @@
 #pragma comment(lib, "mf")
 #pragma comment(lib, "mfuuid")
 #pragma comment(lib, "Strmiids")
+#pragma comment(lib, "Mfreadwrite")
 #pragma comment(lib, "MinCore_Downlevel")
 
 struct IMFMediaType;
@@ -146,7 +149,6 @@ private:
 
 DWORD WINAPI MainThreadFunction( LPVOID lpParam );
 typedef void(*emergensyStopEventCallback)(int, void *);
-typedef unsigned char BYTE;
 
 class RawImage
 {
@@ -1031,7 +1033,7 @@ done:
     SafeRelease(&pEvent);
     SafeRelease(&ig_pSession);
     SafeRelease(&ig_pTopology);
-    
+
     return hr;
 }
 
@@ -1080,7 +1082,7 @@ done:
     SafeRelease(&pPD);
     SafeRelease(&pSD);
     SafeRelease(&pHandler);
-    
+
     return hr;
 }
 
@@ -2939,4 +2941,352 @@ CvCapture* cvCreateCameraCapture_MSMF( int index )
     delete capture;
     return 0;
 }
+
+
+//
+//
+// Media Foundation-based Video Writer
+//
+//
+
+using namespace Microsoft::WRL;
+
+class CvVideoWriter_MSMF : public CvVideoWriter
+{
+public:
+    CvVideoWriter_MSMF();
+    virtual ~CvVideoWriter_MSMF();
+    virtual bool open( const char* filename, int fourcc,
+                       double fps, CvSize frameSize, bool isColor );
+    virtual void close();
+    virtual bool writeFrame( const IplImage* img);
+
+private:
+    UINT32 videoWidth;
+    UINT32 videoHeight;
+    double fps;
+    UINT32 bitRate;
+    UINT32 frameSize;
+    GUID   encodingFormat;
+    GUID   inputFormat;
+
+    DWORD  streamIndex;
+    ComPtr<IMFSinkWriter> sinkWriter;
+
+    bool   initiated;
+
+    LONGLONG rtStart;
+    UINT64 rtDuration;
+
+    HRESULT InitializeSinkWriter(const char* filename);
+    HRESULT WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& rtStart, const LONGLONG& rtDuration);
+};
+
+CvVideoWriter_MSMF::CvVideoWriter_MSMF()
+{
+}
+
+CvVideoWriter_MSMF::~CvVideoWriter_MSMF()
+{
+    close();
+}
+
+bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
+                       double _fps, CvSize frameSize, bool isColor )
+{
+    videoWidth = frameSize.width;
+    videoHeight = frameSize.height;
+    fps = _fps;
+    bitRate = 4*800000;
+    encodingFormat = MFVideoFormat_WMV3;
+    inputFormat = MFVideoFormat_RGB32;
+
+    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+    if (SUCCEEDED(hr))
+    {
+        printf("CoInitializeEx is successfull\n");
+        hr = MFStartup(MF_VERSION);
+        if (SUCCEEDED(hr))
+        {
+            printf("MFStartup is successfull\n");
+            hr = InitializeSinkWriter(filename);
+            if (SUCCEEDED(hr))
+            {
+                printf("InitializeSinkWriter is successfull\n");
+                initiated = true;
+                rtStart = 0;
+                MFFrameRateToAverageTimePerFrame(fps, 1, &rtDuration);
+                printf("duration: %d\n", rtDuration);
+            }
+        }
+    }
+
+    return SUCCEEDED(hr);
+}
+
+void CvVideoWriter_MSMF::close()
+{
+    printf("VideoWriter::close()\n");
+    if (!initiated)
+    {
+        printf("VideoWriter was not Initialized\n");
+        return;
+    }
+
+    initiated = false;
+    HRESULT hr = sinkWriter->Finalize();
+    printf("sinkWriter Finalize status %u\n", hr);
+    MFShutdown();
+}
+
+bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
+{
+    if (!img)
+        return false;
+
+    printf("Writing not empty IplImage\n");
+
+    auto length = img->width * img->height * 4;
+    printf("Image: %dx%d, %d\n", img->width, img->height, length);
+    DWORD* target = new DWORD[length];
+
+    printf("Before for loop\n");
+    for (int rowIdx = 0; rowIdx < img->height; rowIdx++)
+    {
+        char* rowStart = img->imageData + rowIdx*img->widthStep;
+        for (int colIdx = 0; colIdx < img->width; colIdx++)
+        {
+            BYTE b = rowStart[colIdx * img->nChannels + 0];
+            BYTE g = rowStart[colIdx * img->nChannels + 1];
+            BYTE r = rowStart[colIdx * img->nChannels + 2];
+
+                    // On ARM devices data is stored starting from the last line
+        // (and not the first line) so you have to revert them on the Y axis
+#if _M_ARM
+            auto row = index / videoWidth;
+            auto targetRow = videoHeight - row - 1;
+            auto column = index - (row * videoWidth);
+            target[(targetRow * videoWidth) + column] = (r << 16) + (g << 8) + b;
+#else
+            target[rowIdx*img->width+colIdx] = (r << 16) + (g << 8) + b;
+#endif
+        }
+    }
+
+    // Send frame to the sink writer.
+    printf("Before private WriteFrame call\n");
+    HRESULT hr = WriteFrame(target, rtStart, rtDuration);
+    printf("After private WriteFrame call\n");
+    if (FAILED(hr))
+    {
+        printf("Private WriteFrame failed\n");
+        delete[] target;
+        return false;
+    }
+    rtStart += rtDuration;
+
+    printf("End of writing IplImage\n");
+
+    delete[] target;
+
+    return true;
+}
+
+HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
+{
+    ComPtr<IMFAttributes> spAttr;
+    ComPtr<IMFMediaType>  mediaTypeOut;
+    ComPtr<IMFMediaType>  mediaTypeIn;
+    ComPtr<IMFByteStream> spByteStream;
+
+    MFCreateAttributes(&spAttr, 10);
+    spAttr->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, true);
+
+    wchar_t* unicodeFileName = new wchar_t[strlen(filename)+1];
+    MultiByteToWideChar(CP_ACP, 0, filename, -1, unicodeFileName, strlen(filename)+1);
+
+    HRESULT hr = MFCreateSinkWriterFromURL(unicodeFileName, NULL, spAttr.Get(), &sinkWriter);
+
+    delete[] unicodeFileName;
+
+    // Set the output media type.
+    if (SUCCEEDED(hr))
+    {
+        printf("MFCreateSinkWriterFromURL is successfull\n");
+        hr = MFCreateMediaType(&mediaTypeOut);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeOut->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeOut->SetGUID(MF_MT_SUBTYPE, encodingFormat);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeOut->SetUINT32(MF_MT_AVG_BITRATE, bitRate);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeOut->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeSize(mediaTypeOut.Get(), MF_MT_FRAME_SIZE, videoWidth, videoHeight);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_FRAME_RATE, fps, 1);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = sinkWriter->AddStream(mediaTypeOut.Get(), &streamIndex);
+    }
+
+    // Set the input media type.
+    if (SUCCEEDED(hr))
+    {
+        hr = MFCreateMediaType(&mediaTypeIn);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeIn->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeIn->SetGUID(MF_MT_SUBTYPE, inputFormat);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = mediaTypeIn->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeSize(mediaTypeIn.Get(), MF_MT_FRAME_SIZE, videoWidth, videoHeight);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_FRAME_RATE, fps, 1);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = sinkWriter->SetInputMediaType(streamIndex, mediaTypeIn.Get(), NULL);
+    }
+
+    // Tell the sink writer to start accepting data.
+    if (SUCCEEDED(hr))
+    {
+        hr = sinkWriter->BeginWriting();
+    }
+
+    return hr;
+}
+
+HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& Start, const LONGLONG& Duration)
+{
+    printf("Private WriteFrame(%p, %llu, %llu)\n", videoFrameBuffer, Start, Duration);
+    IMFSample* sample;
+    IMFMediaBuffer* buffer;
+
+    const LONG cbWidth = 4 * videoWidth;
+    const DWORD cbBuffer = cbWidth * videoHeight;
+
+    BYTE *pData = NULL;
+
+    // Create a new memory buffer.
+    HRESULT hr = MFCreateMemoryBuffer(cbBuffer, &buffer);
+
+    // Lock the buffer and copy the video frame to the buffer.
+    if (SUCCEEDED(hr))
+    {
+        printf("MFCreateMemoryBuffer successfull\n");
+        hr = buffer->Lock(&pData, NULL, NULL);
+    }
+
+    if (SUCCEEDED(hr))
+    {
+        printf("Before MFCopyImage(%p, %d, %p, %d, %d %d)\n", pData, cbWidth, videoFrameBuffer, cbWidth, cbWidth, videoHeight);
+        hr = MFCopyImage(
+            pData,                      // Destination buffer.
+            cbWidth,                    // Destination stride.
+            (BYTE*)videoFrameBuffer,    // First row in source image.
+            cbWidth,                    // Source stride.
+            cbWidth,                    // Image width in bytes.
+            videoHeight                 // Image height in pixels.
+            );
+        printf("After MFCopyImage()\n");
+    }
+
+    printf("Before buffer.Get()\n");
+    if (buffer)
+    {
+        printf("Before buffer->Unlock\n");
+        buffer->Unlock();
+        printf("After buffer->Unlock\n");
+    }
+
+    // Set the data length of the buffer.
+    if (SUCCEEDED(hr))
+    {
+        printf("MFCopyImage successfull\n");
+        hr = buffer->SetCurrentLength(cbBuffer);
+    }
+
+    // Create a media sample and add the buffer to the sample.
+    if (SUCCEEDED(hr))
+    {
+        hr = MFCreateSample(&sample);
+    }
+    if (SUCCEEDED(hr))
+    {
+        hr = sample->AddBuffer(buffer);
+    }
+
+    // Set the time stamp and the duration.
+    if (SUCCEEDED(hr))
+    {
+        printf("Sample time: %d\n", Start);
+        hr = sample->SetSampleTime(Start);
+    }
+    if (SUCCEEDED(hr))
+    {
+        printf("Duration: %d\n", Duration);
+        hr = sample->SetSampleDuration(Duration);
+    }
+
+    // Send the sample to the Sink Writer.
+    if (SUCCEEDED(hr))
+    {
+        printf("Setting writer params successfull\n");
+        hr = sinkWriter->WriteSample(streamIndex, sample);
+    }
+
+    printf("Private WriteFrame(%d, %p) end with status %u\n", streamIndex, sample, hr);
+
+    SafeRelease(&sample);
+    SafeRelease(&buffer);
+
+    return hr;
+}
+
+CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc,
+                                        double fps, CvSize frameSize, int isColor )
+{
+    printf("Creating Media Foundation VideoWriter\n");
+    CvVideoWriter_MSMF* writer = new CvVideoWriter_MSMF;
+    if( writer->open( filename, fourcc, fps, frameSize, isColor != 0 ))
+        return writer;
+    delete writer;
+    return NULL;
+}
+
 #endif
\ No newline at end of file
diff --git a/modules/highgui/src/precomp.hpp b/modules/highgui/src/precomp.hpp
index aa327d6d7..b9896955c 100644
--- a/modules/highgui/src/precomp.hpp
+++ b/modules/highgui/src/precomp.hpp
@@ -119,6 +119,8 @@ CvVideoWriter* cvCreateVideoWriter_VFW( const char* filename, int fourcc,
                                         double fps, CvSize frameSize, int is_color );
 CvCapture* cvCreateCameraCapture_DShow( int index );
 CvCapture* cvCreateCameraCapture_MSMF( int index );
+CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc,
+                                        double fps, CvSize frameSize, int is_color );
 CvCapture* cvCreateCameraCapture_OpenNI( int index );
 CvCapture* cvCreateFileCapture_OpenNI( const char* filename );
 CvCapture* cvCreateCameraCapture_Android( int index );

From 22b0cfbaa215878809d4685d5bf14dce75ee401f Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 6 May 2013 07:17:53 -0700
Subject: [PATCH 17/75] Media Foundation-based VideoWriter improvements.

FourCC parameter handlig added;
Smart pointers instead SafeRelease call;
Windows RT support (vertical mirroring).
---
 modules/highgui/src/cap_msmf.cpp | 87 ++++++++++++++++++++++++--------
 1 file changed, 67 insertions(+), 20 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 1d6bb597b..d3c365f54 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -2979,6 +2979,7 @@ private:
     UINT64 rtDuration;
 
     HRESULT InitializeSinkWriter(const char* filename);
+    static const GUID FourCC2GUID(int fourcc);
     HRESULT WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& rtStart, const LONGLONG& rtDuration);
 };
 
@@ -2991,14 +2992,65 @@ CvVideoWriter_MSMF::~CvVideoWriter_MSMF()
     close();
 }
 
+const GUID CvVideoWriter_MSMF::FourCC2GUID(int fourcc)
+{
+    switch(fourcc)
+    {
+        case 'dv25':
+            return MFVideoFormat_DV25; break;
+        case 'dv50':
+            return MFVideoFormat_DV50; break;
+        case 'dvc ':
+            return MFVideoFormat_DVC; break;
+        case 'dvh1':
+            return MFVideoFormat_DVH1; break;
+        case 'dvhd':
+            return MFVideoFormat_DVHD; break;
+        case 'dvsd':
+            return MFVideoFormat_DVSD; break;
+        case 'dvsl':
+                return MFVideoFormat_DVSL; break;
+        case 'H263':
+                return MFVideoFormat_H263; break;
+        case 'H264':
+                return MFVideoFormat_H264; break;
+        case 'M4S2':
+                return MFVideoFormat_M4S2; break;
+        case 'MJPG':
+                return MFVideoFormat_MJPG; break;
+        case 'MP43':
+                return MFVideoFormat_MP43; break;
+        case 'MP4S':
+                return MFVideoFormat_MP4S; break;
+        case 'MP4V':
+                return MFVideoFormat_MP4V; break;
+        case 'MPG1':
+                return MFVideoFormat_MPG1; break;
+        case 'MSS1':
+                return MFVideoFormat_MSS1; break;
+        case 'MSS2':
+                return MFVideoFormat_MSS2; break;
+        case 'WMV1':
+                return MFVideoFormat_WMV1; break;
+        case 'WMV2':
+                return MFVideoFormat_WMV2; break;
+        case 'WMV3':
+                return MFVideoFormat_WMV3; break;
+        case 'WVC1':
+                return MFVideoFormat_WVC1; break;
+        default:
+            return MFVideoFormat_H264;
+    }
+}
+
 bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
                        double _fps, CvSize frameSize, bool isColor )
 {
     videoWidth = frameSize.width;
     videoHeight = frameSize.height;
     fps = _fps;
-    bitRate = 4*800000;
-    encodingFormat = MFVideoFormat_WMV3;
+    bitRate = videoWidth*videoHeight; // 1-bit per pixel
+    encodingFormat = FourCC2GUID(fourcc);
     inputFormat = MFVideoFormat_RGB32;
 
     HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
@@ -3015,7 +3067,7 @@ bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
                 printf("InitializeSinkWriter is successfull\n");
                 initiated = true;
                 rtStart = 0;
-                MFFrameRateToAverageTimePerFrame(fps, 1, &rtDuration);
+                MFFrameRateToAverageTimePerFrame((UINT32)fps, 1, &rtDuration);
                 printf("duration: %d\n", rtDuration);
             }
         }
@@ -3046,7 +3098,7 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
 
     printf("Writing not empty IplImage\n");
 
-    auto length = img->width * img->height * 4;
+    int length = img->width * img->height * 4;
     printf("Image: %dx%d, %d\n", img->width, img->height, length);
     DWORD* target = new DWORD[length];
 
@@ -3060,13 +3112,11 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
             BYTE g = rowStart[colIdx * img->nChannels + 1];
             BYTE r = rowStart[colIdx * img->nChannels + 2];
 
-                    // On ARM devices data is stored starting from the last line
-        // (and not the first line) so you have to revert them on the Y axis
+            // On ARM devices data is stored starting from the last line
+            // (and not the first line) so you have to revert them on the Y axis
 #if _M_ARM
-            auto row = index / videoWidth;
-            auto targetRow = videoHeight - row - 1;
-            auto column = index - (row * videoWidth);
-            target[(targetRow * videoWidth) + column] = (r << 16) + (g << 8) + b;
+            int targetRow = videoHeight - rowIdx - 1;
+            target[(targetRow * videoWidth) + colIdx] = (r << 16) + (g << 8) + b;
 #else
             target[rowIdx*img->width+colIdx] = (r << 16) + (g << 8) + b;
 #endif
@@ -3137,7 +3187,7 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     }
     if (SUCCEEDED(hr))
     {
-        hr = MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_FRAME_RATE, fps, 1);
+        hr = MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_FRAME_RATE, (UINT32)fps, 1);
     }
     if (SUCCEEDED(hr))
     {
@@ -3171,7 +3221,7 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     }
     if (SUCCEEDED(hr))
     {
-        hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_FRAME_RATE, fps, 1);
+        hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_FRAME_RATE, (UINT32)fps, 1);
     }
     if (SUCCEEDED(hr))
     {
@@ -3194,8 +3244,8 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
 HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& Start, const LONGLONG& Duration)
 {
     printf("Private WriteFrame(%p, %llu, %llu)\n", videoFrameBuffer, Start, Duration);
-    IMFSample* sample;
-    IMFMediaBuffer* buffer;
+    ComPtr<IMFSample> sample;
+    ComPtr<IMFMediaBuffer> buffer;
 
     const LONG cbWidth = 4 * videoWidth;
     const DWORD cbBuffer = cbWidth * videoHeight;
@@ -3248,7 +3298,7 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
     }
     if (SUCCEEDED(hr))
     {
-        hr = sample->AddBuffer(buffer);
+        hr = sample->AddBuffer(buffer.Get());
     }
 
     // Set the time stamp and the duration.
@@ -3267,13 +3317,10 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
     if (SUCCEEDED(hr))
     {
         printf("Setting writer params successfull\n");
-        hr = sinkWriter->WriteSample(streamIndex, sample);
+        hr = sinkWriter->WriteSample(streamIndex, sample.Get());
     }
 
-    printf("Private WriteFrame(%d, %p) end with status %u\n", streamIndex, sample, hr);
-
-    SafeRelease(&sample);
-    SafeRelease(&buffer);
+    printf("Private WriteFrame(%d, %p) end with status %u\n", streamIndex, sample.Get(), hr);
 
     return hr;
 }

From 9fb762ccecbfc5768e44db7753047dde8f2b8383 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Tue, 14 May 2013 05:17:34 -0700
Subject: [PATCH 18/75] VideoCapture for video files implemented.

Set and Get methods are not implemented;
Camera based video capture is broken due to modifications.
---
 modules/highgui/src/cap.cpp        |  16 +-
 modules/highgui/src/cap_ffmpeg.cpp |   4 -
 modules/highgui/src/cap_msmf.cpp   | 525 +++++++++++++++++++++++++++--
 modules/highgui/src/precomp.hpp    |   1 +
 4 files changed, 521 insertions(+), 25 deletions(-)

diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp
index afab8d4b5..8db873102 100644
--- a/modules/highgui/src/cap.cpp
+++ b/modules/highgui/src/cap.cpp
@@ -363,6 +363,20 @@ CV_IMPL CvCapture * cvCreateFileCapture (const char * filename)
     if (! result)
         result = cvCreateFileCapture_FFMPEG_proxy (filename);
 
+#ifdef HAVE_MSMF
+    if (! result)
+    {
+        printf("Creating Media foundation based reader\n");
+        result = cvCreateFileCapture_MSMF (filename);
+        printf("Construction result %p\n", result);
+    }
+#endif
+
+#ifdef HAVE_VFW
+    if (! result)
+        result = cvCreateFileCapture_VFW (filename);
+#endif
+
 #ifdef HAVE_XINE
     if (! result)
         result = cvCreateFileCapture_XINE (filename);
@@ -415,7 +429,7 @@ CV_IMPL CvVideoWriter* cvCreateVideoWriter( const char* filename, int fourcc,
 
 #ifdef HAVE_VFW
     if(!result)
-     return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, isColor);
+     return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, is_color);
 #endif
 
 #ifdef HAVE_MSMF
diff --git a/modules/highgui/src/cap_ffmpeg.cpp b/modules/highgui/src/cap_ffmpeg.cpp
index 7d4d6af38..bf73c0810 100644
--- a/modules/highgui/src/cap_ffmpeg.cpp
+++ b/modules/highgui/src/cap_ffmpeg.cpp
@@ -209,11 +209,7 @@ CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char * filename)
     if( result->open( filename ))
         return result;
     delete result;
-#ifdef HAVE_VFW
-    return cvCreateFileCapture_VFW(filename);
-#else
     return 0;
-#endif
 }
 
 class CvVideoWriter_FFMPEG_proxy : 
diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index d3c365f54..c037d2f98 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -175,10 +175,17 @@ public:
     ~ImageGrabber(void);
     HRESULT initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat);
     HRESULT startGrabbing(void);
+    void pauseGrabbing();
+    void resumeGrabbing();
     void stopGrabbing();
     RawImage *getRawImage();
     // Function of creation of the instance of the class
     static HRESULT CreateInstance(ImageGrabber **ppIG,unsigned int deviceID);
+
+    HANDLE ig_hFrameReady;
+    HANDLE ig_hFrameGrabbed;
+    HANDLE ig_hFinish;
+
 private:
     bool ig_RIE;
     bool ig_Close;
@@ -198,11 +205,7 @@ private:
     IMFPresentationDescriptor *pPD,
     IMFStreamDescriptor *pSD,
     IMFTopologyNode **ppNode);
-    HRESULT AddOutputNode(
-    IMFTopology *pTopology,
-    IMFActivate *pActivate,
-    DWORD dwId,
-    IMFTopologyNode **ppNode);
+    HRESULT AddOutputNode(IMFTopology *pTopology, IMFActivate *pActivate, DWORD dwId, IMFTopologyNode **ppNode);
     // IUnknown methods
     STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
     STDMETHODIMP_(ULONG) AddRef();
@@ -851,20 +854,37 @@ FormatReader::~FormatReader(void)
 
 #define CHECK_HR(x) if (FAILED(x)) { printf("Checking failed !!!\n"); goto done; }
 
-ImageGrabber::ImageGrabber(unsigned int deviceID): m_cRef(1), ig_DeviceID(deviceID), ig_pSource(NULL), ig_pSession(NULL), ig_pTopology(NULL), ig_RIE(true), ig_Close(false)
-{
-}
+ImageGrabber::ImageGrabber(unsigned int deviceID):
+    m_cRef(1),
+    ig_DeviceID(deviceID),
+    ig_pSource(NULL),
+    ig_pSession(NULL),
+    ig_pTopology(NULL),
+    ig_RIE(true),
+    ig_Close(false),
+    ig_hFrameReady(CreateEvent(NULL, FALSE, FALSE, "ig_hFrameReady")),
+    ig_hFrameGrabbed(CreateEvent(NULL, FALSE, TRUE, "ig_hFrameGrabbed")),
+    ig_hFinish(CreateEvent(NULL, FALSE, FALSE, "ig_hFinish"))
+{}
 
 ImageGrabber::~ImageGrabber(void)
 {
+    printf("ImageGrabber::~ImageGrabber()\n");
     if (ig_pSession)
     {
+        printf("ig_pSession->Shutdown()");
         ig_pSession->Shutdown();
     }
-    //SafeRelease(&ig_pSession);
-    //SafeRelease(&ig_pTopology);
+
+    CloseHandle(ig_hFrameReady);
+    CloseHandle(ig_hFrameGrabbed);
+    CloseHandle(ig_hFinish);
+
+    SafeRelease(&ig_pSession);
+    SafeRelease(&ig_pTopology);
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
-    DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Destroing instance of the ImageGrabber class \n", ig_DeviceID);
+
+    DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Destroing instance of the ImageGrabber class\n", ig_DeviceID);
 }
 
 HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat)
@@ -983,9 +1003,17 @@ HRESULT ImageGrabber::startGrabbing(void)
     PROPVARIANT var;
     PropVariantInit(&var);
     HRESULT hr = S_OK;
-    CHECK_HR(hr = ig_pSession->SetTopology(0, ig_pTopology));
-    CHECK_HR(hr = ig_pSession->Start(&GUID_NULL, &var));
+    hr = ig_pSession->SetTopology(0, ig_pTopology);
+    if (FAILED(hr))
+    {
+        printf("Error: cannot set topology (status %u)\n", hr);
+    }
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Start Grabbing of the images\n", ig_DeviceID);
+    hr = ig_pSession->Start(&GUID_NULL, &var);
+    if (FAILED(hr))
+    {
+        printf("Error: cannot start session (status %u)\n", hr);
+    }
     for(;;)
     {
         HRESULT hrStatus = S_OK;
@@ -1027,6 +1055,9 @@ HRESULT ImageGrabber::startGrabbing(void)
         }
         SafeRelease(&pEvent);
     }
+
+    SetEvent(ig_hFinish);
+
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
 
 done:
@@ -1037,6 +1068,14 @@ done:
     return hr;
 }
 
+void ImageGrabber::pauseGrabbing()
+{
+}
+
+void ImageGrabber::resumeGrabbing()
+{
+}
+
 HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo)
 {
     IMFTopology *pTopology = NULL;
@@ -1229,6 +1268,8 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
     (void)llSampleDuration;
     (void)dwSampleSize;
 
+    WaitForSingleObject(ig_hFrameGrabbed, INFINITE);
+
     printf("ImageGrabber::OnProcessSample() -- begin\n");
 
     if(ig_RIE)
@@ -1245,11 +1286,14 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
 
     printf("ImageGrabber::OnProcessSample() -- end\n");
 
+    SetEvent(ig_hFrameReady);
+
     return S_OK;
 }
 
 STDMETHODIMP ImageGrabber::OnShutdown()
 {
+    SetEvent(ig_hFrameGrabbed);
     return S_OK;
 }
 
@@ -1279,7 +1323,7 @@ HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaS
     return S_OK;
 }
 
-ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID): igt_Handle(NULL), igt_stop(false)
+ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID): igt_func(NULL), igt_Handle(NULL), igt_stop(false)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     HRESULT hr = ImageGrabber::CreateInstance(&igt_pImageGrabber, deviceID);
@@ -1330,11 +1374,11 @@ void ImageGrabberThread::stop()
 void ImageGrabberThread::start()
 {
     igt_Handle = CreateThread(
-            NULL,                   // default security attributes
-            0,                      // use default stack size
-            MainThreadFunction,       // thread function name
-            this,          // argument to thread function
-            0,                      // use default creation flags
+            NULL,                  // default security attributes
+            0,                     // use default stack size
+            MainThreadFunction,    // thread function name
+            this,                  // argument to thread function
+            0,                     // use default creation flags
             &igt_ThreadIdArray);   // returns the thread identifier
 }
 
@@ -1359,6 +1403,7 @@ void ImageGrabberThread::run()
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Emergency Stop thread\n", igt_DeviceID);
         if(igt_func)
         {
+            printf("Calling Emergency stop even handler\n");
             igt_func(igt_DeviceID, igt_userData);
         }
     }
@@ -2701,11 +2746,14 @@ protected:
     IplImage* frame;
     videoInput VI;
 };
+
 struct SuppressVideoInputMessages
 {
     SuppressVideoInputMessages() { videoInput::setVerbose(true); }
 };
+
 static SuppressVideoInputMessages do_it;
+
 CvCaptureCAM_MSMF::CvCaptureCAM_MSMF():
     index(-1),
     width(-1),
@@ -2713,7 +2761,7 @@ CvCaptureCAM_MSMF::CvCaptureCAM_MSMF():
     fourcc(-1),
     widthSet(-1),
     heightSet(-1),
-    frame(0),
+    frame(NULL),
     VI(videoInput::getInstance())
 {
     CoInitialize(0);
@@ -2925,6 +2973,435 @@ bool CvCaptureCAM_MSMF::setProperty( int property_id, double value )
     }
     return false;
 }
+
+class CvCaptureFile_MSMF : public CvCapture
+{
+public:
+    CvCaptureFile_MSMF();
+    virtual ~CvCaptureFile_MSMF();
+
+    virtual bool open( const char* filename );
+    virtual void close();
+
+    virtual double getProperty(int);
+    virtual bool setProperty(int, double);
+    virtual bool grabFrame();
+    virtual IplImage* retrieveFrame(int);
+    virtual int getCaptureDomain() { return CV_CAP_MSMF; }
+protected:
+    ImageGrabberThread* grabberThread;
+    IMFMediaSource* videoFileSource;
+    std::vector<MediaType> captureFormats;
+    int captureFormatIndex;
+    IplImage* frame;
+    bool isOpened;
+
+    long enumerateCaptureFormats(IMFMediaSource *pSource);
+    void processPixels(unsigned char * src, unsigned char * dst, unsigned int width,
+                                unsigned int height, unsigned int bpp, bool bRGB, bool bFlip);
+};
+
+CvCaptureFile_MSMF::CvCaptureFile_MSMF():
+    grabberThread(NULL),
+    videoFileSource(NULL),
+    captureFormatIndex(0),
+    frame(NULL),
+    isOpened(false)
+{
+    MFStartup(MF_VERSION);
+}
+
+CvCaptureFile_MSMF::~CvCaptureFile_MSMF()
+{
+    MFShutdown();
+}
+
+bool CvCaptureFile_MSMF::open(const char* filename)
+{
+    if (!filename)
+        return false;
+
+    wchar_t* unicodeFileName = new wchar_t[strlen(filename)+1];
+    MultiByteToWideChar(CP_ACP, 0, filename, -1, unicodeFileName, strlen(filename)+1);
+
+    HRESULT hr = S_OK;
+
+    MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID;
+
+    IMFSourceResolver* pSourceResolver = NULL;
+    IUnknown* pUnkSource = NULL;
+
+    hr = MFCreateSourceResolver(&pSourceResolver);
+
+    if (SUCCEEDED(hr))
+    {
+        hr = pSourceResolver->CreateObjectFromURL(
+            unicodeFileName,
+            MF_RESOLUTION_MEDIASOURCE,
+            NULL, // Optional property store.
+            &ObjectType,
+            &pUnkSource
+            );
+    }
+
+    // Get the IMFMediaSource from the IUnknown pointer.
+    if (SUCCEEDED(hr))
+    {
+        hr = pUnkSource->QueryInterface(IID_PPV_ARGS(&videoFileSource));
+    }
+
+    SafeRelease(&pSourceResolver);
+    SafeRelease(&pUnkSource);
+
+    enumerateCaptureFormats(videoFileSource);
+
+    if (SUCCEEDED(hr))
+    {
+        hr = ImageGrabberThread::CreateInstance(&grabberThread, videoFileSource, -2);
+    }
+
+    if (SUCCEEDED(hr))
+    {
+        grabberThread->start();
+    }
+
+    isOpened = true;
+
+    return true;
+}
+
+void CvCaptureFile_MSMF::close()
+{
+    if (grabberThread)
+    {
+        isOpened = false;
+        SetEvent(grabberThread->getImageGrabber()->ig_hFrameReady);
+        grabberThread->stop();
+        delete grabberThread;
+    }
+
+    if (videoFileSource)
+    {
+        HRESULT hr = videoFileSource->Shutdown();
+        if (FAILED(hr))
+        {
+            printf("VideoCapture Closing failed!\n");
+        }
+    }
+}
+
+bool CvCaptureFile_MSMF::setProperty(int property_id, double value)
+{
+    // image capture properties
+    bool handled = false;
+    int width, height, fourcc;
+    switch( property_id )
+    {
+    case CV_CAP_PROP_FRAME_WIDTH:
+        // width = cvRound(value);
+        // handled = true;
+        break;
+    case CV_CAP_PROP_FRAME_HEIGHT:
+        // height = cvRound(value);
+        // handled = true;
+        break;
+    case CV_CAP_PROP_FOURCC:
+        fourcc = (int)(unsigned long)(value);
+        if ( fourcc == -1 ) {
+            // following cvCreateVideo usage will pop up caprturepindialog here if fourcc=-1
+            // TODO - how to create a capture pin dialog
+        }
+        handled = true;
+        break;
+    case CV_CAP_PROP_FPS:
+        // FIXME: implement method in VideoInput back end
+        // int fps = cvRound(value);
+        // if (fps != VI.getFPS(index))
+        // {
+        //     VI.stopDevice(index);
+        //     VI.setIdealFramerate(index,fps);
+        //     if (widthSet > 0 && heightSet > 0)
+        //         VI.setupDevice(index, widthSet, heightSet);
+        //     else
+        //         VI.setupDevice(index);
+        // }
+        // return VI.isDeviceSetup(index);
+        ;
+    }
+    if ( handled ) {
+        // a stream setting
+        if( width > 0 && height > 0 )
+        {
+            if( width != captureFormats[captureFormatIndex].width ||
+                height != captureFormats[captureFormatIndex].height )//|| fourcc != VI.getFourcc(index) )
+            {
+                // FIXME: implement method in VideoInput back end
+                // int fps = static_cast<int>(VI.getFPS(index));
+                // VI.stopDevice(index);
+                // VI.setIdealFramerate(index, fps);
+                // VI.setupDeviceFourcc(index, width, height, fourcc);
+            }
+            if (isOpened)
+            {
+                // widthSet = width;
+                // heightSet = height;
+                // width = height = fourcc = -1;
+            }
+            return isOpened;
+        }
+        return true;
+    }
+    // show video/camera filter dialog
+    // FIXME: implement method in VideoInput back end
+    // if ( property_id == CV_CAP_PROP_SETTINGS ) {
+    //     VI.showSettingsWindow(index);
+    //     return true;
+    // }
+    //video Filter properties
+    switch( property_id )
+    {
+    case CV_CAP_PROP_BRIGHTNESS:
+    case CV_CAP_PROP_CONTRAST:
+    case CV_CAP_PROP_HUE:
+    case CV_CAP_PROP_SATURATION:
+    case CV_CAP_PROP_SHARPNESS:
+    case CV_CAP_PROP_GAMMA:
+    case CV_CAP_PROP_MONOCROME:
+    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
+    case CV_CAP_PROP_BACKLIGHT:
+    case CV_CAP_PROP_GAIN:
+        // FIXME: implement method in VideoInput back end
+        //return VI.setVideoSettingFilter(index,VI.getVideoPropertyFromCV(property_id),(long)value);
+        ;
+    }
+    //camera properties
+    switch( property_id )
+    {
+    case CV_CAP_PROP_PAN:
+    case CV_CAP_PROP_TILT:
+    case CV_CAP_PROP_ROLL:
+    case CV_CAP_PROP_ZOOM:
+    case CV_CAP_PROP_EXPOSURE:
+    case CV_CAP_PROP_IRIS:
+    case CV_CAP_PROP_FOCUS:
+        // FIXME: implement method in VideoInput back end
+        //return VI.setVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),(long)value);
+        ;
+    }
+
+    return false;
+}
+
+double CvCaptureFile_MSMF::getProperty(int property_id)
+{
+    // image format proprrties
+    switch( property_id )
+    {
+    case CV_CAP_PROP_FRAME_WIDTH:
+        return captureFormats[captureFormatIndex].width;
+    case CV_CAP_PROP_FRAME_HEIGHT:
+        return captureFormats[captureFormatIndex].height;
+    case CV_CAP_PROP_FOURCC:
+        // FIXME: implement method in VideoInput back end
+        //return VI.getFourcc(index);
+        ;
+    case CV_CAP_PROP_FPS:
+        // FIXME: implement method in VideoInput back end
+        //return VI.getFPS(index);
+        ;
+    }
+    // video filter properties
+    switch( property_id )
+    {
+    case CV_CAP_PROP_BRIGHTNESS:
+    case CV_CAP_PROP_CONTRAST:
+    case CV_CAP_PROP_HUE:
+    case CV_CAP_PROP_SATURATION:
+    case CV_CAP_PROP_SHARPNESS:
+    case CV_CAP_PROP_GAMMA:
+    case CV_CAP_PROP_MONOCROME:
+    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
+    case CV_CAP_PROP_BACKLIGHT:
+    case CV_CAP_PROP_GAIN:
+        // FIXME: implement method in VideoInput back end
+        // if ( VI.getVideoSettingFilter(index, VI.getVideoPropertyFromCV(property_id), min_value,
+        //                               max_value, stepping_delta, current_value, flags,defaultValue) )
+        //     return (double)current_value;
+        return 0.;
+    }
+    // camera properties
+    switch( property_id )
+    {
+    case CV_CAP_PROP_PAN:
+    case CV_CAP_PROP_TILT:
+    case CV_CAP_PROP_ROLL:
+    case CV_CAP_PROP_ZOOM:
+    case CV_CAP_PROP_EXPOSURE:
+    case CV_CAP_PROP_IRIS:
+    case CV_CAP_PROP_FOCUS:
+    // FIXME: implement method in VideoInput back end
+    //     if (VI.getVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),min_value,
+    //          max_value,stepping_delta,current_value,flags,defaultValue) ) return (double)current_value;
+        return 0.;
+    }
+    // unknown parameter or value not available
+    return -1;
+}
+
+bool CvCaptureFile_MSMF::grabFrame()
+{
+    DWORD waitResult;
+    if (isOpened)
+    {
+        HANDLE tmp[] = {grabberThread->getImageGrabber()->ig_hFrameReady, grabberThread->getImageGrabber()->ig_hFinish, 0};
+        waitResult = WaitForMultipleObjects(2, tmp, FALSE, INFINITE);
+        SetEvent(grabberThread->getImageGrabber()->ig_hFrameGrabbed);
+    }
+
+    return isOpened && (waitResult == WAIT_OBJECT_0);
+}
+
+IplImage* CvCaptureFile_MSMF::retrieveFrame(int)
+{
+    unsigned int width = captureFormats[captureFormatIndex].width;
+    unsigned int height = captureFormats[captureFormatIndex].height;
+    unsigned int bytes = 3;
+    if( !frame || width != frame->width || height != frame->height )
+    {
+        if (frame)
+            cvReleaseImage( &frame );
+        frame = cvCreateImage( cvSize(width,height), 8, 3 );
+    }
+
+    RawImage *RIOut = grabberThread->getImageGrabber()->getRawImage();
+    unsigned int size = bytes * width * height;
+
+    if(RIOut && size == RIOut->getSize())
+    {
+        processPixels(RIOut->getpPixels(), (unsigned char*)frame->imageData, width, height, bytes, true, false);
+    }
+
+    return frame;
+}
+
+void CvCaptureFile_MSMF::processPixels(unsigned char * src, unsigned char * dst, unsigned int width,
+                                unsigned int height, unsigned int bpp, bool bRGB, bool bFlip)
+{
+    unsigned int widthInBytes = width * bpp;
+    unsigned int numBytes = widthInBytes * height;
+    int *dstInt, *srcInt;
+    if(!bRGB)
+    {
+        if(bFlip)
+        {
+            for(unsigned int y = 0; y < height; y++)
+            {
+                dstInt = (int *)(dst + (y * widthInBytes));
+                srcInt = (int *)(src + ( (height -y -1) * widthInBytes));
+                memcpy(dstInt, srcInt, widthInBytes);
+            }
+        }
+        else
+        {
+            memcpy(dst, src, numBytes);
+        }
+    }
+    else
+    {
+        if(bFlip)
+        {
+            unsigned int x = 0;
+            unsigned int y = (height - 1) * widthInBytes;
+            src += y;
+            for(unsigned int i = 0; i < numBytes; i+=3)
+            {
+                if(x >= width)
+                {
+                    x = 0;
+                    src -= widthInBytes*2;
+                }
+                *dst = *(src+2);
+                dst++;
+                *dst = *(src+1);
+                dst++;
+                *dst = *src;
+                dst++;
+                src+=3;
+                x++;
+            }
+        }
+        else
+        {
+            for(unsigned int i = 0; i < numBytes; i+=3)
+            {
+                *dst = *(src+2);
+                dst++;
+                *dst = *(src+1);
+                dst++;
+                *dst = *src;
+                dst++;
+                src+=3;
+            }
+        }
+    }
+}
+
+long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
+{
+    IMFPresentationDescriptor *pPD = NULL;
+    IMFStreamDescriptor *pSD = NULL;
+    IMFMediaTypeHandler *pHandler = NULL;
+    IMFMediaType *pType = NULL;
+    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    DWORD cnt;
+
+    pPD->GetStreamDescriptorCount(&cnt);
+
+    printf("Stream count: %d\n", cnt);
+
+    BOOL fSelected;
+    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+    hr = pSD->GetMediaTypeHandler(&pHandler);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+    DWORD cTypes = 0;
+    hr = pHandler->GetMediaTypeCount(&cTypes);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+    for (DWORD i = 0; i < cTypes; i++)
+    {
+        hr = pHandler->GetMediaTypeByIndex(i, &pType);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+        MediaType MT = FormatReader::Read(pType);
+        captureFormats.push_back(MT);
+        SafeRelease(&pType);
+    }
+
+done:
+    SafeRelease(&pPD);
+    SafeRelease(&pSD);
+    SafeRelease(&pHandler);
+    SafeRelease(&pType);
+    return hr;
+}
+
+
 CvCapture* cvCreateCameraCapture_MSMF( int index )
 {
     CvCaptureCAM_MSMF* capture = new CvCaptureCAM_MSMF;
@@ -2942,6 +3419,14 @@ CvCapture* cvCreateCameraCapture_MSMF( int index )
     return 0;
 }
 
+CvCapture* cvCreateFileCapture_MSMF (const char* filename)
+{
+    CvCaptureFile_MSMF* capture = new CvCaptureFile_MSMF;
+    if( capture->open(filename) )
+        return capture;
+    delete capture;
+    return 0;
+}
 
 //
 //
diff --git a/modules/highgui/src/precomp.hpp b/modules/highgui/src/precomp.hpp
index b9896955c..dcd4afdc0 100644
--- a/modules/highgui/src/precomp.hpp
+++ b/modules/highgui/src/precomp.hpp
@@ -119,6 +119,7 @@ CvVideoWriter* cvCreateVideoWriter_VFW( const char* filename, int fourcc,
                                         double fps, CvSize frameSize, int is_color );
 CvCapture* cvCreateCameraCapture_DShow( int index );
 CvCapture* cvCreateCameraCapture_MSMF( int index );
+CvCapture* cvCreateFileCapture_MSMF (const char* filename);
 CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc,
                                         double fps, CvSize frameSize, int is_color );
 CvCapture* cvCreateCameraCapture_OpenNI( int index );

From e94cc0b5ee4f1d4d4207ef73aeb65a59b41a0424 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 15 May 2013 05:12:25 -0700
Subject: [PATCH 19/75] Media Foundation camera capture fixed.

Camera-based VideoCapture updated to fit changes in ImageGrabber from prev
commit
---
 modules/highgui/src/cap_msmf.cpp | 68 ++++++++++++++++++++------------
 1 file changed, 43 insertions(+), 25 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index c037d2f98..f5ea616bf 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -180,15 +180,16 @@ public:
     void stopGrabbing();
     RawImage *getRawImage();
     // Function of creation of the instance of the class
-    static HRESULT CreateInstance(ImageGrabber **ppIG,unsigned int deviceID);
+    static HRESULT CreateInstance(ImageGrabber **ppIG, unsigned int deviceID, bool synchronous = false);
 
-    HANDLE ig_hFrameReady;
-    HANDLE ig_hFrameGrabbed;
-    HANDLE ig_hFinish;
+    const HANDLE ig_hFrameReady;
+    const HANDLE ig_hFrameGrabbed;
+    const HANDLE ig_hFinish;
 
 private:
     bool ig_RIE;
     bool ig_Close;
+    bool ig_Synchronous;
     long m_cRef;
     unsigned int ig_DeviceID;
     IMFMediaSource *ig_pSource;
@@ -197,7 +198,7 @@ private:
     RawImage *ig_RIFirst;
     RawImage *ig_RISecond;
     RawImage *ig_RIOut;
-    ImageGrabber(unsigned int deviceID);
+    ImageGrabber(unsigned int deviceID, bool synchronous);
     HRESULT CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo);
     HRESULT AddSourceNode(
     IMFTopology *pTopology,
@@ -229,7 +230,7 @@ class ImageGrabberThread
     friend DWORD WINAPI MainThreadFunction( LPVOID lpParam );
 public:
     ~ImageGrabberThread(void);
-    static HRESULT CreateInstance(ImageGrabberThread **ppIGT, IMFMediaSource *pSource, unsigned int deviceID);
+    static HRESULT CreateInstance(ImageGrabberThread **ppIGT, IMFMediaSource *pSource, unsigned int deviceID, bool synchronious = false);
     void start();
     void stop();
     void setEmergencyStopEvent(void *userData, void(*func)(int, void *));
@@ -237,7 +238,7 @@ public:
 protected:
     virtual void run();
 private:
-    ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID);
+    ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID, bool synchronious);
     HANDLE igt_Handle;
     DWORD   igt_ThreadIdArray;
     ImageGrabber *igt_pImageGrabber;
@@ -854,7 +855,7 @@ FormatReader::~FormatReader(void)
 
 #define CHECK_HR(x) if (FAILED(x)) { printf("Checking failed !!!\n"); goto done; }
 
-ImageGrabber::ImageGrabber(unsigned int deviceID):
+ImageGrabber::ImageGrabber(unsigned int deviceID, bool synchronous):
     m_cRef(1),
     ig_DeviceID(deviceID),
     ig_pSource(NULL),
@@ -862,9 +863,10 @@ ImageGrabber::ImageGrabber(unsigned int deviceID):
     ig_pTopology(NULL),
     ig_RIE(true),
     ig_Close(false),
-    ig_hFrameReady(CreateEvent(NULL, FALSE, FALSE, "ig_hFrameReady")),
-    ig_hFrameGrabbed(CreateEvent(NULL, FALSE, TRUE, "ig_hFrameGrabbed")),
-    ig_hFinish(CreateEvent(NULL, FALSE, FALSE, "ig_hFinish"))
+    ig_Synchronous(synchronous),
+    ig_hFrameReady(synchronous ? CreateEvent(NULL, FALSE, FALSE, "ig_hFrameReady"): 0),
+    ig_hFrameGrabbed(synchronous ?  CreateEvent(NULL, FALSE, TRUE, "ig_hFrameGrabbed"): 0),
+    ig_hFinish(synchronous ?  CreateEvent(NULL, FALSE, FALSE, "ig_hFinish") : 0)
 {}
 
 ImageGrabber::~ImageGrabber(void)
@@ -876,9 +878,12 @@ ImageGrabber::~ImageGrabber(void)
         ig_pSession->Shutdown();
     }
 
-    CloseHandle(ig_hFrameReady);
-    CloseHandle(ig_hFrameGrabbed);
-    CloseHandle(ig_hFinish);
+    if (ig_Synchronous)
+    {
+        CloseHandle(ig_hFrameReady);
+        CloseHandle(ig_hFrameGrabbed);
+        CloseHandle(ig_hFinish);
+    }
 
     SafeRelease(&ig_pSession);
     SafeRelease(&ig_pTopology);
@@ -1056,7 +1061,10 @@ HRESULT ImageGrabber::startGrabbing(void)
         SafeRelease(&pEvent);
     }
 
-    SetEvent(ig_hFinish);
+    if (ig_Synchronous)
+    {
+        SetEvent(ig_hFinish);
+    }
 
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
 
@@ -1172,9 +1180,9 @@ done:
     return hr;
 }
 
-HRESULT ImageGrabber::CreateInstance(ImageGrabber **ppIG, unsigned int deviceID)
+HRESULT ImageGrabber::CreateInstance(ImageGrabber **ppIG, unsigned int deviceID, bool synchronious)
 {
-    *ppIG = new (std::nothrow) ImageGrabber(deviceID);
+    *ppIG = new (std::nothrow) ImageGrabber(deviceID, synchronious);
     if (ppIG == NULL)
     {
         return E_OUTOFMEMORY;
@@ -1286,14 +1294,21 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
 
     printf("ImageGrabber::OnProcessSample() -- end\n");
 
-    SetEvent(ig_hFrameReady);
+    if (ig_Synchronous)
+    {
+        SetEvent(ig_hFrameReady);
+    }
 
     return S_OK;
 }
 
 STDMETHODIMP ImageGrabber::OnShutdown()
 {
-    SetEvent(ig_hFrameGrabbed);
+    if (ig_Synchronous)
+    {
+        SetEvent(ig_hFrameGrabbed);
+    }
+
     return S_OK;
 }
 
@@ -1309,10 +1324,10 @@ DWORD WINAPI MainThreadFunction( LPVOID lpParam )
     return 0;
 }
 
-HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaSource *pSource, unsigned int deviceID)
+HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaSource *pSource, unsigned int deviceID, bool synchronious)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
-    *ppIGT = new (std::nothrow) ImageGrabberThread(pSource, deviceID);
+    *ppIGT = new (std::nothrow) ImageGrabberThread(pSource, deviceID, synchronious);
     if (ppIGT == NULL)
     {
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Memory cannot be allocated\n", deviceID);
@@ -1323,10 +1338,13 @@ HRESULT ImageGrabberThread::CreateInstance(ImageGrabberThread **ppIGT, IMFMediaS
     return S_OK;
 }
 
-ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID): igt_func(NULL), igt_Handle(NULL), igt_stop(false)
+ImageGrabberThread::ImageGrabberThread(IMFMediaSource *pSource, unsigned int deviceID, bool synchronious):
+    igt_func(NULL),
+    igt_Handle(NULL),
+    igt_stop(false)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
-    HRESULT hr = ImageGrabber::CreateInstance(&igt_pImageGrabber, deviceID);
+    HRESULT hr = ImageGrabber::CreateInstance(&igt_pImageGrabber, deviceID, synchronious);
     igt_DeviceID = deviceID;
     if(SUCCEEDED(hr))
     {
@@ -3057,7 +3075,7 @@ bool CvCaptureFile_MSMF::open(const char* filename)
 
     if (SUCCEEDED(hr))
     {
-        hr = ImageGrabberThread::CreateInstance(&grabberThread, videoFileSource, -2);
+        hr = ImageGrabberThread::CreateInstance(&grabberThread, videoFileSource, -2, true);
     }
 
     if (SUCCEEDED(hr))
@@ -3278,7 +3296,7 @@ IplImage* CvCaptureFile_MSMF::retrieveFrame(int)
 
     if(RIOut && size == RIOut->getSize())
     {
-        processPixels(RIOut->getpPixels(), (unsigned char*)frame->imageData, width, height, bytes, true, false);
+        processPixels(RIOut->getpPixels(), (unsigned char*)frame->imageData, width, height, bytes, false, false);
     }
 
     return frame;

From 0c9d776083db4579404e5f1b5cb9b1bee7582881 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 15 May 2013 06:09:03 -0700
Subject: [PATCH 20/75] Media Foundation-based code refactoring.

I* + SafeRelease -> ComPtr.
---
 modules/highgui/src/cap_msmf.cpp | 191 ++++++++++++++-----------------
 1 file changed, 86 insertions(+), 105 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index f5ea616bf..15f2bdcab 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -53,7 +53,7 @@
 #include <Mfapi.h>
 #include <mfplay.h>
 #include <mfobjects.h>
-#include "Strsafe.h"
+#include <strsafe.h>
 #include <wrl/client.h>
 #include <Mfreadwrite.h>
 #include <new>
@@ -72,6 +72,8 @@
 #pragma comment(lib, "Mfreadwrite")
 #pragma comment(lib, "MinCore_Downlevel")
 
+using namespace Microsoft::WRL;
+
 struct IMFMediaType;
 struct IMFActivate;
 struct IMFMediaSource;
@@ -894,12 +896,12 @@ ImageGrabber::~ImageGrabber(void)
 
 HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat)
 {
-    IMFActivate *pSinkActivate = NULL;
-    IMFMediaType *pType = NULL;
-    IMFPresentationDescriptor *pPD = NULL;
-    IMFStreamDescriptor *pSD = NULL;
-    IMFMediaTypeHandler *pHandler = NULL;
-    IMFMediaType *pCurrentType = NULL;
+    ComPtr<IMFActivate> pSinkActivate = NULL;
+    ComPtr<IMFMediaType> pType = NULL;
+    ComPtr<IMFPresentationDescriptor> pPD = NULL;
+    ComPtr<IMFStreamDescriptor> pSD = NULL;
+    ComPtr<IMFMediaTypeHandler> pHandler = NULL;
+    ComPtr<IMFMediaType> pCurrentType = NULL;
     HRESULT hr = S_OK;
     MediaType MT;
      // Clean up.
@@ -940,13 +942,9 @@ HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat
             printf("Error GetCurrentMediaType()\n");
             goto err;
         }
-        MT = FormatReader::Read(pCurrentType);
+        MT = FormatReader::Read(pCurrentType.Get());
     }
 err:
-    SafeRelease(&pPD);
-    SafeRelease(&pSD);
-    SafeRelease(&pHandler);
-    SafeRelease(&pCurrentType);
     unsigned int sizeRawImage = 0;
     if(VideoFormat == MFVideoFormat_RGB24)
     {
@@ -966,17 +964,17 @@ err:
     // Configure the media type that the Sample Grabber will receive.
     // Setting the major and subtype is usually enough for the topology loader
     // to resolve the topology.
-    CHECK_HR(hr = MFCreateMediaType(&pType));
+    CHECK_HR(hr = MFCreateMediaType(pType.GetAddressOf()));
     CHECK_HR(hr = pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));
     CHECK_HR(hr = pType->SetGUID(MF_MT_SUBTYPE, VideoFormat));
     // Create the sample grabber sink.
-    CHECK_HR(hr = MFCreateSampleGrabberSinkActivate(pType, this, &pSinkActivate));
+    CHECK_HR(hr = MFCreateSampleGrabberSinkActivate(pType.Get(), this, pSinkActivate.GetAddressOf()));
     // To run as fast as possible, set this attribute (requires Windows 7):
     CHECK_HR(hr = pSinkActivate->SetUINT32(MF_SAMPLEGRABBERSINK_IGNORE_CLOCK, TRUE));
     // Create the Media Session.
     CHECK_HR(hr = MFCreateMediaSession(NULL, &ig_pSession));
     // Create the topology.
-    CHECK_HR(hr = CreateTopology(pSource, pSinkActivate, &ig_pTopology));
+    CHECK_HR(hr = CreateTopology(pSource, pSinkActivate.Get(), &ig_pTopology));
 done:
     // Clean up.
     if (FAILED(hr))
@@ -988,8 +986,7 @@ done:
         SafeRelease(&ig_pSession);
         SafeRelease(&ig_pTopology);
     }
-    SafeRelease(&pSinkActivate);
-    SafeRelease(&pType);
+
     return hr;
 }
 
@@ -1004,7 +1001,7 @@ void ImageGrabber::stopGrabbing()
 HRESULT ImageGrabber::startGrabbing(void)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
-    IMFMediaEvent *pEvent = NULL;
+    ComPtr<IMFMediaEvent> pEvent = NULL;
     PROPVARIANT var;
     PropVariantInit(&var);
     HRESULT hr = S_OK;
@@ -1058,7 +1055,6 @@ HRESULT ImageGrabber::startGrabbing(void)
             DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: MEVideoCaptureDeviceRemoved \n", ig_DeviceID);
             break;
         }
-        SafeRelease(&pEvent);
     }
 
     if (ig_Synchronous)
@@ -1069,7 +1065,6 @@ HRESULT ImageGrabber::startGrabbing(void)
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
 
 done:
-    SafeRelease(&pEvent);
     SafeRelease(&ig_pSession);
     SafeRelease(&ig_pTopology);
 
@@ -1086,16 +1081,16 @@ void ImageGrabber::resumeGrabbing()
 
 HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo)
 {
-    IMFTopology *pTopology = NULL;
-    IMFPresentationDescriptor *pPD = NULL;
-    IMFStreamDescriptor *pSD = NULL;
-    IMFMediaTypeHandler *pHandler = NULL;
-    IMFTopologyNode *pNode1 = NULL;
-    IMFTopologyNode *pNode2 = NULL;
+    ComPtr<IMFTopology> pTopology = NULL;
+    ComPtr<IMFPresentationDescriptor> pPD = NULL;
+    ComPtr<IMFStreamDescriptor> pSD = NULL;
+    ComPtr<IMFMediaTypeHandler> pHandler = NULL;
+    ComPtr<IMFTopologyNode> pNode1 = NULL;
+    ComPtr<IMFTopologyNode> pNode2 = NULL;
     HRESULT hr = S_OK;
     DWORD cStreams = 0;
-    CHECK_HR(hr = MFCreateTopology(&pTopology));
-    CHECK_HR(hr = pSource->CreatePresentationDescriptor(&pPD));
+    CHECK_HR(hr = MFCreateTopology(pTopology.GetAddressOf()));
+    CHECK_HR(hr = pSource->CreatePresentationDescriptor(pPD.GetAddressOf()));
     CHECK_HR(hr = pPD->GetStreamDescriptorCount(&cStreams));
     for (DWORD i = 0; i < cStreams; i++)
     {
@@ -1107,29 +1102,20 @@ HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSink
         CHECK_HR(hr = pHandler->GetMajorType(&majorType));
         if (majorType == MFMediaType_Video && fSelected)
         {
-            CHECK_HR(hr = AddSourceNode(pTopology, pSource, pPD, pSD, &pNode1));
-            CHECK_HR(hr = AddOutputNode(pTopology, pSinkActivate, 0, &pNode2));
-            CHECK_HR(hr = pNode1->ConnectOutput(0, pNode2, 0));
+            CHECK_HR(hr = AddSourceNode(pTopology.Get(), pSource, pPD.Get(), pSD.Get(), pNode1.GetAddressOf()));
+            CHECK_HR(hr = AddOutputNode(pTopology.Get(), pSinkActivate, 0, pNode2.GetAddressOf()));
+            CHECK_HR(hr = pNode1->ConnectOutput(0, pNode2.Get(), 0));
             break;
         }
         else
         {
             CHECK_HR(hr = pPD->DeselectStream(i));
         }
-        SafeRelease(&pSD);
-        SafeRelease(&pHandler);
     }
-    *ppTopo = pTopology;
+    *ppTopo = pTopology.Get();
     (*ppTopo)->AddRef();
 
 done:
-    SafeRelease(&pTopology);
-    SafeRelease(&pNode1);
-    SafeRelease(&pNode2);
-    SafeRelease(&pPD);
-    SafeRelease(&pSD);
-    SafeRelease(&pHandler);
-
     return hr;
 }
 
@@ -1140,20 +1126,18 @@ HRESULT ImageGrabber::AddSourceNode(
     IMFStreamDescriptor *pSD,         // Stream descriptor.
     IMFTopologyNode **ppNode)         // Receives the node pointer.
 {
-    IMFTopologyNode *pNode = NULL;
+    ComPtr<IMFTopologyNode> pNode = NULL;
     HRESULT hr = S_OK;
-    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &pNode));
+    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, pNode.GetAddressOf()));
     CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_SOURCE, pSource));
     CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, pPD));
     CHECK_HR(hr = pNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, pSD));
-    CHECK_HR(hr = pTopology->AddNode(pNode));
+    CHECK_HR(hr = pTopology->AddNode(pNode.Get()));
     // Return the pointer to the caller.
-    *ppNode = pNode;
+    *ppNode = pNode.Get();
     (*ppNode)->AddRef();
 
 done:
-    SafeRelease(&pNode);
-
     return hr;
 }
 
@@ -1163,20 +1147,18 @@ HRESULT ImageGrabber::AddOutputNode(
     DWORD dwId,                 // Identifier of the stream sink.
     IMFTopologyNode **ppNode)   // Receives the node pointer.
 {
-    IMFTopologyNode *pNode = NULL;
+    ComPtr<IMFTopologyNode> pNode = NULL;
     HRESULT hr = S_OK;
-    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &pNode));
+    CHECK_HR(hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, pNode.GetAddressOf()));
     CHECK_HR(hr = pNode->SetObject(pActivate));
     CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_STREAMID, dwId));
     CHECK_HR(hr = pNode->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE));
-    CHECK_HR(hr = pTopology->AddNode(pNode));
+    CHECK_HR(hr = pTopology->AddNode(pNode.Get()));
     // Return the pointer to the caller.
-    *ppNode = pNode;
+    *ppNode = pNode.Get();
     (*ppNode)->AddRef();
 
 done:
-    SafeRelease(&pNode);
-
     return hr;
 }
 
@@ -1457,9 +1439,9 @@ Media_Foundation::~Media_Foundation(void)
 bool Media_Foundation::buildListOfDevices()
 {
     HRESULT hr = S_OK;
-    IMFAttributes *pAttributes = NULL;
+    ComPtr<IMFAttributes> pAttributes = NULL;
     CoInitialize(NULL);
-    hr = MFCreateAttributes(&pAttributes, 1);
+    hr = MFCreateAttributes(pAttributes.GetAddressOf(), 1);
     if (SUCCEEDED(hr))
     {
         hr = pAttributes->SetGUID(
@@ -1470,14 +1452,14 @@ bool Media_Foundation::buildListOfDevices()
     if (SUCCEEDED(hr))
     {
         videoDevices *vDs = &videoDevices::getInstance();
-        hr = vDs->initDevices(pAttributes);
+        hr = vDs->initDevices(pAttributes.Get());
     }
     else
     {
        DebugPrintOut *DPO = &DebugPrintOut::getInstance();
        DPO->printOut(L"MEDIA FOUNDATION: The access to the video cameras denied\n");
     }
-    SafeRelease(&pAttributes);
+
     return (SUCCEEDED(hr));
 }
 
@@ -1721,14 +1703,15 @@ long videoDevice::checkDevice(IMFAttributes *pAttributes, IMFActivate **pDevice)
     }
     return hr;
 }
+
 long videoDevice::initDevice()
 {
     HRESULT hr = -1;
-    IMFAttributes *pAttributes = NULL;
-    IMFActivate * vd_pActivate= NULL;
+    ComPtr<IMFAttributes> pAttributes = NULL;
+    IMFActivate *vd_pActivate = NULL;
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     CoInitialize(NULL);
-    hr = MFCreateAttributes(&pAttributes, 1);
+    hr = MFCreateAttributes(pAttributes.GetAddressOf(), 1);
     if (SUCCEEDED(hr))
     {
         hr = pAttributes->SetGUID(
@@ -1738,7 +1721,7 @@ long videoDevice::initDevice()
     }
     if (SUCCEEDED(hr))
     {
-        hr = checkDevice(pAttributes, &vd_pActivate);
+        hr = checkDevice(pAttributes.Get(), &vd_pActivate);
         if (SUCCEEDED(hr) && vd_pActivate)
         {
             SafeRelease(&vd_pSource);
@@ -1760,9 +1743,10 @@ long videoDevice::initDevice()
     {
         DPO->printOut(L"VIDEODEVICE %i: The attribute of video cameras cannot be getting \n", vd_CurrentNumber);
     }
-    SafeRelease(&pAttributes);
+
     return hr;
 }
+
 MediaType videoDevice::getFormat(unsigned int id)
 {
     if(id < vd_CurrentFormats.size())
@@ -1887,45 +1871,45 @@ void videoDevice::buildLibraryofTypes()
         count++;
     }
 }
+
 long videoDevice::setDeviceFormat(IMFMediaSource *pSource, unsigned long  dwFormatIndex)
 {
-    IMFPresentationDescriptor *pPD = NULL;
-    IMFStreamDescriptor *pSD = NULL;
-    IMFMediaTypeHandler *pHandler = NULL;
-    IMFMediaType *pType = NULL;
-    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
+    ComPtr<IMFPresentationDescriptor> pPD = NULL;
+    ComPtr<IMFStreamDescriptor> pSD = NULL;
+    ComPtr<IMFMediaTypeHandler> pHandler = NULL;
+    ComPtr<IMFMediaType> pType = NULL;
+    HRESULT hr = pSource->CreatePresentationDescriptor(pPD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
     BOOL fSelected;
-    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
+    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, pSD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
-    hr = pSD->GetMediaTypeHandler(&pHandler);
+    hr = pSD->GetMediaTypeHandler(pHandler.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
-    hr = pHandler->GetMediaTypeByIndex((DWORD)dwFormatIndex, &pType);
+    hr = pHandler->GetMediaTypeByIndex((DWORD)dwFormatIndex, pType.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
-    hr = pHandler->SetCurrentMediaType(pType);
+    hr = pHandler->SetCurrentMediaType(pType.Get());
+
 done:
-    SafeRelease(&pPD);
-    SafeRelease(&pSD);
-    SafeRelease(&pHandler);
-    SafeRelease(&pType);
     return hr;
 }
+
 bool videoDevice::isDeviceSetup()
 {
     return vd_IsSetuped;
 }
+
 RawImage * videoDevice::getRawImageOut()
 {
     if(!vd_IsSetuped) return NULL;
@@ -1938,6 +1922,7 @@ RawImage * videoDevice::getRawImageOut()
     }
     return NULL;
 }
+
 bool videoDevice::isFrameNew()
 {
     if(!vd_IsSetuped) return false;
@@ -1962,16 +1947,19 @@ bool videoDevice::isFrameNew()
     }
     return false;
 }
+
 bool videoDevice::isDeviceMediaSource()
 {
     if(vd_LockOut == MediaSourceLock) return true;
     return false;
 }
+
 bool videoDevice::isDeviceRawDataSource()
 {
     if(vd_LockOut == RawDataLock) return true;
     return false;
 }
+
 bool videoDevice::setupDevice(unsigned int id)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
@@ -2002,15 +1990,18 @@ bool videoDevice::setupDevice(unsigned int id)
         return false;
     }
 }
+
 bool videoDevice::setupDevice(unsigned int w, unsigned int h, unsigned int idealFramerate)
 {
     unsigned int id = findType(w * h, idealFramerate);
     return setupDevice(id);
 }
+
 wchar_t *videoDevice::getName()
 {
     return vd_pFriendlyName;
 }
+
 videoDevice::~videoDevice(void)
 {
     closeDevice();
@@ -2018,24 +2009,25 @@ videoDevice::~videoDevice(void)
     if(vd_pFriendlyName)
         CoTaskMemFree(vd_pFriendlyName);
 }
+
 long videoDevice::enumerateCaptureFormats(IMFMediaSource *pSource)
 {
-    IMFPresentationDescriptor *pPD = NULL;
-    IMFStreamDescriptor *pSD = NULL;
-    IMFMediaTypeHandler *pHandler = NULL;
-    IMFMediaType *pType = NULL;
-    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
+    ComPtr<IMFPresentationDescriptor> pPD = NULL;
+    ComPtr<IMFStreamDescriptor> pSD = NULL;
+    ComPtr<IMFMediaTypeHandler> pHandler = NULL;
+    ComPtr<IMFMediaType> pType = NULL;
+    HRESULT hr = pSource->CreatePresentationDescriptor(pPD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
     BOOL fSelected;
-    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
+    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, pSD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
-    hr = pSD->GetMediaTypeHandler(&pHandler);
+    hr = pSD->GetMediaTypeHandler(pHandler.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
@@ -2048,20 +2040,16 @@ long videoDevice::enumerateCaptureFormats(IMFMediaSource *pSource)
     }
     for (DWORD i = 0; i < cTypes; i++)
     {
-        hr = pHandler->GetMediaTypeByIndex(i, &pType);
+        hr = pHandler->GetMediaTypeByIndex(i, pType.GetAddressOf());
         if (FAILED(hr))
         {
             goto done;
         }
-        MediaType MT = FormatReader::Read(pType);
+        MediaType MT = FormatReader::Read(pType.Get());
         vd_CurrentFormats.push_back(MT);
-        SafeRelease(&pType);
     }
+
 done:
-    SafeRelease(&pPD);
-    SafeRelease(&pSD);
-    SafeRelease(&pHandler);
-    SafeRelease(&pType);
     return hr;
 }
 
@@ -3366,11 +3354,11 @@ void CvCaptureFile_MSMF::processPixels(unsigned char * src, unsigned char * dst,
 
 long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
 {
-    IMFPresentationDescriptor *pPD = NULL;
-    IMFStreamDescriptor *pSD = NULL;
-    IMFMediaTypeHandler *pHandler = NULL;
-    IMFMediaType *pType = NULL;
-    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
+    ComPtr<IMFPresentationDescriptor> pPD = NULL;
+    ComPtr<IMFStreamDescriptor> pSD = NULL;
+    ComPtr<IMFMediaTypeHandler> pHandler = NULL;
+    ComPtr<IMFMediaType> pType = NULL;
+    HRESULT hr = pSource->CreatePresentationDescriptor(pPD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
@@ -3383,12 +3371,12 @@ long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
     printf("Stream count: %d\n", cnt);
 
     BOOL fSelected;
-    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
+    hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, pSD.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
     }
-    hr = pSD->GetMediaTypeHandler(&pHandler);
+    hr = pSD->GetMediaTypeHandler(pHandler.GetAddressOf());
     if (FAILED(hr))
     {
         goto done;
@@ -3401,21 +3389,16 @@ long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
     }
     for (DWORD i = 0; i < cTypes; i++)
     {
-        hr = pHandler->GetMediaTypeByIndex(i, &pType);
+        hr = pHandler->GetMediaTypeByIndex(i, pType.GetAddressOf());
         if (FAILED(hr))
         {
             goto done;
         }
-        MediaType MT = FormatReader::Read(pType);
+        MediaType MT = FormatReader::Read(pType.Get());
         captureFormats.push_back(MT);
-        SafeRelease(&pType);
     }
 
 done:
-    SafeRelease(&pPD);
-    SafeRelease(&pSD);
-    SafeRelease(&pHandler);
-    SafeRelease(&pType);
     return hr;
 }
 
@@ -3452,8 +3435,6 @@ CvCapture* cvCreateFileCapture_MSMF (const char* filename)
 //
 //
 
-using namespace Microsoft::WRL;
-
 class CvVideoWriter_MSMF : public CvVideoWriter
 {
 public:

From 996f02a531318f5aa3004d876fb1b3f2af429e3b Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Sat, 18 May 2013 13:04:31 -0700
Subject: [PATCH 21/75] Multiple Media Foundation video i/o fixes.

Video i/o tests enabled for media foundation;
Negative stride support added to VideoCapture;
Error handling improved, dead lock in case of playback error fixed;
Some code refacotring done.
---
 modules/highgui/src/cap_msmf.cpp       | 178 ++++++++++---------------
 modules/highgui/test/test_precomp.hpp  |   6 +-
 modules/highgui/test/test_video_io.cpp |  38 +++++-
 3 files changed, 112 insertions(+), 110 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 15f2bdcab..814fb75be 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -54,7 +54,6 @@
 #include <mfplay.h>
 #include <mfobjects.h>
 #include <strsafe.h>
-#include <wrl/client.h>
 #include <Mfreadwrite.h>
 #include <new>
 #include <map>
@@ -72,6 +71,8 @@
 #pragma comment(lib, "Mfreadwrite")
 #pragma comment(lib, "MinCore_Downlevel")
 
+// for ComPtr usage
+#include <wrl/client.h>
 using namespace Microsoft::WRL;
 
 struct IMFMediaType;
@@ -112,7 +113,7 @@ struct MediaType
     unsigned int width;
     unsigned int MF_MT_YUV_MATRIX;
     unsigned int MF_MT_VIDEO_LIGHTING;
-    unsigned int MF_MT_DEFAULT_STRIDE;
+    int MF_MT_DEFAULT_STRIDE; // stride is negative if image is bottom-up
     unsigned int MF_MT_VIDEO_CHROMA_SITING;
     GUID MF_MT_AM_FORMAT_TYPE;
     wchar_t *pMF_MT_AM_FORMAT_TYPEName;
@@ -226,6 +227,7 @@ private:
         DWORD dwSampleSize);
     STDMETHODIMP OnShutdown();
 };
+
 /// Class for controlling of thread of the grabbing raw data from video device
 class ImageGrabberThread
 {
@@ -249,6 +251,7 @@ private:
     bool igt_stop;
     unsigned int igt_DeviceID;
 };
+
 // Structure for collecting info about one parametr of current video device
 struct Parametr
 {
@@ -260,6 +263,7 @@ struct Parametr
     long Flag;
     Parametr();
 };
+
 // Structure for collecting info about 17 parametrs of current video device
 struct CamParametrs
 {
@@ -281,11 +285,13 @@ struct CamParametrs
         Parametr Iris;
         Parametr Focus;
 };
+
 typedef std::wstring String;
 typedef std::vector<int> vectorNum;
 typedef std::map<String, vectorNum> SUBTYPEMap;
 typedef std::map<UINT64, SUBTYPEMap> FrameRateMap;
 typedef void(*emergensyStopEventCallback)(int, void *);
+
 /// Class for controlling of video device
 class videoDevice
 {
@@ -329,7 +335,7 @@ private:
     IMFMediaSource *vd_pSource;
     emergensyStopEventCallback vd_func;
     void *vd_userData;
-    long enumerateCaptureFormats(IMFMediaSource *pSource);
+    HRESULT enumerateCaptureFormats(IMFMediaSource *pSource);
     long setDeviceFormat(IMFMediaSource *pSource, unsigned long dwFormatIndex);
     void buildLibraryofTypes();
     int findType(unsigned int size, unsigned int frameRate = 0);
@@ -337,6 +343,7 @@ private:
     long initDevice();
     long checkDevice(IMFAttributes *pAttributes, IMFActivate **pDevice);
 };
+
 /// Class for managing of list of video devices
 class videoDevices
 {
@@ -352,6 +359,7 @@ private:
     std::vector<videoDevice *> vds_Devices;
     videoDevices(void);
 };
+
 // Class for creating of Media Foundation context
 class Media_Foundation
 {
@@ -362,6 +370,7 @@ public:
 private:
     Media_Foundation(void);
 };
+
 /// The only visiable class for controlling of video devices in format singelton
 class videoInput
 {
@@ -411,23 +420,27 @@ public:
     bool isFrameNew(int deviceID);
     // Writing of Raw Data pixels from video device with deviceID with correction of RedAndBlue flipping flipRedAndBlue and vertical flipping flipImage
     bool getPixels(int deviceID, unsigned char * pixels, bool flipRedAndBlue = false, bool flipImage = false);
+    static void processPixels(unsigned char * src, unsigned char * dst, unsigned int width, unsigned int height, unsigned int bpp, bool bRGB, bool bFlip);
 private:
     bool accessToDevices;
     videoInput(void);
-    void processPixels(unsigned char * src, unsigned char * dst, unsigned int width, unsigned int height, unsigned int bpp, bool bRGB, bool bFlip);
     void updateListOfDevices();
 };
+
 DebugPrintOut::DebugPrintOut(void):verbose(true)
 {
 }
+
 DebugPrintOut::~DebugPrintOut(void)
 {
 }
+
 DebugPrintOut& DebugPrintOut::getInstance()
 {
     static DebugPrintOut instance;
     return instance;
 }
+
 void DebugPrintOut::printOut(const wchar_t *format, ...)
 {
     if(verbose)
@@ -448,14 +461,17 @@ void DebugPrintOut::printOut(const wchar_t *format, ...)
         va_end (args);
     }
 }
+
 void DebugPrintOut::setVerbose(bool state)
 {
     verbose = state;
 }
+
 LPCWSTR GetGUIDNameConstNew(const GUID& guid);
 HRESULT GetGUIDNameNew(const GUID& guid, WCHAR **ppwsz);
 HRESULT LogAttributeValueByIndexNew(IMFAttributes *pAttr, DWORD index);
 HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, MediaType &out);
+
 unsigned int *GetParametr(GUID guid, MediaType &out)
 {
     if(guid == MF_MT_YUV_MATRIX)
@@ -463,7 +479,7 @@ unsigned int *GetParametr(GUID guid, MediaType &out)
     if(guid == MF_MT_VIDEO_LIGHTING)
         return &(out.MF_MT_VIDEO_LIGHTING);
     if(guid == MF_MT_DEFAULT_STRIDE)
-        return &(out.MF_MT_DEFAULT_STRIDE);
+        return (unsigned int*)&(out.MF_MT_DEFAULT_STRIDE);
     if(guid == MF_MT_VIDEO_CHROMA_SITING)
         return &(out.MF_MT_VIDEO_CHROMA_SITING);
     if(guid == MF_MT_VIDEO_NOMINAL_RANGE)
@@ -480,6 +496,7 @@ unsigned int *GetParametr(GUID guid, MediaType &out)
         return &(out.MF_MT_INTERLACE_MODE);
     return NULL;
 }
+
 HRESULT LogAttributeValueByIndexNew(IMFAttributes *pAttr, DWORD index, MediaType &out)
 {
     WCHAR *pGuidName = NULL;
@@ -566,6 +583,7 @@ done:
     PropVariantClear(&var);
     return hr;
 }
+
 HRESULT GetGUIDNameNew(const GUID& guid, WCHAR **ppwsz)
 {
     HRESULT hr = S_OK;
@@ -625,6 +643,10 @@ HRESULT LogVideoAreaNew(const PROPVARIANT& var)
 }
 HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, MediaType &out)
 {
+    if (guid == MF_MT_DEFAULT_STRIDE)
+    {
+        out.MF_MT_DEFAULT_STRIDE = var.intVal;
+    } else
     if (guid == MF_MT_FRAME_SIZE)
     {
         UINT32 uHigh = 0, uLow = 0;
@@ -1039,6 +1061,7 @@ HRESULT ImageGrabber::startGrabbing(void)
             hr = S_OK;
             goto done;
         }
+        printf("media foundation event: %d\n", met);
         if (met == MESessionEnded)
         {
             DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: MESessionEnded \n", ig_DeviceID);
@@ -1055,16 +1078,21 @@ HRESULT ImageGrabber::startGrabbing(void)
             DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: MEVideoCaptureDeviceRemoved \n", ig_DeviceID);
             break;
         }
+        if ((met == MEError) || (met == MENonFatalError))
+        {
+            pEvent->GetStatus(&hrStatus);
+            DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: MEError | MENonFatalError: %u\n", ig_DeviceID, hrStatus);
+            break;
+        }
     }
+    DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
 
+done:
     if (ig_Synchronous)
     {
         SetEvent(ig_hFinish);
     }
 
-    DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
-
-done:
     SafeRelease(&ig_pSession);
     SafeRelease(&ig_pTopology);
 
@@ -2010,7 +2038,7 @@ videoDevice::~videoDevice(void)
         CoTaskMemFree(vd_pFriendlyName);
 }
 
-long videoDevice::enumerateCaptureFormats(IMFMediaSource *pSource)
+HRESULT videoDevice::enumerateCaptureFormats(IMFMediaSource *pSource)
 {
     ComPtr<IMFPresentationDescriptor> pPD = NULL;
     ComPtr<IMFStreamDescriptor> pSD = NULL;
@@ -3002,9 +3030,7 @@ protected:
     IplImage* frame;
     bool isOpened;
 
-    long enumerateCaptureFormats(IMFMediaSource *pSource);
-    void processPixels(unsigned char * src, unsigned char * dst, unsigned int width,
-                                unsigned int height, unsigned int bpp, bool bRGB, bool bFlip);
+    HRESULT enumerateCaptureFormats(IMFMediaSource *pSource);
 };
 
 CvCaptureFile_MSMF::CvCaptureFile_MSMF():
@@ -3034,10 +3060,10 @@ bool CvCaptureFile_MSMF::open(const char* filename)
 
     MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID;
 
-    IMFSourceResolver* pSourceResolver = NULL;
+    ComPtr<IMFSourceResolver> pSourceResolver = NULL;
     IUnknown* pUnkSource = NULL;
 
-    hr = MFCreateSourceResolver(&pSourceResolver);
+    hr = MFCreateSourceResolver(pSourceResolver.GetAddressOf());
 
     if (SUCCEEDED(hr))
     {
@@ -3056,10 +3082,12 @@ bool CvCaptureFile_MSMF::open(const char* filename)
         hr = pUnkSource->QueryInterface(IID_PPV_ARGS(&videoFileSource));
     }
 
-    SafeRelease(&pSourceResolver);
     SafeRelease(&pUnkSource);
 
-    enumerateCaptureFormats(videoFileSource);
+    if (SUCCEEDED(hr))
+    {
+        hr = enumerateCaptureFormats(videoFileSource);
+    }
 
     if (SUCCEEDED(hr))
     {
@@ -3071,9 +3099,9 @@ bool CvCaptureFile_MSMF::open(const char* filename)
         grabberThread->start();
     }
 
-    isOpened = true;
+    isOpened = SUCCEEDED(hr);
 
-    return true;
+    return isOpened;
 }
 
 void CvCaptureFile_MSMF::close()
@@ -3207,6 +3235,8 @@ double CvCaptureFile_MSMF::getProperty(int property_id)
         return captureFormats[captureFormatIndex].width;
     case CV_CAP_PROP_FRAME_HEIGHT:
         return captureFormats[captureFormatIndex].height;
+    case CV_CAP_PROP_FRAME_COUNT:
+        return 30;
     case CV_CAP_PROP_FOURCC:
         // FIXME: implement method in VideoInput back end
         //return VI.getFourcc(index);
@@ -3282,77 +3312,18 @@ IplImage* CvCaptureFile_MSMF::retrieveFrame(int)
     RawImage *RIOut = grabberThread->getImageGrabber()->getRawImage();
     unsigned int size = bytes * width * height;
 
+    bool verticalFlip = captureFormats[captureFormatIndex].MF_MT_DEFAULT_STRIDE < 0;
+
     if(RIOut && size == RIOut->getSize())
     {
-        processPixels(RIOut->getpPixels(), (unsigned char*)frame->imageData, width, height, bytes, false, false);
+         videoInput::processPixels(RIOut->getpPixels(), (unsigned char*)frame->imageData, width, 
+             height, bytes, false, verticalFlip);
     }
 
     return frame;
 }
 
-void CvCaptureFile_MSMF::processPixels(unsigned char * src, unsigned char * dst, unsigned int width,
-                                unsigned int height, unsigned int bpp, bool bRGB, bool bFlip)
-{
-    unsigned int widthInBytes = width * bpp;
-    unsigned int numBytes = widthInBytes * height;
-    int *dstInt, *srcInt;
-    if(!bRGB)
-    {
-        if(bFlip)
-        {
-            for(unsigned int y = 0; y < height; y++)
-            {
-                dstInt = (int *)(dst + (y * widthInBytes));
-                srcInt = (int *)(src + ( (height -y -1) * widthInBytes));
-                memcpy(dstInt, srcInt, widthInBytes);
-            }
-        }
-        else
-        {
-            memcpy(dst, src, numBytes);
-        }
-    }
-    else
-    {
-        if(bFlip)
-        {
-            unsigned int x = 0;
-            unsigned int y = (height - 1) * widthInBytes;
-            src += y;
-            for(unsigned int i = 0; i < numBytes; i+=3)
-            {
-                if(x >= width)
-                {
-                    x = 0;
-                    src -= widthInBytes*2;
-                }
-                *dst = *(src+2);
-                dst++;
-                *dst = *(src+1);
-                dst++;
-                *dst = *src;
-                dst++;
-                src+=3;
-                x++;
-            }
-        }
-        else
-        {
-            for(unsigned int i = 0; i < numBytes; i+=3)
-            {
-                *dst = *(src+2);
-                dst++;
-                *dst = *(src+1);
-                dst++;
-                *dst = *src;
-                dst++;
-                src+=3;
-            }
-        }
-    }
-}
-
-long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
+HRESULT CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
 {
     ComPtr<IMFPresentationDescriptor> pPD = NULL;
     ComPtr<IMFStreamDescriptor> pSD = NULL;
@@ -3364,12 +3335,6 @@ long CvCaptureFile_MSMF::enumerateCaptureFormats(IMFMediaSource *pSource)
         goto done;
     }
 
-    DWORD cnt;
-
-    pPD->GetStreamDescriptorCount(&cnt);
-
-    printf("Stream count: %d\n", cnt);
-
     BOOL fSelected;
     hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, pSD.GetAddressOf());
     if (FAILED(hr))
@@ -3423,10 +3388,21 @@ CvCapture* cvCreateCameraCapture_MSMF( int index )
 CvCapture* cvCreateFileCapture_MSMF (const char* filename)
 {
     CvCaptureFile_MSMF* capture = new CvCaptureFile_MSMF;
-    if( capture->open(filename) )
-        return capture;
-    delete capture;
-    return 0;
+    try
+    {
+        if( capture->open(filename) )
+            return capture;
+        else
+        {
+            delete capture;
+            return NULL;
+        }
+    }
+    catch(...)
+    {
+        delete capture;
+        throw;
+    }
 }
 
 //
@@ -3440,10 +3416,10 @@ class CvVideoWriter_MSMF : public CvVideoWriter
 public:
     CvVideoWriter_MSMF();
     virtual ~CvVideoWriter_MSMF();
-    virtual bool open( const char* filename, int fourcc,
-                       double fps, CvSize frameSize, bool isColor );
+    virtual bool open(const char* filename, int fourcc,
+                       double fps, CvSize frameSize, bool isColor);
     virtual void close();
-    virtual bool writeFrame( const IplImage* img);
+    virtual bool writeFrame(const IplImage* img);
 
 private:
     UINT32 videoWidth;
@@ -3533,7 +3509,7 @@ bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
     videoWidth = frameSize.width;
     videoHeight = frameSize.height;
     fps = _fps;
-    bitRate = videoWidth*videoHeight; // 1-bit per pixel
+    bitRate = fps*videoWidth*videoHeight; // 1-bit per pixel
     encodingFormat = FourCC2GUID(fourcc);
     inputFormat = MFVideoFormat_RGB32;
 
@@ -3596,14 +3572,7 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
             BYTE g = rowStart[colIdx * img->nChannels + 1];
             BYTE r = rowStart[colIdx * img->nChannels + 2];
 
-            // On ARM devices data is stored starting from the last line
-            // (and not the first line) so you have to revert them on the Y axis
-#if _M_ARM
-            int targetRow = videoHeight - rowIdx - 1;
-            target[(targetRow * videoWidth) + colIdx] = (r << 16) + (g << 8) + b;
-#else
             target[rowIdx*img->width+colIdx] = (r << 16) + (g << 8) + b;
-#endif
         }
     }
 
@@ -3677,6 +3646,7 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     {
         hr = MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
     }
+
     if (SUCCEEDED(hr))
     {
         hr = sinkWriter->AddStream(mediaTypeOut.Get(), &streamIndex);
@@ -3711,7 +3681,7 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     {
         hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
     }
-    if (SUCCEEDED(hr))
+        if (SUCCEEDED(hr))
     {
         hr = sinkWriter->SetInputMediaType(streamIndex, mediaTypeIn.Get(), NULL);
     }
diff --git a/modules/highgui/test/test_precomp.hpp b/modules/highgui/test/test_precomp.hpp
index 0d0bd8022..be06c0643 100644
--- a/modules/highgui/test/test_precomp.hpp
+++ b/modules/highgui/test/test_precomp.hpp
@@ -47,7 +47,8 @@
     defined(HAVE_QUICKTIME)    || \
     defined(HAVE_AVFOUNDATION) || \
     /*defined(HAVE_OPENNI)     || too specialized */ \
-    defined(HAVE_FFMPEG)
+    defined(HAVE_FFMPEG)       || \
+    defined(HAVE_MSMF)
 #  define BUILD_WITH_VIDEO_INPUT_SUPPORT 1
 #else
 #  define BUILD_WITH_VIDEO_INPUT_SUPPORT 0
@@ -57,7 +58,8 @@
     defined(HAVE_GSTREAMER)    || \
     defined(HAVE_QUICKTIME)    || \
     defined(HAVE_AVFOUNDATION) || \
-    defined(HAVE_FFMPEG)
+    defined(HAVE_FFMPEG)       || \
+    defined(HAVE_MSMF)
 #  define BUILD_WITH_VIDEO_OUTPUT_SUPPORT 1
 #else
 #  define BUILD_WITH_VIDEO_OUTPUT_SUPPORT 0
diff --git a/modules/highgui/test/test_video_io.cpp b/modules/highgui/test/test_video_io.cpp
index b0c2e53ba..34ec0bdd8 100644
--- a/modules/highgui/test/test_video_io.cpp
+++ b/modules/highgui/test/test_video_io.cpp
@@ -54,6 +54,33 @@ string fourccToString(int fourcc)
     return format("%c%c%c%c", fourcc & 255, (fourcc >> 8) & 255, (fourcc >> 16) & 255, (fourcc >> 24) & 255);
 }
 
+#ifdef HAVE_MSMF
+const VideoFormat g_specific_fmt_list[] =
+{
+/*        VideoFormat("avi", 'dv25'),
+        VideoFormat("avi", 'dv50'),
+        VideoFormat("avi", 'dvc '),
+        VideoFormat("avi", 'dvh1'),
+        VideoFormat("avi", 'dvhd'),
+        VideoFormat("avi", 'dvsd'),
+        VideoFormat("avi", 'dvsl'),
+        VideoFormat("avi", 'M4S2'), */
+        VideoFormat("wmv", 'WMV3'),
+        // VideoFormat("avi", 'H264'),
+        // VideoFormat("avi", 'MJPG'),
+        // VideoFormat("avi", 'MP43'),
+        // VideoFormat("avi", 'MP4S'),
+        // VideoFormat("avi", 'MP4V'),
+/*        VideoFormat("avi", 'MPG1'),
+        VideoFormat("avi", 'MSS1'),
+        VideoFormat("avi", 'MSS2'),
+        VideoFormat("avi", 'WMV1'),
+        VideoFormat("avi", 'WMV2'),
+        VideoFormat("avi", 'WMV3'),
+        VideoFormat("avi", 'WVC1'), */
+        VideoFormat()
+};
+#else
 const VideoFormat g_specific_fmt_list[] =
 {
     VideoFormat("avi", CV_FOURCC('X', 'V', 'I', 'D')),
@@ -63,17 +90,17 @@ const VideoFormat g_specific_fmt_list[] =
     VideoFormat("mkv", CV_FOURCC('X', 'V', 'I', 'D')),
     VideoFormat("mkv", CV_FOURCC('M', 'P', 'E', 'G')),
     VideoFormat("mkv", CV_FOURCC('M', 'J', 'P', 'G')),
-
     VideoFormat("mov", CV_FOURCC('m', 'p', '4', 'v')),
     VideoFormat()
 };
+#endif
 
 }
 
 class CV_HighGuiTest : public cvtest::BaseTest
 {
 protected:
-    void ImageTest(const string& dir);
+    void ImageTest (const string& dir);
     void VideoTest (const string& dir, const cvtest::VideoFormat& fmt);
     void SpecificImageTest (const string& dir);
     void SpecificVideoTest (const string& dir, const cvtest::VideoFormat& fmt);
@@ -291,8 +318,11 @@ void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt
         if (psnr < thresDbell)
         {
             printf("Too low psnr = %gdb\n", psnr);
-            // imwrite("img.png", img);
-            // imwrite("img1.png", img1);
+            //imwrite("original.png", img);
+            //imwrite("after_test.png", img1);
+            //Mat diff;
+            //absdiff(img, img1, diff);
+            //imwrite("diff.png", diff);
             ts->set_failed_test_info(ts->FAIL_MISMATCH);
             break;
         }

From bb9a0b725341d939ba08808e495b836d3ba41834 Mon Sep 17 00:00:00 2001
From: Alexander Shishkov <shishkov.alexander@gmail.com>
Date: Mon, 24 Jun 2013 14:52:17 +0400
Subject: [PATCH 22/75] Update Info.plist.in

---
 platforms/ios/Info.plist.in | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/platforms/ios/Info.plist.in b/platforms/ios/Info.plist.in
index 012de8856..6bcfe862d 100644
--- a/platforms/ios/Info.plist.in
+++ b/platforms/ios/Info.plist.in
@@ -5,7 +5,7 @@
     <key>CFBundleName</key>
     <string>OpenCV</string>
     <key>CFBundleIdentifier</key>
-    <string>opencv.org</string>
+    <string>org.opencv</string>
     <key>CFBundleVersion</key>
     <string>${VERSION}</string>
     <key>CFBundleShortVersionString</key>

From 6db776f957253d1e484bba8b05afd5a9a8f415a1 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Tue, 25 Jun 2013 14:11:28 +0800
Subject: [PATCH 23/75] add "-c" for cpu ocl mode in perf tests

---
 modules/ocl/perf/main.cpp | 61 ++++++++++++++++++++-------------------
 1 file changed, 32 insertions(+), 29 deletions(-)

diff --git a/modules/ocl/perf/main.cpp b/modules/ocl/perf/main.cpp
index dfcac20bc..bd2a4ec4b 100644
--- a/modules/ocl/perf/main.cpp
+++ b/modules/ocl/perf/main.cpp
@@ -44,43 +44,21 @@
 
 int main(int argc, const char *argv[])
 {
-    vector<ocl::Info> oclinfo;
-    int num_devices = getDevice(oclinfo);
-
-    if (num_devices < 1)
-    {
-        cerr << "no device found\n";
-        return -1;
-    }
-    // set this to overwrite binary cache every time the test starts
-    ocl::setBinaryDiskCache(ocl::CACHE_UPDATE);
-
-    int devidx = 0;
-
-    for (size_t i = 0; i < oclinfo.size(); i++)
-    {
-        for (size_t j = 0; j < oclinfo[i].DeviceName.size(); j++)
-        {
-            printf("device %d: %s\n", devidx++, oclinfo[i].DeviceName[j].c_str());
-        }
-    }
-
-    redirectError(cvErrorCallback);
-
     const char *keys =
         "{ h | help    | false | print help message }"
         "{ f | filter  |       | filter for test }"
         "{ w | workdir |       | set working directory }"
         "{ l | list    | false | show all tests }"
         "{ d | device  | 0     | device id }"
+        "{ c | cpu_ocl | false | use cpu as ocl device}"
         "{ i | iters   | 10    | iteration count }"
         "{ m | warmup  | 1     | gpu warm up iteration count}"
-        "{ t | xtop    | 1.1	  | xfactor top boundary}"
-        "{ b | xbottom | 0.9	  | xfactor bottom boundary}"
+        "{ t | xtop    | 1.1   | xfactor top boundary}"
+        "{ b | xbottom | 0.9   | xfactor bottom boundary}"
         "{ v | verify  | false | only run gpu once to verify if problems occur}";
 
+    redirectError(cvErrorCallback);
     CommandLineParser cmd(argc, argv, keys);
-
     if (cmd.get<bool>("help"))
     {
         cout << "Avaible options:" << endl;
@@ -88,14 +66,40 @@ int main(int argc, const char *argv[])
         return 0;
     }
 
-    int device = cmd.get<int>("device");
+    // get ocl devices
+    bool use_cpu = cmd.get<bool>("c");
+    vector<ocl::Info> oclinfo;
+    int num_devices = 0;
+    if(use_cpu)
+        num_devices = getDevice(oclinfo, ocl::CVCL_DEVICE_TYPE_CPU);
+    else
+        num_devices = getDevice(oclinfo);
+    if (num_devices < 1)
+    {
+        cerr << "no device found\n";
+        return -1;
+    }
 
+    // show device info
+    int devidx = 0;
+    for (size_t i = 0; i < oclinfo.size(); i++)
+    {
+        for (size_t j = 0; j < oclinfo[i].DeviceName.size(); j++)
+        {
+            cout << "device " << devidx++ << ": " << oclinfo[i].DeviceName[j] << endl;
+        }
+    }
+
+    int device = cmd.get<int>("device");
     if (device < 0 || device >= num_devices)
     {
         cerr << "Invalid device ID" << endl;
         return -1;
     }
 
+    // set this to overwrite binary cache every time the test starts
+    ocl::setBinaryDiskCache(ocl::CACHE_UPDATE);
+    
     if (cmd.get<bool>("verify"))
     {
         TestSystem::instance().setNumIters(1);
@@ -104,7 +108,6 @@ int main(int argc, const char *argv[])
     }
 
     devidx = 0;
-
     for (size_t i = 0; i < oclinfo.size(); i++)
     {
         for (size_t j = 0; j < oclinfo[i].DeviceName.size(); j++, devidx++)
@@ -113,7 +116,7 @@ int main(int argc, const char *argv[])
             {
                 ocl::setDevice(oclinfo[i], (int)j);
                 TestSystem::instance().setRecordName(oclinfo[i].DeviceName[j]);
-                printf("\nuse %d: %s\n", devidx, oclinfo[i].DeviceName[j].c_str());
+                cout << "use " << devidx << ": " <<oclinfo[i].DeviceName[j] << endl;
                 goto END_DEV;
             }
         }

From dbdeff2069ee4cbaadd7f20f8f13024ac8e77179 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Tue, 25 Jun 2013 14:12:02 +0800
Subject: [PATCH 24/75] fix stereobm crash on some cpu ocl

---
 modules/ocl/src/opencl/stereobm.cl | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/modules/ocl/src/opencl/stereobm.cl b/modules/ocl/src/opencl/stereobm.cl
index bd86a7f3f..552874d42 100644
--- a/modules/ocl/src/opencl/stereobm.cl
+++ b/modules/ocl/src/opencl/stereobm.cl
@@ -162,8 +162,8 @@ __kernel void stereoKernel(__global unsigned char *left, __global unsigned char
     int y_tex;
     int x_tex = X - radius;
 
-    if (x_tex >= cwidth)
-        return;
+    //if (x_tex >= cwidth)
+    //    return;
 
     for(int d = STEREO_MIND; d < maxdisp; d += STEREO_DISP_STEP)
     {

From 1227e00f3d03daed6a96ff52c32e3051b5114782 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Tue, 25 Jun 2013 16:26:33 +0800
Subject: [PATCH 25/75] fix moments

---
 modules/ocl/src/moments.cpp       |  43 ++-
 modules/ocl/src/opencl/moments.cl | 536 +++++++++++++++---------------
 modules/ocl/test/test_moments.cpp |   8 +-
 3 files changed, 290 insertions(+), 297 deletions(-)

diff --git a/modules/ocl/src/moments.cpp b/modules/ocl/src/moments.cpp
index d6baba207..cb16fb136 100644
--- a/modules/ocl/src/moments.cpp
+++ b/modules/ocl/src/moments.cpp
@@ -16,7 +16,7 @@
 // Third party copyrights are property of their respective owners.
 //
 // @Authors
-//    Sen Liu, sen@multicorewareinc.com
+//    Sen Liu, swjtuls1987@126.com
 //
 // Redistribution and use in source and binary forms, with or without modification,
 // are permitted provided that the following conditions are met:
@@ -277,8 +277,8 @@ static void ocl_cvMoments( const void* array, CvMoments* mom, int binary )
         blocky = size.height/TILE_SIZE;
     else
         blocky = size.height/TILE_SIZE + 1;
-    cv::ocl::oclMat dst_m(blocky * 10, blockx, CV_64FC1);
-    cl_mem sum = openCLCreateBuffer(src.clCxt,CL_MEM_READ_WRITE,10*sizeof(double));
+    oclMat dst_m(blocky * 10, blockx, CV_64FC1);
+    oclMat sum(1, 10, CV_64FC1);
     int tile_width  = std::min(size.width,TILE_SIZE);
     int tile_height = std::min(size.height,TILE_SIZE);
     size_t localThreads[3]  = { tile_height, 1, 1};
@@ -288,19 +288,16 @@ static void ocl_cvMoments( const void* array, CvMoments* mom, int binary )
     args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
-    args.push_back( make_pair( sizeof(cl_int) , (void *)&tileSize.width ));
-    args.push_back( make_pair( sizeof(cl_int) , (void *)&tileSize.height ));
     args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.cols ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&blocky ));
-    args.push_back( make_pair( sizeof(cl_int) , (void *)&type ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&depth ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&cn ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&coi ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&binary ));
     args.push_back( make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
-    openCLExecuteKernel(dst_m.clCxt, &moments, "CvMoments", globalThreads, localThreads, args, -1, depth);
+    openCLExecuteKernel(Context::getContext(), &moments, "CvMoments", globalThreads, localThreads, args, -1, depth);
 
     size_t localThreadss[3]  = { 128, 1, 1};
     size_t globalThreadss[3] = { 128, 1, 1};
@@ -309,25 +306,23 @@ static void ocl_cvMoments( const void* array, CvMoments* mom, int binary )
     args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&tile_height ));
     args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&tile_width ));
     args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
-    args_sum.push_back( make_pair( sizeof(cl_mem) , (void *)&sum ));
+    args_sum.push_back( make_pair( sizeof(cl_mem) , (void *)&sum.data ));
     args_sum.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
     args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
-    openCLExecuteKernel(dst_m.clCxt, &moments, "dst_sum", globalThreadss, localThreadss, args_sum, -1, -1);
-    double* dstsum = new double[10];
-    memset(dstsum,0,10*sizeof(double));
-    openCLReadBuffer(dst_m.clCxt,sum,(void *)dstsum,10*sizeof(double));
-    mom->m00 = dstsum[0];
-    mom->m10 = dstsum[1];
-    mom->m01 = dstsum[2];
-    mom->m20 = dstsum[3];
-    mom->m11 = dstsum[4];
-    mom->m02 = dstsum[5];
-    mom->m30 = dstsum[6];
-    mom->m21 = dstsum[7];
-    mom->m12 = dstsum[8];
-    mom->m03 = dstsum[9];
-    delete [] dstsum;
-    openCLSafeCall(clReleaseMemObject(sum));
+    openCLExecuteKernel(Context::getContext(), &moments, "dst_sum", globalThreadss, localThreadss, args_sum, -1, -1);
+
+    Mat dstsum(sum);
+    mom->m00 = dstsum.at<double>(0, 0);
+    mom->m10 = dstsum.at<double>(0, 1);
+    mom->m01 = dstsum.at<double>(0, 2);
+    mom->m20 = dstsum.at<double>(0, 3);
+    mom->m11 = dstsum.at<double>(0, 4);
+    mom->m02 = dstsum.at<double>(0, 5);
+    mom->m30 = dstsum.at<double>(0, 6);
+    mom->m21 = dstsum.at<double>(0, 7);
+    mom->m12 = dstsum.at<double>(0, 8);
+    mom->m03 = dstsum.at<double>(0, 9);
+
     icvCompleteMomentState( mom );
 }
 
diff --git a/modules/ocl/src/opencl/moments.cl b/modules/ocl/src/opencl/moments.cl
index 2378f4f84..71313017a 100644
--- a/modules/ocl/src/opencl/moments.cl
+++ b/modules/ocl/src/opencl/moments.cl
@@ -173,10 +173,10 @@ __kernel void dst_sum(int src_rows, int src_cols, int tile_height, int tile_widt
             sum[i] = dst_sum[i][0];
 }
 
-__kernel void CvMoments_D0(__global uchar16* src_data, int src_rows, int src_cols, int src_step, int tileSize_width, int tileSize_height,
+__kernel void CvMoments_D0(__global uchar16* src_data, int src_rows, int src_cols, int src_step,
                            __global F* dst_m,
                            int dst_cols, int dst_step, int blocky,
-                           int type, int depth, int cn, int coi, int binary, int TILE_SIZE)
+                           int depth, int cn, int coi, int binary, int TILE_SIZE)
 {
     uchar tmp_coi[16]; // get the coi data
     uchar16 tmp[16];
@@ -192,35 +192,43 @@ __kernel void CvMoments_D0(__global uchar16* src_data, int src_rows, int src_col
     int x = wgidx*TILE_SIZE;  // vector length of uchar
     int kcn = (cn==2)?2:4;
     int rstep = min(src_step, TILE_SIZE);
-    tileSize_height = min(TILE_SIZE, src_rows - y);
-    tileSize_width = min(TILE_SIZE, src_cols - x);
+    int tileSize_height = min(TILE_SIZE, src_rows - y);
+    int tileSize_width = min(TILE_SIZE, src_cols - x);
+
+    if ( y+lidy < src_rows )
+    {
+        if( tileSize_width < TILE_SIZE )
+            for(int i = tileSize_width; i < rstep && (x+i) < src_cols; i++ )
+                *((__global uchar*)src_data+(y+lidy)*src_step+x+i) = 0;
+
+        if( coi > 0 )	//channel of interest
+            for(int i = 0; i < tileSize_width; i += VLEN_C)
+            {
+                for(int j=0; j<VLEN_C; j++)
+                    tmp_coi[j] = *((__global uchar*)src_data+(y+lidy)*src_step+(x+i+j)*kcn+coi-1);
+                tmp[i/VLEN_C] = (uchar16)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7],
+                                          tmp_coi[8],tmp_coi[9],tmp_coi[10],tmp_coi[11],tmp_coi[12],tmp_coi[13],tmp_coi[14],tmp_coi[15]);
+            }
+        else
+            for(int i=0; i < tileSize_width; i+=VLEN_C)
+                tmp[i/VLEN_C] = *(src_data+(y+lidy)*src_step/VLEN_C+(x+i)/VLEN_C);
+    }
 
-    if( tileSize_width < TILE_SIZE )
-        for(int i = tileSize_width; i < rstep; i++ )
-            *((__global uchar*)src_data+(y+lidy)*src_step+x+i) = 0;
-    if( coi > 0 )	//channel of interest
-        for(int i = 0; i < tileSize_width; i += VLEN_C)
-        {
-            for(int j=0; j<VLEN_C; j++)
-                tmp_coi[j] = *((__global uchar*)src_data+(y+lidy)*src_step+(x+i+j)*kcn+coi-1);
-            tmp[i/VLEN_C] = (uchar16)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7],
-                                      tmp_coi[8],tmp_coi[9],tmp_coi[10],tmp_coi[11],tmp_coi[12],tmp_coi[13],tmp_coi[14],tmp_coi[15]);
-        }
-    else
-        for(int i=0; i < tileSize_width; i+=VLEN_C)
-            tmp[i/VLEN_C] = *(src_data+(y+lidy)*src_step/VLEN_C+(x+i)/VLEN_C);
     uchar16 zero = (uchar16)(0);
     uchar16 full = (uchar16)(255);
     if( binary )
         for(int i=0; i < tileSize_width; i+=VLEN_C)
             tmp[i/VLEN_C] = (tmp[i/VLEN_C]!=zero)?full:zero;
+
     F mom[10];
     __local int m[10][128];
-    if(lidy == 0)
+    if(lidy < 128)
+    {
         for(int i=0; i<10; i++)
-            for(int j=0; j<128; j++)
-                m[i][j]=0;
+            m[i][lidy]=0;
+    }
     barrier(CLK_LOCAL_MEM_FENCE);
+
     int lm[10] = {0};
     int16 x0 = (int16)(0);
     int16 x1 = (int16)(0);
@@ -281,6 +289,7 @@ __kernel void CvMoments_D0(__global uchar16* src_data, int src_rows, int src_col
                 m[i][lidy-j/2] = lm[i];
         barrier(CLK_LOCAL_MEM_FENCE);
     }
+
     if(lidy == 0&&lidx == 0)
     {
         for( int mt = 0; mt < 10; mt++ )
@@ -328,10 +337,10 @@ __kernel void CvMoments_D0(__global uchar16* src_data, int src_rows, int src_col
     }
 }
 
-__kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_cols, int src_step, int tileSize_width, int tileSize_height,
+__kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_cols, int src_step,
                            __global F* dst_m,
                            int dst_cols, int dst_step, int blocky,
-                           int type, int depth, int cn, int coi, int binary, const int TILE_SIZE)
+                           int depth, int cn, int coi, int binary, const int TILE_SIZE)
 {
     ushort tmp_coi[8]; // get the coi data
     ushort8 tmp[32];
@@ -346,21 +355,26 @@ __kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_col
     int x = wgidx*TILE_SIZE;  // real X index of pixel
     int kcn = (cn==2)?2:4;
     int rstep = min(src_step/2, TILE_SIZE);
-    tileSize_height = min(TILE_SIZE, src_rows - y);
-    tileSize_width = min(TILE_SIZE, src_cols -x);
-    if(src_cols > TILE_SIZE && tileSize_width < TILE_SIZE)
-        for(int i=tileSize_width; i < rstep; i++ )
-            *((__global ushort*)src_data+(y+lidy)*src_step/2+x+i) = 0;
-    if( coi > 0 )
-        for(int i=0; i < tileSize_width; i+=VLEN_US)
-        {
-            for(int j=0; j<VLEN_US; j++)
-                tmp_coi[j] = *((__global ushort*)src_data+(y+lidy)*(int)src_step/2+(x+i+j)*kcn+coi-1);
-            tmp[i/VLEN_US] = (ushort8)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7]);
-        }
-    else
-        for(int i=0; i < tileSize_width; i+=VLEN_US)
-            tmp[i/VLEN_US] = *(src_data+(y+lidy)*src_step/(2*VLEN_US)+(x+i)/VLEN_US);
+    int tileSize_height = min(TILE_SIZE, src_rows - y);
+    int tileSize_width = min(TILE_SIZE, src_cols -x);
+
+    if ( y+lidy < src_rows )
+    {
+        if(src_cols > TILE_SIZE && tileSize_width < TILE_SIZE)
+            for(int i=tileSize_width; i < rstep && (x+i) < src_cols; i++ )
+                *((__global ushort*)src_data+(y+lidy)*src_step/2+x+i) = 0;
+        if( coi > 0 )
+            for(int i=0; i < tileSize_width; i+=VLEN_US)
+            {
+                for(int j=0; j<VLEN_US; j++)
+                    tmp_coi[j] = *((__global ushort*)src_data+(y+lidy)*(int)src_step/2+(x+i+j)*kcn+coi-1);
+                tmp[i/VLEN_US] = (ushort8)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7]);
+            }
+        else
+            for(int i=0; i < tileSize_width; i+=VLEN_US)
+                tmp[i/VLEN_US] = *(src_data+(y+lidy)*src_step/(2*VLEN_US)+(x+i)/VLEN_US);
+    }
+
     ushort8 zero = (ushort8)(0);
     ushort8 full = (ushort8)(255);
     if( binary )
@@ -368,11 +382,11 @@ __kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_col
             tmp[i/VLEN_US] = (tmp[i/VLEN_US]!=zero)?full:zero;
     F mom[10];
     __local long m[10][128];
-    if(lidy == 0)
+    if(lidy < 128)
         for(int i=0; i<10; i++)
-            for(int j=0; j<128; j++)
-                m[i][j]=0;
+            m[i][lidy]=0;
     barrier(CLK_LOCAL_MEM_FENCE);
+
     long lm[10] = {0};
     int8 x0 = (int8)(0);
     int8 x1 = (int8)(0);
@@ -422,17 +436,22 @@ __kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_col
         lm[0] = x0.s0;             // m00
     }
     barrier(CLK_LOCAL_MEM_FENCE);
+
     for( int j = TILE_SIZE/2; j >= 1; j = j/2 )
     {
         if(lidy < j)
             for( int i = 0; i < 10; i++ )
                 lm[i] = lm[i] + m[i][lidy];
-        barrier(CLK_LOCAL_MEM_FENCE);
+    }
+    barrier(CLK_LOCAL_MEM_FENCE);
+    for( int j = TILE_SIZE/2; j >= 1; j = j/2 )
+    {
         if(lidy >= j/2&&lidy < j)
             for( int i = 0; i < 10; i++ )
                 m[i][lidy-j/2] = lm[i];
-        barrier(CLK_LOCAL_MEM_FENCE);
     }
+    barrier(CLK_LOCAL_MEM_FENCE);
+
     if(lidy == 0&&lidx == 0)
     {
         for(int mt = 0; mt < 10; mt++ )
@@ -482,10 +501,10 @@ __kernel void CvMoments_D2(__global ushort8* src_data, int src_rows, int src_col
     }
 }
 
-__kernel void CvMoments_D3(__global short8* src_data, int src_rows, int src_cols, int src_step, int tileSize_width, int tileSize_height,
+__kernel void CvMoments_D3(__global short8* src_data, int src_rows, int src_cols, int src_step,
                            __global F* dst_m,
                            int dst_cols, int dst_step, int blocky,
-                           int type, int depth, int cn, int coi, int binary, const int TILE_SIZE)
+                           int depth, int cn, int coi, int binary, const int TILE_SIZE)
 {
     short tmp_coi[8]; // get the coi data
     short8 tmp[32];
@@ -500,21 +519,26 @@ __kernel void CvMoments_D3(__global short8* src_data, int src_rows, int src_cols
     int x = wgidx*TILE_SIZE;  // real X index of pixel
     int kcn = (cn==2)?2:4;
     int rstep = min(src_step/2, TILE_SIZE);
-    tileSize_height = min(TILE_SIZE, src_rows - y);
-    tileSize_width = min(TILE_SIZE, src_cols -x);
-    if(tileSize_width < TILE_SIZE)
-        for(int i = tileSize_width; i < rstep; i++ )
-            *((__global short*)src_data+(y+lidy)*src_step/2+x+i) = 0;
-    if( coi > 0 )
-        for(int i=0; i < tileSize_width; i+=VLEN_S)
-        {
-            for(int j=0; j<VLEN_S; j++)
-                tmp_coi[j] = *((__global short*)src_data+(y+lidy)*src_step/2+(x+i+j)*kcn+coi-1);
-            tmp[i/VLEN_S] = (short8)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7]);
-        }
-    else
-        for(int i=0; i < tileSize_width; i+=VLEN_S)
-            tmp[i/VLEN_S] = *(src_data+(y+lidy)*src_step/(2*VLEN_S)+(x+i)/VLEN_S);
+    int tileSize_height = min(TILE_SIZE, src_rows - y);
+    int tileSize_width = min(TILE_SIZE, src_cols -x);
+
+    if ( y+lidy < src_rows )
+    {
+        if(tileSize_width < TILE_SIZE)
+            for(int i = tileSize_width; i < rstep && (x+i) < src_cols; i++ )
+                *((__global short*)src_data+(y+lidy)*src_step/2+x+i) = 0;
+        if( coi > 0 )
+            for(int i=0; i < tileSize_width; i+=VLEN_S)
+            {
+                for(int j=0; j<VLEN_S; j++)
+                    tmp_coi[j] = *((__global short*)src_data+(y+lidy)*src_step/2+(x+i+j)*kcn+coi-1);
+                tmp[i/VLEN_S] = (short8)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3],tmp_coi[4],tmp_coi[5],tmp_coi[6],tmp_coi[7]);
+            }
+        else
+            for(int i=0; i < tileSize_width; i+=VLEN_S)
+                tmp[i/VLEN_S] = *(src_data+(y+lidy)*src_step/(2*VLEN_S)+(x+i)/VLEN_S);
+    }
+
     short8 zero = (short8)(0);
     short8 full = (short8)(255);
     if( binary )
@@ -523,10 +547,9 @@ __kernel void CvMoments_D3(__global short8* src_data, int src_rows, int src_cols
 
     F mom[10];
     __local long m[10][128];
-    if(lidy == 0)
+    if(lidy < 128)
         for(int i=0; i<10; i++)
-            for(int j=0; j<128; j++)
-                m[i][j]=0;
+            m[i][lidy]=0;
     barrier(CLK_LOCAL_MEM_FENCE);
     long lm[10] = {0};
     int8 x0 = (int8)(0);
@@ -637,10 +660,10 @@ __kernel void CvMoments_D3(__global short8* src_data, int src_rows, int src_cols
     }
 }
 
-__kernel void CvMoments_D5( __global float* src_data, int src_rows, int src_cols, int src_step, int tileSize_width, int tileSize_height,
+__kernel void CvMoments_D5( __global float* src_data, int src_rows, int src_cols, int src_step,
                             __global F* dst_m,
                             int dst_cols, int dst_step, int blocky,
-                            int type, int depth, int cn, int coi, int binary, const int TILE_SIZE)
+                            int depth, int cn, int coi, int binary, const int TILE_SIZE)
 {
     float tmp_coi[4]; // get the coi data
     float4 tmp[64] ;
@@ -654,33 +677,30 @@ __kernel void CvMoments_D5( __global float* src_data, int src_rows, int src_cols
     int y = wgidy*TILE_SIZE;  // real Y index of pixel
     int x = wgidx*TILE_SIZE;  // real X index of pixel
     int kcn = (cn==2)?2:4;
-    src_step /= sizeof(*src_data);
-    int rstep = min(src_step, TILE_SIZE);
-    tileSize_height = min(TILE_SIZE, src_rows - y);
-    tileSize_width = min(TILE_SIZE, src_cols -x);
+    int rstep = min(src_step/4, TILE_SIZE);
+    int tileSize_height = min(TILE_SIZE, src_rows - y);
+    int tileSize_width = min(TILE_SIZE, src_cols -x);
     int maxIdx = mul24(src_rows, src_cols);
     int yOff = (y+lidy)*src_step;
     int index;
-    if(tileSize_width < TILE_SIZE && yOff < src_rows)
-        for(int i = tileSize_width; i < rstep && (yOff+x+i) < maxIdx; i++ )
-            *(src_data+yOff+x+i) = 0;
-    if( coi > 0 )
-        for(int i=0; i < tileSize_width; i+=VLEN_F)
-        {
-#pragma unroll
-            for(int j=0; j<4; j++)
+
+    if ( y+lidy < src_rows )
+    {
+        if(tileSize_width < TILE_SIZE)
+            for(int i = tileSize_width; i < rstep && (x+i) < src_cols; i++ )
+                *((__global float*)src_data+(y+lidy)*src_step/4+x+i) = 0;
+        if( coi > 0 )
+            for(int i=0; i < tileSize_width; i+=VLEN_F)
             {
-                index = yOff+(x+i+j)*kcn+coi-1;
-                if (index < maxIdx)
-                    tmp_coi[j] = *(src_data+index);
-                else
-                    tmp_coi[j] = 0;
+                for(int j=0; j<4; j++)
+                    tmp_coi[j] = *(src_data+(y+lidy)*src_step/4+(x+i+j)*kcn+coi-1);
+                tmp[i/VLEN_F] = (float4)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3]);
             }
-            tmp[i/VLEN_F] = (float4)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3]);
-        }
-    else
-        for(int i=0; i < tileSize_width && (yOff+x+i) < maxIdx; i+=VLEN_F)
-            tmp[i/VLEN_F] = (*(__global float4 *)(src_data+yOff+x+i));
+        else
+            for(int i=0; i < tileSize_width; i+=VLEN_F)
+                tmp[i/VLEN_F] = (float4)(*(src_data+(y+lidy)*src_step/4+x+i),*(src_data+(y+lidy)*src_step/4+x+i+1),*(src_data+(y+lidy)*src_step/4+x+i+2),*(src_data+(y+lidy)*src_step/4+x+i+3));
+    }
+
     float4 zero = (float4)(0);
     float4 full = (float4)(255);
     if( binary )
@@ -688,10 +708,9 @@ __kernel void CvMoments_D5( __global float* src_data, int src_rows, int src_cols
             tmp[i/VLEN_F] = (tmp[i/VLEN_F]!=zero)?full:zero;
     F mom[10];
     __local F m[10][128];
-    if(lidy == 0)
+    if(lidy < 128)
         for(int i = 0; i < 10; i ++)
-            for(int j = 0; j < 128; j ++)
-                m[i][j] = 0;
+            m[i][lidy] = 0;
     barrier(CLK_LOCAL_MEM_FENCE);
     F lm[10] = {0};
     F4 x0 = (F4)(0);
@@ -729,185 +748,6 @@ __kernel void CvMoments_D5( __global float* src_data, int src_rows, int src_cols
         m[0][lidy-bheight] = x0.s0;             // m00
     }
 
-    else if(lidy < bheight)
-    {
-        lm[9] = ((F)py) * sy;  // m03
-        lm[8] = ((F)x1.s0) * sy;  // m12
-        lm[7] = ((F)x2.s0) * lidy;  // m21
-        lm[6] = x3.s0;             // m30
-        lm[5] = x0.s0 * sy;        // m02
-        lm[4] = x1.s0 * lidy;         // m11
-        lm[3] = x2.s0;             // m20
-        lm[2] = py;             // m01
-        lm[1] = x1.s0;             // m10
-        lm[0] = x0.s0;             // m00
-    }
-    barrier(CLK_LOCAL_MEM_FENCE);
-    for( int j = TILE_SIZE/2; j >= 1; j = j/2 )
-    {
-        if(lidy < j)
-            for( int i = 0; i < 10; i++ )
-                lm[i] = lm[i] + m[i][lidy];
-        barrier(CLK_LOCAL_MEM_FENCE);
-        if(lidy >= j/2&&lidy < j)
-            for( int i = 0; i < 10; i++ )
-                m[i][lidy-j/2] = lm[i];
-        barrier(CLK_LOCAL_MEM_FENCE);
-    }
-    if(lidy == 0&&lidx == 0)
-    {
-        for( int mt = 0; mt < 10; mt++ )
-            mom[mt] = (F)lm[mt];
-        if(binary)
-        {
-            F s = 1./255;
-            for( int mt = 0; mt < 10; mt++ )
-                mom[mt] *= s;
-        }
-
-        F xm = x * mom[0], ym = y * mom[0];
-
-        // accumulate moments computed in each tile
-        dst_step /= sizeof(F);
-
-        int dst_x_off = mad24(wgidy, dst_cols, wgidx);
-        int dst_off = 0;
-        int max_dst_index = 10 * blocky * get_global_size(1);
-
-        // + m00 ( = m00' )
-        dst_off = mad24(DST_ROW_00 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[0];
-
-        // + m10 ( = m10' + x*m00' )
-        dst_off = mad24(DST_ROW_10 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[1] + xm;
-
-        // + m01 ( = m01' + y*m00' )
-        dst_off = mad24(DST_ROW_01 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[2] + ym;
-
-        // + m20 ( = m20' + 2*x*m10' + x*x*m00' )
-        dst_off = mad24(DST_ROW_20 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[3] + x * (mom[1] * 2 + xm);
-
-        // + m11 ( = m11' + x*m01' + y*m10' + x*y*m00' )
-        dst_off = mad24(DST_ROW_11 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[4] + x * (mom[2] + ym) + y * mom[1];
-
-        // + m02 ( = m02' + 2*y*m01' + y*y*m00' )
-        dst_off = mad24(DST_ROW_02 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[5] + y * (mom[2] * 2 + ym);
-
-        // + m30 ( = m30' + 3*x*m20' + 3*x*x*m10' + x*x*x*m00' )
-        dst_off = mad24(DST_ROW_30 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm));
-
-        // + m21 ( = m21' + x*(2*m11' + 2*y*m10' + x*m01' + x*y*m00') + y*m20')
-        dst_off = mad24(DST_ROW_21 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3];
-
-        // + m12 ( = m12' + y*(2*m11' + 2*x*m01' + y*m10' + x*y*m00') + x*m02')
-        dst_off = mad24(DST_ROW_12 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5];
-
-        // + m03 ( = m03' + 3*y*m02' + 3*y*y*m01' + y*y*y*m00' )
-        dst_off = mad24(DST_ROW_03 * blocky, dst_step, dst_x_off);
-        if (dst_off < max_dst_index)
-            *(dst_m + dst_off) = mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym));
-    }
-}
-
-__kernel void CvMoments_D6(__global F* src_data,  int src_rows, int src_cols, int src_step, int tileSize_width, int tileSize_height,
-                           __global F* dst_m,
-                           int dst_cols, int dst_step, int blocky,
-                           int type, int depth, int cn, int coi, int binary, const int TILE_SIZE)
-{
-    F tmp_coi[4]; // get the coi data
-    F4 tmp[64];
-    int VLEN_D = 4; // length of vetor
-    int gidy = get_global_id(0);
-    int gidx = get_global_id(1);
-    int wgidy = get_group_id(0);
-    int wgidx = get_group_id(1);
-    int lidy = get_local_id(0);
-    int lidx = get_local_id(1);
-    int y = wgidy*TILE_SIZE;  // real Y index of pixel
-    int x = wgidx*TILE_SIZE;  // real X index of pixel
-    int kcn = (cn==2)?2:4;
-    int rstep = min(src_step/8, TILE_SIZE);
-    tileSize_height = min(TILE_SIZE,  src_rows - y);
-    tileSize_width = min(TILE_SIZE, src_cols - x);
-
-    if(tileSize_width < TILE_SIZE)
-        for(int i = tileSize_width; i < rstep; i++ )
-            *((__global F*)src_data+(y+lidy)*src_step/8+x+i) = 0;
-    if( coi > 0 )
-        for(int i=0; i < tileSize_width; i+=VLEN_D)
-        {
-            for(int j=0; j<4; j++)
-                tmp_coi[j] = *(src_data+(y+lidy)*src_step/8+(x+i+j)*kcn+coi-1);
-            tmp[i/VLEN_D] = (F4)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3]);
-        }
-    else
-        for(int i=0; i < tileSize_width; i+=VLEN_D)
-            tmp[i/VLEN_D] = (F4)(*(src_data+(y+lidy)*src_step/8+x+i),*(src_data+(y+lidy)*src_step/8+x+i+1),*(src_data+(y+lidy)*src_step/8+x+i+2),*(src_data+(y+lidy)*src_step/8+x+i+3));
-    F4 zero = (F4)(0);
-    F4 full = (F4)(255);
-    if( binary )
-        for(int i=0; i < tileSize_width; i+=VLEN_D)
-            tmp[i/VLEN_D] = (tmp[i/VLEN_D]!=zero)?full:zero;
-    F mom[10];
-    __local F m[10][128];
-    if(lidy == 0)
-        for(int i=0; i<10; i++)
-            for(int j=0; j<128; j++)
-                m[i][j]=0;
-    barrier(CLK_LOCAL_MEM_FENCE);
-    F lm[10] = {0};
-    F4 x0 = (F4)(0);
-    F4 x1 = (F4)(0);
-    F4 x2 = (F4)(0);
-    F4 x3 = (F4)(0);
-    for( int xt = 0 ; xt < tileSize_width; xt+=VLEN_D )
-    {
-        F4 v_xt = (F4)(xt, xt+1, xt+2, xt+3);
-        F4 p = tmp[xt/VLEN_D];
-        F4 xp = v_xt * p, xxp = xp * v_xt;
-        x0 += p;
-        x1 += xp;
-        x2 += xxp;
-        x3 += xxp *v_xt;
-    }
-    x0.s0 += x0.s1 + x0.s2 + x0.s3;
-    x1.s0 += x1.s1 + x1.s2 + x1.s3;
-    x2.s0 += x2.s1 + x2.s2 + x2.s3;
-    x3.s0 += x3.s1 + x3.s2 + x3.s3;
-
-    F py = lidy * x0.s0, sy = lidy*lidy;
-    int bheight = min(tileSize_height, TILE_SIZE/2);
-    if(bheight >= TILE_SIZE/2&&lidy > bheight-1&&lidy < tileSize_height)
-    {
-        m[9][lidy-bheight] = ((F)py) * sy;  // m03
-        m[8][lidy-bheight] = ((F)x1.s0) * sy;  // m12
-        m[7][lidy-bheight] = ((F)x2.s0) * lidy;  // m21
-        m[6][lidy-bheight] = x3.s0;             // m30
-        m[5][lidy-bheight] = x0.s0 * sy;        // m02
-        m[4][lidy-bheight] = x1.s0 * lidy;         // m11
-        m[3][lidy-bheight] = x2.s0;             // m20
-        m[2][lidy-bheight] = py;             // m01
-        m[1][lidy-bheight] = x1.s0;             // m10
-        m[0][lidy-bheight] = x0.s0;             // m00
-    }
-
     else if(lidy < bheight)
     {
         lm[9] = ((F)py) * sy;  // m03
@@ -922,6 +762,164 @@ __kernel void CvMoments_D6(__global F* src_data,  int src_rows, int src_cols, in
         lm[0] = x0.s0;             // m00
     }
     barrier(CLK_LOCAL_MEM_FENCE);
+    for( int j = TILE_SIZE/2; j >= 1; j = j/2 )
+    {
+        if(lidy < j)
+            for( int i = 0; i < 10; i++ )
+                lm[i] = lm[i] + m[i][lidy];
+        barrier(CLK_LOCAL_MEM_FENCE);
+        if(lidy >= j/2&&lidy < j)
+            for( int i = 0; i < 10; i++ )
+                m[i][lidy-j/2] = lm[i];
+        barrier(CLK_LOCAL_MEM_FENCE);
+    }
+    if(lidy == 0&&lidx == 0)
+    {
+        for( int mt = 0; mt < 10; mt++ )
+            mom[mt] = (F)lm[mt];
+        if(binary)
+        {
+            F s = 1./255;
+            for( int mt = 0; mt < 10; mt++ )
+                mom[mt] *= s;
+        }
+
+        F xm = x * mom[0], ym = y * mom[0];
+
+        // accumulate moments computed in each tile
+        dst_step /= sizeof(F);
+
+        // + m00 ( = m00' )
+        *(dst_m + mad24(DST_ROW_00 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[0];
+
+        // + m10 ( = m10' + x*m00' )
+        *(dst_m + mad24(DST_ROW_10 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[1] + xm;
+
+        // + m01 ( = m01' + y*m00' )
+        *(dst_m + mad24(DST_ROW_01 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[2] + ym;
+
+        // + m20 ( = m20' + 2*x*m10' + x*x*m00' )
+        *(dst_m + mad24(DST_ROW_20 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[3] + x * (mom[1] * 2 + xm);
+
+        // + m11 ( = m11' + x*m01' + y*m10' + x*y*m00' )
+        *(dst_m + mad24(DST_ROW_11 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[4] + x * (mom[2] + ym) + y * mom[1];
+
+        // + m02 ( = m02' + 2*y*m01' + y*y*m00' )
+        *(dst_m + mad24(DST_ROW_02 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[5] + y * (mom[2] * 2 + ym);
+
+        // + m30 ( = m30' + 3*x*m20' + 3*x*x*m10' + x*x*x*m00' )
+        *(dst_m + mad24(DST_ROW_30 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm));
+
+        // + m21 ( = m21' + x*(2*m11' + 2*y*m10' + x*m01' + x*y*m00') + y*m20')
+        *(dst_m + mad24(DST_ROW_21 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3];
+
+        // + m12 ( = m12' + y*(2*m11' + 2*x*m01' + y*m10' + x*y*m00') + x*m02')
+        *(dst_m + mad24(DST_ROW_12 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5];
+
+        // + m03 ( = m03' + 3*y*m02' + 3*y*y*m01' + y*y*y*m00' )
+        *(dst_m + mad24(DST_ROW_03 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym));
+    }
+}
+
+__kernel void CvMoments_D6(__global F* src_data,  int src_rows, int src_cols, int src_step,
+                           __global F* dst_m,
+                           int dst_cols, int dst_step, int blocky,
+                           int depth, int cn, int coi, int binary, const int TILE_SIZE)
+{
+    F tmp_coi[4]; // get the coi data
+    F4 tmp[64];
+    int VLEN_D = 4; // length of vetor
+    int gidy = get_global_id(0);
+    int gidx = get_global_id(1);
+    int wgidy = get_group_id(0);
+    int wgidx = get_group_id(1);
+    int lidy = get_local_id(0);
+    int lidx = get_local_id(1);
+    int y = wgidy*TILE_SIZE;  // real Y index of pixel
+    int x = wgidx*TILE_SIZE;  // real X index of pixel
+    int kcn = (cn==2)?2:4;
+    int rstep = min(src_step/8, TILE_SIZE);
+    int tileSize_height = min(TILE_SIZE,  src_rows - y);
+    int tileSize_width = min(TILE_SIZE, src_cols - x);
+
+    if ( y+lidy < src_rows )
+    {
+        if(tileSize_width < TILE_SIZE)
+            for(int i = tileSize_width; i < rstep && (x+i) < src_cols; i++ )
+                *((__global F*)src_data+(y+lidy)*src_step/8+x+i) = 0;
+        if( coi > 0 )
+            for(int i=0; i < tileSize_width; i+=VLEN_D)
+            {
+                for(int j=0; j<4 && ((x+i+j)*kcn+coi-1)<src_cols; j++)
+                    tmp_coi[j] = *(src_data+(y+lidy)*src_step/8+(x+i+j)*kcn+coi-1);
+                tmp[i/VLEN_D] = (F4)(tmp_coi[0],tmp_coi[1],tmp_coi[2],tmp_coi[3]);
+            }
+        else
+            for(int i=0; i < tileSize_width && (x+i+3) < src_cols; i+=VLEN_D)
+                tmp[i/VLEN_D] = (F4)(*(src_data+(y+lidy)*src_step/8+x+i),*(src_data+(y+lidy)*src_step/8+x+i+1),*(src_data+(y+lidy)*src_step/8+x+i+2),*(src_data+(y+lidy)*src_step/8+x+i+3));
+    }
+
+    F4 zero = (F4)(0);
+    F4 full = (F4)(255);
+    if( binary )
+        for(int i=0; i < tileSize_width; i+=VLEN_D)
+            tmp[i/VLEN_D] = (tmp[i/VLEN_D]!=zero)?full:zero;
+    F mom[10];
+    __local F m[10][128];
+    if(lidy < 128)
+        for(int i=0; i<10; i++)
+            m[i][lidy]=0;
+    barrier(CLK_LOCAL_MEM_FENCE);
+    F lm[10] = {0};
+    F4 x0 = (F4)(0);
+    F4 x1 = (F4)(0);
+    F4 x2 = (F4)(0);
+    F4 x3 = (F4)(0);
+    for( int xt = 0 ; xt < tileSize_width; xt+=VLEN_D )
+    {
+        F4 v_xt = (F4)(xt, xt+1, xt+2, xt+3);
+        F4 p = tmp[xt/VLEN_D];
+        F4 xp = v_xt * p, xxp = xp * v_xt;
+        x0 += p;
+        x1 += xp;
+        x2 += xxp;
+        x3 += xxp *v_xt;
+    }
+    x0.s0 += x0.s1 + x0.s2 + x0.s3;
+    x1.s0 += x1.s1 + x1.s2 + x1.s3;
+    x2.s0 += x2.s1 + x2.s2 + x2.s3;
+    x3.s0 += x3.s1 + x3.s2 + x3.s3;
+
+    F py = lidy * x0.s0, sy = lidy*lidy;
+    int bheight = min(tileSize_height, TILE_SIZE/2);
+    if(bheight >= TILE_SIZE/2&&lidy > bheight-1&&lidy < tileSize_height)
+    {
+        m[9][lidy-bheight] = ((F)py) * sy;  // m03
+        m[8][lidy-bheight] = ((F)x1.s0) * sy;  // m12
+        m[7][lidy-bheight] = ((F)x2.s0) * lidy;  // m21
+        m[6][lidy-bheight] = x3.s0;             // m30
+        m[5][lidy-bheight] = x0.s0 * sy;        // m02
+        m[4][lidy-bheight] = x1.s0 * lidy;         // m11
+        m[3][lidy-bheight] = x2.s0;             // m20
+        m[2][lidy-bheight] = py;             // m01
+        m[1][lidy-bheight] = x1.s0;             // m10
+        m[0][lidy-bheight] = x0.s0;             // m00
+    }
+    else if(lidy < bheight)
+    {
+        lm[9] = ((F)py) * sy;  // m03
+        lm[8] = ((F)x1.s0) * sy;  // m12
+        lm[7] = ((F)x2.s0) * lidy;  // m21
+        lm[6] = x3.s0;             // m30
+        lm[5] = x0.s0 * sy;        // m02
+        lm[4] = x1.s0 * lidy;         // m11
+        lm[3] = x2.s0;             // m20
+        lm[2] = py;             // m01
+        lm[1] = x1.s0;             // m10
+        lm[0] = x0.s0;             // m00
+    }
+    barrier(CLK_LOCAL_MEM_FENCE);
+
     for( int j = TILE_SIZE/2; j >= 1; j = j/2 )
     {
         if(lidy < j)
diff --git a/modules/ocl/test/test_moments.cpp b/modules/ocl/test/test_moments.cpp
index 98c66def3..86f4779d6 100644
--- a/modules/ocl/test/test_moments.cpp
+++ b/modules/ocl/test/test_moments.cpp
@@ -45,12 +45,12 @@ TEST_P(MomentsTest, Mat)
     {
         if(test_contours)
         {
-            Mat src = imread( workdir + "../cpp/pic3.png", 1 );
-            Mat src_gray, canny_output;
-            cvtColor( src, src_gray, CV_BGR2GRAY );
+            Mat src = imread( workdir + "../cpp/pic3.png", IMREAD_GRAYSCALE );
+            ASSERT_FALSE(src.empty());
+            Mat canny_output;
             vector<vector<Point> > contours;
             vector<Vec4i> hierarchy;
-            Canny( src_gray, canny_output, 100, 200, 3 );
+            Canny( src, canny_output, 100, 200, 3 );
             findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
             for( size_t i = 0; i < contours.size(); i++ )
             {

From 43122939cbe17e534442bd9ba9bb299e752a13a5 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 22 May 2013 04:21:23 -0700
Subject: [PATCH 26/75] Media foundation video i/o fixes.

Bug in Video for Windows capture init fixed;
Media Foundation based capture finalization fixed;
Highgui tests for video i/o updated.
---
 .../include/opencv2/highgui/highgui_c.h       |   4 +-
 modules/highgui/src/cap.cpp                   |  39 ++---
 modules/highgui/src/cap_msmf.cpp              | 138 ++++++++----------
 modules/highgui/src/cap_vfw.cpp               |   4 +-
 modules/highgui/test/test_video_io.cpp        |  58 ++++----
 5 files changed, 110 insertions(+), 133 deletions(-)

diff --git a/modules/highgui/include/opencv2/highgui/highgui_c.h b/modules/highgui/include/opencv2/highgui/highgui_c.h
index 12be9867a..fbcdba24f 100644
--- a/modules/highgui/include/opencv2/highgui/highgui_c.h
+++ b/modules/highgui/include/opencv2/highgui/highgui_c.h
@@ -558,9 +558,11 @@ CVAPI(int)    cvGetCaptureDomain( CvCapture* capture);
 /* "black box" video file writer structure */
 typedef struct CvVideoWriter CvVideoWriter;
 
+#define CV_FOURCC_MACRO(c1, c2, c3, c4) ((c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24))
+
 CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4)
 {
-    return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24);
+    return CV_FOURCC_MACRO(c1, c2, c3, c4);
 }
 
 #define CV_FOURCC_PROMPT -1  /* Open Codec Selection Dialog (Windows only) */
diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp
index 8db873102..cc92da3d0 100644
--- a/modules/highgui/src/cap.cpp
+++ b/modules/highgui/src/cap.cpp
@@ -199,15 +199,6 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index)
 
         switch (domains[i])
         {
-#ifdef HAVE_MSMF
-        case CV_CAP_MSMF:
-             printf("Creating Media foundation capture\n");
-             capture = cvCreateCameraCapture_MSMF (index);
-             printf("Capture address %p\n", capture);
-             if (capture)
-                 return capture;
-            break;
-#endif
 #ifdef HAVE_DSHOW
         case CV_CAP_DSHOW:
              capture = cvCreateCameraCapture_DShow (index);
@@ -215,7 +206,13 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index)
                  return capture;
             break;
 #endif
-
+#ifdef HAVE_MSMF
+        case CV_CAP_MSMF:
+             capture = cvCreateCameraCapture_MSMF (index);
+             if (capture)
+                 return capture;
+            break;
+#endif
 #ifdef HAVE_TYZX
         case CV_CAP_STEREO:
             capture = cvCreateCameraCapture_TYZX (index);
@@ -223,14 +220,12 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index)
                 return capture;
             break;
 #endif
-
-        case CV_CAP_VFW:
 #ifdef HAVE_VFW
+        case CV_CAP_VFW:
             capture = cvCreateCameraCapture_VFW (index);
             if (capture)
                 return capture;
 #endif
-
 #if defined HAVE_LIBV4L || defined HAVE_CAMV4L || defined HAVE_CAMV4L2 || defined HAVE_VIDEOIO
             capture = cvCreateCameraCapture_V4L (index);
             if (capture)
@@ -363,20 +358,16 @@ CV_IMPL CvCapture * cvCreateFileCapture (const char * filename)
     if (! result)
         result = cvCreateFileCapture_FFMPEG_proxy (filename);
 
-#ifdef HAVE_MSMF
-    if (! result)
-    {
-        printf("Creating Media foundation based reader\n");
-        result = cvCreateFileCapture_MSMF (filename);
-        printf("Construction result %p\n", result);
-    }
-#endif
-
 #ifdef HAVE_VFW
     if (! result)
         result = cvCreateFileCapture_VFW (filename);
 #endif
 
+#ifdef HAVE_MSMF
+    if (! result)
+        result = cvCreateFileCapture_MSMF (filename);
+#endif
+
 #ifdef HAVE_XINE
     if (! result)
         result = cvCreateFileCapture_XINE (filename);
@@ -422,14 +413,12 @@ CV_IMPL CvVideoWriter* cvCreateVideoWriter( const char* filename, int fourcc,
     if(!fourcc || !fps)
         result = cvCreateVideoWriter_Images(filename);
 
-#ifdef HAVE_FFMPEG
     if(!result)
         result = cvCreateVideoWriter_FFMPEG_proxy (filename, fourcc, fps, frameSize, is_color);
-#endif
 
 #ifdef HAVE_VFW
     if(!result)
-     return cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, is_color);
+        result = cvCreateVideoWriter_VFW(filename, fourcc, fps, frameSize, is_color);
 #endif
 
 #ifdef HAVE_MSMF
diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 814fb75be..7af85382b 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -840,9 +840,11 @@ LPCWSTR GetGUIDNameConstNew(const GUID& guid)
     IF_EQUAL_RETURN(guid, MFAudioFormat_ADTS); //             WAVE_FORMAT_MPEG_ADTS_AAC
     return NULL;
 }
+
 FormatReader::FormatReader(void)
 {
 }
+
 MediaType FormatReader::Read(IMFMediaType *pType)
 {
     UINT32 count = 0;
@@ -888,9 +890,9 @@ ImageGrabber::ImageGrabber(unsigned int deviceID, bool synchronous):
     ig_RIE(true),
     ig_Close(false),
     ig_Synchronous(synchronous),
-    ig_hFrameReady(synchronous ? CreateEvent(NULL, FALSE, FALSE, "ig_hFrameReady"): 0),
-    ig_hFrameGrabbed(synchronous ?  CreateEvent(NULL, FALSE, TRUE, "ig_hFrameGrabbed"): 0),
-    ig_hFinish(synchronous ?  CreateEvent(NULL, FALSE, FALSE, "ig_hFinish") : 0)
+    ig_hFrameReady(synchronous ? CreateEvent(NULL, FALSE, FALSE, NULL): 0),
+    ig_hFrameGrabbed(synchronous ? CreateEvent(NULL, FALSE, TRUE, NULL): 0),
+    ig_hFinish(CreateEvent(NULL, TRUE, FALSE, NULL))
 {}
 
 ImageGrabber::~ImageGrabber(void)
@@ -898,15 +900,16 @@ ImageGrabber::~ImageGrabber(void)
     printf("ImageGrabber::~ImageGrabber()\n");
     if (ig_pSession)
     {
-        printf("ig_pSession->Shutdown()");
+        printf("ig_pSession->Shutdown()\n");
         ig_pSession->Shutdown();
     }
 
+    CloseHandle(ig_hFinish);
+
     if (ig_Synchronous)
     {
         CloseHandle(ig_hFrameReady);
         CloseHandle(ig_hFrameGrabbed);
-        CloseHandle(ig_hFinish);
     }
 
     SafeRelease(&ig_pSession);
@@ -1061,7 +1064,6 @@ HRESULT ImageGrabber::startGrabbing(void)
             hr = S_OK;
             goto done;
         }
-        printf("media foundation event: %d\n", met);
         if (met == MESessionEnded)
         {
             DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: MESessionEnded \n", ig_DeviceID);
@@ -1088,13 +1090,7 @@ HRESULT ImageGrabber::startGrabbing(void)
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Finish startGrabbing \n", ig_DeviceID);
 
 done:
-    if (ig_Synchronous)
-    {
-        SetEvent(ig_hFinish);
-    }
-
-    SafeRelease(&ig_pSession);
-    SafeRelease(&ig_pTopology);
+    SetEvent(ig_hFinish);
 
     return hr;
 }
@@ -1109,7 +1105,7 @@ void ImageGrabber::resumeGrabbing()
 
 HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo)
 {
-    ComPtr<IMFTopology> pTopology = NULL;
+    IMFTopology* pTopology = NULL;
     ComPtr<IMFPresentationDescriptor> pPD = NULL;
     ComPtr<IMFStreamDescriptor> pSD = NULL;
     ComPtr<IMFMediaTypeHandler> pHandler = NULL;
@@ -1117,7 +1113,7 @@ HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSink
     ComPtr<IMFTopologyNode> pNode2 = NULL;
     HRESULT hr = S_OK;
     DWORD cStreams = 0;
-    CHECK_HR(hr = MFCreateTopology(pTopology.GetAddressOf()));
+    CHECK_HR(hr = MFCreateTopology(&pTopology));
     CHECK_HR(hr = pSource->CreatePresentationDescriptor(pPD.GetAddressOf()));
     CHECK_HR(hr = pPD->GetStreamDescriptorCount(&cStreams));
     for (DWORD i = 0; i < cStreams; i++)
@@ -1130,8 +1126,8 @@ HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSink
         CHECK_HR(hr = pHandler->GetMajorType(&majorType));
         if (majorType == MFMediaType_Video && fSelected)
         {
-            CHECK_HR(hr = AddSourceNode(pTopology.Get(), pSource, pPD.Get(), pSD.Get(), pNode1.GetAddressOf()));
-            CHECK_HR(hr = AddOutputNode(pTopology.Get(), pSinkActivate, 0, pNode2.GetAddressOf()));
+            CHECK_HR(hr = AddSourceNode(pTopology, pSource, pPD.Get(), pSD.Get(), pNode1.GetAddressOf()));
+            CHECK_HR(hr = AddOutputNode(pTopology, pSinkActivate, 0, pNode2.GetAddressOf()));
             CHECK_HR(hr = pNode1->ConnectOutput(0, pNode2.Get(), 0));
             break;
         }
@@ -1140,7 +1136,7 @@ HRESULT ImageGrabber::CreateTopology(IMFMediaSource *pSource, IMFActivate *pSink
             CHECK_HR(hr = pPD->DeselectStream(i));
         }
     }
-    *ppTopo = pTopology.Get();
+    *ppTopo = pTopology;
     (*ppTopo)->AddRef();
 
 done:
@@ -1286,9 +1282,15 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
     (void)llSampleDuration;
     (void)dwSampleSize;
 
-    WaitForSingleObject(ig_hFrameGrabbed, INFINITE);
+    //printf("ImageGrabber::OnProcessSample() -- begin\n");
+    HANDLE tmp[] = {ig_hFinish, ig_hFrameGrabbed, NULL};
 
-    printf("ImageGrabber::OnProcessSample() -- begin\n");
+    DWORD status = WaitForMultipleObjects(2, tmp, FALSE, INFINITE);
+    if (status == WAIT_OBJECT_0)
+    {
+        printf("OnProcessFrame called after ig_hFinish event\n");
+        return S_OK;
+    }
 
     if(ig_RIE)
     {
@@ -1300,25 +1302,24 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
         ig_RISecond->fastCopy(pSampleBuffer);
         ig_RIOut = ig_RISecond;
     }
-    ig_RIE = !ig_RIE;
 
-    printf("ImageGrabber::OnProcessSample() -- end\n");
+    //printf("ImageGrabber::OnProcessSample() -- end\n");
 
     if (ig_Synchronous)
     {
         SetEvent(ig_hFrameReady);
     }
+    else
+    {
+        ig_RIE = !ig_RIE;
+    }
 
     return S_OK;
 }
 
 STDMETHODIMP ImageGrabber::OnShutdown()
 {
-    if (ig_Synchronous)
-    {
-        SetEvent(ig_hFrameGrabbed);
-    }
-
+    SetEvent(ig_hFinish);
     return S_OK;
 }
 
@@ -1387,6 +1388,8 @@ ImageGrabberThread::~ImageGrabberThread(void)
 {
     DebugPrintOut *DPO = &DebugPrintOut::getInstance();
     DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Destroing ImageGrabberThread\n", igt_DeviceID);
+    if (igt_Handle)
+        WaitForSingleObject(igt_Handle, INFINITE);
     delete igt_pImageGrabber;
 }
 
@@ -1431,7 +1434,6 @@ void ImageGrabberThread::run()
         DPO->printOut(L"IMAGEGRABBERTHREAD VIDEODEVICE %i: Emergency Stop thread\n", igt_DeviceID);
         if(igt_func)
         {
-            printf("Calling Emergency stop even handler\n");
             igt_func(igt_DeviceID, igt_userData);
         }
     }
@@ -3045,6 +3047,7 @@ CvCaptureFile_MSMF::CvCaptureFile_MSMF():
 
 CvCaptureFile_MSMF::~CvCaptureFile_MSMF()
 {
+    close();
     MFShutdown();
 }
 
@@ -3109,7 +3112,7 @@ void CvCaptureFile_MSMF::close()
     if (grabberThread)
     {
         isOpened = false;
-        SetEvent(grabberThread->getImageGrabber()->ig_hFrameReady);
+        SetEvent(grabberThread->getImageGrabber()->ig_hFinish);
         grabberThread->stop();
         delete grabberThread;
     }
@@ -3289,12 +3292,12 @@ bool CvCaptureFile_MSMF::grabFrame()
     DWORD waitResult;
     if (isOpened)
     {
+        SetEvent(grabberThread->getImageGrabber()->ig_hFrameGrabbed);
         HANDLE tmp[] = {grabberThread->getImageGrabber()->ig_hFrameReady, grabberThread->getImageGrabber()->ig_hFinish, 0};
         waitResult = WaitForMultipleObjects(2, tmp, FALSE, INFINITE);
-        SetEvent(grabberThread->getImageGrabber()->ig_hFrameGrabbed);
     }
 
-    return isOpened && (waitResult == WAIT_OBJECT_0);
+    return isOpened && grabberThread->getImageGrabber()->getRawImage()->isNew() && (waitResult == WAIT_OBJECT_0);
 }
 
 IplImage* CvCaptureFile_MSMF::retrieveFrame(int)
@@ -3443,7 +3446,8 @@ private:
     HRESULT WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& rtStart, const LONGLONG& rtDuration);
 };
 
-CvVideoWriter_MSMF::CvVideoWriter_MSMF()
+CvVideoWriter_MSMF::CvVideoWriter_MSMF():
+    initiated(false)
 {
 }
 
@@ -3456,47 +3460,47 @@ const GUID CvVideoWriter_MSMF::FourCC2GUID(int fourcc)
 {
     switch(fourcc)
     {
-        case 'dv25':
+        case CV_FOURCC_MACRO('d', 'v', '2', '5'):
             return MFVideoFormat_DV25; break;
-        case 'dv50':
+        case CV_FOURCC_MACRO('d', 'v', '5', '0'):
             return MFVideoFormat_DV50; break;
-        case 'dvc ':
+        case CV_FOURCC_MACRO('d', 'v', 'c', ' '):
             return MFVideoFormat_DVC; break;
-        case 'dvh1':
+        case CV_FOURCC_MACRO('d', 'v', 'h', '1'):
             return MFVideoFormat_DVH1; break;
-        case 'dvhd':
+        case CV_FOURCC_MACRO('d', 'v', 'h', 'd'):
             return MFVideoFormat_DVHD; break;
-        case 'dvsd':
+        case CV_FOURCC_MACRO('d', 'v', 's', 'd'):
             return MFVideoFormat_DVSD; break;
-        case 'dvsl':
+        case CV_FOURCC_MACRO('d', 'v', 's', 'l'):
                 return MFVideoFormat_DVSL; break;
-        case 'H263':
+        case CV_FOURCC_MACRO('H', '2', '6', '3'):
                 return MFVideoFormat_H263; break;
-        case 'H264':
+        case CV_FOURCC_MACRO('H', '2', '6', '4'):
                 return MFVideoFormat_H264; break;
-        case 'M4S2':
+        case CV_FOURCC_MACRO('M', '4', 'S', '2'):
                 return MFVideoFormat_M4S2; break;
-        case 'MJPG':
+        case CV_FOURCC_MACRO('M', 'J', 'P', 'G'):
                 return MFVideoFormat_MJPG; break;
-        case 'MP43':
+        case CV_FOURCC_MACRO('M', 'P', '4', '3'):
                 return MFVideoFormat_MP43; break;
-        case 'MP4S':
+        case CV_FOURCC_MACRO('M', 'P', '4', 'S'):
                 return MFVideoFormat_MP4S; break;
-        case 'MP4V':
+        case CV_FOURCC_MACRO('M', 'P', '4', 'V'):
                 return MFVideoFormat_MP4V; break;
-        case 'MPG1':
+        case CV_FOURCC_MACRO('M', 'P', 'G', '1'):
                 return MFVideoFormat_MPG1; break;
-        case 'MSS1':
+        case CV_FOURCC_MACRO('M', 'S', 'S', '1'):
                 return MFVideoFormat_MSS1; break;
-        case 'MSS2':
+        case CV_FOURCC_MACRO('M', 'S', 'S', '2'):
                 return MFVideoFormat_MSS2; break;
-        case 'WMV1':
+        case CV_FOURCC_MACRO('W', 'M', 'V', '1'):
                 return MFVideoFormat_WMV1; break;
-        case 'WMV2':
+        case CV_FOURCC_MACRO('W', 'M', 'V', '2'):
                 return MFVideoFormat_WMV2; break;
-        case 'WMV3':
+        case CV_FOURCC_MACRO('W', 'M', 'V', '3'):
                 return MFVideoFormat_WMV3; break;
-        case 'WVC1':
+        case CV_FOURCC_MACRO('W', 'V', 'C', '1'):
                 return MFVideoFormat_WVC1; break;
         default:
             return MFVideoFormat_H264;
@@ -3516,19 +3520,15 @@ bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
     HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
     if (SUCCEEDED(hr))
     {
-        printf("CoInitializeEx is successfull\n");
         hr = MFStartup(MF_VERSION);
         if (SUCCEEDED(hr))
         {
-            printf("MFStartup is successfull\n");
             hr = InitializeSinkWriter(filename);
             if (SUCCEEDED(hr))
             {
-                printf("InitializeSinkWriter is successfull\n");
                 initiated = true;
                 rtStart = 0;
                 MFFrameRateToAverageTimePerFrame((UINT32)fps, 1, &rtDuration);
-                printf("duration: %d\n", rtDuration);
             }
         }
     }
@@ -3556,13 +3556,9 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
     if (!img)
         return false;
 
-    printf("Writing not empty IplImage\n");
-
     int length = img->width * img->height * 4;
-    printf("Image: %dx%d, %d\n", img->width, img->height, length);
     DWORD* target = new DWORD[length];
 
-    printf("Before for loop\n");
     for (int rowIdx = 0; rowIdx < img->height; rowIdx++)
     {
         char* rowStart = img->imageData + rowIdx*img->widthStep;
@@ -3577,9 +3573,7 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
     }
 
     // Send frame to the sink writer.
-    printf("Before private WriteFrame call\n");
     HRESULT hr = WriteFrame(target, rtStart, rtDuration);
-    printf("After private WriteFrame call\n");
     if (FAILED(hr))
     {
         printf("Private WriteFrame failed\n");
@@ -3588,8 +3582,6 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
     }
     rtStart += rtDuration;
 
-    printf("End of writing IplImage\n");
-
     delete[] target;
 
     return true;
@@ -3681,7 +3673,8 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     {
         hr = MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
     }
-        if (SUCCEEDED(hr))
+
+    if (SUCCEEDED(hr))
     {
         hr = sinkWriter->SetInputMediaType(streamIndex, mediaTypeIn.Get(), NULL);
     }
@@ -3697,7 +3690,6 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
 
 HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG& Start, const LONGLONG& Duration)
 {
-    printf("Private WriteFrame(%p, %llu, %llu)\n", videoFrameBuffer, Start, Duration);
     ComPtr<IMFSample> sample;
     ComPtr<IMFMediaBuffer> buffer;
 
@@ -3712,13 +3704,11 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
     // Lock the buffer and copy the video frame to the buffer.
     if (SUCCEEDED(hr))
     {
-        printf("MFCreateMemoryBuffer successfull\n");
         hr = buffer->Lock(&pData, NULL, NULL);
     }
 
     if (SUCCEEDED(hr))
     {
-        printf("Before MFCopyImage(%p, %d, %p, %d, %d %d)\n", pData, cbWidth, videoFrameBuffer, cbWidth, cbWidth, videoHeight);
         hr = MFCopyImage(
             pData,                      // Destination buffer.
             cbWidth,                    // Destination stride.
@@ -3727,21 +3717,16 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
             cbWidth,                    // Image width in bytes.
             videoHeight                 // Image height in pixels.
             );
-        printf("After MFCopyImage()\n");
     }
 
-    printf("Before buffer.Get()\n");
     if (buffer)
     {
-        printf("Before buffer->Unlock\n");
         buffer->Unlock();
-        printf("After buffer->Unlock\n");
     }
 
     // Set the data length of the buffer.
     if (SUCCEEDED(hr))
     {
-        printf("MFCopyImage successfull\n");
         hr = buffer->SetCurrentLength(cbBuffer);
     }
 
@@ -3758,24 +3743,19 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
     // Set the time stamp and the duration.
     if (SUCCEEDED(hr))
     {
-        printf("Sample time: %d\n", Start);
         hr = sample->SetSampleTime(Start);
     }
     if (SUCCEEDED(hr))
     {
-        printf("Duration: %d\n", Duration);
         hr = sample->SetSampleDuration(Duration);
     }
 
     // Send the sample to the Sink Writer.
     if (SUCCEEDED(hr))
     {
-        printf("Setting writer params successfull\n");
         hr = sinkWriter->WriteSample(streamIndex, sample.Get());
     }
 
-    printf("Private WriteFrame(%d, %p) end with status %u\n", streamIndex, sample.Get(), hr);
-
     return hr;
 }
 
diff --git a/modules/highgui/src/cap_vfw.cpp b/modules/highgui/src/cap_vfw.cpp
index d419a4891..d845953f8 100644
--- a/modules/highgui/src/cap_vfw.cpp
+++ b/modules/highgui/src/cap_vfw.cpp
@@ -613,8 +613,10 @@ bool CvVideoWriter_VFW::open( const char* filename, int _fourcc, double _fps, Cv
             close();
             return false;
         }
+        return true;
     }
-    return true;
+    else
+        return false;
 }
 
 
diff --git a/modules/highgui/test/test_video_io.cpp b/modules/highgui/test/test_video_io.cpp
index 34ec0bdd8..f46235b3e 100644
--- a/modules/highgui/test/test_video_io.cpp
+++ b/modules/highgui/test/test_video_io.cpp
@@ -57,27 +57,27 @@ string fourccToString(int fourcc)
 #ifdef HAVE_MSMF
 const VideoFormat g_specific_fmt_list[] =
 {
-/*        VideoFormat("avi", 'dv25'),
-        VideoFormat("avi", 'dv50'),
-        VideoFormat("avi", 'dvc '),
-        VideoFormat("avi", 'dvh1'),
-        VideoFormat("avi", 'dvhd'),
-        VideoFormat("avi", 'dvsd'),
-        VideoFormat("avi", 'dvsl'),
-        VideoFormat("avi", 'M4S2'), */
-        VideoFormat("wmv", 'WMV3'),
-        // VideoFormat("avi", 'H264'),
-        // VideoFormat("avi", 'MJPG'),
-        // VideoFormat("avi", 'MP43'),
-        // VideoFormat("avi", 'MP4S'),
-        // VideoFormat("avi", 'MP4V'),
-/*        VideoFormat("avi", 'MPG1'),
-        VideoFormat("avi", 'MSS1'),
-        VideoFormat("avi", 'MSS2'),
-        VideoFormat("avi", 'WMV1'),
-        VideoFormat("avi", 'WMV2'),
-        VideoFormat("avi", 'WMV3'),
-        VideoFormat("avi", 'WVC1'), */
+        /*VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', '2', '5')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', '5', '0')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', 'c', ' ')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', 'h', '1')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', 'h', 'd')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', 's', 'd')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('d', 'v', 's', 'l')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('H', '2', '6', '3')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('M', '4', 'S', '2')),
+        VideoFormat("avi", CV_FOURCC_MACRO('M', 'J', 'P', 'G')),
+        VideoFormat("mp4", CV_FOURCC_MACRO('M', 'P', '4', 'S')),
+        VideoFormat("mp4", CV_FOURCC_MACRO('M', 'P', '4', 'V')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('M', 'P', '4', '3')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('M', 'P', 'G', '1')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('M', 'S', 'S', '1')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('M', 'S', 'S', '2')),*/
+        //VideoFormat("avi", CV_FOURCC_MACRO('H', '2', '6', '4')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '1')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '2')),
+        VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '3')),
+        //VideoFormat("wmv", CV_FOURCC_MACRO('W', 'V', 'C', '1')),
         VideoFormat()
 };
 #else
@@ -269,19 +269,19 @@ void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt
 
     for(;;)
     {
-        IplImage * img = cvQueryFrame( cap );
+        IplImage* img = cvQueryFrame( cap );
 
         if (!img)
             break;
 
         frames.push_back(Mat(img).clone());
 
-        if (writer == 0)
+        if (writer == NULL)
         {
             writer = cvCreateVideoWriter(tmp_name.c_str(), fmt.fourcc, 24, cvGetSize(img));
-            if (writer == 0)
+            if (writer == NULL)
             {
-                ts->printf(ts->LOG, "can't create writer (with fourcc : %d)\n",
+                ts->printf(ts->LOG, "can't create writer (with fourcc : %s)\n",
                            cvtest::fourccToString(fmt.fourcc).c_str());
                 cvReleaseCapture( &cap );
                 ts->set_failed_test_info(ts->FAIL_MISMATCH);
@@ -317,18 +317,22 @@ void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt
         double psnr = PSNR(img1, img);
         if (psnr < thresDbell)
         {
-            printf("Too low psnr = %gdb\n", psnr);
+            ts->printf(ts->LOG, "Too low frame %d psnr = %gdb\n", i, psnr);
+            ts->set_failed_test_info(ts->FAIL_MISMATCH);
+
             //imwrite("original.png", img);
             //imwrite("after_test.png", img1);
             //Mat diff;
             //absdiff(img, img1, diff);
             //imwrite("diff.png", diff);
-            ts->set_failed_test_info(ts->FAIL_MISMATCH);
+
             break;
         }
     }
 
+    printf("Before saved release for %s\n", tmp_name.c_str());
     cvReleaseCapture( &saved );
+    printf("After release\n");
 
     ts->printf(ts->LOG, "end test function : ImagesVideo \n");
 }

From 08a0e1c91b121cea67d08000c5339a6d7960e43d Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 22 May 2013 07:26:43 -0700
Subject: [PATCH 27/75] TBB support for WinRT fixed.

Development release of TBB with WinRT support added;
TBB.dll is placed in bin folder now.
---
 3rdparty/tbb/CMakeLists.txt | 31 ++++++++++++++++++++-----------
 1 file changed, 20 insertions(+), 11 deletions(-)

diff --git a/3rdparty/tbb/CMakeLists.txt b/3rdparty/tbb/CMakeLists.txt
index 9dcb63b7f..942404133 100644
--- a/3rdparty/tbb/CMakeLists.txt
+++ b/3rdparty/tbb/CMakeLists.txt
@@ -1,12 +1,19 @@
 #Cross compile TBB from source
 project(tbb)
 
-# 4.1 update 3 dev - works fine
-set(tbb_ver "tbb41_20130401oss")
-set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130401oss_src.tgz")
-set(tbb_md5 "f2f591a0d2ca8f801e221ce7d9ea84bb")
+# Development release
+set(tbb_ver "tbb41_20130516oss")
+set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130516oss_src.tgz")
+set(tbb_md5 "08c14d1c196bc9595d8c52bedc239937")
 set(tbb_version_file "version_string.ver")
-ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow)
+ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow -Wunused-parameter)
+
+# 4.1 update 3 dev - works fine
+#set(tbb_ver "tbb41_20130401oss")
+#set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130401oss_src.tgz")
+#set(tbb_md5 "f2f591a0d2ca8f801e221ce7d9ea84bb")
+#set(tbb_version_file "version_string.ver")
+#ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow)
 
 # 4.1 update 2 - works fine
 #set(tbb_ver "tbb41_20130116oss")
@@ -115,7 +122,6 @@ if(NOT EXISTS "${tbb_src_dir}")
 
   if(NOT tbb_untar_RESULT EQUAL 0 OR NOT EXISTS "${tbb_src_dir}")
     message(FATAL_ERROR "Failed to unpack TBB sources (${tbb_untar_RESULT} ${tbb_src_dir})")
-
   endif()
 endif()
 
@@ -133,12 +139,16 @@ list(APPEND lib_srcs "${tbb_src_dir}/src/rml/client/rml_tbb.cpp")
 if (WIN32)
   add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0
                 /D__TBB_BUILD=1
+                /DTBB_NO_LEGACY=1
                 /D_UNICODE
                 /DUNICODE
                 /DWINAPI_FAMILY=WINAPI_FAMILY_APP
                 /DDO_ITT_NOTIFY=0
                 /DUSE_WINTHREAD
+                /D_WIN32_WINNT=0x0602
+                /D__TBB_WIN32_USE_CL_BUILTINS
                ) # defines were copied from windows.cl.inc
+
 set(CMAKE_LINKER_FLAGS "${CMAKE_LINKER_FLAGS} /APPCONTAINER")
 else()
   add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0         #required
@@ -183,10 +193,10 @@ set(TBB_SOURCE_FILES ${TBB_SOURCE_FILES} "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_vers
 
 add_library(tbb ${TBB_SOURCE_FILES})
 
-if (WIN32)
+if (ARM AND WIN32)
   add_custom_command(TARGET tbb
                      PRE_BUILD
-                     COMMAND ${CMAKE_C_COMPILER} /nologo /TC /EP ${tbb_src_dir}\\src\\tbb\\win32-tbb-export.def /DTBB_NO_LEGACY /DUSE_WINTHREAD /D_CRT_SECURE_NO_DEPRECATE /D_WIN32_WINNT=0x0400 /D__TBB_BUILD=1 /I${tbb_src_dir}\\src /I${tbb_src_dir}\\include > "${tbb_src_dir}\\src\\tbb\\tbb.def"
+                     COMMAND ${CMAKE_C_COMPILER} /nologo /TC /EP ${tbb_src_dir}\\src\\tbb\\win32-tbb-export.def /DTBB_NO_LEGACY=1 /D_CRT_SECURE_NO_DEPRECATE /D__TBB_BUILD=1 /D_M_ARM=1 /I${tbb_src_dir}\\src /I${tbb_src_dir}\\include > "${tbb_src_dir}\\src\\tbb\\tbb.def"
                      WORKING_DIRECTORY ${tbb_src_dir}\\src\\tbb
                      COMMENT "Generating tbb.def file" VERBATIM
                     )
@@ -194,9 +204,7 @@ endif()
 
 if (WIN32)
   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEF:${tbb_src_dir}/src/tbb/tbb.def /DLL /MAP /fixed:no /INCREMENTAL:NO")
-endif()
-
-if (NOT WIN32)
+else()
   target_link_libraries(tbb c m dl)
 endif()
 
@@ -207,6 +215,7 @@ set_target_properties(tbb
   PROPERTIES OUTPUT_NAME tbb
   DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
   ARCHIVE_OUTPUT_DIRECTORY ${3P_LIBRARY_OUTPUT_PATH}
+  RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}
   )
 
 if(ENABLE_SOLUTION_FOLDERS)

From 2bc1d3709c40dfa326b1f2b6a0725c1ffa42f506 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 22 May 2013 09:50:54 -0700
Subject: [PATCH 28/75] GetProperty method for MSMF VideoCapture implemented.

---
 modules/highgui/src/cap_msmf.cpp | 103 ++++++++++++++-----------------
 1 file changed, 48 insertions(+), 55 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index 7af85382b..ae82b2c67 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -119,8 +119,8 @@ struct MediaType
     wchar_t *pMF_MT_AM_FORMAT_TYPEName;
     unsigned int MF_MT_FIXED_SIZE_SAMPLES;
     unsigned int MF_MT_VIDEO_NOMINAL_RANGE;
-    unsigned int MF_MT_FRAME_RATE;
-    unsigned int MF_MT_FRAME_RATE_low;
+    unsigned int MF_MT_FRAME_RATE_NUMERATOR;
+    unsigned int MF_MT_FRAME_RATE_DENOMINATOR;
     unsigned int MF_MT_PIXEL_ASPECT_RATIO;
     unsigned int MF_MT_PIXEL_ASPECT_RATIO_low;
     unsigned int MF_MT_ALL_SAMPLES_INDEPENDENT;
@@ -625,14 +625,17 @@ done:
     }
     return hr;
 }
+
 void LogUINT32AsUINT64New(const PROPVARIANT& var, UINT32 &uHigh, UINT32 &uLow)
 {
     Unpack2UINT32AsUINT64(var.uhVal.QuadPart, &uHigh, &uLow);
 }
+
 float OffsetToFloatNew(const MFOffset& offset)
 {
     return offset.value + (static_cast<float>(offset.fract) / 65536.0f);
 }
+
 HRESULT LogVideoAreaNew(const PROPVARIANT& var)
 {
     if (var.caub.cElems < sizeof(MFVideoArea))
@@ -641,6 +644,7 @@ HRESULT LogVideoAreaNew(const PROPVARIANT& var)
     }
     return S_OK;
 }
+
 HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, MediaType &out)
 {
     if (guid == MF_MT_DEFAULT_STRIDE)
@@ -660,8 +664,8 @@ HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, MediaTyp
     {
         UINT32 uHigh = 0, uLow = 0;
         LogUINT32AsUINT64New(var, uHigh, uLow);
-        out.MF_MT_FRAME_RATE = uHigh;
-        out.MF_MT_FRAME_RATE_low = uLow;
+        out.MF_MT_FRAME_RATE_NUMERATOR = uHigh;
+        out.MF_MT_FRAME_RATE_DENOMINATOR = uLow;
     }
     else
     if (guid == MF_MT_FRAME_RATE_RANGE_MAX)
@@ -693,9 +697,11 @@ HRESULT SpecialCaseAttributeValueNew(GUID guid, const PROPVARIANT& var, MediaTyp
     }
     return S_OK;
 }
+
 #ifndef IF_EQUAL_RETURN
 #define IF_EQUAL_RETURN(param, val) if(val == param) return L#val
 #endif
+
 LPCWSTR GetGUIDNameConstNew(const GUID& guid)
 {
     IF_EQUAL_RETURN(guid, MF_MT_MAJOR_TYPE);
@@ -875,6 +881,7 @@ MediaType FormatReader::Read(IMFMediaType *pType)
     }
     return out;
 }
+
 FormatReader::~FormatReader(void)
 {
 }
@@ -1880,6 +1887,7 @@ int videoDevice::findType(unsigned int size, unsigned int frameRate)
         return 0;
     return VN[0];
 }
+
 void videoDevice::buildLibraryofTypes()
 {
     unsigned int size;
@@ -1889,7 +1897,7 @@ void videoDevice::buildLibraryofTypes()
     for(; i != vd_CurrentFormats.end(); i++)
     {
         size = (*i).MF_MT_FRAME_SIZE;
-        framerate = (*i).MF_MT_FRAME_RATE;
+        framerate = (*i).MF_MT_FRAME_RATE_NUMERATOR;
         FrameRateMap FRM = vd_CaptureFormats[size];
         SUBTYPEMap STM = FRM[framerate];
         String subType((*i).pMF_MT_SUBTYPEName);
@@ -2187,8 +2195,8 @@ void MediaType::Clear()
     MF_MT_VIDEO_CHROMA_SITING = 0;
     MF_MT_FIXED_SIZE_SAMPLES = 0;
     MF_MT_VIDEO_NOMINAL_RANGE = 0;
-    MF_MT_FRAME_RATE = 0;
-    MF_MT_FRAME_RATE_low = 0;
+    MF_MT_FRAME_RATE_NUMERATOR = 0;
+    MF_MT_FRAME_RATE_DENOMINATOR = 0;
     MF_MT_PIXEL_ASPECT_RATIO = 0;
     MF_MT_PIXEL_ASPECT_RATIO_low = 0;
     MF_MT_ALL_SAMPLES_INDEPENDENT = 0;
@@ -3033,6 +3041,7 @@ protected:
     bool isOpened;
 
     HRESULT enumerateCaptureFormats(IMFMediaSource *pSource);
+    HRESULT getSourceDuration(IMFMediaSource *pSource, MFTIME *pDuration);
 };
 
 CvCaptureFile_MSMF::CvCaptureFile_MSMF():
@@ -3094,7 +3103,7 @@ bool CvCaptureFile_MSMF::open(const char* filename)
 
     if (SUCCEEDED(hr))
     {
-        hr = ImageGrabberThread::CreateInstance(&grabberThread, videoFileSource, -2, true);
+        hr = ImageGrabberThread::CreateInstance(&grabberThread, videoFileSource, (unsigned int)-2, true);
     }
 
     if (SUCCEEDED(hr))
@@ -3131,7 +3140,8 @@ bool CvCaptureFile_MSMF::setProperty(int property_id, double value)
 {
     // image capture properties
     bool handled = false;
-    int width, height, fourcc;
+    unsigned int width, height;
+    int fourcc;
     switch( property_id )
     {
     case CV_CAP_PROP_FRAME_WIDTH:
@@ -3239,57 +3249,26 @@ double CvCaptureFile_MSMF::getProperty(int property_id)
     case CV_CAP_PROP_FRAME_HEIGHT:
         return captureFormats[captureFormatIndex].height;
     case CV_CAP_PROP_FRAME_COUNT:
-        return 30;
+        {
+            MFTIME duration;
+            getSourceDuration(this->videoFileSource, &duration);
+            double fps = ((double)captureFormats[captureFormatIndex].MF_MT_FRAME_RATE_NUMERATOR) /
+            ((double)captureFormats[captureFormatIndex].MF_MT_FRAME_RATE_DENOMINATOR);
+            return (double)floor(((double)duration/1e7)*fps+0.5);
+        }
     case CV_CAP_PROP_FOURCC:
-        // FIXME: implement method in VideoInput back end
-        //return VI.getFourcc(index);
-        ;
+        return captureFormats[captureFormatIndex].MF_MT_SUBTYPE.Data1;
     case CV_CAP_PROP_FPS:
-        // FIXME: implement method in VideoInput back end
-        //return VI.getFPS(index);
-        ;
+        return ((double)captureFormats[captureFormatIndex].MF_MT_FRAME_RATE_NUMERATOR) /
+            ((double)captureFormats[captureFormatIndex].MF_MT_FRAME_RATE_DENOMINATOR);
     }
-    // video filter properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_BRIGHTNESS:
-    case CV_CAP_PROP_CONTRAST:
-    case CV_CAP_PROP_HUE:
-    case CV_CAP_PROP_SATURATION:
-    case CV_CAP_PROP_SHARPNESS:
-    case CV_CAP_PROP_GAMMA:
-    case CV_CAP_PROP_MONOCROME:
-    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
-    case CV_CAP_PROP_BACKLIGHT:
-    case CV_CAP_PROP_GAIN:
-        // FIXME: implement method in VideoInput back end
-        // if ( VI.getVideoSettingFilter(index, VI.getVideoPropertyFromCV(property_id), min_value,
-        //                               max_value, stepping_delta, current_value, flags,defaultValue) )
-        //     return (double)current_value;
-        return 0.;
-    }
-    // camera properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_PAN:
-    case CV_CAP_PROP_TILT:
-    case CV_CAP_PROP_ROLL:
-    case CV_CAP_PROP_ZOOM:
-    case CV_CAP_PROP_EXPOSURE:
-    case CV_CAP_PROP_IRIS:
-    case CV_CAP_PROP_FOCUS:
-    // FIXME: implement method in VideoInput back end
-    //     if (VI.getVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),min_value,
-    //          max_value,stepping_delta,current_value,flags,defaultValue) ) return (double)current_value;
-        return 0.;
-    }
-    // unknown parameter or value not available
+ 
     return -1;
 }
 
 bool CvCaptureFile_MSMF::grabFrame()
 {
-    DWORD waitResult;
+    DWORD waitResult = -1;
     if (isOpened)
     {
         SetEvent(grabberThread->getImageGrabber()->ig_hFrameGrabbed);
@@ -3305,7 +3284,7 @@ IplImage* CvCaptureFile_MSMF::retrieveFrame(int)
     unsigned int width = captureFormats[captureFormatIndex].width;
     unsigned int height = captureFormats[captureFormatIndex].height;
     unsigned int bytes = 3;
-    if( !frame || width != frame->width || height != frame->height )
+    if( !frame || (int)width != frame->width || (int)height != frame->height )
     {
         if (frame)
             cvReleaseImage( &frame );
@@ -3370,6 +3349,20 @@ done:
     return hr;
 }
 
+HRESULT CvCaptureFile_MSMF::getSourceDuration(IMFMediaSource *pSource, MFTIME *pDuration)
+{
+    *pDuration = 0;
+
+    IMFPresentationDescriptor *pPD = NULL;
+
+    HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
+    if (SUCCEEDED(hr))
+    {
+        hr = pPD->GetUINT64(MF_PD_DURATION, (UINT64*)pDuration);
+        pPD->Release();
+    }
+    return hr;
+}
 
 CvCapture* cvCreateCameraCapture_MSMF( int index )
 {
@@ -3508,12 +3501,12 @@ const GUID CvVideoWriter_MSMF::FourCC2GUID(int fourcc)
 }
 
 bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
-                       double _fps, CvSize frameSize, bool isColor )
+                       double _fps, CvSize frameSize, bool /*isColor*/ )
 {
     videoWidth = frameSize.width;
     videoHeight = frameSize.height;
     fps = _fps;
-    bitRate = fps*videoWidth*videoHeight; // 1-bit per pixel
+    bitRate = (UINT32)fps*videoWidth*videoHeight; // 1-bit per pixel
     encodingFormat = FourCC2GUID(fourcc);
     inputFormat = MFVideoFormat_RGB32;
 

From 34c659875293058f3db7c082d6c2917dc8ea190e Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Fri, 24 May 2013 06:34:42 -0700
Subject: [PATCH 29/75] Perf test failure fixes for Media Foundation.

---
 modules/highgui/perf/perf_input.cpp   | 10 ++++++++++
 modules/highgui/perf/perf_output.cpp  | 12 +++++++++---
 modules/highgui/perf/perf_precomp.hpp |  2 ++
 3 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/modules/highgui/perf/perf_input.cpp b/modules/highgui/perf/perf_input.cpp
index 0c1e8e0a7..414c85365 100644
--- a/modules/highgui/perf/perf_input.cpp
+++ b/modules/highgui/perf/perf_input.cpp
@@ -11,11 +11,21 @@ using std::tr1::get;
 
 typedef perf::TestBaseWithParam<String> VideoCapture_Reading;
 
+#if defined(HAVE_MSMF)
+// MPEG2 is not supported by Media Foundation yet
+// http://social.msdn.microsoft.com/Forums/en-US/mediafoundationdevelopment/thread/39a36231-8c01-40af-9af5-3c105d684429
+PERF_TEST_P(VideoCapture_Reading, ReadFile, testing::Values( "highgui/video/big_buck_bunny.avi",
+                                               "highgui/video/big_buck_bunny.mov",
+                                               "highgui/video/big_buck_bunny.mp4",
+                                               "highgui/video/big_buck_bunny.wmv" ) )
+
+#else
 PERF_TEST_P(VideoCapture_Reading, ReadFile, testing::Values( "highgui/video/big_buck_bunny.avi",
                                                "highgui/video/big_buck_bunny.mov",
                                                "highgui/video/big_buck_bunny.mp4",
                                                "highgui/video/big_buck_bunny.mpg",
                                                "highgui/video/big_buck_bunny.wmv" ) )
+#endif
 {
   string filename = getDataPath(GetParam());
 
diff --git a/modules/highgui/perf/perf_output.cpp b/modules/highgui/perf/perf_output.cpp
index 6428bb4f0..2adfe8965 100644
--- a/modules/highgui/perf/perf_output.cpp
+++ b/modules/highgui/perf/perf_output.cpp
@@ -22,10 +22,16 @@ PERF_TEST_P(VideoWriter_Writing, WriteFrame,
 {
   string filename = getDataPath(get<0>(GetParam()));
   bool isColor = get<1>(GetParam());
+  Mat image = imread(filename, 1);
+#if defined(HAVE_MSMF) && !defined(HAVE_VFW) && !defined(HAVE_FFMPEG) // VFW has greater priority
+  VideoWriter writer(cv::tempfile(".wmv"), CV_FOURCC('W', 'M', 'V', '3'),
+                            25, cv::Size(image.cols, image.rows), isColor);
+#else
+  VideoWriter writer(cv::tempfile(".avi"), CV_FOURCC('X', 'V', 'I', 'D'),
+                            25, cv::Size(image.cols, image.rows), isColor);
+#endif
 
-  VideoWriter writer(cv::tempfile(".avi"), CV_FOURCC('X', 'V', 'I', 'D'), 25, cv::Size(640, 480), isColor);
-
-  TEST_CYCLE() { Mat image = imread(filename, 1); writer << image; }
+  TEST_CYCLE() { image = imread(filename, 1); writer << image; }
 
   bool dummy = writer.isOpened();
   SANITY_CHECK(dummy);
diff --git a/modules/highgui/perf/perf_precomp.hpp b/modules/highgui/perf/perf_precomp.hpp
index 529187d3b..d6b28b6d2 100644
--- a/modules/highgui/perf/perf_precomp.hpp
+++ b/modules/highgui/perf/perf_precomp.hpp
@@ -21,6 +21,7 @@
     defined(HAVE_QUICKTIME)    || \
     defined(HAVE_AVFOUNDATION) || \
     defined(HAVE_FFMPEG)       || \
+    defined(HAVE_MSMF)         || \
     defined(HAVE_VFW)
     /*defined(HAVE_OPENNI) too specialized */ \
 
@@ -34,6 +35,7 @@
     defined(HAVE_QUICKTIME)    || \
     defined(HAVE_AVFOUNDATION) || \
     defined(HAVE_FFMPEG)       || \
+    defined(HAVE_MSMF)         || \
     defined(HAVE_VFW)
 #  define BUILD_WITH_VIDEO_OUTPUT_SUPPORT 1
 #else

From ee591efb9fbd6b1bc274fd56a39cca734900e7cb Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 29 May 2013 01:14:01 -0700
Subject: [PATCH 30/75] Build fix for Windows RT.

---
 modules/contrib/src/inputoutput.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/contrib/src/inputoutput.cpp b/modules/contrib/src/inputoutput.cpp
index d10d884c8..a711f242a 100644
--- a/modules/contrib/src/inputoutput.cpp
+++ b/modules/contrib/src/inputoutput.cpp
@@ -1,7 +1,7 @@
 
 #include "opencv2/contrib/contrib.hpp"
 
-#ifdef WIN32
+#if defined(WIN32) || defined(_WIN32)
     #include <windows.h>
     #include <tchar.h>
 #else

From 49903367608af0a89adb5ff83f61e2d7b9b7c514 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Thu, 6 Jun 2013 01:34:57 -0700
Subject: [PATCH 31/75] Base camera access sample for Windows RT added.

Microsoft Media Foundation Camera Sample for Windows RT added.
---
 .../C++/AdvancedCapture.xaml                  |   81 +
 .../C++/AdvancedCapture.xaml.cpp              | 1034 +++++
 .../C++/AdvancedCapture.xaml.h                |  103 +
 samples/winrt/ImageManipulations/C++/App.xaml |   30 +
 .../winrt/ImageManipulations/C++/App.xaml.cpp |  114 +
 .../winrt/ImageManipulations/C++/App.xaml.h   |   35 +
 .../ImageManipulations/C++/AudioCapture.xaml  |   62 +
 .../C++/AudioCapture.xaml.cpp                 |  366 ++
 .../C++/AudioCapture.xaml.h                   |   70 +
 .../ImageManipulations/C++/BasicCapture.xaml  |   87 +
 .../C++/BasicCapture.xaml.cpp                 |  535 +++
 .../C++/BasicCapture.xaml.h                   |   88 +
 .../ImageManipulations/C++/Constants.cpp      |   24 +
 .../winrt/ImageManipulations/C++/Constants.h  |   45 +
 .../ImageManipulations/C++/MainPage.xaml      |  166 +
 .../ImageManipulations/C++/MainPage.xaml.cpp  |  315 ++
 .../ImageManipulations/C++/MainPage.xaml.h    |  105 +
 .../ImageManipulations/C++/MediaCapture.sln   |   52 +
 .../C++/MediaCapture.vcxproj                  |  200 +
 .../C++/MediaCapture.vcxproj.filters          |   88 +
 .../C++/MediaExtensions/Common/AsyncCB.h      |   81 +
 .../C++/MediaExtensions/Common/BufferLock.h   |  102 +
 .../C++/MediaExtensions/Common/CritSec.h      |   62 +
 .../C++/MediaExtensions/Common/LinkList.h     |  516 +++
 .../C++/MediaExtensions/Common/OpQueue.h      |  222 +
 .../MediaExtensions/Grayscale/Grayscale.cpp   | 1783 ++++++++
 .../MediaExtensions/Grayscale/Grayscale.def   |    4 +
 .../C++/MediaExtensions/Grayscale/Grayscale.h |  266 ++
 .../Grayscale/Grayscale.vcxproj               |  313 ++
 .../Grayscale/Grayscale.vcxproj.filters       |   22 +
 .../Grayscale/GrayscaleTransform.idl          |   11 +
 .../C++/MediaExtensions/Grayscale/dllmain.cpp |   58 +
 .../C++/Package.appxmanifest                  |   39 +
 .../C++/assets/microsoft-sdk.png              |  Bin 0 -> 1583 bytes
 .../C++/assets/placeholder-sdk.png            |  Bin 0 -> 8991 bytes
 .../C++/assets/smallTile-sdk.png              |  Bin 0 -> 1248 bytes
 .../C++/assets/splash-sdk.png                 |  Bin 0 -> 5068 bytes
 .../C++/assets/squareTile-sdk.png             |  Bin 0 -> 2482 bytes
 .../C++/assets/storeLogo-sdk.png              |  Bin 0 -> 1550 bytes
 .../C++/assets/tile-sdk.png                   |  Bin 0 -> 2665 bytes
 .../C++/assets/windows-sdk.png                |  Bin 0 -> 2997 bytes
 .../C++/common/LayoutAwarePage.cpp            |  452 ++
 .../C++/common/LayoutAwarePage.h              |   88 +
 .../C++/common/StandardStyles.xaml            |  978 +++++
 .../C++/common/suspensionmanager.cpp          |  481 +++
 .../C++/common/suspensionmanager.h            |   50 +
 samples/winrt/ImageManipulations/C++/pch.cpp  |   16 +
 samples/winrt/ImageManipulations/C++/pch.h    |   23 +
 .../sample-utils/SampleTemplateStyles.xaml    |   51 +
 .../winrt/ImageManipulations/description.html |  238 ++
 ...a0-3e7e-46df-b80b-1692acc1c812Combined.css |    0
 .../ImageManipulations/description/Brand.css  | 3629 +++++++++++++++++
 .../description/Combined.css                  |    0
 .../description/Galleries.css                 |  418 ++
 .../ImageManipulations/description/Layout.css |  147 +
 ...69f54-1c43-4037-b90b-5f775f1d945fBrand.css |  303 ++
 .../description/iframedescription.css         |  179 +
 .../ImageManipulations/description/offline.js |   52 +
 samples/winrt/ImageManipulations/license.rtf  |   25 +
 59 files changed, 14209 insertions(+)
 create mode 100644 samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
 create mode 100644 samples/winrt/ImageManipulations/C++/App.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/App.xaml.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/App.xaml.h
 create mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
 create mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h
 create mode 100644 samples/winrt/ImageManipulations/C++/Constants.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/Constants.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MainPage.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/MainPage.xaml.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaCapture.sln
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/Package.appxmanifest
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/splash-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/tile-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/windows-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h
 create mode 100644 samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml
 create mode 100644 samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/common/suspensionmanager.h
 create mode 100644 samples/winrt/ImageManipulations/C++/pch.cpp
 create mode 100644 samples/winrt/ImageManipulations/C++/pch.h
 create mode 100644 samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml
 create mode 100644 samples/winrt/ImageManipulations/description.html
 create mode 100644 samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css
 create mode 100644 samples/winrt/ImageManipulations/description/Brand.css
 create mode 100644 samples/winrt/ImageManipulations/description/Combined.css
 create mode 100644 samples/winrt/ImageManipulations/description/Galleries.css
 create mode 100644 samples/winrt/ImageManipulations/description/Layout.css
 create mode 100644 samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
 create mode 100644 samples/winrt/ImageManipulations/description/iframedescription.css
 create mode 100644 samples/winrt/ImageManipulations/description/offline.js
 create mode 100644 samples/winrt/ImageManipulations/license.rtf

diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
new file mode 100644
index 000000000..4e6ebfd30
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
@@ -0,0 +1,81 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<common:LayoutAwarePage
+    x:Class="SDKSample.MediaCapture.AdvancedCapture"
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+    xmlns:local="using:$rootsnamespace$"
+    xmlns:common="using:SDKSample.Common"
+    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+    mc:Ignorable="d">
+
+    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="*"/>
+        </Grid.RowDefinitions>
+        <Grid x:Name="Input" Grid.Row="0">
+            <Grid.RowDefinitions>
+                <RowDefinition Height="Auto"/>
+                <RowDefinition Height="Auto"/>
+                <RowDefinition Height="*"/>
+            </Grid.RowDefinitions>
+            <TextBlock TextWrapping="Wrap" Grid.Row="0"  Text="This scenario shows how to enumerate cameras in the system. Choose a camera from the list to preview, record or take a photo from the chosen camera.  You can add the gray scale effect using the checkbox provided." Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left"/>
+            <StackPanel Orientation="Horizontal" Grid.Row="1" Margin="0,10,0,0">
+                <ListBox x:Name="EnumedDeviceList2" SelectionChanged="lstEnumedDevices_SelectionChanged" ></ListBox>
+                <Button x:Name="btnStartDevice2" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>
+                <Button x:Name="btnStartPreview2" Click="btnStartPreview_Click" IsEnabled="true"  Margin="0,0,10,0">StartPreview</Button>
+                <Button x:Name="btnStartStopRecord2" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>
+                <Button x:Name="btnTakePhoto2" Click="btnTakePhoto_Click" IsEnabled="false"  Margin="0,0,10,0">TakePhoto</Button>
+            </StackPanel>
+            <StackPanel Orientation="Horizontal" Grid.Row="2" Margin="0,10,0,0">
+                <CheckBox x:Name="chkAddRemoveEffect" Margin="0,0,10,0" Content="Grayscale Effect"  IsEnabled="False" Checked="chkAddRemoveEffect_Checked" Unchecked="chkAddRemoveEffect_Unchecked"/>
+            </StackPanel>
+        </Grid>
+
+        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
+            <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
+                <StackPanel>
+                    <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Preview' />
+                    <Canvas x:Name="previewCanvas2" Width="320"  Height="240" Background="Gray">
+                        <CaptureElement x:Name="previewElement2" Width="320" Height="240" />
+                    </Canvas>
+                </StackPanel>
+                <StackPanel>
+                    <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Video' />
+                    <Canvas x:Name='playbackCanvas2' Width='320' Height ='240' >
+                        <MediaElement  x:Name='playbackElement2'	  Width="320"  Height="240" />
+                    </Canvas>
+                </StackPanel>
+                <StackPanel>
+                    <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Images' />
+                    <Canvas x:Name="imageCanvas2" Width='320' Height ='240' >
+                        <Image x:Name="imageElement2"  Width="320"   Height="240"/>
+                    </Canvas>
+                </StackPanel>
+            </StackPanel>
+        </Grid>
+
+        <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts -->
+        <VisualStateManager.VisualStateGroups>
+            <VisualStateGroup>
+                <VisualState x:Name="FullScreenLandscape"/>
+                <VisualState x:Name="Filled"/>
+                <VisualState x:Name="FullScreenPortrait"/>
+                <VisualState x:Name="Snapped"/>
+            </VisualStateGroup>
+        </VisualStateManager.VisualStateGroups>
+    </Grid>
+
+</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
new file mode 100644
index 000000000..dc59acc2e
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
@@ -0,0 +1,1034 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// AdvancedCapture.xaml.cpp
+// Implementation of the AdvancedCapture class
+//
+
+#include "pch.h"
+#include "AdvancedCapture.xaml.h"
+
+using namespace SDKSample::MediaCapture;
+
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Navigation;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::System;
+using namespace Windows::Foundation;
+using namespace Platform;
+using namespace Windows::UI;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::UI::Xaml::Media;
+using namespace Windows::Storage;
+using namespace Windows::Media::MediaProperties;
+using namespace Windows::Storage::Streams;
+using namespace Windows::System;
+using namespace Windows::UI::Xaml::Media::Imaging;
+using namespace Windows::Devices::Enumeration;
+
+ref class ReencodeState sealed
+{
+public:
+    ReencodeState()
+    {
+    }
+
+    virtual ~ReencodeState()
+    {
+        if (InputStream != nullptr)
+        {
+            delete InputStream;
+        }
+        if (OutputStream != nullptr)
+        {
+            delete OutputStream;
+        }
+    }
+
+internal:
+    Windows::Storage::Streams::IRandomAccessStream ^InputStream;
+    Windows::Storage::Streams::IRandomAccessStream ^OutputStream;
+    Windows::Storage::StorageFile ^PhotoStorage;
+    Windows::Graphics::Imaging::BitmapDecoder ^Decoder;
+    Windows::Graphics::Imaging::BitmapEncoder ^Encoder;
+};
+
+AdvancedCapture::AdvancedCapture()
+{
+    InitializeComponent();
+    ScenarioInit();
+}
+
+/// <summary>
+/// Invoked when this page is about to be displayed in a Frame.
+/// </summary>
+/// <param name="e">Event data that describes how this page was reached.  The Parameter
+/// property is typically used to configure the page.</param>
+void AdvancedCapture::OnNavigatedTo(NavigationEventArgs^ e)
+{
+    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
+    // as NotifyUser()
+    rootPage = MainPage::Current;
+    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AdvancedCapture::SoundLevelChanged);
+
+    m_orientationChangedEventToken = Windows::Graphics::Display::DisplayProperties::OrientationChanged += ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(this, &AdvancedCapture::DisplayProperties_OrientationChanged);
+}
+
+void AdvancedCapture::OnNavigatedFrom(NavigationEventArgs^ e)
+{
+    Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
+    Windows::Graphics::Display::DisplayProperties::OrientationChanged  -= m_orientationChangedEventToken;
+}
+
+void  AdvancedCapture::ScenarioInit()
+{
+    rootPage = MainPage::Current;
+    btnStartDevice2->IsEnabled = true;
+    btnStartPreview2->IsEnabled = false;
+    btnStartStopRecord2->IsEnabled = false;
+    m_bRecording = false;
+    m_bPreviewing = false;
+    m_bEffectAdded = false;
+    btnStartStopRecord2->Content = "StartRecord";
+    btnTakePhoto2->IsEnabled = false;
+    previewElement2->Source = nullptr;
+    playbackElement2->Source = nullptr;
+    imageElement2->Source= nullptr;
+    ShowStatusMessage("");
+    chkAddRemoveEffect->IsChecked = false;
+    chkAddRemoveEffect->IsEnabled = false;
+    previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+    EnumerateWebcamsAsync();
+    m_bSuspended = false;
+}
+
+void AdvancedCapture::ScenarioReset()
+{
+    previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+    ScenarioInit();
+}
+
+void AdvancedCapture::SoundLevelChanged(Object^ sender, Object^ e)
+{
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
+    {    
+        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
+        {
+            ScenarioReset();
+        }
+        else
+        {
+            if (m_bRecording)
+            {
+                ShowStatusMessage("Stopping Record on invisibility");
+
+                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                {
+                    try
+                    {
+                        recordTask.get();
+                        m_bRecording = false;
+                    }
+                    catch (Exception ^e)
+                    {
+                        ShowExceptionMessage(e);
+                    }
+                });
+            }
+            if (m_bPreviewing)
+            {
+                ShowStatusMessage("Stopping Preview on invisibility");
+
+                create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
+                {
+                    try
+                    {
+                        previewTask.get();
+                        m_bPreviewing = false;
+
+                    }catch (Exception ^e)
+                    {
+                        ShowExceptionMessage(e);
+                    }
+                });
+            }
+        }
+    })));
+}
+
+void AdvancedCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
+{
+    try
+    {
+        if (m_bRecording)
+        {
+            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
+            {
+                try
+                {
+                    ShowStatusMessage("Stopping Record on exceeding max record duration");
+                    EnableButton(false, "StartStopRecord");
+                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
+                        }
+                        catch (Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                        }
+                    });
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+            })));
+        }
+    }
+    catch (Exception ^e)
+    {
+        m_bRecording = false;
+        SwitchRecordButtonContent();
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+    }
+}
+
+void AdvancedCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
+{
+    String ^message = "Fatal error" + currentFailure->Message;
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, 
+        ref new Windows::UI::Core::DispatchedHandler([this, message]()
+    {
+        ShowStatusMessage(message);
+    })));
+}
+
+void AdvancedCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        EnableButton(false, "StartDevice");
+        ShowStatusMessage("Starting device");
+        auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
+        m_mediaCaptureMgr = mediaCapture;
+        auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings();
+        auto chosenDevInfo = m_devInfoCollection->GetAt(EnumedDeviceList2->SelectedIndex);
+        settings->VideoDeviceId = chosenDevInfo->Id;
+        if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Back)
+        {
+            m_bRotateVideoOnOrientationChange = true;
+            m_bReversePreviewRotation = false;
+        }
+        else if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front)
+        {
+            m_bRotateVideoOnOrientationChange = true;
+            m_bReversePreviewRotation = true;
+        }
+        else
+        {
+            m_bRotateVideoOnOrientationChange = false;
+        }
+
+        create_task(mediaCapture->InitializeAsync(settings)).then([this](task<void> initTask)
+        {
+            try
+            {
+                initTask.get();
+
+                auto mediaCapture =  m_mediaCaptureMgr.Get();
+
+                DisplayProperties_OrientationChanged(nullptr);
+
+                EnableButton(true, "StartPreview");
+                EnableButton(true, "StartStopRecord");
+                EnableButton(true, "TakePhoto");
+                ShowStatusMessage("Device initialized successful");
+                chkAddRemoveEffect->IsEnabled = true;
+                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AdvancedCapture::RecordLimitationExceeded);
+                mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AdvancedCapture::Failed);
+            }
+            catch (Exception ^ e)
+            {
+                ShowExceptionMessage(e);
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+    }
+}
+
+void AdvancedCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    m_bPreviewing = false;
+    try
+    {
+        ShowStatusMessage("Starting preview");
+        EnableButton(false, "StartPreview");
+
+        auto mediaCapture = m_mediaCaptureMgr.Get();
+        previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Visible;
+        previewElement2->Source = mediaCapture;
+        create_task(mediaCapture->StartPreviewAsync()).then([this](task<void> previewTask)
+        {
+            try
+            {
+                previewTask.get();
+                m_bPreviewing = true;
+                ShowStatusMessage("Start preview successful");
+            }
+            catch (Exception ^e)
+            {
+                ShowExceptionMessage(e);
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        m_bPreviewing = false;
+        previewElement2->Source = nullptr;
+        EnableButton(true, "StartPreview");
+        ShowExceptionMessage(e);
+    }
+}
+
+void AdvancedCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        ShowStatusMessage("Taking photo");
+        EnableButton(false, "TakePhoto");
+        auto currentRotation = GetCurrentPhotoRotation();
+
+        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(TEMP_PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this, currentRotation](task<StorageFile^> getFileTask) 
+        {
+            try
+            {
+                auto tempPhotoStorageFile = getFileTask.get();
+                ShowStatusMessage("Create photo file successful");
+                ImageEncodingProperties^ imageProperties = ImageEncodingProperties::CreateJpeg();
+
+                create_task(m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, tempPhotoStorageFile)).then([this,tempPhotoStorageFile,currentRotation](task<void> photoTask)
+                {
+                    try
+                    {
+                        photoTask.get();
+
+                        ReencodePhotoAsync(tempPhotoStorageFile, currentRotation).then([this] (task<StorageFile^> reencodeImageTask)
+                        {
+                            try
+                            {
+                                auto photoStorageFile = reencodeImageTask.get();
+
+                                EnableButton(true, "TakePhoto");
+                                ShowStatusMessage("Photo taken");
+
+                                task<IRandomAccessStream^>(photoStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> getStreamTask)
+                                {
+                                    try
+                                    {
+                                        auto photoStream = getStreamTask.get();
+                                        ShowStatusMessage("File open successful");
+                                        auto bmpimg = ref new BitmapImage();
+
+                                        bmpimg->SetSource(photoStream);
+                                        imageElement2->Source = bmpimg;
+                                    }
+                                    catch (Exception^ e)
+                                    {
+                                        ShowExceptionMessage(e);
+                                        EnableButton(true, "TakePhoto");
+                                    }
+                                });
+                            }
+                            catch (Platform::Exception ^ e)
+                            {
+                                ShowExceptionMessage(e);
+                                EnableButton(true, "TakePhoto");
+                            }
+                        });
+                    }
+                    catch (Platform::Exception ^ e)
+                    {
+                        ShowExceptionMessage(e);
+                        EnableButton(true, "TakePhoto");
+                    }
+                });
+            }
+            catch (Exception^ e)
+            {
+                ShowExceptionMessage(e);
+                EnableButton(true, "TakePhoto");
+
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+        EnableButton(true, "TakePhoto");
+    }
+}
+
+void AdvancedCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        String ^fileName;
+        EnableButton(false, "StartStopRecord");
+
+        if (!m_bRecording)
+        {
+            ShowStatusMessage("Starting Record");
+
+            fileName = VIDEO_FILE_NAME;
+
+            PrepareForVideoRecording();
+
+            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
+            {
+                try
+                {
+                    this->m_recordStorageFile = fileTask.get();
+                    ShowStatusMessage("Create record file successful");
+
+                    MediaEncodingProfile^ recordProfile= nullptr;
+                    recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
+
+                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = true;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+
+                            ShowStatusMessage("Start Record successful");
+                        }
+                        catch (Exception ^e)
+                        {
+                            m_bRecording = true;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                            ShowExceptionMessage(e);
+                        }
+                    });
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+            });
+        }
+        else
+        {
+            ShowStatusMessage("Stopping Record");
+
+            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+            {
+                try
+                {
+                    recordTask.get();
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    SwitchRecordButtonContent();
+
+                    ShowStatusMessage("Stop record successful");
+                    if (!m_bSuspended)
+                    {
+                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
+                        {
+                            try
+                            {
+                                auto stream = streamTask.get();
+                                ShowStatusMessage("Record file opened");
+                                ShowStatusMessage(this->m_recordStorageFile->Path);
+                                playbackElement2->AutoPlay = true;
+                                playbackElement2->SetSource(stream, this->m_recordStorageFile->FileType);
+                                playbackElement2->Play();
+                            }
+                            catch (Exception ^e)
+                            {
+                                ShowExceptionMessage(e);
+                                m_bRecording = false;
+                                EnableButton(true, "StartStopRecord");
+                                SwitchRecordButtonContent();
+                            }
+                        });
+                    }
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    SwitchRecordButtonContent();
+                    ShowExceptionMessage(e);
+                }
+            });
+        }
+    }
+    catch (Platform::Exception^ e)
+    {
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+        m_bRecording = false;
+        SwitchRecordButtonContent();
+    }
+}
+void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
+{
+     if ( m_bPreviewing )
+     {
+         create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
+         {
+             try
+             {
+                 previewTask.get();
+                 m_bPreviewing = false;
+             }
+             catch (Exception ^e)
+             {
+                ShowExceptionMessage(e);
+             }
+         });
+    }
+ 
+    btnStartDevice2->IsEnabled = true;
+    btnStartPreview2->IsEnabled = false;
+    btnStartStopRecord2->IsEnabled = false;
+    m_bRecording = false;
+    btnStartStopRecord2->Content = "StartRecord";
+    btnTakePhoto2->IsEnabled = false;
+    previewElement2->Source = nullptr;
+    playbackElement2->Source = nullptr;
+    imageElement2->Source= nullptr;
+    chkAddRemoveEffect->IsEnabled = false;
+    chkAddRemoveEffect->IsChecked = false;
+    m_bEffectAdded = false;
+    m_bEffectAddedToRecord = false;
+    m_bEffectAddedToPhoto = false;
+    ShowStatusMessage("");
+}
+
+void AdvancedCapture::EnumerateWebcamsAsync()
+{
+    try
+    {
+        ShowStatusMessage("Enumerating Webcams...");
+        m_devInfoCollection = nullptr;
+
+        EnumedDeviceList2->Items->Clear();
+
+        task<DeviceInformationCollection^>(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture)).then([this](task<DeviceInformationCollection^> findTask)
+        {
+            try
+            {
+                m_devInfoCollection = findTask.get();
+                if (m_devInfoCollection == nullptr || m_devInfoCollection->Size == 0)
+                {
+                    ShowStatusMessage("No WebCams found.");
+                }
+                else
+                {
+                    for(unsigned int i = 0; i < m_devInfoCollection->Size; i++)
+                    {
+                        auto devInfo = m_devInfoCollection->GetAt(i);
+                        EnumedDeviceList2->Items->Append(devInfo->Name);
+                    }
+                    EnumedDeviceList2->SelectedIndex = 0;
+                    ShowStatusMessage("Enumerating Webcams completed successfully.");
+                    btnStartDevice2->IsEnabled = true;
+                }
+            }
+            catch (Exception ^e)
+            {
+                ShowExceptionMessage(e);
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+    }
+}
+
+void AdvancedCapture::AddEffectToImageStream()
+{    
+    auto mediaCapture = m_mediaCaptureMgr.Get();
+    Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
+
+    if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
+        (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical) && 
+        (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::RecordPhotoStreamsIdentical))
+    {
+        Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
+        if(props->Type->Equals("Image"))
+        {
+            //Switch to a video media type instead since we cant add an effect to a image media type
+            Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::IMediaEncodingProperties^>^ supportedPropsList = mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
+            {
+                unsigned int i = 0;
+                while (i<  supportedPropsList->Size)
+                {
+                    Windows::Media::MediaProperties::IMediaEncodingProperties^ props = supportedPropsList->GetAt(i);
+
+                    String^ s = props->Type;
+                    if(props->Type->Equals("Video"))
+                    {                                                    
+                        task<void>(mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Windows::Media::Capture::MediaStreamType::Photo,props)).then([this](task<void> changeTypeTask)
+                        {
+                            try
+                            {
+                                changeTypeTask.get();
+                                ShowStatusMessage("Change type on photo stream successful");
+                                //Now add the effect on the image pin
+                                task<void>(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
+                                {
+                                    try
+                                    {
+                                        effectTask3.get();
+                                        m_bEffectAddedToPhoto = true;
+                                        ShowStatusMessage("Adding effect to photo stream successful");                                                                    
+                                        chkAddRemoveEffect->IsEnabled = true;
+
+                                    }
+                                    catch(Exception ^e)
+                                    {
+                                        ShowExceptionMessage(e);
+                                        chkAddRemoveEffect->IsEnabled = true;
+                                        chkAddRemoveEffect->IsChecked = false;
+                                    }
+                                });
+
+                            }
+                            catch(Exception ^e)
+                            {
+                                ShowExceptionMessage(e);
+                                chkAddRemoveEffect->IsEnabled = true;
+                                chkAddRemoveEffect->IsChecked = false;																	
+
+                            }
+
+                        });
+                        break;
+
+                    }
+                    i++;
+                }
+            }
+        }
+        else
+        {
+            //Add the effect to the image pin if the type is already "Video"
+            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
+            {
+                try
+                {
+                    effectTask3.get();
+                    m_bEffectAddedToPhoto = true;
+                    ShowStatusMessage("Adding effect to photo stream successful");
+                    chkAddRemoveEffect->IsEnabled = true;
+
+                }
+                catch(Exception ^e)
+                {
+                    ShowExceptionMessage(e);
+                    chkAddRemoveEffect->IsEnabled = true;
+                    chkAddRemoveEffect->IsChecked = false;
+                }
+            });
+        }
+    }
+}
+
+
+
+void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        chkAddRemoveEffect->IsEnabled = false;
+        m_bEffectAdded = true;
+        create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask)
+        {
+            try
+            {
+                effectTask.get();
+
+                auto mediaCapture = m_mediaCaptureMgr.Get();
+                Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
+
+                ShowStatusMessage("Add effect successful to preview stream successful");                
+                if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) && 
+                    (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical))
+                {
+                    Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord);
+                    Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties  = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props);
+                    if(!videoEncodingProperties->Subtype->Equals("H264")) //Cant add an effect to an H264 stream
+                    {
+                        task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask2)
+                        {
+                            try
+                            {
+                                effectTask2.get();
+                                ShowStatusMessage("Add effect successful to record stream successful");
+                                m_bEffectAddedToRecord = true;
+                                AddEffectToImageStream();
+                                chkAddRemoveEffect->IsEnabled = true;
+                            } 
+                            catch(Exception ^e)
+                            {
+                                ShowExceptionMessage(e);
+                                chkAddRemoveEffect->IsEnabled = true;
+                                chkAddRemoveEffect->IsChecked = false;
+                            }
+                        }); 						
+                    }
+                    else
+                    {
+                        AddEffectToImageStream();
+                        chkAddRemoveEffect->IsEnabled = true;
+                    }
+
+                }                
+                else
+                {
+                    AddEffectToImageStream();
+                    chkAddRemoveEffect->IsEnabled = true;
+                }
+            }
+            catch (Exception ^e)
+            {
+                ShowExceptionMessage(e);
+                chkAddRemoveEffect->IsEnabled = true;
+                chkAddRemoveEffect->IsChecked = false;
+            }
+        });
+    }
+    catch (Platform::Exception ^e)
+    {
+        ShowExceptionMessage(e);
+        chkAddRemoveEffect->IsEnabled = true;
+        chkAddRemoveEffect->IsChecked = false;
+    }
+}
+
+void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        chkAddRemoveEffect->IsEnabled = false;
+        m_bEffectAdded = false;
+        create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> effectTask)
+        {
+            try
+            {
+                effectTask.get();
+                ShowStatusMessage("Remove effect from video preview stream successful");
+                if(m_bEffectAddedToRecord)
+                {
+                    task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoRecord)).then([this](task<void> effectTask)
+                    {
+                        try
+                        {
+                            effectTask.get();
+                            ShowStatusMessage("Remove effect from video record stream successful");
+                            m_bEffectAddedToRecord = false;
+                            if(m_bEffectAddedToPhoto)
+                            {
+                                task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
+                                {
+                                    try
+                                    {
+                                        effectTask.get();
+                                        ShowStatusMessage("Remove effect from Photo stream successful");
+                                        m_bEffectAddedToPhoto = false;
+
+                                    }
+                                    catch(Exception ^e)
+                                    {
+                                        ShowExceptionMessage(e);
+                                        chkAddRemoveEffect->IsEnabled = true;
+                                        chkAddRemoveEffect->IsChecked = true;				
+                                    }
+
+                                });
+                            }
+                            else
+                            {
+                            }
+                            chkAddRemoveEffect->IsEnabled = true;
+                        }
+                        catch(Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            chkAddRemoveEffect->IsEnabled = true;
+                            chkAddRemoveEffect->IsChecked = true;				
+
+                        }
+
+                    });
+
+                }
+                else if(m_bEffectAddedToPhoto)
+                {
+                    task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
+                    {
+                        try
+                        {
+                            effectTask.get();
+                            ShowStatusMessage("Remove effect from Photo stream successful");
+                            m_bEffectAddedToPhoto = false;
+
+                        }
+                        catch(Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            chkAddRemoveEffect->IsEnabled = true;
+                            chkAddRemoveEffect->IsChecked = true;				
+                        }
+
+                    });
+                }
+                else
+                {
+                    chkAddRemoveEffect->IsEnabled = true;
+                    chkAddRemoveEffect->IsChecked = true;	
+                }
+            }
+            catch (Exception ^e)
+            {
+                ShowExceptionMessage(e);
+                chkAddRemoveEffect->IsEnabled = true;
+                chkAddRemoveEffect->IsChecked = true;
+            }
+        });
+    }
+    catch (Platform::Exception ^e)
+    {
+        ShowExceptionMessage(e);
+        chkAddRemoveEffect->IsEnabled = true;
+        chkAddRemoveEffect->IsChecked = true;
+    }
+}
+
+void AdvancedCapture::ShowStatusMessage(Platform::String^ text)
+{
+    rootPage->NotifyUser(text, NotifyType::StatusMessage);
+}
+
+void AdvancedCapture::ShowExceptionMessage(Platform::Exception^ ex)
+{
+    rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
+}
+
+void AdvancedCapture::SwitchRecordButtonContent()
+{
+    if (m_bRecording)
+    {
+        btnStartStopRecord2->Content="StopRecord";
+    }
+    else
+    {
+        btnStartStopRecord2->Content="StartRecord";
+    }
+}
+
+void AdvancedCapture::EnableButton(bool enabled, String^ name)
+{
+    if (name->Equals("StartDevice"))
+    {
+        btnStartDevice2->IsEnabled = enabled;
+    }
+    else if (name->Equals("StartPreview"))
+    {
+        btnStartPreview2->IsEnabled = enabled;
+    }
+    else if (name->Equals("StartStopRecord"))
+    {
+        btnStartStopRecord2->IsEnabled = enabled;
+    }
+    else if (name->Equals("TakePhoto"))
+    {
+        btnTakePhoto2->IsEnabled = enabled;
+    }
+}
+
+task<Windows::Storage::StorageFile^> AdvancedCapture::ReencodePhotoAsync(
+    Windows::Storage::StorageFile ^tempStorageFile,
+    Windows::Storage::FileProperties::PhotoOrientation photoRotation)
+{
+    ReencodeState ^state = ref new ReencodeState();
+
+    return create_task(tempStorageFile->OpenAsync(Windows::Storage::FileAccessMode::Read)).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream)
+    {
+        state->InputStream = stream;
+        return Windows::Graphics::Imaging::BitmapDecoder::CreateAsync(state->InputStream);
+    }).then([state](Windows::Graphics::Imaging::BitmapDecoder ^decoder)
+    {
+        state->Decoder = decoder;
+        return Windows::Storage::KnownFolders::PicturesLibrary->CreateFileAsync(PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName);
+    }).then([state](Windows::Storage::StorageFile ^storageFile)
+    {
+        state->PhotoStorage = storageFile;
+        return state->PhotoStorage->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
+    }).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream)
+    {
+        state->OutputStream = stream;
+        state->OutputStream->Size = 0;
+        return Windows::Graphics::Imaging::BitmapEncoder::CreateForTranscodingAsync(state->OutputStream, state->Decoder);
+    }).then([state, photoRotation](Windows::Graphics::Imaging::BitmapEncoder ^encoder)
+    {
+        state->Encoder = encoder;
+        auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet();
+        properties->Insert("System.Photo.Orientation",
+            ref new Windows::Graphics::Imaging::BitmapTypedValue((unsigned short)photoRotation, Windows::Foundation::PropertyType::UInt16));
+        return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties));
+    }).then([state]()
+    {
+        return state->Encoder->FlushAsync();
+    }).then([tempStorageFile, state](task<void> previousTask)
+    {
+        auto result = state->PhotoStorage;
+        delete state;
+
+        tempStorageFile->DeleteAsync(Windows::Storage::StorageDeleteOption::PermanentDelete);
+
+        previousTask.get();
+
+        return result;
+    });
+}
+
+Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::GetCurrentPhotoRotation()
+{
+    bool counterclockwiseRotation = m_bReversePreviewRotation;
+
+    if (m_bRotateVideoOnOrientationChange)
+    {
+        return PhotoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation);
+    }
+    else
+    {
+        return Windows::Storage::FileProperties::PhotoOrientation::Normal;
+    }
+}
+
+void AdvancedCapture::PrepareForVideoRecording()
+{
+    Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get();
+    if (mediaCapture == nullptr)
+    {
+        return;
+    }
+
+    bool counterclockwiseRotation = m_bReversePreviewRotation;
+
+    if (m_bRotateVideoOnOrientationChange)
+    {
+        mediaCapture->SetRecordRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation));
+    }
+    else
+    {
+        mediaCapture->SetRecordRotation(Windows::Media::Capture::VideoRotation::None);
+    }
+}
+
+void AdvancedCapture::DisplayProperties_OrientationChanged(Platform::Object^ sender)
+{
+    Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get();
+    if (mediaCapture == nullptr)
+    {
+        return;
+    }
+
+    bool previewMirroring = mediaCapture->GetPreviewMirroring();
+    bool counterclockwiseRotation = (previewMirroring && !m_bReversePreviewRotation) ||
+        (!previewMirroring && m_bReversePreviewRotation);
+
+    if (m_bRotateVideoOnOrientationChange)
+    {
+        mediaCapture->SetPreviewRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation));
+    }
+    else
+    {
+        mediaCapture->SetPreviewRotation(Windows::Media::Capture::VideoRotation::None);
+    }
+}
+
+Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::PhotoRotationLookup(
+    Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise)
+{
+    switch (displayOrientation)
+    {
+    case Windows::Graphics::Display::DisplayOrientations::Landscape:
+        return Windows::Storage::FileProperties::PhotoOrientation::Normal;
+
+    case Windows::Graphics::Display::DisplayOrientations::Portrait:
+        return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate270:
+            Windows::Storage::FileProperties::PhotoOrientation::Rotate90;
+
+    case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
+        return Windows::Storage::FileProperties::PhotoOrientation::Rotate180;
+
+    case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped:
+        return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate90 :
+            Windows::Storage::FileProperties::PhotoOrientation::Rotate270;
+
+    default:
+        return Windows::Storage::FileProperties::PhotoOrientation::Unspecified;
+    }
+}
+
+Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup(
+    Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise)
+{
+    switch (displayOrientation)
+    {
+    case Windows::Graphics::Display::DisplayOrientations::Landscape:
+        return Windows::Media::Capture::VideoRotation::None;
+
+    case Windows::Graphics::Display::DisplayOrientations::Portrait:
+        return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise270Degrees :
+            Windows::Media::Capture::VideoRotation::Clockwise90Degrees;
+
+    case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
+        return Windows::Media::Capture::VideoRotation::Clockwise180Degrees;
+
+    case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped:
+        return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise90Degrees:
+            Windows::Media::Capture::VideoRotation::Clockwise270Degrees ;
+
+    default:
+        return Windows::Media::Capture::VideoRotation::None;
+    }
+}
+
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
new file mode 100644
index 000000000..83556b95e
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
@@ -0,0 +1,103 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// AdvancedCapture.xaml.h
+// Declaration of the AdvancedCapture class
+//
+
+#pragma once
+
+#include "pch.h"
+#include "AdvancedCapture.g.h"
+#include "MainPage.xaml.h"
+#include <ppl.h>
+
+#define VIDEO_FILE_NAME "video.mp4"
+#define PHOTO_FILE_NAME "photo.jpg"
+#define TEMP_PHOTO_FILE_NAME "photoTmp.jpg"
+
+using namespace concurrency;
+using namespace Windows::Devices::Enumeration;
+
+namespace SDKSample
+{
+    namespace MediaCapture
+    {
+        /// <summary>
+        /// An empty page that can be used on its own or navigated to within a Frame.
+        /// </summary>
+        [Windows::Foundation::Metadata::WebHostHidden]
+        public ref class AdvancedCapture sealed
+        {
+        public:
+            AdvancedCapture();
+
+        protected:
+            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+
+        private:
+            MainPage^ rootPage;
+            void ScenarioInit();
+            void ScenarioReset();
+
+            void SoundLevelChanged(Object^ sender, Object^ e);
+            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
+            void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
+
+            void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+
+            void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+
+            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+
+            void btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+
+            void lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
+            void EnumerateWebcamsAsync();
+
+            void chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void AddEffectToImageStream();
+
+            void ShowStatusMessage(Platform::String^ text);
+            void ShowExceptionMessage(Platform::Exception^ ex);
+
+            void EnableButton(bool enabled, Platform::String ^name);
+            void SwitchRecordButtonContent();
+
+            task<Windows::Storage::StorageFile^> ReencodePhotoAsync(
+                Windows::Storage::StorageFile ^tempStorageFile,
+                Windows::Storage::FileProperties::PhotoOrientation photoRotation);
+            Windows::Storage::FileProperties::PhotoOrientation GetCurrentPhotoRotation();
+            void PrepareForVideoRecording();
+            void DisplayProperties_OrientationChanged(Platform::Object^ sender);
+            Windows::Storage::FileProperties::PhotoOrientation PhotoRotationLookup(
+                Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise);
+            Windows::Media::Capture::VideoRotation VideoRotationLookup(
+                Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise);
+
+            Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
+            Windows::Storage::StorageFile^ m_recordStorageFile;
+            bool m_bRecording;
+            bool m_bEffectAdded;
+            bool m_bEffectAddedToRecord;
+            bool m_bEffectAddedToPhoto;
+            bool m_bSuspended;
+            bool m_bPreviewing;
+            DeviceInformationCollection^ m_devInfoCollection;
+            Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
+            bool m_bRotateVideoOnOrientationChange;
+            bool m_bReversePreviewRotation;
+            Windows::Foundation::EventRegistrationToken m_orientationChangedEventToken;
+        };
+    }
+}
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml b/samples/winrt/ImageManipulations/C++/App.xaml
new file mode 100644
index 000000000..2edfd7790
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/App.xaml
@@ -0,0 +1,30 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
+    x:Class="SDKSample.App"
+    RequestedTheme="Light">
+    <Application.Resources>
+
+        <ResourceDictionary>
+            <ResourceDictionary.MergedDictionaries>
+                <!-- 
+                    Styles that define common aspects of the platform look and feel
+                    Required by Visual Studio project and item templates
+                 -->
+                <ResourceDictionary Source="Common/StandardStyles.xaml"/>
+                <ResourceDictionary Source="Sample-Utils/SampleTemplateStyles.xaml"/>
+            </ResourceDictionary.MergedDictionaries>
+        </ResourceDictionary>
+    </Application.Resources>
+</Application>
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml.cpp b/samples/winrt/ImageManipulations/C++/App.xaml.cpp
new file mode 100644
index 000000000..ef733a1cc
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/App.xaml.cpp
@@ -0,0 +1,114 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// App.xaml.cpp
+// Implementation of the App.xaml class.
+//
+
+#include "pch.h"
+#include "MainPage.xaml.h"
+#include "Common\SuspensionManager.h"
+
+using namespace SDKSample;
+using namespace SDKSample::Common;
+
+using namespace Concurrency;
+using namespace Platform;
+using namespace Windows::ApplicationModel;
+using namespace Windows::ApplicationModel::Activation;
+using namespace Windows::Foundation;
+using namespace Windows::Foundation::Collections;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Controls::Primitives;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::UI::Xaml::Input;
+using namespace Windows::UI::Xaml::Interop;
+using namespace Windows::UI::Xaml::Media;
+using namespace Windows::UI::Xaml::Navigation;
+
+/// <summary>
+/// Initializes the singleton application object.  This is the first line of authored code
+/// executed, and as such is the logical equivalent of main() or WinMain().
+/// </summary>
+App::App()
+{
+    InitializeComponent();
+    this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
+}
+
+/// <summary>
+/// Invoked when the application is launched normally by the end user.  Other entry points will
+/// be used when the application is launched to open a specific file, to display search results,
+/// and so forth.
+/// </summary>
+/// <param name="pArgs">Details about the launch request and process.</param>
+void App::OnLaunched(LaunchActivatedEventArgs^ pArgs)
+{
+    this->LaunchArgs = pArgs;
+
+    // Do not repeat app initialization when already running, just ensure that
+    // the window is active
+    if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running)
+    {
+        Window::Current->Activate();
+        return;
+    }
+
+    // Create a Frame to act as the navigation context and associate it with
+    // a SuspensionManager key
+    auto rootFrame = ref new Frame();
+    SuspensionManager::RegisterFrame(rootFrame, "AppFrame");
+
+    auto prerequisite = task<void>([](){});
+    if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated)
+    {
+        // Restore the saved session state only when appropriate, scheduling the
+        // final launch steps after the restore is complete
+        prerequisite = SuspensionManager::RestoreAsync();
+    }
+    prerequisite.then([=]()
+    {
+        // When the navigation stack isn't restored navigate to the first page,
+        // configuring the new page by passing required information as a navigation
+        // parameter
+        if (rootFrame->Content == nullptr)
+        {
+            if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
+            {
+                throw ref new FailureException("Failed to create initial page");
+            }
+        }
+
+        // Place the frame in the current Window and ensure that it is active
+        Window::Current->Content = rootFrame;
+        Window::Current->Activate();
+    }, task_continuation_context::use_current());
+}
+
+/// <summary>
+/// Invoked when application execution is being suspended.  Application state is saved
+/// without knowing whether the application will be terminated or resumed with the contents
+/// of memory still intact.
+/// </summary>
+/// <param name="sender">The source of the suspend request.</param>
+/// <param name="e">Details about the suspend request.</param>
+void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
+{
+    (void) sender;	// Unused parameter
+
+    auto deferral = e->SuspendingOperation->GetDeferral();
+    SuspensionManager::SaveAsync().then([=]()
+    {
+        deferral->Complete();
+    });
+}
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml.h b/samples/winrt/ImageManipulations/C++/App.xaml.h
new file mode 100644
index 000000000..a8b606424
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/App.xaml.h
@@ -0,0 +1,35 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// App.xaml.h
+// Declaration of the App.xaml class.
+//
+
+#pragma once
+
+#include "pch.h"
+#include "App.g.h"
+#include "MainPage.g.h"
+
+namespace SDKSample
+{
+    ref class App
+    {
+    internal:
+        App();
+        virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs);
+        Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs;
+    protected:
+        virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override;
+    private:
+        Windows::UI::Xaml::Controls::Frame^ rootFrame;
+    };
+}
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml
new file mode 100644
index 000000000..be65bcd8c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml
@@ -0,0 +1,62 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<common:LayoutAwarePage
+    x:Class="SDKSample.MediaCapture.AudioCapture"
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+    xmlns:local="using:$rootsnamespace$"
+    xmlns:common="using:SDKSample.Common"
+    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+    mc:Ignorable="d">
+
+    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="*"/>
+        </Grid.RowDefinitions>
+        <Grid x:Name="Input" Grid.Row="0">
+            <Grid.RowDefinitions>
+                <RowDefinition Height="Auto"/>
+                <RowDefinition Height="*"/>
+            </Grid.RowDefinitions>
+          <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left"  >
+            This scenario shows how to do an audio only capture using the default microphone. Click on StartRecord to start recording.
+          </TextBlock>
+          <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
+            <Button x:Name="btnStartDevice3" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>            
+            <Button x:Name="btnStartStopRecord3" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>            
+          </StackPanel>
+        </Grid>
+
+        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
+          <StackPanel>
+            <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Audio' />
+            <Canvas x:Name='playbackCanvas3' Width='320' Height ='240' >
+              <MediaElement  x:Name='playbackElement3'	  Width="320"  Height="240" Margin="10,5,10,5"/>
+            </Canvas>
+          </StackPanel>
+        </Grid>
+
+        <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts -->
+        <VisualStateManager.VisualStateGroups>
+            <VisualStateGroup>
+                <VisualState x:Name="FullScreenLandscape"/>
+                <VisualState x:Name="Filled"/>
+                <VisualState x:Name="FullScreenPortrait"/>
+                <VisualState x:Name="Snapped"/>
+            </VisualStateGroup>
+        </VisualStateManager.VisualStateGroups>
+    </Grid>
+
+</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
new file mode 100644
index 000000000..37fc379d3
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
@@ -0,0 +1,366 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// AudioCapture.xaml.cpp
+// Implementation of the AudioCapture class
+//
+
+#include "pch.h"
+#include "AudioCapture.xaml.h"
+#include <ppl.h>
+using namespace concurrency;
+
+using namespace SDKSample::MediaCapture;
+
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Navigation;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::System;
+using namespace Windows::Foundation;
+using namespace Platform;
+using namespace Windows::UI;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::UI::Xaml::Media;
+using namespace Windows::Storage;
+using namespace Windows::Media::MediaProperties;
+using namespace Windows::Storage::Streams;
+using namespace Windows::System;
+using namespace Windows::UI::Xaml::Media::Imaging;
+
+
+AudioCapture::AudioCapture()
+{
+    InitializeComponent();
+    ScenarioInit();
+}
+
+/// <summary>
+/// Invoked when this page is about to be displayed in a Frame.
+/// </summary>
+/// <param name="e">Event data that describes how this page was reached.  The Parameter
+/// property is typically used to configure the page.</param>
+void AudioCapture::OnNavigatedTo(NavigationEventArgs^ e)
+{
+    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
+    // as NotifyUser()
+    rootPage = MainPage::Current;
+    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AudioCapture::SoundLevelChanged);
+}
+
+void AudioCapture::OnNavigatedFrom(NavigationEventArgs^ e)
+{
+    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
+    // as NotifyUser()
+    Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
+}
+
+void  AudioCapture::ScenarioInit()
+{
+    try
+    {
+        rootPage = MainPage::Current;
+        btnStartDevice3->IsEnabled = true;
+        btnStartStopRecord3->IsEnabled = false;
+        m_bRecording = false;
+        playbackElement3->Source = nullptr;
+        m_bSuspended = false;
+        ShowStatusMessage("");
+    }
+    catch (Exception ^e)
+    {
+        ShowExceptionMessage(e);
+    }
+
+}
+
+void AudioCapture::ScenarioReset()
+{
+    ScenarioInit();
+}
+
+
+void AudioCapture::SoundLevelChanged(Object^ sender, Object^ e)
+{
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
+    {    
+        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
+        {
+            ScenarioReset();
+        }
+        else
+        {
+            if (m_bRecording)
+            {
+                ShowStatusMessage("Stopping Record on invisibility");
+
+                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                {
+                    try
+                    {
+                        recordTask.get();
+                        m_bRecording = false;
+                    }catch (Exception ^e)
+                    {
+                        ShowExceptionMessage(e);
+                    }
+                });
+            }
+        }
+    })));
+}
+
+void AudioCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
+{
+    try
+    {
+        if (m_bRecording)
+        {
+            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this](){
+                try
+                {
+                    ShowStatusMessage("Stopping Record on exceeding max record duration");
+                    EnableButton(false, "StartStopRecord");
+                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
+                        }
+                        catch (Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                        }
+                    });
+
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+
+            })));
+        }
+    }
+    catch (Exception ^e)
+    {
+        m_bRecording = false;
+        SwitchRecordButtonContent();
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+    }
+}
+
+void AudioCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
+{
+    String ^message = "Fatal error: " + currentFailure->Message;
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, 
+        ref new Windows::UI::Core::DispatchedHandler([this, message]()
+    {
+        ShowStatusMessage(message);
+    })));
+}
+
+void AudioCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        EnableButton(false, "StartDevice");
+        ShowStatusMessage("Starting device");
+        auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
+        m_mediaCaptureMgr = mediaCapture;
+        auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings();
+        settings->StreamingCaptureMode = Windows::Media::Capture::StreamingCaptureMode::Audio;
+        create_task(mediaCapture->InitializeAsync()).then([this](task<void> initTask)
+        {
+            try
+            {
+                initTask.get();
+
+                auto mediaCapture = m_mediaCaptureMgr.Get();
+                EnableButton(true, "StartPreview");
+                EnableButton(true, "StartStopRecord");
+                EnableButton(true, "TakePhoto");
+                ShowStatusMessage("Device initialized successful");
+                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AudioCapture::RecordLimitationExceeded);
+                mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AudioCapture::Failed);
+            }
+            catch (Exception ^ e)
+            {
+                ShowExceptionMessage(e);
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+    }
+}
+
+void AudioCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        String ^fileName;
+        EnableButton(false, "StartStopRecord");
+
+        if (!m_bRecording)
+        {
+            ShowStatusMessage("Starting Record");
+
+            fileName = AUDIO_FILE_NAME;
+
+            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
+            {
+                try
+                {
+                    this->m_recordStorageFile = fileTask.get();
+                    ShowStatusMessage("Create record file successful");
+
+                    MediaEncodingProfile^ recordProfile= nullptr;
+                    recordProfile = MediaEncodingProfile::CreateM4a(Windows::Media::MediaProperties::AudioEncodingQuality::Auto);
+
+                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = true;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+
+                            ShowStatusMessage("Start Record successful");
+
+
+                        }catch (Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                        }
+                    });
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+            }
+            );
+        }
+        else
+        {
+            ShowStatusMessage("Stopping Record");
+
+            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void>)
+            {
+                try
+                {
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    SwitchRecordButtonContent();
+
+                    ShowStatusMessage("Stop record successful");
+                    if (!m_bSuspended)
+                    {
+                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
+                        {
+                            try
+                            {
+                                ShowStatusMessage("Record file opened");
+                                auto stream = streamTask.get();
+                                ShowStatusMessage(this->m_recordStorageFile->Path);
+                                playbackElement3->AutoPlay = true;
+                                playbackElement3->SetSource(stream, this->m_recordStorageFile->FileType);
+                                playbackElement3->Play();
+                            }
+                            catch (Exception ^e)
+                            {
+                                ShowExceptionMessage(e);
+                                m_bRecording = false;
+                                SwitchRecordButtonContent();
+                                EnableButton(true, "StartStopRecord");
+                            }
+                        });
+                    }
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+            });
+        }
+    }
+    catch (Platform::Exception^ e)
+    {
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+        m_bRecording = false;
+        SwitchRecordButtonContent();
+    }
+}
+
+
+void AudioCapture::ShowStatusMessage(Platform::String^ text)
+{
+    rootPage->NotifyUser(text, NotifyType::StatusMessage);
+}
+
+void AudioCapture::ShowExceptionMessage(Platform::Exception^ ex)
+{
+    rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
+}
+
+void AudioCapture::SwitchRecordButtonContent()
+{
+    {
+        if (m_bRecording)
+        {
+            btnStartStopRecord3->Content="StopRecord";
+        }
+        else
+        {
+            btnStartStopRecord3->Content="StartRecord";
+        }
+    }
+}
+void AudioCapture::EnableButton(bool enabled, String^ name)
+{
+    if (name->Equals("StartDevice"))
+    {
+        btnStartDevice3->IsEnabled = enabled;
+    }
+
+    else if (name->Equals("StartStopRecord"))
+    {
+        btnStartStopRecord3->IsEnabled = enabled;
+    }
+
+}
+
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
new file mode 100644
index 000000000..b75efdc72
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
@@ -0,0 +1,70 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// AudioCapture.xaml.h
+// Declaration of the AudioCapture class
+//
+
+#pragma once
+
+#include "pch.h"
+#include "AudioCapture.g.h"
+#include "MainPage.xaml.h"
+
+#define AUDIO_FILE_NAME "audio.mp4"
+
+namespace SDKSample
+{
+    namespace MediaCapture
+    {
+        /// <summary>
+        /// An empty page that can be used on its own or navigated to within a Frame.
+        /// </summary>
+    	[Windows::Foundation::Metadata::WebHostHidden]
+        public ref class AudioCapture sealed
+        {
+        public:
+            AudioCapture();
+    
+        protected:
+            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+        private:
+            MainPage^ rootPage;
+    
+            void ScenarioInit();
+            void ScenarioReset();
+    
+            void SoundLevelChanged(Object^ sender, Object^ e);
+            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
+            void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
+    
+            void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void ShowStatusMessage(Platform::String^ text);
+            void ShowExceptionMessage(Platform::Exception^ ex);
+    
+            void EnableButton(bool enabled, Platform::String ^name);
+            void SwitchRecordButtonContent();
+    
+            Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
+            Windows::Storage::StorageFile^ m_photoStorageFile;
+            Windows::Storage::StorageFile^ m_recordStorageFile;
+            bool m_bRecording;
+            bool m_bSuspended;
+            Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
+        };
+    }
+}
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml
new file mode 100644
index 000000000..2cc0b0a5f
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml
@@ -0,0 +1,87 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<common:LayoutAwarePage
+    x:Class="SDKSample.MediaCapture.BasicCapture"
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+    xmlns:local="using:$rootsnamespace$"
+    xmlns:common="using:SDKSample.Common"
+    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+    mc:Ignorable="d">
+
+    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"/>
+            <RowDefinition Height="*"/>
+        </Grid.RowDefinitions>
+        <Grid x:Name="Input" Grid.Row="0">
+            <Grid.RowDefinitions>
+              <RowDefinition Height="Auto"/>
+              <RowDefinition Height="Auto"/>
+                <RowDefinition Height="*"/>
+            </Grid.RowDefinitions>
+            <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" >
+              This scenario demonstrates how to use the MediaCapture API to preview the camera stream, record a video, and take a picture using default initialization settings.
+              You can also adjust the brightness and contrast.
+            </TextBlock>
+            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
+              <Button x:Name="btnStartDevice1" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>
+              <Button x:Name="btnStartPreview1" Click="btnStartPreview_Click" IsEnabled="true"  Margin="0,0,10,0">StartPreview</Button>
+              <Button x:Name="btnStartStopRecord1" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>
+              <Button x:Name="btnTakePhoto1" Click="btnTakePhoto_Click" IsEnabled="false"  Margin="0,0,10,0">TakePhoto</Button>                        
+            </StackPanel>
+          <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="2">
+            <TextBlock TextWrapping="Wrap" Text="Brightness" Style="{StaticResource BasicTextStyle}"  Margin="0,0,10,0" VerticalAlignment="Center"/>
+            <Slider x:Name="sldBrightness"   IsEnabled="False" ValueChanged="sldBrightness_ValueChanged"  Width="207" Margin="0,0,10,0"/>
+            <TextBlock TextWrapping="Wrap" Text="Contrast" Style="{StaticResource BasicTextStyle}"  Margin="0,0,10,0" VerticalAlignment="Center" />
+            <Slider x:Name="sldContrast"   IsEnabled="False" ValueChanged="sldContrast_ValueChanged"  Width="207"  Margin="0,0,10,0"/>
+          </StackPanel>
+        </Grid>
+
+        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
+          <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
+            <StackPanel>
+              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Preview' />
+              <Canvas x:Name="previewCanvas1" Width="320"  Height="240" Background="Gray">
+                <CaptureElement x:Name="previewElement1" Width="320" Height="240" />
+              </Canvas>
+            </StackPanel>
+            <StackPanel>
+              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Video' />
+              <Canvas x:Name='playbackCanvas1' Width='320' Height ='240' >
+                <MediaElement  x:Name='playbackElement1'	  Width="320"  Height="240" />
+              </Canvas>
+            </StackPanel>
+            <StackPanel>
+              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Images' />
+              <Canvas x:Name="imageCanvas1" Width='320' Height ='240' >
+                <Image x:Name="imageElement1"  Width="320"   Height="240"/>
+              </Canvas>
+            </StackPanel>
+          </StackPanel>
+
+        </Grid>
+
+        <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts -->
+        <VisualStateManager.VisualStateGroups>
+            <VisualStateGroup>
+                <VisualState x:Name="FullScreenLandscape"/>
+                <VisualState x:Name="Filled"/>
+                <VisualState x:Name="FullScreenPortrait"/>
+                <VisualState x:Name="Snapped"/>
+            </VisualStateGroup>
+        </VisualStateManager.VisualStateGroups>
+    </Grid>
+
+</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
new file mode 100644
index 000000000..f385fa9a7
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
@@ -0,0 +1,535 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// BasicCapture.xaml.cpp
+// Implementation of the BasicCapture class
+//
+
+#include "pch.h"
+#include "BasicCapture.xaml.h"
+#include "ppl.h"
+
+using namespace Windows::System;
+using namespace Windows::Foundation;
+using namespace Platform;
+using namespace Windows::UI;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Navigation;
+using namespace Windows::UI::Xaml::Data;
+using namespace Windows::UI::Xaml::Media;
+using namespace Windows::Storage;
+using namespace Windows::Media::MediaProperties;
+using namespace Windows::Storage::Streams;
+using namespace Windows::System;
+using namespace Windows::UI::Xaml::Media::Imaging;
+
+using namespace SDKSample::MediaCapture;
+using namespace concurrency;
+
+
+BasicCapture::BasicCapture()
+{
+    InitializeComponent();
+    ScenarioInit();
+}
+
+/// <summary>
+/// Invoked when this page is about to be displayed in a Frame.
+/// </summary>
+/// <param name="e">Event data that describes how this page was reached.  The Parameter
+/// property is typically used to configure the page.</param>
+void BasicCapture::OnNavigatedTo(NavigationEventArgs^ e)
+{
+    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
+    // as NotifyUser()
+    rootPage = MainPage::Current;
+    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &BasicCapture::SoundLevelChanged);
+}
+
+void BasicCapture::OnNavigatedFrom(NavigationEventArgs^ e)
+{
+    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
+    // as NotifyUser()
+
+    Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
+    m_currentScenarioLoaded = false;
+}
+
+
+void  BasicCapture::ScenarioInit()
+{
+    try
+    {
+        btnStartDevice1->IsEnabled = true;
+        btnStartPreview1->IsEnabled = false;
+        btnStartStopRecord1->IsEnabled = false;
+        m_bRecording = false;
+        m_bPreviewing = false;
+        btnStartStopRecord1->Content = "StartRecord";
+        btnTakePhoto1->IsEnabled = false;
+        previewElement1->Source = nullptr;
+        playbackElement1->Source = nullptr;
+        imageElement1->Source= nullptr;
+        sldBrightness->IsEnabled = false;
+        sldContrast->IsEnabled = false;
+        m_bSuspended = false;
+        previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+
+    }
+    catch (Exception ^e)
+    {
+        ShowExceptionMessage(e);
+    }
+
+}
+
+void BasicCapture::ScenarioReset()
+{
+    previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+    ScenarioInit();
+}
+
+void BasicCapture::SoundLevelChanged(Object^ sender, Object^ e)
+{
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
+    {    
+        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
+        {
+            ScenarioReset();
+        }
+        else
+        {
+            if (m_bRecording)
+            {
+                ShowStatusMessage("Stopping Record on invisibility");
+
+                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                {
+                    m_bRecording = false;
+                });
+            }
+            if (m_bPreviewing)
+            {
+                ShowStatusMessage("Stopping Preview on invisibility");
+
+                create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
+                {
+                    try
+                    {
+                        previewTask.get();
+                        m_bPreviewing = false;
+                    }
+                    catch (Exception ^e)
+                    {
+                        ShowExceptionMessage(e);
+                    }
+                });
+            }
+        }
+    })));
+}
+
+void BasicCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
+{
+    try
+    {
+        if (m_bRecording)
+        {
+            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this](){
+                try
+                {
+                    ShowStatusMessage("Stopping Record on exceeding max record duration");
+                    EnableButton(false, "StartStopRecord");
+                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
+                        }
+                        catch (Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                            m_bRecording = false;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+                        }
+                    });
+
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+
+            })));
+        }
+    }
+    catch (Exception ^e)
+    {
+        m_bRecording = false;
+        SwitchRecordButtonContent();
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+    }
+}
+
+void BasicCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
+{
+    String ^message = "Fatal error: " + currentFailure->Message;
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
+        ref new Windows::UI::Core::DispatchedHandler([this, message]()
+    {
+        ShowStatusMessage(message);
+    })));
+}
+
+void BasicCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        EnableButton(false, "StartDevice");
+        ShowStatusMessage("Starting device");
+        auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
+        m_mediaCaptureMgr = mediaCapture;
+        create_task(mediaCapture->InitializeAsync()).then([this](task<void> initTask)
+        {
+            try
+            {
+                initTask.get();
+
+                auto mediaCapture = m_mediaCaptureMgr.Get();
+                EnableButton(true, "StartPreview");
+                EnableButton(true, "StartStopRecord");
+                EnableButton(true, "TakePhoto");
+                ShowStatusMessage("Device initialized successful");
+                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &BasicCapture::RecordLimitationExceeded);
+                mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &BasicCapture::Failed);
+            }
+            catch (Exception ^ e)
+            {
+                ShowExceptionMessage(e);
+            }
+        }
+        );
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+    }
+}
+
+void BasicCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    m_bPreviewing = false;
+    try
+    {
+        ShowStatusMessage("Starting preview");
+        EnableButton(false, "StartPreview");
+        auto mediaCapture = m_mediaCaptureMgr.Get();
+
+        previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Visible;
+        previewElement1->Source = mediaCapture;
+        create_task(mediaCapture->StartPreviewAsync()).then([this](task<void> previewTask)
+        {
+            try
+            {
+                previewTask.get();
+                auto mediaCapture = m_mediaCaptureMgr.Get();
+                m_bPreviewing = true;
+                ShowStatusMessage("Start preview successful");
+                if(mediaCapture->VideoDeviceController->Brightness)
+                {
+                    SetupVideoDeviceControl(mediaCapture->VideoDeviceController->Brightness, sldBrightness);
+                }
+                if(mediaCapture->VideoDeviceController->Contrast)
+                {                
+                    SetupVideoDeviceControl(mediaCapture->VideoDeviceController->Contrast, sldContrast);
+                }
+
+            }catch (Exception ^e)
+            {
+                ShowExceptionMessage(e);
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        m_bPreviewing = false;
+        previewElement1->Source = nullptr;
+        EnableButton(true, "StartPreview");
+        ShowExceptionMessage(e);
+    }
+}
+
+void BasicCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        ShowStatusMessage("Taking photo");
+        EnableButton(false, "TakePhoto");
+
+        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> getFileTask) 
+        {
+            try
+            {
+                this->m_photoStorageFile = getFileTask.get();
+                ShowStatusMessage("Create photo file successful");
+                ImageEncodingProperties^ imageProperties = ImageEncodingProperties::CreateJpeg();
+
+                create_task(m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, this->m_photoStorageFile)).then([this](task<void> photoTask)
+                {
+                    try
+                    {
+                        photoTask.get();
+                        EnableButton(true, "TakePhoto");
+                        ShowStatusMessage("Photo taken");
+
+                        task<IRandomAccessStream^>(this->m_photoStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> getStreamTask)
+                        {
+                            try
+                            {
+                                auto photoStream = getStreamTask.get();
+                                ShowStatusMessage("File open successful");
+                                auto bmpimg = ref new BitmapImage();
+
+                                bmpimg->SetSource(photoStream);
+                                imageElement1->Source = bmpimg;
+                            }
+                            catch (Exception^ e)
+                            {
+                                ShowExceptionMessage(e);
+                                EnableButton(true, "TakePhoto");
+                            }
+                        });
+                    }
+                    catch (Platform::Exception ^ e)
+                    {
+                        ShowExceptionMessage(e);
+                        EnableButton(true, "TakePhoto");
+                    }
+                });
+            }
+            catch (Exception^ e)
+            {
+                ShowExceptionMessage(e);
+                EnableButton(true, "TakePhoto");
+            }
+        });
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+        EnableButton(true, "TakePhoto");
+    }
+}
+
+void BasicCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        String ^fileName;
+        EnableButton(false, "StartStopRecord");
+
+        if (!m_bRecording)
+        {
+            ShowStatusMessage("Starting Record");
+
+            fileName = VIDEO_FILE_NAME;
+
+            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName,Windows::Storage::CreationCollisionOption::GenerateUniqueName )).then([this](task<StorageFile^> fileTask)
+            {
+                try
+                {
+                    this->m_recordStorageFile = fileTask.get();
+                    ShowStatusMessage("Create record file successful");
+
+                    MediaEncodingProfile^ recordProfile= nullptr;
+                    recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
+
+                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
+                    {
+                        try
+                        {
+                            recordTask.get();
+                            m_bRecording = true;
+                            SwitchRecordButtonContent();
+                            EnableButton(true, "StartStopRecord");
+
+                            ShowStatusMessage("Start Record successful");
+                        }
+                        catch (Exception ^e)
+                        {
+                            ShowExceptionMessage(e);
+                        }
+                    });
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    SwitchRecordButtonContent();
+                    EnableButton(true, "StartStopRecord");
+                    ShowExceptionMessage(e);
+                }
+            }
+            );
+        }
+        else
+        {
+            ShowStatusMessage("Stopping Record");
+
+            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
+            {
+                try
+                {
+                    recordTask.get();
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    SwitchRecordButtonContent();
+
+                    ShowStatusMessage("Stop record successful");
+                    if (!m_bSuspended)
+                    {
+                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
+                        {
+                            try
+                            {
+                                auto stream = streamTask.get();
+                                ShowStatusMessage("Record file opened");
+                                ShowStatusMessage(this->m_recordStorageFile->Path);
+                                playbackElement1->AutoPlay = true;
+                                playbackElement1->SetSource(stream, this->m_recordStorageFile->FileType);
+                                playbackElement1->Play();
+                            }
+                            catch (Exception ^e)
+                            {
+                                ShowExceptionMessage(e);
+                                m_bRecording = false;
+                                EnableButton(true, "StartStopRecord");
+                                SwitchRecordButtonContent();
+                            }
+                        });
+                    }
+                }
+                catch (Exception ^e)
+                {
+                    m_bRecording = false;
+                    EnableButton(true, "StartStopRecord");
+                    SwitchRecordButtonContent();
+                    ShowExceptionMessage(e);
+                }
+            });
+        }
+    }
+    catch (Platform::Exception^ e)
+    {
+        EnableButton(true, "StartStopRecord");
+        ShowExceptionMessage(e);
+        SwitchRecordButtonContent();
+        m_bRecording = false;
+    }
+}
+
+void BasicCapture::SetupVideoDeviceControl(Windows::Media::Devices::MediaDeviceControl^ videoDeviceControl, Slider^ slider)
+{
+    try
+    {		
+        if ((videoDeviceControl->Capabilities)->Supported)
+        {
+            slider->IsEnabled = true;
+            slider->Maximum = videoDeviceControl->Capabilities->Max;
+            slider->Minimum = videoDeviceControl->Capabilities->Min;
+            slider->StepFrequency = videoDeviceControl->Capabilities->Step;
+            double controlValue = 0;
+            if (videoDeviceControl->TryGetValue(&controlValue))
+            {
+                slider->Value = controlValue;
+            }
+        }
+        else
+        {
+            slider->IsEnabled = false;
+        }
+    }
+    catch (Platform::Exception^ e)
+    {
+        ShowExceptionMessage(e);
+    }
+}
+
+// VideoDeviceControllers
+void BasicCapture::sldBrightness_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
+{
+    bool succeeded = m_mediaCaptureMgr->VideoDeviceController->Brightness->TrySetValue(sldBrightness->Value);
+    if (!succeeded)
+    {
+        ShowStatusMessage("Set Brightness failed");
+    }
+}
+
+void BasicCapture::sldContrast_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs ^e)
+{
+    bool succeeded = m_mediaCaptureMgr->VideoDeviceController->Contrast->TrySetValue(sldContrast->Value);
+    if (!succeeded)
+    {
+        ShowStatusMessage("Set Contrast failed");
+    }
+}
+
+void BasicCapture::ShowStatusMessage(Platform::String^ text)
+{
+    rootPage->NotifyUser(text, NotifyType::StatusMessage);
+}
+
+void BasicCapture::ShowExceptionMessage(Platform::Exception^ ex)
+{
+    rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
+}
+
+void BasicCapture::SwitchRecordButtonContent()
+{
+    if (m_bRecording)
+    {
+        btnStartStopRecord1->Content="StopRecord";
+    }
+    else
+    {
+        btnStartStopRecord1->Content="StartRecord";
+    }
+}
+void BasicCapture::EnableButton(bool enabled, String^ name)
+{
+    if (name->Equals("StartDevice"))
+    {
+        btnStartDevice1->IsEnabled = enabled;
+    }
+    else if (name->Equals("StartPreview"))
+    {
+        btnStartPreview1->IsEnabled = enabled;
+    }
+    else if (name->Equals("StartStopRecord"))
+    {
+        btnStartStopRecord1->IsEnabled = enabled;
+    }
+    else if (name->Equals("TakePhoto"))
+    {
+        btnTakePhoto1->IsEnabled = enabled;
+    }
+}
+
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h
new file mode 100644
index 000000000..28129efb7
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h
@@ -0,0 +1,88 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// BasicCapture.xaml.h
+// Declaration of the BasicCapture class
+//
+
+#pragma once
+
+#include "pch.h"
+#include "BasicCapture.g.h"
+#include "MainPage.xaml.h"
+
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::Graphics::Display;
+using namespace Windows::UI::ViewManagement;
+using namespace Windows::Devices::Enumeration;
+#define VIDEO_FILE_NAME "video.mp4"
+#define PHOTO_FILE_NAME "photo.jpg"
+namespace SDKSample
+{
+    namespace MediaCapture
+    {
+        /// <summary>
+        /// An empty page that can be used on its own or navigated to within a Frame.
+        /// </summary>
+    	[Windows::Foundation::Metadata::WebHostHidden]
+        public ref class BasicCapture sealed
+        {
+        public:
+            BasicCapture();
+    
+        protected:
+            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+    
+        private:
+            MainPage^ rootPage;
+            void ScenarioInit();
+            void ScenarioReset();
+    
+            void Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
+            void Resuming(Object^ sender, Object^ e);
+    
+            void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void SoundLevelChanged(Object^ sender, Object^ e);
+            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
+            void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
+    
+    
+            void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+    
+            void SetupVideoDeviceControl(Windows::Media::Devices::MediaDeviceControl^ videoDeviceControl, Slider^ slider);
+            void sldBrightness_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
+            void sldContrast_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
+    
+            void ShowStatusMessage(Platform::String^ text);
+            void ShowExceptionMessage(Platform::Exception^ ex);
+    
+            void EnableButton(bool enabled, Platform::String ^name);
+            void SwitchRecordButtonContent();
+    
+            Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
+            Windows::Storage::StorageFile^ m_photoStorageFile;
+            Windows::Storage::StorageFile^ m_recordStorageFile;
+            bool m_bRecording;
+            bool m_bEffectAdded;
+            bool m_bSuspended;
+            bool m_bPreviewing;
+            Windows::UI::Xaml::WindowVisibilityChangedEventHandler ^m_visbilityHandler;
+            Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
+            bool m_currentScenarioLoaded;
+        };
+    }
+}
diff --git a/samples/winrt/ImageManipulations/C++/Constants.cpp b/samples/winrt/ImageManipulations/C++/Constants.cpp
new file mode 100644
index 000000000..873b98381
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/Constants.cpp
@@ -0,0 +1,24 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+#include "pch.h"
+#include "MainPage.xaml.h"
+#include "Constants.h"
+
+using namespace SDKSample;
+
+Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
+{
+    // The format here is the following:
+    //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
+    { "Video preview, record and take pictures", "SDKSample.MediaCapture.BasicCapture" },
+    { "Enumerate cameras and add a video effect", "SDKSample.MediaCapture.AdvancedCapture" },
+    { "Audio Capture", "SDKSample.MediaCapture.AudioCapture" }
+};
diff --git a/samples/winrt/ImageManipulations/C++/Constants.h b/samples/winrt/ImageManipulations/C++/Constants.h
new file mode 100644
index 000000000..917f66487
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/Constants.h
@@ -0,0 +1,45 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+#pragma once
+
+#include <collection.h>
+namespace SDKSample
+{
+    public value struct Scenario
+    {
+        Platform::String^ Title;
+        Platform::String^ ClassName;
+    };
+
+    partial ref class MainPage
+    {
+    public:
+        static property Platform::String^ FEATURE_NAME
+        {
+            Platform::String^ get()
+            {
+                return ref new Platform::String(L"MediaCapture CPP sample");
+            }
+        }
+
+        static property Platform::Array<Scenario>^ scenarios
+        {
+            Platform::Array<Scenario>^ get()
+            {
+                return scenariosInner;
+            }
+        }
+    private:
+        static Platform::Array<Scenario>^ scenariosInner;
+    };
+
+
+}
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml b/samples/winrt/ImageManipulations/C++/MainPage.xaml
new file mode 100644
index 000000000..d830e3cf0
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml
@@ -0,0 +1,166 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<common:LayoutAwarePage 
+    x:Class="SDKSample.MainPage"
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+    xmlns:common="using:SDKSample.Common"
+    mc:Ignorable="d"
+    x:Name="RootPage">
+
+    <common:LayoutAwarePage.Resources>
+        <Style x:Key="BaseStatusStyle" TargetType="TextBlock">
+            <Setter Property="FontFamily" Value="Segoe UI Semilight"/>
+            <Setter Property="FontSize" Value="14.667"/>
+            <Setter Property="Margin" Value="0,0,0,5"/>
+        </Style>
+        <Style x:Key="StatusStyle" BasedOn="{StaticResource BaseStatusStyle}" TargetType="TextBlock">
+            <Setter Property="Foreground" Value="Green"/>
+        </Style>
+        <Style x:Key="ErrorStyle" BasedOn="{StaticResource BaseStatusStyle}" TargetType="TextBlock">
+            <Setter Property="Foreground" Value="Blue"/>
+        </Style>
+    </common:LayoutAwarePage.Resources>
+
+
+    <Grid x:Name="LayoutRoot" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
+        
+        <Grid x:Name="ContentRoot" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="100,20,100,20">
+            <Grid.RowDefinitions>
+                <RowDefinition Height="Auto"/>
+                <RowDefinition Height="*"/>
+                <RowDefinition Height="Auto"/>
+            </Grid.RowDefinitions>
+
+            <!-- Header -->
+            <StackPanel Orientation="Horizontal" Grid.Row="0">
+                <Image x:Name="WindowsLogo" Stretch="None" Source="Assets/windows-sdk.png" AutomationProperties.Name="Windows Logo" HorizontalAlignment="Left" Grid.Column="0"/>
+                <TextBlock  Text="Windows 8 SDK Samples" VerticalAlignment="Bottom" Style="{StaticResource TitleTextStyle}" TextWrapping="Wrap" Grid.Column="1"/>
+            </StackPanel>
+            <ScrollViewer x:Name="MainScrollViewer" Grid.Row="1" ZoomMode="Disabled" IsTabStop="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Padding="0,0,0,20" >
+                <Grid>
+                    <Grid.RowDefinitions>
+                        <RowDefinition Height="Auto"/>
+                        <RowDefinition Height="*"/>
+                    </Grid.RowDefinitions>
+                    <TextBlock x:Name="FeatureName" Grid.Row="0"  Text="Add Sample Title Here" Style="{StaticResource HeaderTextStyle}" TextWrapping="Wrap"/>
+
+                    <!-- Content -->
+                    <Grid Grid.Row="1">
+
+                        <!-- All XAML in this section is purely for design time so you can see sample content in the designer. -->
+                        <!-- This will be repaced at runtime by live content.                                                  -->
+                        <Grid>
+                            <Grid.RowDefinitions>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="Auto"/>
+                                <RowDefinition Height="*"/>
+                            </Grid.RowDefinitions>
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="Auto"/>
+                                <ColumnDefinition Width="*"/>
+                            </Grid.ColumnDefinitions>
+                            <TextBlock Grid.Row="0" Text="Input" Style="{StaticResource H2Style}"/>
+
+                            <TextBlock x:Name="ScenarioListLabel" Text="Select Scenario:" Grid.Row="1"  Style="{StaticResource SubheaderTextStyle}" Margin="0,5,0,0" />
+                            <ListBox x:Name="Scenarios" Margin="0,0,20,0" Grid.Row="2" AutomationProperties.Name="Scenarios" HorizontalAlignment="Left" 
+                                         VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Auto"
+                                         AutomationProperties.LabeledBy="{Binding ElementName=ScenarioListLabel}" MaxHeight="125">
+                                <ListBox.ItemTemplate>
+                                    <DataTemplate>
+                                        <TextBlock Text="{Binding Name}"/>
+                                    </DataTemplate>
+                                </ListBox.ItemTemplate>
+                            </ListBox>
+                            <TextBlock x:Name="DescriptionText" Margin="0,5,0,0" Text="Description:" Style="{StaticResource SubheaderTextStyle}" Grid.Row="1" Grid.Column="1"/>
+                            <!-- Input Scenarios -->
+                            <UserControl x:Name="InputSection" Margin="0,5,0,0" IsTabStop="False" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top"/>
+                                
+                            <!-- Output section -->
+                            <TextBlock Text="Output" Grid.Row="5"  Margin="0,25,0,20" Style="{StaticResource H2Style}" Grid.ColumnSpan="2"/>
+                            <TextBlock x:Name="StatusBlock" Grid.Row="6" Margin="0,0,0,5" Grid.ColumnSpan="2"/>
+
+                            <!-- Output Scenarios -->
+                            <UserControl x:Name="OutputSection" Grid.Row="7" Grid.ColumnSpan="2" BorderThickness="0"/>
+                        </Grid>
+                    </Grid>
+                </Grid>
+            </ScrollViewer>
+
+            <!-- Footer -->
+            <Grid x:Name="Footer"  Grid.Row="3" Margin="0,10,0,10" VerticalAlignment="Bottom" >
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="Auto"/>
+                    <RowDefinition Height="Auto"/>
+                    <RowDefinition Height="Auto"/>
+                </Grid.RowDefinitions>
+
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="Auto"/>
+                    <ColumnDefinition Width="*"/>
+                </Grid.ColumnDefinitions>
+                <Image Grid.Row="0"  Source="Assets/microsoft-sdk.png" AutomationProperties.Name="Microsoft Logo" Stretch="None" HorizontalAlignment="Left"/>
+                <TextBlock Style="{StaticResource FooterStyle}" Text="© Microsoft Corporation. All rights reserved." TextWrapping="Wrap" Grid.Row="1" HorizontalAlignment="Left"/>
+                <StackPanel x:Name="FooterPanel" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right">
+                    <HyperlinkButton Content="Terms of use" Tag="http://www.microsoft.com/About/Legal/EN/US/IntellectualProperty/Copyright/default.aspx"
+                        Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
+                    <TextBlock Text="|" Style="{StaticResource SeparatorStyle}" VerticalAlignment="Center"/>
+                    <HyperlinkButton Content="Trademarks" Tag="http://www.microsoft.com/About/Legal/EN/US/IntellectualProperty/Trademarks/EN-US.aspx"
+                        Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
+                    <TextBlock Text="|"  Style="{StaticResource SeparatorStyle}" VerticalAlignment="Center"/>
+                    <HyperlinkButton Content="Privacy Statement" Tag="http://privacy.microsoft.com" Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
+                </StackPanel>
+            </Grid>
+
+
+        </Grid>
+
+        <VisualStateManager.VisualStateGroups>
+            <!-- Visual states reflect the application's view state -->
+            <VisualStateGroup>
+                <VisualState x:Name="FullScreenLandscape">
+                    <Storyboard>
+                    </Storyboard>
+                </VisualState>
+                <VisualState x:Name="Filled">
+                    <Storyboard>
+                    </Storyboard>
+                </VisualState>
+
+                <VisualState x:Name="FullScreenPortrait">
+                    <Storyboard>
+                    </Storyboard>
+                </VisualState>
+
+                <VisualState x:Name="Snapped">
+                    <Storyboard>
+                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="ContentRoot">
+                            <DiscreteObjectKeyFrame KeyTime="0">
+                                <DiscreteObjectKeyFrame.Value>
+                                    <Thickness>20,20,20,20</Thickness>
+                                </DiscreteObjectKeyFrame.Value>
+                            </DiscreteObjectKeyFrame>
+                        </ObjectAnimationUsingKeyFrames>
+                    </Storyboard>
+                </VisualState>
+            </VisualStateGroup>
+        </VisualStateManager.VisualStateGroups>
+    </Grid>
+</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp b/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
new file mode 100644
index 000000000..070278191
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
@@ -0,0 +1,315 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// MainPage.xaml.cpp
+// Implementation of the MainPage.xaml class.
+//
+
+#include "pch.h"
+#include "MainPage.xaml.h"
+#include "App.xaml.h"
+
+#include <collection.h>
+
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::Foundation;
+using namespace Windows::Foundation::Collections;
+using namespace Platform;
+using namespace SDKSample;
+using namespace Windows::UI::Xaml::Navigation;
+using namespace Windows::UI::Xaml::Interop;
+using namespace Windows::Graphics::Display;
+using namespace Windows::UI::ViewManagement;
+
+MainPage^ MainPage::Current = nullptr;
+
+MainPage::MainPage()
+{
+    InitializeComponent();
+
+    // This frame is hidden, meaning it is never shown.  It is simply used to load
+    // each scenario page and then pluck out the input and output sections and
+    // place them into the UserControls on the main page.
+    HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame();
+    HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+    ContentRoot->Children->Append(HiddenFrame);
+
+    FeatureName->Text = FEATURE_NAME;
+
+    this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged);
+    Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged);
+
+    MainPage::Current = this;
+    autoSizeInputSectionWhenSnapped = true;
+}
+
+/// <summary>
+/// We need to handle SizeChanged so that we can make the sample layout property
+/// in the various layouts.
+/// </summary>
+/// <param name="sender"></param>
+/// <param name="e"></param>
+void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
+{
+    InvalidateSize();
+    MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs();
+    args->ViewState = ApplicationView::Value;
+    MainPageResized(this, args);
+
+}
+
+void MainPage::InvalidateSize()
+{
+    // Get the window width
+    double windowWidth = this->ActualWidth;
+
+    if (windowWidth != 0.0)
+    {
+        // Get the width of the ListBox.
+        double listBoxWidth = Scenarios->ActualWidth;
+
+        // Is the ListBox using any margins that we need to consider?
+        double listBoxMarginLeft = Scenarios->Margin.Left;
+        double listBoxMarginRight = Scenarios->Margin.Right;
+
+        // Figure out how much room is left after considering the list box width
+        double availableWidth = windowWidth - listBoxWidth;
+
+        // Is the top most child using margins?
+        double layoutRootMarginLeft = ContentRoot->Margin.Left;
+        double layoutRootMarginRight = ContentRoot->Margin.Right;
+
+        // We have different widths to use depending on the view state
+        if (ApplicationView::Value != ApplicationViewState::Snapped)
+        {
+            // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
+            // and the LayoutRoot's margins
+            InputSection->Width = ((availableWidth) - 
+                (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
+        }
+        else
+        {
+            // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
+            if (autoSizeInputSectionWhenSnapped)
+            {
+                InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
+            }
+        }
+    }
+    InvalidateViewState();
+}
+
+void MainPage::InvalidateViewState()
+{
+    // Are we going to snapped mode?
+    if (ApplicationView::Value == ApplicationViewState::Snapped)
+    {
+        Grid::SetRow(DescriptionText, 3);
+        Grid::SetColumn(DescriptionText, 0);
+
+        Grid::SetRow(InputSection, 4);
+        Grid::SetColumn(InputSection, 0);
+
+        Grid::SetRow(FooterPanel, 2);
+        Grid::SetColumn(FooterPanel, 0);
+    }
+    else
+    {
+        Grid::SetRow(DescriptionText, 1);
+        Grid::SetColumn(DescriptionText, 1);
+
+        Grid::SetRow(InputSection, 2);
+        Grid::SetColumn(InputSection, 1);
+
+        Grid::SetRow(FooterPanel, 1);
+        Grid::SetColumn(FooterPanel, 1);
+    }
+
+    //  Since we don't load the scenario page in the traditional manner (we just pluck out the
+    // input and output sections from the page) we need to ensure that any VSM code used
+    // by the scenario's input and output sections is fired.
+    VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
+    VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false);
+}
+
+void MainPage::PopulateScenarios()
+{
+    ScenarioList = ref new Platform::Collections::Vector<Object^>();
+
+    // Populate the ListBox with the list of scenarios as defined in Constants.cpp.
+    for (unsigned int i = 0; i < scenarios->Length; ++i)
+    {
+        Scenario s = scenarios[i];
+        ListBoxItem^ item = ref new ListBoxItem();
+        item->Name = s.ClassName;
+        item->Content = (i + 1).ToString() + ") " + s.Title;
+        ScenarioList->Append(item);
+    }
+
+    // Bind the ListBox to the scenario list.
+    Scenarios->ItemsSource = ScenarioList;
+    Scenarios->ScrollIntoView(Scenarios->SelectedItem);
+}
+
+/// <summary>
+/// This method is responsible for loading the individual input and output sections for each scenario.  This 
+/// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
+/// and output sections into the respective UserControl on the main page.
+/// </summary>
+/// <param name="scenarioName"></param>
+void MainPage::LoadScenario(String^ scenarioName)
+{
+    autoSizeInputSectionWhenSnapped = true;
+
+    // Load the ScenarioX.xaml file into the Frame.
+    TypeName scenarioType = {scenarioName, TypeKind::Custom};
+    HiddenFrame->Navigate(scenarioType, this);
+
+    // Get the top element, the Page, so we can look up the elements
+    // that represent the input and output sections of the ScenarioX file.
+    Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content);
+
+    // Get each element.
+    UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input"));
+    UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output"));
+
+    if (input == nullptr)
+    {
+        // Malformed input section.
+        NotifyUser("Cannot load scenario input section for " + scenarioName + 
+            "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
+        return;
+    }
+
+    if (output == nullptr)
+    {
+        // Malformed output section.
+        NotifyUser("Cannot load scenario output section for " + scenarioName + 
+            "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
+        return;
+    }
+
+    // Find the LayoutRoot which parents the input and output sections in the main page.
+    Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot"));
+
+    if (panel != nullptr)
+    {
+        unsigned int index = 0;
+        UIElementCollection^ collection = panel->Children;
+
+        // Get rid of the content that is currently in the intput and output sections.
+        collection->IndexOf(input, &index);
+        collection->RemoveAt(index);
+
+        collection->IndexOf(output, &index);
+        collection->RemoveAt(index);
+
+        // Populate the input and output sections with the newly loaded content.
+        InputSection->Content = input;
+        OutputSection->Content = output;
+
+        ScenarioLoaded(this, nullptr);
+    }
+    else
+    {
+        // Malformed Scenario file.
+        NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" + 
+            scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
+    }
+}
+
+void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
+{
+    if (Scenarios->SelectedItem != nullptr)
+    {
+        NotifyUser("", NotifyType::StatusMessage);
+
+        LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name);
+        InvalidateSize();
+    }
+}
+
+void MainPage::NotifyUser(String^ strMessage, NotifyType type)
+{
+    switch (type)
+    {
+    case NotifyType::StatusMessage:
+        // Use the status message style.
+        StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle"));
+        break;
+    case NotifyType::ErrorMessage:
+        // Use the error message style.
+        StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle"));
+        break;
+    default:
+        break;
+    }
+    StatusBlock->Text = strMessage;
+
+    // Collapsed the StatusBlock if it has no text to conserve real estate.
+    if (StatusBlock->Text != "")
+    {
+        StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
+    }
+    else
+    {
+        StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
+    }
+}
+
+void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
+{
+    auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
+    Windows::System::Launcher::LaunchUriAsync(uri);
+}
+
+
+/// <summary>
+/// Populates the page with content passed during navigation.  Any saved state is also
+/// provided when recreating a page from a prior session.
+/// </summary>
+/// <param name="navigationParameter">The parameter value passed to
+/// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
+/// </param>
+/// <param name="pageState">A map of state preserved by this page during an earlier
+/// session.  This will be null the first time a page is visited.</param>
+void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
+{
+    (void) navigationParameter;	// Unused parameter
+
+    PopulateScenarios();
+
+    // Starting scenario is the first or based upon a previous state.
+    ListBoxItem^ startingScenario = nullptr;
+    int startingScenarioIndex = -1;
+
+    if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex"))
+    {
+        startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex"));
+    }
+
+    Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0;
+
+    InvalidateViewState();
+}
+
+/// <summary>
+/// Preserves state associated with this page in case the application is suspended or the
+/// page is discarded from the navigation cache.  Values must conform to the serialization
+/// requirements of <see cref="SuspensionManager::SessionState"/>.
+/// </summary>
+/// <param name="pageState">An empty map to be populated with serializable state.</param>
+void MainPage::SaveState(IMap<String^, Object^>^ pageState)
+{
+    int selectedListBoxItemIndex = Scenarios->SelectedIndex;
+    pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex);
+}
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml.h b/samples/winrt/ImageManipulations/C++/MainPage.xaml.h
new file mode 100644
index 000000000..36fb7796a
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml.h
@@ -0,0 +1,105 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// MainPage.xaml.h
+// Declaration of the MainPage.xaml class.
+//
+
+#pragma once
+
+#include "pch.h"
+#include "MainPage.g.h"
+#include "Common\LayoutAwarePage.h" // Required by generated header
+#include "Constants.h"
+
+namespace SDKSample
+{
+    public enum class NotifyType
+    {
+        StatusMessage,
+        ErrorMessage
+    };
+
+    public ref class MainPageSizeChangedEventArgs sealed
+    {
+    public:
+        property Windows::UI::ViewManagement::ApplicationViewState ViewState
+        {
+            Windows::UI::ViewManagement::ApplicationViewState get()
+            {
+                return viewState;
+            }
+
+            void set(Windows::UI::ViewManagement::ApplicationViewState value)
+            {
+                viewState = value;
+            }
+        }
+
+    private:
+        Windows::UI::ViewManagement::ApplicationViewState viewState;
+    };
+
+    public ref class MainPage sealed
+    {
+    public:
+        MainPage();
+
+    protected:
+        virtual void LoadState(Platform::Object^ navigationParameter,
+            Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
+        virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override;
+
+    internal:
+        property bool AutoSizeInputSectionWhenSnapped
+        {
+            bool get()
+            {
+                return autoSizeInputSectionWhenSnapped;
+            }
+
+            void set(bool value)
+            {
+                autoSizeInputSectionWhenSnapped = value;
+            }
+        }
+
+        property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs
+       {
+            Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get()
+            {
+                return safe_cast<App^>(App::Current)->LaunchArgs;
+            }
+        }
+
+        void NotifyUser(Platform::String^ strMessage, NotifyType type);
+        void LoadScenario(Platform::String^ scenarioName);
+        event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded;
+        event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized;
+
+    private:
+        void PopulateScenarios();
+        void InvalidateSize();
+        void InvalidateViewState();
+
+        Platform::Collections::Vector<Object^>^ ScenarioList;
+        Windows::UI::Xaml::Controls::Frame^ HiddenFrame;
+        void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+        bool autoSizeInputSectionWhenSnapped;
+
+        void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
+        void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
+
+    internal:
+        static MainPage^ Current;
+
+    };
+}
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.sln b/samples/winrt/ImageManipulations/C++/MediaCapture.sln
new file mode 100644
index 000000000..7b99bce31
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.sln
@@ -0,0 +1,52 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 11 Express for Windows 8
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MediaCapture", "MediaCapture.vcxproj", "{C5B886A7-8300-46FF-B533-9613DE2AF637}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GrayscaleTransform", "MediaExtensions\Grayscale\Grayscale.vcxproj", "{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|ARM = Debug|ARM
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|ARM = Release|ARM
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|ARM.ActiveCfg = Debug|ARM
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|ARM.Build.0 = Debug|ARM
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|Win32.ActiveCfg = Debug|Win32
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|Win32.Build.0 = Debug|Win32
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|x64.ActiveCfg = Debug|x64
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Debug|x64.Build.0 = Debug|x64
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|ARM.ActiveCfg = Release|ARM
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|ARM.Build.0 = Release|ARM
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|Win32.ActiveCfg = Release|Win32
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|Win32.Build.0 = Release|Win32
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|x64.ActiveCfg = Release|x64
+		{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}.Release|x64.Build.0 = Release|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|ARM.ActiveCfg = Debug|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|ARM.Build.0 = Debug|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|ARM.Deploy.0 = Debug|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|Win32.ActiveCfg = Debug|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|Win32.Build.0 = Debug|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|Win32.Deploy.0 = Debug|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|x64.ActiveCfg = Debug|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|x64.Build.0 = Debug|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Debug|x64.Deploy.0 = Debug|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|ARM.ActiveCfg = Release|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|ARM.Build.0 = Release|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|ARM.Deploy.0 = Release|ARM
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|Win32.ActiveCfg = Release|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|Win32.Build.0 = Release|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|Win32.Deploy.0 = Release|Win32
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|x64.ActiveCfg = Release|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|x64.Build.0 = Release|x64
+		{C5B886A7-8300-46FF-B533-9613DE2AF637}.Release|x64.Deploy.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
new file mode 100644
index 000000000..d2f255d1b
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
@@ -0,0 +1,200 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|ARM">
+      <Configuration>Debug</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|ARM">
+      <Configuration>Release</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{C5B886A7-8300-46FF-B533-9613DE2AF637}</ProjectGuid>
+    <RootNamespace>SDKSample</RootNamespace>
+    <DefaultLanguage>en-US</DefaultLanguage>
+    <VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and '$(VisualStudioVersion)' == ''">$(VCTargetsPath11)</VCTargetsPath>
+    <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion>
+    <AppContainerApplication>true</AppContainerApplication>
+    <ProjectName>MediaCapture</ProjectName>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="AdvancedCapture.xaml.h">
+      <DependentUpon>AdvancedCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClInclude>
+    <ClInclude Include="AudioCapture.xaml.h">
+      <DependentUpon>AudioCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClInclude>
+    <ClInclude Include="BasicCapture.xaml.h">
+      <DependentUpon>BasicCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClInclude>
+    <ClInclude Include="Constants.h" />
+    <ClInclude Include="MainPage.xaml.h">
+      <DependentUpon>MainPage.xaml</DependentUpon>
+    </ClInclude>
+    <ClInclude Include="pch.h" />
+    <ClInclude Include="Common\LayoutAwarePage.h" />
+    <ClInclude Include="Common\SuspensionManager.h" />
+    <ClInclude Include="App.xaml.h">
+      <DependentUpon>App.xaml</DependentUpon>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ApplicationDefinition Include="App.xaml">
+      <SubType>Designer</SubType>
+    </ApplicationDefinition>
+    <Page Include="AdvancedCapture.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="AudioCapture.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="BasicCapture.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="Common\StandardStyles.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="MainPage.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+    <Page Include="Sample-Utils\SampleTemplateStyles.xaml">
+      <SubType>Designer</SubType>
+    </Page>
+  </ItemGroup>
+  <ItemGroup>
+    <AppxManifest Include="Package.appxmanifest">
+      <SubType>Designer</SubType>
+    </AppxManifest>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="AdvancedCapture.xaml.cpp">
+      <DependentUpon>AdvancedCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClCompile>
+    <ClCompile Include="App.xaml.cpp">
+      <DependentUpon>App.xaml</DependentUpon>
+    </ClCompile>
+    <ClCompile Include="AudioCapture.xaml.cpp">
+      <DependentUpon>AudioCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClCompile>
+    <ClCompile Include="BasicCapture.xaml.cpp">
+      <DependentUpon>BasicCapture.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </ClCompile>
+    <ClCompile Include="Common\LayoutAwarePage.cpp" />
+    <ClCompile Include="Constants.cpp" />
+    <ClCompile Include="Common\SuspensionManager.cpp" />
+    <ClCompile Include="MainPage.xaml.cpp">
+      <DependentUpon>MainPage.xaml</DependentUpon>
+    </ClCompile>
+    <ClCompile Include="pch.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <Image Include="Assets\microsoft-sdk.png" />
+    <Image Include="Assets\placeholder-sdk.png" />
+    <Image Include="Assets\smallTile-sdk.png" />
+    <Image Include="Assets\splash-sdk.png" />
+    <Image Include="Assets\squareTile-sdk.png" />
+    <Image Include="Assets\storeLogo-sdk.png" />
+    <Image Include="Assets\tile-sdk.png" />
+    <Image Include="Assets\windows-sdk.png" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="MediaExtensions\Grayscale\Grayscale.vcxproj">
+      <Project>{ba69218f-da5c-4d14-a78d-21a9e4dec669}</Project>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
new file mode 100644
index 000000000..5f6124c2b
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
@@ -0,0 +1,88 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Image Include="Assets\microsoft-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\placeholder-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\smallTile-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\splash-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\squareTile-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\storeLogo-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\tile-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+    <Image Include="Assets\windows-sdk.png">
+      <Filter>Assets</Filter>
+    </Image>
+  </ItemGroup>
+  <ItemGroup>
+    <ApplicationDefinition Include="App.xaml" />
+  </ItemGroup>
+  <ItemGroup>
+    <AppxManifest Include="Package.appxmanifest" />
+  </ItemGroup>
+  <ItemGroup>
+    <Page Include="MainPage.xaml" />
+    <Page Include="Common\StandardStyles.xaml">
+      <Filter>Common</Filter>
+    </Page>
+    <Page Include="Sample-Utils\SampleTemplateStyles.xaml">
+      <Filter>Sample-Utils</Filter>
+    </Page>
+    <Page Include="BasicCapture.xaml" />
+    <Page Include="AdvancedCapture.xaml" />
+    <Page Include="AudioCapture.xaml" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="MainPage.xaml.h" />
+    <ClInclude Include="pch.h" />
+    <ClInclude Include="App.xaml.h" />
+    <ClInclude Include="Common\SuspensionManager.h">
+      <Filter>Common</Filter>
+    </ClInclude>
+    <ClInclude Include="Common\LayoutAwarePage.h">
+      <Filter>Common</Filter>
+    </ClInclude>
+    <ClInclude Include="Constants.h" />
+    <ClInclude Include="AdvancedCapture.xaml.h" />
+    <ClInclude Include="AudioCapture.xaml.h" />
+    <ClInclude Include="BasicCapture.xaml.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="App.xaml.cpp" />
+    <ClCompile Include="MainPage.xaml.cpp" />
+    <ClCompile Include="pch.cpp" />
+    <ClCompile Include="Common\LayoutAwarePage.cpp">
+      <Filter>Common</Filter>
+    </ClCompile>
+    <ClCompile Include="Common\SuspensionManager.cpp">
+      <Filter>Common</Filter>
+    </ClCompile>
+    <ClCompile Include="Constants.cpp" />
+    <ClCompile Include="AdvancedCapture.xaml.cpp" />
+    <ClCompile Include="AudioCapture.xaml.cpp" />
+    <ClCompile Include="BasicCapture.xaml.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <Filter Include="Assets">
+      <UniqueIdentifier>{132eec18-b164-4b15-a746-643880e9c5d9}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Common">
+      <UniqueIdentifier>{476b4177-f316-4458-8e13-cab3dc2381c5}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Sample-Utils">
+      <UniqueIdentifier>{54f287f8-e4cb-4f47-97d0-4c469de6992e}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h
new file mode 100644
index 000000000..04ff69ed8
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h
@@ -0,0 +1,81 @@
+#pragma once
+
+//////////////////////////////////////////////////////////////////////////
+//  AsyncCallback [template]
+//
+//  Description: 
+//  Helper class that routes IMFAsyncCallback::Invoke calls to a class
+//  method on the parent class.
+//
+//  Usage:
+//  Add this class as a member variable. In the parent class constructor,
+//  initialize the AsyncCallback class like this:
+//  	m_cb(this, &CYourClass::OnInvoke)
+//  where
+//      m_cb       = AsyncCallback object
+//      CYourClass = parent class
+//      OnInvoke   = Method in the parent class to receive Invoke calls.
+//
+//  The parent's OnInvoke method (you can name it anything you like) must
+//  have a signature that matches the InvokeFn typedef below.
+//////////////////////////////////////////////////////////////////////////
+
+// T: Type of the parent object
+template<class T>
+class AsyncCallback : public IMFAsyncCallback
+{
+public: 
+    typedef HRESULT (T::*InvokeFn)(IMFAsyncResult *pAsyncResult);
+
+    AsyncCallback(T *pParent, InvokeFn fn) : m_pParent(pParent), m_pInvokeFn(fn)
+    {
+    }
+
+    // IUnknown
+    STDMETHODIMP_(ULONG) AddRef() { 
+        // Delegate to parent class.
+        return m_pParent->AddRef(); 
+    }
+    STDMETHODIMP_(ULONG) Release() { 
+        // Delegate to parent class.
+        return m_pParent->Release(); 
+    }
+    STDMETHODIMP QueryInterface(REFIID iid, void** ppv)
+    {
+        if (!ppv)
+        {
+            return E_POINTER;
+        }
+        if (iid == __uuidof(IUnknown))
+        {
+            *ppv = static_cast<IUnknown*>(static_cast<IMFAsyncCallback*>(this));
+        }
+        else if (iid == __uuidof(IMFAsyncCallback))
+        {
+            *ppv = static_cast<IMFAsyncCallback*>(this);
+        }
+        else
+        {
+            *ppv = NULL;
+            return E_NOINTERFACE;
+        }
+        AddRef();
+        return S_OK;
+    }
+
+
+    // IMFAsyncCallback methods
+    STDMETHODIMP GetParameters(DWORD*, DWORD*)
+    {
+        // Implementation of this method is optional.
+        return E_NOTIMPL;
+    }
+
+    STDMETHODIMP Invoke(IMFAsyncResult* pAsyncResult)
+    {
+        return (m_pParent->*m_pInvokeFn)(pAsyncResult);
+    }
+
+    T *m_pParent;
+    InvokeFn m_pInvokeFn;
+};
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h
new file mode 100644
index 000000000..92de15eac
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h
@@ -0,0 +1,102 @@
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved
+
+
+#pragma once
+
+
+//////////////////////////////////////////////////////////////////////////
+//  VideoBufferLock
+//
+//  Description:
+//  Locks a video buffer that might or might not support IMF2DBuffer.
+//
+//////////////////////////////////////////////////////////////////////////
+
+class VideoBufferLock
+{
+public:
+    VideoBufferLock(IMFMediaBuffer *pBuffer) : m_p2DBuffer(NULL)
+    {
+        m_pBuffer = pBuffer;
+        m_pBuffer->AddRef();
+
+        // Query for the 2-D buffer interface. OK if this fails.
+        m_pBuffer->QueryInterface(IID_PPV_ARGS(&m_p2DBuffer));
+    }
+
+    ~VideoBufferLock()
+    {
+        UnlockBuffer();
+        SafeRelease(&m_pBuffer);
+        SafeRelease(&m_p2DBuffer);
+    }
+
+    // LockBuffer:
+    // Locks the buffer. Returns a pointer to scan line 0 and returns the stride.
+
+    // The caller must provide the default stride as an input parameter, in case
+    // the buffer does not expose IMF2DBuffer. You can calculate the default stride
+    // from the media type.
+
+    HRESULT LockBuffer(
+        LONG  lDefaultStride,    // Minimum stride (with no padding).
+        DWORD dwHeightInPixels,  // Height of the image, in pixels.
+        BYTE  **ppbScanLine0,    // Receives a pointer to the start of scan line 0.
+        LONG  *plStride          // Receives the actual stride.
+        )
+    {
+        HRESULT hr = S_OK;
+
+        // Use the 2-D version if available.
+        if (m_p2DBuffer)
+        {
+            hr = m_p2DBuffer->Lock2D(ppbScanLine0, plStride);
+        }
+        else
+        {
+            // Use non-2D version.
+            BYTE *pData = NULL;
+
+            hr = m_pBuffer->Lock(&pData, NULL, NULL);
+            if (SUCCEEDED(hr))
+            {
+                *plStride = lDefaultStride;
+                if (lDefaultStride < 0)
+                {
+                    // Bottom-up orientation. Return a pointer to the start of the
+                    // last row *in memory* which is the top row of the image.
+                    *ppbScanLine0 = pData + abs(lDefaultStride) * (dwHeightInPixels - 1);
+                }
+                else
+                {
+                    // Top-down orientation. Return a pointer to the start of the
+                    // buffer.
+                    *ppbScanLine0 = pData;
+                }
+            }
+        }
+        return hr;
+    }
+
+    HRESULT UnlockBuffer()
+    {
+        if (m_p2DBuffer)
+        {
+            return m_p2DBuffer->Unlock2D();
+        }
+        else
+        {
+            return m_pBuffer->Unlock();
+        }
+    }
+
+private:
+    IMFMediaBuffer  *m_pBuffer;
+    IMF2DBuffer     *m_p2DBuffer;
+};
+
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h
new file mode 100644
index 000000000..d5ea05bfd
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h
@@ -0,0 +1,62 @@
+#pragma once
+
+//////////////////////////////////////////////////////////////////////////
+//  CritSec
+//  Description: Wraps a critical section.
+//////////////////////////////////////////////////////////////////////////
+
+class CritSec
+{
+public:
+    CRITICAL_SECTION m_criticalSection;
+public:
+    CritSec()
+    {
+        InitializeCriticalSectionEx(&m_criticalSection, 100, 0);
+    }
+
+    ~CritSec()
+    {
+        DeleteCriticalSection(&m_criticalSection);
+    }
+
+	_Acquires_lock_(m_criticalSection)
+    void Lock()
+    {
+        EnterCriticalSection(&m_criticalSection);
+    }
+
+	_Releases_lock_(m_criticalSection)
+    void Unlock()
+    {
+        LeaveCriticalSection(&m_criticalSection);
+    }
+};
+
+
+//////////////////////////////////////////////////////////////////////////
+//  AutoLock
+//  Description: Provides automatic locking and unlocking of a 
+//               of a critical section.
+//
+//  Note: The AutoLock object must go out of scope before the CritSec.
+//////////////////////////////////////////////////////////////////////////
+
+class AutoLock
+{
+private:
+    CritSec *m_pCriticalSection;
+public:
+	_Acquires_lock_(m_pCriticalSection)
+    AutoLock(CritSec& crit)
+    {
+        m_pCriticalSection = &crit;
+        m_pCriticalSection->Lock();
+    }
+
+	_Releases_lock_(m_pCriticalSection)
+    ~AutoLock()
+    {
+	    m_pCriticalSection->Unlock();
+    }
+};
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h
new file mode 100644
index 000000000..c67c0f2ca
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h
@@ -0,0 +1,516 @@
+//-----------------------------------------------------------------------------
+// File: Linklist.h
+// Desc: Linked list class.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+//  Copyright (C) Microsoft Corporation. All rights reserved.
+//-----------------------------------------------------------------------------
+
+#pragma once
+
+// Notes:
+// 
+// The List class template implements a simple double-linked list. 
+// It uses STL's copy semantics. 
+
+// There are two versions of the Clear() method:
+//  Clear(void) clears the list w/out cleaning up the object.
+//  Clear(FN fn) takes a functor object that releases the objects, if they need cleanup.
+
+// The List class supports enumeration. Example of usage:
+//
+// List<T>::POSIITON pos = list.GetFrontPosition();
+// while (pos != list.GetEndPosition())
+// {
+//     T item;
+//     hr = list.GetItemPos(&item);
+//     pos = list.Next(pos);
+// }
+
+// The ComPtrList class template derives from List<> and implements a list of COM pointers.
+
+template <class T>
+struct NoOp
+{
+    void operator()(T& t)
+    {
+    }
+};
+
+template <class T>
+class List
+{
+protected:
+
+    // Nodes in the linked list
+    struct Node
+    {
+        Node *prev;
+        Node *next;
+        T    item;
+
+        Node() : prev(nullptr), next(nullptr)
+        {
+        }
+
+        Node(T item) : prev(nullptr), next(nullptr)
+        {
+            this->item = item;
+        }
+
+        T Item() const { return item; }
+    };
+
+public:
+
+    // Object for enumerating the list.
+    class POSITION
+    {
+        friend class List<T>;
+
+    public:
+        POSITION() : pNode(nullptr)
+        {
+        }
+
+        bool operator==(const POSITION &p) const
+        {
+            return pNode == p.pNode;
+        }
+
+        bool operator!=(const POSITION &p) const
+        {
+            return pNode != p.pNode;
+        }
+
+    private:
+        const Node *pNode;
+
+        POSITION(Node *p) : pNode(p) 
+        {
+        }
+    };
+
+protected:
+    Node    m_anchor;  // Anchor node for the linked list.
+    DWORD   m_count;   // Number of items in the list.
+
+    Node* Front() const
+    {
+        return m_anchor.next;
+    }
+
+    Node* Back() const
+    {
+        return m_anchor.prev;
+    }
+
+    virtual HRESULT InsertAfter(T item, Node *pBefore)
+    {
+        if (pBefore == nullptr)
+        {
+            return E_POINTER;
+        }
+
+        Node *pNode = new Node(item);
+        if (pNode == nullptr)
+        {
+            return E_OUTOFMEMORY;
+        }
+
+        Node *pAfter = pBefore->next;
+            
+        pBefore->next = pNode;
+        pAfter->prev = pNode;
+
+        pNode->prev = pBefore;
+        pNode->next = pAfter;
+
+        m_count++;
+
+        return S_OK;
+    }
+
+    virtual HRESULT GetItem(const Node *pNode, T* ppItem)
+    {
+        if (pNode == nullptr || ppItem == nullptr)
+        {
+            return E_POINTER;
+        }
+
+        *ppItem = pNode->item;
+        return S_OK;
+    }
+
+    // RemoveItem:
+    // Removes a node and optionally returns the item.
+    // ppItem can be nullptr.
+    virtual HRESULT RemoveItem(Node *pNode, T *ppItem)
+    {
+        if (pNode == nullptr)
+        {
+            return E_POINTER;
+        }
+
+        assert(pNode != &m_anchor); // We should never try to remove the anchor node.
+        if (pNode == &m_anchor)
+        {
+            return E_INVALIDARG;
+        }
+
+
+        T item;
+
+        // The next node's previous is this node's previous.
+        pNode->next->prev = pNode->prev;
+
+        // The previous node's next is this node's next.
+        pNode->prev->next = pNode->next;
+
+        item = pNode->item;
+        delete pNode;
+
+        m_count--;
+
+        if (ppItem)
+        {
+            *ppItem = item;
+        }
+
+        return S_OK;
+    }
+
+public:
+
+    List()
+    {
+        m_anchor.next = &m_anchor;
+        m_anchor.prev = &m_anchor;
+
+        m_count = 0;
+    }
+
+    virtual ~List()
+    {
+        Clear();
+    }
+
+    // Insertion functions
+    HRESULT InsertBack(T item)
+    {
+        return InsertAfter(item, m_anchor.prev);
+    }
+
+
+    HRESULT InsertFront(T item)
+    {
+        return InsertAfter(item, &m_anchor);
+    }
+
+    HRESULT InsertPos(POSITION pos, T item)
+    {
+        if (pos.pNode == nullptr)
+        {
+            return InsertBack(item);
+        }
+
+        return InsertAfter(item, pos.pNode->prev);
+    }
+
+    // RemoveBack: Removes the tail of the list and returns the value.
+    // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
+    HRESULT RemoveBack(T *ppItem)
+    {
+        if (IsEmpty())
+        {
+            return E_FAIL;
+        }
+        else
+        {
+            return RemoveItem(Back(), ppItem);
+        }
+    }
+
+    // RemoveFront: Removes the head of the list and returns the value.
+    // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
+    HRESULT RemoveFront(T *ppItem)
+    {
+        if (IsEmpty())
+        {
+            return E_FAIL;
+        }
+        else
+        {
+            return RemoveItem(Front(), ppItem);
+        }
+    }
+
+    // GetBack: Gets the tail item.
+    HRESULT GetBack(T *ppItem)
+    {
+        if (IsEmpty())
+        {
+            return E_FAIL;
+        }
+        else
+        {
+            return GetItem(Back(), ppItem);
+        }
+    }
+
+    // GetFront: Gets the front item.
+    HRESULT GetFront(T *ppItem)
+    {
+        if (IsEmpty())
+        {
+            return E_FAIL;
+        }
+        else
+        {
+            return GetItem(Front(), ppItem);
+        }
+    }
+
+
+    // GetCount: Returns the number of items in the list.
+    DWORD GetCount() const { return m_count; }
+
+    bool IsEmpty() const
+    {
+        return (GetCount() == 0);
+    }
+
+    // Clear: Takes a functor object whose operator()
+    // frees the object on the list.
+    template <class FN>
+    void Clear(FN& clear_fn)
+    {
+        Node *n = m_anchor.next;
+
+        // Delete the nodes
+        while (n != &m_anchor)
+        {
+            clear_fn(n->item);
+
+            Node *tmp = n->next;
+            delete n;
+            n = tmp;
+        }
+
+        // Reset the anchor to point at itself
+        m_anchor.next = &m_anchor;
+        m_anchor.prev = &m_anchor;
+
+        m_count = 0;
+    }
+
+    // Clear: Clears the list. (Does not delete or release the list items.)
+    virtual void Clear()
+    {
+        NoOp<T> clearOp;
+        Clear<>(clearOp);
+    }
+
+
+    // Enumerator functions
+
+    POSITION FrontPosition()
+    {
+        if (IsEmpty())
+        {
+            return POSITION(nullptr);
+        }
+        else
+        {
+            return POSITION(Front());
+        }
+    }
+
+    POSITION EndPosition() const
+    {
+        return POSITION();
+    }
+
+    HRESULT GetItemPos(POSITION pos, T *ppItem)
+    {   
+        if (pos.pNode)
+        {
+            return GetItem(pos.pNode, ppItem);
+        }
+        else 
+        {
+            return E_FAIL;
+        }
+    }
+
+    POSITION Next(const POSITION pos)
+    {
+        if (pos.pNode && (pos.pNode->next != &m_anchor))
+        {
+            return POSITION(pos.pNode->next);
+        }
+        else
+        {
+            return POSITION(nullptr);
+        }
+    }
+
+    // Remove an item at a position. 
+    // The item is returns in ppItem, unless ppItem is nullptr.
+    // NOTE: This method invalidates the POSITION object.
+    HRESULT Remove(POSITION& pos, T *ppItem)
+    {
+        if (pos.pNode)
+        {
+            // Remove const-ness temporarily...
+            Node *pNode = const_cast<Node*>(pos.pNode);
+
+            pos = POSITION();
+
+            return RemoveItem(pNode, ppItem);
+        }
+        else
+        {
+            return E_INVALIDARG;
+        }
+    }
+
+};
+
+
+
+// Typical functors for Clear method.
+
+// ComAutoRelease: Releases COM pointers.
+// MemDelete: Deletes pointers to new'd memory.
+
+class ComAutoRelease
+{
+public: 
+    void operator()(IUnknown *p)
+    {
+        if (p)
+        {
+            p->Release();
+        }
+    }
+};
+        
+class MemDelete
+{
+public: 
+    void operator()(void *p)
+    {
+        if (p)
+        {
+            delete p;
+        }
+    }
+};
+
+
+// ComPtrList class
+// Derived class that makes it safer to store COM pointers in the List<> class.
+// It automatically AddRef's the pointers that are inserted onto the list
+// (unless the insertion method fails). 
+//
+// T must be a COM interface type. 
+// example: ComPtrList<IUnknown>
+//
+// NULLABLE: If true, client can insert nullptr pointers. This means GetItem can
+// succeed but return a nullptr pointer. By default, the list does not allow nullptr
+// pointers.
+
+template <class T, bool NULLABLE = FALSE>
+class ComPtrList : public List<T*>
+{
+public:
+
+    typedef T* Ptr;
+
+    void Clear()
+    {
+        ComAutoRelease car;
+        List<Ptr>::Clear(car);
+    }
+
+    ~ComPtrList()
+    {
+        Clear();
+    }
+
+protected:
+    HRESULT InsertAfter(Ptr item, Node *pBefore)
+    {
+        // Do not allow nullptr item pointers unless NULLABLE is true.
+        if (item == nullptr && !NULLABLE)
+        {
+            return E_POINTER;
+        }
+
+        if (item)
+        {
+            item->AddRef();
+        }
+
+        HRESULT hr = List<Ptr>::InsertAfter(item, pBefore);
+        if (FAILED(hr) && item != nullptr)
+        {
+            item->Release();
+        }
+        return hr;
+    }
+
+    HRESULT GetItem(const Node *pNode, Ptr* ppItem)
+    {
+        Ptr pItem = nullptr;
+
+        // The base class gives us the pointer without AddRef'ing it.
+        // If we return the pointer to the caller, we must AddRef().
+        HRESULT hr = List<Ptr>::GetItem(pNode, &pItem);
+        if (SUCCEEDED(hr))
+        {
+            assert(pItem || NULLABLE);
+            if (pItem)
+            {
+                *ppItem = pItem;
+                (*ppItem)->AddRef();
+            }
+        }
+        return hr;
+    }
+
+    HRESULT RemoveItem(Node *pNode, Ptr *ppItem)
+    {
+        // ppItem can be nullptr, but we need to get the
+        // item so that we can release it. 
+
+        // If ppItem is not nullptr, we will AddRef it on the way out.
+
+        Ptr pItem = nullptr;
+
+        HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem);
+
+        if (SUCCEEDED(hr))
+        {
+            assert(pItem || NULLABLE);
+            if (ppItem && pItem)
+            {
+                *ppItem = pItem;
+                (*ppItem)->AddRef();
+            }
+
+            if (pItem)
+            {
+                pItem->Release();
+                pItem = nullptr;
+            }
+        }
+
+        return hr;
+    }
+};
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h
new file mode 100644
index 000000000..dd0813be3
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h
@@ -0,0 +1,222 @@
+//////////////////////////////////////////////////////////////////////////
+//
+// OpQueue.h
+// Async operation queue.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+//////////////////////////////////////////////////////////////////////////
+
+#pragma once
+
+#pragma warning( push )
+#pragma warning( disable : 4355 )  // 'this' used in base member initializer list
+
+/*
+    This header file defines an object to help queue and serialize
+    asynchronous operations.
+
+    Background:
+
+    To perform an operation asynchronously in Media Foundation, an object
+    does one of the following:
+
+        1. Calls MFPutWorkItem(Ex), using either a standard work queue
+           identifier or a caller-allocated work queue. The work-queue
+           thread invokes the object's callback.
+
+        2. Creates an async result object (IMFAsyncResult) and calls
+           MFInvokeCallback to invoke the object's callback.
+
+    Ultimately, either of these cause the object's callback to be invoked
+    from a work-queue thread. The object can then complete the operation
+    inside the callback.
+
+    However, the Media Foundation platform may dispatch async callbacks in
+    parallel on several threads. Putting an item on a work queue does NOT
+    guarantee that one operation will complete before the next one starts,
+    or even that work items will be dispatched in the same order they were
+    called.
+
+    To serialize async operations that should not overlap, an object should
+    use a queue. While one operation is pending, subsequent operations are
+    put on the queue, and only dispatched after the previous operation is
+    complete.
+
+    The granularity of a single "operation" depends on the requirements of
+    that particular object. A single operation might involve several
+    asynchronous calls before the object dispatches the next operation on
+    the queue.
+
+
+*/
+
+
+
+//-------------------------------------------------------------------
+// OpQueue class template
+//
+// Base class for an async operation queue.
+//
+// TOperation: The class used to describe operations. This class must
+//          implement IUnknown.
+//
+// The OpQueue class is an abstract class. The derived class must
+// implement the following pure-virtual methods:
+//
+// - IUnknown methods (AddRef, Release, QI)
+//
+// - DispatchOperation:
+//
+//      Performs the asynchronous operation specified by pOp.
+//
+//      At the end of each operation, the derived class must call
+//      ProcessQueue to process the next operation in the queue.
+//
+//      NOTE: An operation is not required to complete inside the
+//      DispatchOperation method. A single operation might consist
+//      of several asynchronous method calls.
+//
+// - ValidateOperation:
+//
+//      Checks whether the object can perform the operation specified
+//      by pOp at this time.
+//
+//      If the object cannot perform the operation now (e.g., because
+//      another operation is still in progress) the method should
+//      return MF_E_NOTACCEPTING.
+//
+//-------------------------------------------------------------------
+#include "linklist.h"
+#include "AsyncCB.h"
+
+template <class T, class TOperation>
+class OpQueue //: public IUnknown
+{
+public:
+
+    typedef ComPtrList<TOperation>   OpList;
+
+    HRESULT QueueOperation(TOperation *pOp);
+
+protected:
+
+    HRESULT ProcessQueue();
+    HRESULT ProcessQueueAsync(IMFAsyncResult *pResult);
+
+    virtual HRESULT DispatchOperation(TOperation *pOp) = 0;
+    virtual HRESULT ValidateOperation(TOperation *pOp) = 0;
+
+    OpQueue(CRITICAL_SECTION& critsec)
+        : m_OnProcessQueue(static_cast<T *>(this), &OpQueue::ProcessQueueAsync),
+          m_critsec(critsec)
+    {
+    }
+
+    virtual ~OpQueue()
+    {
+    }
+
+protected:
+    OpList                  m_OpQueue;         // Queue of operations.
+    CRITICAL_SECTION&       m_critsec;         // Protects the queue state.
+    AsyncCallback<T>  m_OnProcessQueue;  // ProcessQueueAsync callback.
+};
+
+
+
+//-------------------------------------------------------------------
+// Place an operation on the queue.
+// Public method.
+//-------------------------------------------------------------------
+
+template <class T, class TOperation>
+HRESULT OpQueue<T, TOperation>::QueueOperation(TOperation *pOp)
+{
+    HRESULT hr = S_OK;
+
+    EnterCriticalSection(&m_critsec);
+
+    hr = m_OpQueue.InsertBack(pOp);
+    if (SUCCEEDED(hr))
+    {
+        hr = ProcessQueue();
+    }
+
+    LeaveCriticalSection(&m_critsec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// Process the next operation on the queue.
+// Protected method.
+//
+// Note: This method dispatches the operation to a work queue.
+//-------------------------------------------------------------------
+
+template <class T, class TOperation>
+HRESULT OpQueue<T, TOperation>::ProcessQueue()
+{
+    HRESULT hr = S_OK;
+    if (m_OpQueue.GetCount() > 0)
+    {
+        hr = MFPutWorkItem2(
+            MFASYNC_CALLBACK_QUEUE_STANDARD,    // Use the standard work queue.
+            0,                                  // Default priority
+            &m_OnProcessQueue,                  // Callback method.
+            nullptr                             // State object.
+            );
+    }
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// Process the next operation on the queue.
+// Protected method.
+//
+// Note: This method is called from a work-queue thread.
+//-------------------------------------------------------------------
+
+template <class T, class TOperation>
+HRESULT OpQueue<T, TOperation>::ProcessQueueAsync(IMFAsyncResult *pResult)
+{
+    HRESULT hr = S_OK;
+    TOperation *pOp = nullptr;
+
+    EnterCriticalSection(&m_critsec);
+
+    if (m_OpQueue.GetCount() > 0)
+    {
+        hr = m_OpQueue.GetFront(&pOp);
+
+        if (SUCCEEDED(hr))
+        {
+            hr = ValidateOperation(pOp);
+        }
+        if (SUCCEEDED(hr))
+        {
+            hr = m_OpQueue.RemoveFront(nullptr);
+        }
+        if (SUCCEEDED(hr))
+        {
+            (void)DispatchOperation(pOp);
+        }
+    }
+
+    if (pOp != nullptr)
+    {
+        pOp->Release();
+    }
+
+    LeaveCriticalSection(&m_critsec);
+    return hr;
+}
+
+#pragma warning( pop )
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
new file mode 100644
index 000000000..687386ece
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
@@ -0,0 +1,1783 @@
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+
+#include "Grayscale.h"
+#include "bufferlock.h"
+
+#pragma comment(lib, "d2d1")
+
+using namespace Microsoft::WRL;
+
+/*
+
+This sample implements a video effect as a Media Foundation transform (MFT).
+
+The video effect manipulates chroma values in a YUV image. In the default setting,
+the entire image is converted to grayscale. Optionally, the application may set any
+of the following attributes:
+
+MFT_GRAYSCALE_DESTINATION_RECT (type = blob, UINT32[4] array)
+
+    Sets the destination rectangle for the effect. Pixels outside the destination
+    rectangle are not altered.
+
+MFT_GRAYSCALE_SATURATION (type = double)
+
+    Sets the saturation level. The nominal range is [0...1]. Values beyond 1.0f 
+    result in supersaturated colors. Values below 0.0f create inverted colors.
+    
+MFT_GRAYSCALE_CHROMA_ROTATION (type = double)
+
+    Rotates the chroma values of each pixel. The attribue value is the angle of
+    rotation in degrees. The result is a shift in hue.
+
+The effect is implemented by treating the chroma value of each pixel as a vector [u,v],
+and applying a transformation matrix to the vector. The saturation parameter is applied
+as a scaling transform.
+
+
+NOTES ON THE MFT IMPLEMENTATION
+
+1. The MFT has fixed streams: One input stream and one output stream. 
+
+2. The MFT supports the following formats: UYVY, YUY2, NV12.
+
+3. If the MFT is holding an input sample, SetInputType and SetOutputType both fail.
+
+4. The input and output types must be identical.
+
+5. If both types are set, no type can be set until the current type is cleared.
+
+6. Preferred input types:
+ 
+     (a) If the output type is set, that's the preferred type.
+     (b) Otherwise, the preferred types are partial types, constructed from the 
+         list of supported subtypes.
+ 
+7. Preferred output types: As above.
+
+8. Streaming: 
+ 
+    The private BeingStreaming() method is called in response to the 
+    MFT_MESSAGE_NOTIFY_BEGIN_STREAMING message. 
+
+    If the client does not send MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, the MFT calls
+    BeginStreaming inside the first call to ProcessInput or ProcessOutput. 
+
+    This is a good approach for allocating resources that your MFT requires for
+    streaming. 
+    
+9. The configuration attributes are applied in the BeginStreaming method. If the 
+   client changes the attributes during streaming, the change is ignored until 
+   streaming is stopped (either by changing the media types or by sending the 
+   MFT_MESSAGE_NOTIFY_END_STREAMING message) and then restarted.
+   
+*/
+
+
+// Video FOURCC codes.
+const DWORD FOURCC_YUY2 = '2YUY'; 
+const DWORD FOURCC_UYVY = 'YVYU'; 
+const DWORD FOURCC_NV12 = '21VN'; 
+
+// Static array of media types (preferred and accepted).
+const GUID g_MediaSubtypes[] =
+{
+    MFVideoFormat_NV12,
+    MFVideoFormat_YUY2,
+    MFVideoFormat_UYVY
+};
+
+HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage);
+HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride);
+bool ValidateRect(const RECT& rc);
+
+template <typename T>
+inline T clamp(const T& val, const T& minVal, const T& maxVal)
+{
+    return (val < minVal ? minVal : (val > maxVal ? maxVal : val));
+}
+
+
+// TransformChroma:
+// Apply the transforms to calculate the output chroma values.
+
+void TransformChroma(const D2D1::Matrix3x2F& mat, BYTE *pu, BYTE *pv)
+{
+    // Normalize the chroma values to [-112, 112] range
+
+    D2D1_POINT_2F pt = { static_cast<float>(*pu) - 128, static_cast<float>(*pv) - 128 };
+
+    pt = mat.TransformPoint(pt);
+
+    // Clamp to valid range.
+    clamp(pt.x, -112.0f, 112.0f);
+    clamp(pt.y, -112.0f, 112.0f);
+
+    // Map back to [16...240] range.
+    *pu = static_cast<BYTE>(pt.x + 128.0f);
+    *pv = static_cast<BYTE>(pt.y + 128.0f);
+}
+
+//-------------------------------------------------------------------
+// Functions to convert a YUV images to grayscale.
+//
+// In all cases, the same transformation is applied to the 8-bit
+// chroma values, but the pixel layout in memory differs.
+//
+// The image conversion functions take the following parameters:
+//
+// mat               Transfomation matrix for chroma values.
+// rcDest            Destination rectangle.
+// pDest             Pointer to the destination buffer.
+// lDestStride       Stride of the destination buffer, in bytes.
+// pSrc              Pointer to the source buffer.
+// lSrcStride        Stride of the source buffer, in bytes.
+// dwWidthInPixels   Frame width in pixels.
+// dwHeightInPixels  Frame height, in pixels.
+//-------------------------------------------------------------------
+
+// Convert UYVY image.
+
+void TransformImage_UYVY(
+    const D2D1::Matrix3x2F& mat,
+    const D2D_RECT_U& rcDest,
+    _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest, 
+    _In_ LONG lDestStride, 
+    _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
+    _In_ LONG lSrcStride, 
+    _In_ DWORD dwWidthInPixels, 
+    _In_ DWORD dwHeightInPixels)
+{
+    DWORD y = 0;
+    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
+
+    // Lines above the destination rectangle.
+    for ( ; y < rcDest.top; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels * 2);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+
+    // Lines within the destination rectangle.
+    for ( ; y < y0; y++)
+    {
+        WORD *pSrc_Pixel = (WORD*)pSrc;
+        WORD *pDest_Pixel = (WORD*)pDest;
+
+        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
+        {
+            // Byte order is U0 Y0 V0 Y1
+            // Each WORD is a byte pair (U/V, Y)
+            // Windows is little-endian so the order appears reversed.
+
+            if (x >= rcDest.left && x < rcDest.right)
+            {
+                BYTE u = pSrc_Pixel[x] & 0x00FF;
+                BYTE v = pSrc_Pixel[x+1] & 0x00FF;
+
+                TransformChroma(mat, &u, &v);
+
+                pDest_Pixel[x] = (pSrc_Pixel[x] & 0xFF00) | u;
+                pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0xFF00) | v;
+            }
+            else
+            {
+#pragma warning(push)
+#pragma warning(disable: 6385) 
+#pragma warning(disable: 6386) 
+                pDest_Pixel[x] = pSrc_Pixel[x];
+                pDest_Pixel[x+1] = pSrc_Pixel[x+1];
+#pragma warning(pop)
+            }
+        }
+
+        pDest += lDestStride;
+        pSrc += lSrcStride;
+    }
+
+    // Lines below the destination rectangle.
+    for ( ; y < dwHeightInPixels; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels * 2);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+}
+
+
+// Convert YUY2 image.
+
+void TransformImage_YUY2(
+    const D2D1::Matrix3x2F& mat,
+    const D2D_RECT_U& rcDest,
+    _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest, 
+    _In_ LONG lDestStride, 
+    _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
+    _In_ LONG lSrcStride, 
+    _In_ DWORD dwWidthInPixels, 
+    _In_ DWORD dwHeightInPixels)
+{
+    DWORD y = 0;
+    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
+
+    // Lines above the destination rectangle.
+    for ( ; y < rcDest.top; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels * 2);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+
+    // Lines within the destination rectangle.
+    for ( ; y < y0; y++)
+    {
+        WORD *pSrc_Pixel = (WORD*)pSrc;
+        WORD *pDest_Pixel = (WORD*)pDest;
+
+        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
+        {
+            // Byte order is Y0 U0 Y1 V0
+            // Each WORD is a byte pair (Y, U/V)
+            // Windows is little-endian so the order appears reversed.
+
+            if (x >= rcDest.left && x < rcDest.right)
+            {
+                BYTE u = pSrc_Pixel[x] >> 8;
+                BYTE v = pSrc_Pixel[x+1] >> 8;
+
+                TransformChroma(mat, &u, &v);
+
+                pDest_Pixel[x] = (pSrc_Pixel[x] & 0x00FF) | (u<<8);
+                pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0x00FF) | (v<<8);
+            }
+            else
+            {
+#pragma warning(push)
+#pragma warning(disable: 6385) 
+#pragma warning(disable: 6386) 
+                pDest_Pixel[x] = pSrc_Pixel[x];
+                pDest_Pixel[x+1] = pSrc_Pixel[x+1];
+#pragma warning(pop)
+            }
+        }
+        pDest += lDestStride;
+        pSrc += lSrcStride;
+    }
+
+    // Lines below the destination rectangle.
+    for ( ; y < dwHeightInPixels; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels * 2);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+}
+
+// Convert NV12 image
+
+void TransformImage_NV12(
+    const D2D1::Matrix3x2F& mat,
+    const D2D_RECT_U& rcDest,
+    _Inout_updates_(_Inexpressible_(2 * lDestStride * dwHeightInPixels)) BYTE *pDest, 
+    _In_ LONG lDestStride, 
+    _In_reads_(_Inexpressible_(2 * lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
+    _In_ LONG lSrcStride, 
+    _In_ DWORD dwWidthInPixels, 
+    _In_ DWORD dwHeightInPixels)
+{
+    // NV12 is planar: Y plane, followed by packed U-V plane.
+
+    // Y plane
+    for (DWORD y = 0; y < dwHeightInPixels; y++)
+    {
+        CopyMemory(pDest, pSrc, dwWidthInPixels);
+        pDest += lDestStride;
+        pSrc += lSrcStride;
+    }
+
+    // U-V plane
+
+    // NOTE: The U-V plane has 1/2 the number of lines as the Y plane.
+
+    // Lines above the destination rectangle.
+    DWORD y = 0;
+    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
+
+    for ( ; y < rcDest.top/2; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+
+    // Lines within the destination rectangle.
+    for ( ; y < y0/2; y++)
+    {
+        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
+        {
+            if (x >= rcDest.left && x < rcDest.right)
+            {
+                BYTE u = pSrc[x];
+                BYTE v = pSrc[x+1];
+
+                TransformChroma(mat, &u, &v);
+
+                pDest[x] = u;
+                pDest[x+1] = v;
+            }
+            else
+            {
+                pDest[x] = pSrc[x];
+                pDest[x+1] = pSrc[x+1];
+            }
+        }
+        pDest += lDestStride;
+        pSrc += lSrcStride;
+    }
+
+    // Lines below the destination rectangle.
+    for ( ; y < dwHeightInPixels/2; y++)
+    {
+        memcpy(pDest, pSrc, dwWidthInPixels);
+        pSrc += lSrcStride;
+        pDest += lDestStride;
+    }
+}
+
+CGrayscale::CGrayscale() :
+    m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL), m_pTransformFn(NULL),
+    m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
+    m_transform(D2D1::Matrix3x2F::Identity()), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
+    m_pAttributes(NULL)
+{
+    InitializeCriticalSectionEx(&m_critSec, 3000, 0);
+}
+
+CGrayscale::~CGrayscale()
+{
+    SafeRelease(&m_pInputType);
+    SafeRelease(&m_pOutputType);
+    SafeRelease(&m_pSample);
+    SafeRelease(&m_pAttributes);
+    DeleteCriticalSection(&m_critSec);
+}
+
+// Initialize the instance.
+STDMETHODIMP CGrayscale::RuntimeClassInitialize()
+{
+    // Create the attribute store.
+    return MFCreateAttributes(&m_pAttributes, 3);
+}
+
+// IMediaExtension methods
+
+//-------------------------------------------------------------------
+// SetProperties
+// Sets the configuration of the effect
+//-------------------------------------------------------------------
+HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
+{
+    return S_OK;
+}
+
+// IMFTransform methods. Refer to the Media Foundation SDK documentation for details.
+
+//-------------------------------------------------------------------
+// GetStreamLimits
+// Returns the minimum and maximum number of streams.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetStreamLimits(
+    DWORD   *pdwInputMinimum,
+    DWORD   *pdwInputMaximum,
+    DWORD   *pdwOutputMinimum,
+    DWORD   *pdwOutputMaximum
+)
+{
+    if ((pdwInputMinimum == NULL) ||
+        (pdwInputMaximum == NULL) ||
+        (pdwOutputMinimum == NULL) ||
+        (pdwOutputMaximum == NULL))
+    {
+        return E_POINTER;
+    }
+
+    // This MFT has a fixed number of streams.
+    *pdwInputMinimum = 1;
+    *pdwInputMaximum = 1;
+    *pdwOutputMinimum = 1;
+    *pdwOutputMaximum = 1;
+    return S_OK;
+}
+
+
+//-------------------------------------------------------------------
+// GetStreamCount
+// Returns the actual number of streams.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetStreamCount(
+    DWORD   *pcInputStreams,
+    DWORD   *pcOutputStreams
+)
+{
+    if ((pcInputStreams == NULL) || (pcOutputStreams == NULL))
+
+    {
+        return E_POINTER;
+    }
+
+    // This MFT has a fixed number of streams.
+    *pcInputStreams = 1;
+    *pcOutputStreams = 1;
+    return S_OK;
+}
+
+
+
+//-------------------------------------------------------------------
+// GetStreamIDs
+// Returns stream IDs for the input and output streams.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetStreamIDs(
+    DWORD   dwInputIDArraySize,
+    DWORD   *pdwInputIDs,
+    DWORD   dwOutputIDArraySize,
+    DWORD   *pdwOutputIDs
+)
+{
+    // It is not required to implement this method if the MFT has a fixed number of
+    // streams AND the stream IDs are numbered sequentially from zero (that is, the
+    // stream IDs match the stream indexes).
+
+    // In that case, it is OK to return E_NOTIMPL.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// GetInputStreamInfo
+// Returns information about an input stream.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetInputStreamInfo(
+    DWORD                     dwInputStreamID,
+    MFT_INPUT_STREAM_INFO *   pStreamInfo
+)
+{
+    if (pStreamInfo == NULL)
+    {
+        return E_POINTER;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    // NOTE: This method should succeed even when there is no media type on the
+    //       stream. If there is no media type, we only need to fill in the dwFlags
+    //       member of MFT_INPUT_STREAM_INFO. The other members depend on having a
+    //       a valid media type.
+
+    pStreamInfo->hnsMaxLatency = 0;
+    pStreamInfo->dwFlags = MFT_INPUT_STREAM_WHOLE_SAMPLES | MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER;
+
+    if (m_pInputType == NULL)
+    {
+        pStreamInfo->cbSize = 0;
+    }
+    else
+    {
+        pStreamInfo->cbSize = m_cbImageSize;
+    }
+
+    pStreamInfo->cbMaxLookahead = 0;
+    pStreamInfo->cbAlignment = 0;
+
+    LeaveCriticalSection(&m_critSec);
+    return S_OK;
+}
+
+//-------------------------------------------------------------------
+// GetOutputStreamInfo
+// Returns information about an output stream.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetOutputStreamInfo(
+    DWORD                     dwOutputStreamID,
+    MFT_OUTPUT_STREAM_INFO *  pStreamInfo
+)
+{
+    if (pStreamInfo == NULL)
+    {
+        return E_POINTER;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidOutputStream(dwOutputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    // NOTE: This method should succeed even when there is no media type on the
+    //       stream. If there is no media type, we only need to fill in the dwFlags
+    //       member of MFT_OUTPUT_STREAM_INFO. The other members depend on having a
+    //       a valid media type.
+
+    pStreamInfo->dwFlags =
+        MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
+        MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
+        MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE ;
+
+    if (m_pOutputType == NULL)
+    {
+        pStreamInfo->cbSize = 0;
+    }
+    else
+    {
+        pStreamInfo->cbSize = m_cbImageSize;
+    }
+
+    pStreamInfo->cbAlignment = 0;
+
+    LeaveCriticalSection(&m_critSec);
+    return S_OK;
+}
+
+
+//-------------------------------------------------------------------
+// GetAttributes
+// Returns the attributes for the MFT.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetAttributes(IMFAttributes** ppAttributes)
+{
+    if (ppAttributes == NULL)
+    {
+        return E_POINTER;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    *ppAttributes = m_pAttributes;
+    (*ppAttributes)->AddRef();
+
+    LeaveCriticalSection(&m_critSec);
+    return S_OK;
+}
+
+
+//-------------------------------------------------------------------
+// GetInputStreamAttributes
+// Returns stream-level attributes for an input stream.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetInputStreamAttributes(
+    DWORD           dwInputStreamID,
+    IMFAttributes   **ppAttributes
+)
+{
+    // This MFT does not support any stream-level attributes, so the method is not implemented.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// GetOutputStreamAttributes
+// Returns stream-level attributes for an output stream.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetOutputStreamAttributes(
+    DWORD           dwOutputStreamID,
+    IMFAttributes   **ppAttributes
+)
+{
+    // This MFT does not support any stream-level attributes, so the method is not implemented.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// DeleteInputStream
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::DeleteInputStream(DWORD dwStreamID)
+{
+    // This MFT has a fixed number of input streams, so the method is not supported.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// AddInputStreams
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::AddInputStreams(
+    DWORD   cStreams,
+    DWORD   *adwStreamIDs
+)
+{
+    // This MFT has a fixed number of output streams, so the method is not supported.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// GetInputAvailableType
+// Returns a preferred input type.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetInputAvailableType(
+    DWORD           dwInputStreamID,
+    DWORD           dwTypeIndex, // 0-based
+    IMFMediaType    **ppType
+)
+{
+    if (ppType == NULL)
+    {
+        return E_INVALIDARG;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    HRESULT hr = S_OK;
+
+    // If the output type is set, return that type as our preferred input type.
+    if (m_pOutputType == NULL)
+    {
+        // The output type is not set. Create a partial media type.
+        hr = OnGetPartialType(dwTypeIndex, ppType);
+    }
+    else if (dwTypeIndex > 0)
+    {
+        hr = MF_E_NO_MORE_TYPES;
+    }
+    else
+    {
+        *ppType = m_pOutputType;
+        (*ppType)->AddRef();
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+
+//-------------------------------------------------------------------
+// GetOutputAvailableType
+// Returns a preferred output type.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetOutputAvailableType(
+    DWORD           dwOutputStreamID,
+    DWORD           dwTypeIndex, // 0-based
+    IMFMediaType    **ppType
+)
+{
+    if (ppType == NULL)
+    {
+        return E_INVALIDARG;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidOutputStream(dwOutputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    HRESULT hr = S_OK;
+
+    if (m_pInputType == NULL)
+    {
+        // The input type is not set. Create a partial media type.
+        hr = OnGetPartialType(dwTypeIndex, ppType);
+    }
+    else if (dwTypeIndex > 0)
+    {
+        hr = MF_E_NO_MORE_TYPES;
+    }
+    else
+    {
+        *ppType = m_pInputType;
+        (*ppType)->AddRef();
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// SetInputType
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::SetInputType(
+    DWORD           dwInputStreamID,
+    IMFMediaType    *pType, // Can be NULL to clear the input type.
+    DWORD           dwFlags
+)
+{
+    // Validate flags.
+    if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
+    {
+        return E_INVALIDARG;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    HRESULT hr = S_OK;
+
+    // Does the caller want us to set the type, or just test it?
+    BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
+
+    // If we have an input sample, the client cannot change the type now.
+    if (HasPendingOutput())
+    {
+        hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
+        goto done;
+    }
+
+    // Validate the type, if non-NULL.
+    if (pType)
+    {
+        hr = OnCheckInputType(pType);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+    }
+
+    // The type is OK. Set the type, unless the caller was just testing.
+    if (bReallySet)
+    {
+        OnSetInputType(pType);
+
+        // When the type changes, end streaming.
+        hr = EndStreaming();
+    }
+
+done:
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+
+//-------------------------------------------------------------------
+// SetOutputType
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::SetOutputType(
+    DWORD           dwOutputStreamID,
+    IMFMediaType    *pType, // Can be NULL to clear the output type.
+    DWORD           dwFlags
+)
+{
+    // Validate flags.
+    if (dwFlags & ~MFT_SET_TYPE_TEST_ONLY)
+    {
+        return E_INVALIDARG;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidOutputStream(dwOutputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    HRESULT hr = S_OK;
+
+    // Does the caller want us to set the type, or just test it?
+    BOOL bReallySet = ((dwFlags & MFT_SET_TYPE_TEST_ONLY) == 0);
+
+    // If we have an input sample, the client cannot change the type now.
+    if (HasPendingOutput())
+    {
+        hr = MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING;
+        goto done;
+    }
+
+    // Validate the type, if non-NULL.
+    if (pType)
+    {
+        hr = OnCheckOutputType(pType);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+    }
+
+    // The type is OK. Set the type, unless the caller was just testing.
+    if (bReallySet)
+    {
+        OnSetOutputType(pType);
+
+        // When the type changes, end streaming.
+        hr = EndStreaming();
+    }
+
+done:
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// GetInputCurrentType
+// Returns the current input type.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetInputCurrentType(
+    DWORD           dwInputStreamID,
+    IMFMediaType    **ppType
+)
+{
+    if (ppType == NULL)
+    {
+        return E_POINTER;
+    }
+
+    HRESULT hr = S_OK;
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        hr = MF_E_INVALIDSTREAMNUMBER;
+    }
+    else if (!m_pInputType)
+    {
+        hr = MF_E_TRANSFORM_TYPE_NOT_SET;
+    }
+    else
+    {
+        *ppType = m_pInputType;
+        (*ppType)->AddRef();
+    }
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// GetOutputCurrentType
+// Returns the current output type.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetOutputCurrentType(
+    DWORD           dwOutputStreamID,
+    IMFMediaType    **ppType
+)
+{
+    if (ppType == NULL)
+    {
+        return E_POINTER;
+    }
+
+    HRESULT hr = S_OK;
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidOutputStream(dwOutputStreamID))
+    {
+        hr = MF_E_INVALIDSTREAMNUMBER;
+    }
+    else if (!m_pOutputType)
+    {
+        hr = MF_E_TRANSFORM_TYPE_NOT_SET;
+    }
+    else
+    {
+        *ppType = m_pOutputType;
+        (*ppType)->AddRef();
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// GetInputStatus
+// Query if the MFT is accepting more input.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetInputStatus(
+    DWORD           dwInputStreamID,
+    DWORD           *pdwFlags
+)
+{
+    if (pdwFlags == NULL)
+    {
+        return E_POINTER;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        LeaveCriticalSection(&m_critSec);
+        return MF_E_INVALIDSTREAMNUMBER;
+    }
+
+    // If an input sample is already queued, do not accept another sample until the 
+    // client calls ProcessOutput or Flush.
+
+    // NOTE: It is possible for an MFT to accept more than one input sample. For 
+    // example, this might be required in a video decoder if the frames do not 
+    // arrive in temporal order. In the case, the decoder must hold a queue of 
+    // samples. For the video effect, each sample is transformed independently, so
+    // there is no reason to queue multiple input samples.
+
+    if (m_pSample == NULL)
+    {
+        *pdwFlags = MFT_INPUT_STATUS_ACCEPT_DATA;
+    }
+    else
+    {
+        *pdwFlags = 0;
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return S_OK;
+}
+
+
+
+//-------------------------------------------------------------------
+// GetOutputStatus
+// Query if the MFT can produce output.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::GetOutputStatus(DWORD *pdwFlags)
+{
+    if (pdwFlags == NULL)
+    {
+        return E_POINTER;
+    }
+
+    EnterCriticalSection(&m_critSec);
+
+    // The MFT can produce an output sample if (and only if) there an input sample.
+    if (m_pSample != NULL)
+    {
+        *pdwFlags = MFT_OUTPUT_STATUS_SAMPLE_READY;
+    }
+    else
+    {
+        *pdwFlags = 0;
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return S_OK;
+}
+
+
+//-------------------------------------------------------------------
+// SetOutputBounds
+// Sets the range of time stamps that the MFT will output.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::SetOutputBounds(
+    LONGLONG        hnsLowerBound,
+    LONGLONG        hnsUpperBound
+)
+{
+    // Implementation of this method is optional.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// ProcessEvent
+// Sends an event to an input stream.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::ProcessEvent(
+    DWORD              dwInputStreamID,
+    IMFMediaEvent      *pEvent
+)
+{
+    // This MFT does not handle any stream events, so the method can
+    // return E_NOTIMPL. This tells the pipeline that it can stop
+    // sending any more events to this MFT.
+    return E_NOTIMPL;
+}
+
+
+//-------------------------------------------------------------------
+// ProcessMessage
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::ProcessMessage(
+    MFT_MESSAGE_TYPE    eMessage,
+    ULONG_PTR           ulParam
+)
+{
+    EnterCriticalSection(&m_critSec);
+
+    HRESULT hr = S_OK;
+
+    switch (eMessage)
+    {
+    case MFT_MESSAGE_COMMAND_FLUSH:
+        // Flush the MFT.
+        hr = OnFlush();
+        break;
+
+    case MFT_MESSAGE_COMMAND_DRAIN:
+        // Drain: Tells the MFT to reject further input until all pending samples are
+        // processed. That is our default behavior already, so there is nothing to do.
+        //
+        // For a decoder that accepts a queue of samples, the MFT might need to drain
+        // the queue in response to this command.
+    break;
+
+    case MFT_MESSAGE_SET_D3D_MANAGER:
+        // Sets a pointer to the IDirect3DDeviceManager9 interface.
+
+        // The pipeline should never send this message unless the MFT sets the MF_SA_D3D_AWARE 
+        // attribute set to TRUE. Because this MFT does not set MF_SA_D3D_AWARE, it is an error
+        // to send the MFT_MESSAGE_SET_D3D_MANAGER message to the MFT. Return an error code in
+        // this case.
+
+        // NOTE: If this MFT were D3D-enabled, it would cache the IDirect3DDeviceManager9 
+        // pointer for use during streaming.
+
+        hr = E_NOTIMPL;
+        break;
+
+    case MFT_MESSAGE_NOTIFY_BEGIN_STREAMING:
+        hr = BeginStreaming();
+        break;
+
+    case MFT_MESSAGE_NOTIFY_END_STREAMING:
+        hr = EndStreaming();
+        break;
+
+    // The next two messages do not require any action from this MFT.
+
+    case MFT_MESSAGE_NOTIFY_END_OF_STREAM:
+        break;
+
+    case MFT_MESSAGE_NOTIFY_START_OF_STREAM:
+        break;
+    }
+
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// ProcessInput
+// Process an input sample.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::ProcessInput(
+    DWORD               dwInputStreamID,
+    IMFSample           *pSample,
+    DWORD               dwFlags
+)
+{
+    // Check input parameters.
+    if (pSample == NULL)
+    {
+        return E_POINTER;
+    }
+
+    if (dwFlags != 0)
+    {
+        return E_INVALIDARG; // dwFlags is reserved and must be zero.
+    }
+
+    HRESULT hr = S_OK;
+
+    EnterCriticalSection(&m_critSec);
+
+    // Validate the input stream number.
+    if (!IsValidInputStream(dwInputStreamID))
+    {
+        hr = MF_E_INVALIDSTREAMNUMBER;
+        goto done;
+    }
+
+    // Check for valid media types.
+    // The client must set input and output types before calling ProcessInput.
+    if (!m_pInputType || !m_pOutputType)
+    {
+        hr = MF_E_NOTACCEPTING;   
+        goto done;
+    }
+
+    // Check if an input sample is already queued.
+    if (m_pSample != NULL)
+    {
+        hr = MF_E_NOTACCEPTING;   // We already have an input sample.
+        goto done;
+    }
+
+    // Initialize streaming.
+    hr = BeginStreaming();
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Cache the sample. We do the actual work in ProcessOutput.
+    m_pSample = pSample;
+    pSample->AddRef();  // Hold a reference count on the sample.
+
+done:
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+
+//-------------------------------------------------------------------
+// ProcessOutput
+// Process an output sample.
+//-------------------------------------------------------------------
+
+HRESULT CGrayscale::ProcessOutput(
+    DWORD                   dwFlags,
+    DWORD                   cOutputBufferCount,
+    MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
+    DWORD                   *pdwStatus
+)
+{
+    // Check input parameters...
+
+    // This MFT does not accept any flags for the dwFlags parameter.
+
+    // The only defined flag is MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER. This flag 
+    // applies only when the MFT marks an output stream as lazy or optional. But this
+    // MFT has no lazy or optional streams, so the flag is not valid.
+
+    if (dwFlags != 0)
+    {
+        return E_INVALIDARG;
+    }
+
+    if (pOutputSamples == NULL || pdwStatus == NULL)
+    {
+        return E_POINTER;
+    }
+
+    // There must be exactly one output buffer.
+    if (cOutputBufferCount != 1)
+    {
+        return E_INVALIDARG;
+    }
+
+    // It must contain a sample.
+    if (pOutputSamples[0].pSample == NULL)
+    {
+        return E_INVALIDARG;
+    }
+
+    HRESULT hr = S_OK;
+
+    IMFMediaBuffer *pInput = NULL;
+    IMFMediaBuffer *pOutput = NULL;
+
+    EnterCriticalSection(&m_critSec);
+
+    // There must be an input sample available for processing.
+    if (m_pSample == NULL)
+    {
+        hr = MF_E_TRANSFORM_NEED_MORE_INPUT;
+        goto done;
+    }
+
+    // Initialize streaming.
+
+    hr = BeginStreaming();
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Get the input buffer.
+    hr = m_pSample->ConvertToContiguousBuffer(&pInput);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Get the output buffer.
+    hr = pOutputSamples[0].pSample->ConvertToContiguousBuffer(&pOutput);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    hr = OnProcessOutput(pInput, pOutput);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Set status flags.
+    pOutputSamples[0].dwStatus = 0;
+    *pdwStatus = 0;
+
+
+    // Copy the duration and time stamp from the input sample, if present.
+
+    LONGLONG hnsDuration = 0;
+    LONGLONG hnsTime = 0;
+
+    if (SUCCEEDED(m_pSample->GetSampleDuration(&hnsDuration)))
+    {
+        hr = pOutputSamples[0].pSample->SetSampleDuration(hnsDuration);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+    }
+
+    if (SUCCEEDED(m_pSample->GetSampleTime(&hnsTime)))
+    {
+        hr = pOutputSamples[0].pSample->SetSampleTime(hnsTime);
+    }
+
+done:
+    SafeRelease(&m_pSample);   // Release our input sample.
+    SafeRelease(&pInput);
+    SafeRelease(&pOutput);
+    LeaveCriticalSection(&m_critSec);
+    return hr;
+}
+
+// PRIVATE METHODS
+
+// All methods that follow are private to this MFT and are not part of the IMFTransform interface.
+
+// Create a partial media type from our list.
+//
+// dwTypeIndex: Index into the list of peferred media types.
+// ppmt:        Receives a pointer to the media type.
+
+HRESULT CGrayscale::OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt)
+{
+    if (dwTypeIndex >= ARRAYSIZE(g_MediaSubtypes))
+    {
+        return MF_E_NO_MORE_TYPES;
+    }
+
+    IMFMediaType *pmt = NULL;
+
+    HRESULT hr = MFCreateMediaType(&pmt);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    hr = pmt->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    hr = pmt->SetGUID(MF_MT_SUBTYPE, g_MediaSubtypes[dwTypeIndex]);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    *ppmt = pmt;
+    (*ppmt)->AddRef();
+
+done:
+    SafeRelease(&pmt);
+    return hr;
+}
+
+
+// Validate an input media type.
+
+HRESULT CGrayscale::OnCheckInputType(IMFMediaType *pmt)
+{
+    assert(pmt != NULL);
+
+    HRESULT hr = S_OK;
+
+    // If the output type is set, see if they match.
+    if (m_pOutputType != NULL)
+    {
+        DWORD flags = 0;
+        hr = pmt->IsEqual(m_pOutputType, &flags);
+
+        // IsEqual can return S_FALSE. Treat this as failure.
+        if (hr != S_OK)
+        {
+            hr = MF_E_INVALIDMEDIATYPE;
+        }
+    }
+    else
+    {
+        // Output type is not set. Just check this type.
+        hr = OnCheckMediaType(pmt);
+    }
+    return hr;
+}
+
+
+// Validate an output media type.
+
+HRESULT CGrayscale::OnCheckOutputType(IMFMediaType *pmt)
+{
+    assert(pmt != NULL);
+
+    HRESULT hr = S_OK;
+
+    // If the input type is set, see if they match.
+    if (m_pInputType != NULL)
+    {
+        DWORD flags = 0;
+        hr = pmt->IsEqual(m_pInputType, &flags);
+
+        // IsEqual can return S_FALSE. Treat this as failure.
+        if (hr != S_OK)
+        {
+            hr = MF_E_INVALIDMEDIATYPE;
+        }
+
+    }
+    else
+    {
+        // Input type is not set. Just check this type.
+        hr = OnCheckMediaType(pmt);
+    }
+    return hr;
+}
+
+
+// Validate a media type (input or output)
+
+HRESULT CGrayscale::OnCheckMediaType(IMFMediaType *pmt)
+{
+    BOOL bFoundMatchingSubtype = FALSE;
+
+    // Major type must be video.
+    GUID major_type;
+    HRESULT hr = pmt->GetGUID(MF_MT_MAJOR_TYPE, &major_type);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    if (major_type != MFMediaType_Video)
+    {
+        hr = MF_E_INVALIDMEDIATYPE;
+        goto done;
+    }
+
+    // Subtype must be one of the subtypes in our global list.
+
+    // Get the subtype GUID.
+    GUID subtype;
+    hr = pmt->GetGUID(MF_MT_SUBTYPE, &subtype);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Look for the subtype in our list of accepted types.
+    for (DWORD i = 0; i < ARRAYSIZE(g_MediaSubtypes); i++)
+    {
+        if (subtype == g_MediaSubtypes[i])
+        {
+            bFoundMatchingSubtype = TRUE;
+            break;
+        }
+    }
+
+    if (!bFoundMatchingSubtype)
+    {
+        hr = MF_E_INVALIDMEDIATYPE; // The MFT does not support this subtype.
+        goto done;
+    }
+
+    // Reject single-field media types. 
+    UINT32 interlace = MFGetAttributeUINT32(pmt, MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
+    if (interlace == MFVideoInterlace_FieldSingleUpper  || interlace == MFVideoInterlace_FieldSingleLower)
+    {
+        hr = MF_E_INVALIDMEDIATYPE;
+    }
+
+done:
+    return hr;
+}
+
+
+// Set or clear the input media type.
+//
+// Prerequisite: The input type was already validated.
+
+void CGrayscale::OnSetInputType(IMFMediaType *pmt)
+{
+    // if pmt is NULL, clear the type.
+    // if pmt is non-NULL, set the type.
+
+    SafeRelease(&m_pInputType);
+    m_pInputType = pmt;
+    if (m_pInputType)
+    {
+        m_pInputType->AddRef();
+    }
+
+    // Update the format information.
+    UpdateFormatInfo();
+}
+
+
+// Set or clears the output media type.
+//
+// Prerequisite: The output type was already validated.
+
+void CGrayscale::OnSetOutputType(IMFMediaType *pmt)
+{
+    // If pmt is NULL, clear the type. Otherwise, set the type.
+
+    SafeRelease(&m_pOutputType);
+    m_pOutputType = pmt;
+    if (m_pOutputType)
+    {
+        m_pOutputType->AddRef();
+    }
+}
+
+
+// Initialize streaming parameters.
+//
+// This method is called if the client sends the MFT_MESSAGE_NOTIFY_BEGIN_STREAMING
+// message, or when the client processes a sample, whichever happens first.
+
+HRESULT CGrayscale::BeginStreaming()
+{
+    HRESULT hr = S_OK;
+
+    if (!m_bStreamingInitialized)
+    {
+        // Get the configuration attributes.
+
+        // Get the destination rectangle.
+
+        RECT rcDest;
+        hr = m_pAttributes->GetBlob(MFT_GRAYSCALE_DESTINATION_RECT, (UINT8*)&rcDest, sizeof(rcDest), NULL);
+        if (hr == MF_E_ATTRIBUTENOTFOUND || !ValidateRect(rcDest))
+        {
+            // The client did not set this attribute, or the client provided an invalid rectangle.
+            // Default to the entire image.
+
+            m_rcDest = D2D1::RectU(0, 0, m_imageWidthInPixels, m_imageHeightInPixels);
+            hr = S_OK;
+        }
+        else if (SUCCEEDED(hr))
+        {
+            m_rcDest = D2D1::RectU(rcDest.left, rcDest.top, rcDest.right, rcDest.bottom);
+        }
+        else
+        {
+            goto done;
+        }
+
+        // Get the chroma transformations.
+
+        float scale = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_SATURATION, 0.0f);
+        float angle = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_CHROMA_ROTATION, 0.0f);
+
+        m_transform = D2D1::Matrix3x2F::Scale(scale, scale) * D2D1::Matrix3x2F::Rotation(angle);
+
+        m_bStreamingInitialized = true;
+    }
+
+done:
+    return hr;
+}
+
+
+// End streaming. 
+
+// This method is called if the client sends an MFT_MESSAGE_NOTIFY_END_STREAMING
+// message, or when the media type changes. In general, it should be called whenever
+// the streaming parameters need to be reset.
+
+HRESULT CGrayscale::EndStreaming()
+{
+    m_bStreamingInitialized = false;
+    return S_OK;
+}
+
+
+
+// Generate output data.
+
+HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
+{
+    BYTE *pDest = NULL;         // Destination buffer.
+    LONG lDestStride = 0;       // Destination stride.
+
+    BYTE *pSrc = NULL;          // Source buffer.
+    LONG lSrcStride = 0;        // Source stride.
+
+    // Helper objects to lock the buffers.
+    VideoBufferLock inputLock(pIn);
+    VideoBufferLock outputLock(pOut);
+
+    // Stride if the buffer does not support IMF2DBuffer
+    LONG lDefaultStride = 0;
+
+    HRESULT hr = GetDefaultStride(m_pInputType, &lDefaultStride);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Lock the input buffer.
+    hr = inputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pSrc, &lSrcStride);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Lock the output buffer.
+    hr = outputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pDest, &lDestStride);
+    if (FAILED(hr))
+    {
+        goto done;
+    }
+
+    // Invoke the image transform function.
+    assert (m_pTransformFn != NULL);
+    if (m_pTransformFn)
+    {
+        (*m_pTransformFn)(m_transform, m_rcDest, pDest, lDestStride, pSrc, lSrcStride,
+            m_imageWidthInPixels, m_imageHeightInPixels);
+    }
+    else
+    {
+        hr = E_UNEXPECTED;
+        goto done;
+    }
+
+
+    // Set the data size on the output buffer.
+    hr = pOut->SetCurrentLength(m_cbImageSize);
+
+    // The VideoBufferLock class automatically unlocks the buffers.
+done:
+    return hr;
+}
+
+
+// Flush the MFT.
+
+HRESULT CGrayscale::OnFlush()
+{
+    // For this MFT, flushing just means releasing the input sample.
+    SafeRelease(&m_pSample);
+    return S_OK;
+}
+
+
+// Update the format information. This method is called whenever the
+// input type is set.
+
+HRESULT CGrayscale::UpdateFormatInfo()
+{
+    HRESULT hr = S_OK;
+
+    GUID subtype = GUID_NULL;
+
+    m_imageWidthInPixels = 0;
+    m_imageHeightInPixels = 0;
+    m_cbImageSize = 0;
+
+    m_pTransformFn = NULL;
+
+    if (m_pInputType != NULL)
+    {
+        hr = m_pInputType->GetGUID(MF_MT_SUBTYPE, &subtype);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+        if (subtype == MFVideoFormat_YUY2)
+        {
+            m_pTransformFn = TransformImage_YUY2;
+        }
+        else if (subtype == MFVideoFormat_UYVY)
+        {
+            m_pTransformFn = TransformImage_UYVY;
+        }
+        else if (subtype == MFVideoFormat_NV12)
+        {
+            m_pTransformFn = TransformImage_NV12;
+        }
+        else
+        {
+            hr = E_UNEXPECTED;
+            goto done;
+        }
+
+        hr = MFGetAttributeSize(m_pInputType, MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
+        if (FAILED(hr))
+        {
+            goto done;
+        }
+
+        // Calculate the image size (not including padding)
+        hr = GetImageSize(subtype.Data1, m_imageWidthInPixels, m_imageHeightInPixels, &m_cbImageSize);
+    }
+
+done:
+    return hr;
+}
+
+
+// Calculate the size of the buffer needed to store the image.
+
+// fcc: The FOURCC code of the video format.
+
+HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage)
+{
+    HRESULT hr = S_OK;
+
+    switch (fcc)
+    {
+    case FOURCC_YUY2:
+    case FOURCC_UYVY:
+        // check overflow
+        if ((width > MAXDWORD / 2) || (width * 2 > MAXDWORD / height))
+        {
+            hr = E_INVALIDARG;
+        }
+        else
+        {   
+            // 16 bpp
+            *pcbImage = width * height * 2;
+        }
+        break;
+
+    case FOURCC_NV12:
+        // check overflow
+        if ((height/2 > MAXDWORD - height) || ((height + height/2) > MAXDWORD / width))
+        {
+            hr = E_INVALIDARG;
+        }
+        else
+        {
+            // 12 bpp
+            *pcbImage = width * (height + (height/2));
+        }
+        break;
+
+    default:
+        hr = E_FAIL;    // Unsupported type.
+    }
+    return hr;
+}
+
+// Get the default stride for a video format. 
+HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
+{
+    LONG lStride = 0;
+
+    // Try to get the default stride from the media type.
+    HRESULT hr = pType->GetUINT32(MF_MT_DEFAULT_STRIDE, (UINT32*)&lStride);
+    if (FAILED(hr))
+    {
+        // Attribute not set. Try to calculate the default stride.
+        GUID subtype = GUID_NULL;
+
+        UINT32 width = 0;
+        UINT32 height = 0;
+
+        // Get the subtype and the image size.
+        hr = pType->GetGUID(MF_MT_SUBTYPE, &subtype);
+        if (SUCCEEDED(hr))
+        {
+            hr = MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &width, &height);
+        }
+        if (SUCCEEDED(hr))
+        {
+            if (subtype == MFVideoFormat_NV12)
+            {
+                lStride = width;
+            }
+            else if (subtype == MFVideoFormat_YUY2 || subtype == MFVideoFormat_UYVY)
+            {
+                lStride = ((width * 2) + 3) & ~3;
+            }
+            else
+            {
+                hr = E_INVALIDARG;
+            }
+        }
+
+        // Set the attribute for later reference.
+        if (SUCCEEDED(hr))
+        {
+            (void)pType->SetUINT32(MF_MT_DEFAULT_STRIDE, UINT32(lStride));
+        }
+    }
+    if (SUCCEEDED(hr))
+    {
+        *plStride = lStride;
+    }
+    return hr;
+}
+
+
+// Validate that a rectangle meets the following criteria:
+//
+//  - All coordinates are non-negative.
+//  - The rectangle is not flipped (top > bottom, left > right)
+//
+// These are the requirements for the destination rectangle.
+
+bool ValidateRect(const RECT& rc)
+{
+    if (rc.left < 0 || rc.top < 0)
+    {
+        return false;
+    }
+    if (rc.left > rc.right || rc.top > rc.bottom)
+    {
+        return false;
+    }
+    return true;
+}
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def
new file mode 100644
index 000000000..0b801908c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def
@@ -0,0 +1,4 @@
+EXPORTS
+    DllCanUnloadNow                     PRIVATE
+    DllGetActivationFactory             PRIVATE
+    DllGetClassObject                   PRIVATE
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
new file mode 100644
index 000000000..b83223bce
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
@@ -0,0 +1,266 @@
+// Defines the transform class.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+
+#ifndef GRAYSCALE_H
+#define GRAYSCALE_H
+
+#include <new>
+#include <mfapi.h>
+#include <mftransform.h>
+#include <mfidl.h>
+#include <mferror.h>
+#include <strsafe.h>
+#include <assert.h>
+
+// Note: The Direct2D helper library is included for its 2D matrix operations.
+#include <D2d1helper.h>
+
+#include <wrl\implements.h>
+#include <wrl\module.h>
+#include <windows.media.h>
+
+#include "GrayscaleTransform.h"
+
+// CLSID of the MFT.
+DEFINE_GUID(CLSID_GrayscaleMFT,
+0x2f3dbc05, 0xc011, 0x4a8f, 0xb2, 0x64, 0xe4, 0x2e, 0x35, 0xc6, 0x7b, 0xf4);
+
+//
+// * IMPORTANT: If you implement your own MFT, create a new GUID for the CLSID. *
+//
+
+
+// Configuration attributes
+
+// {7BBBB051-133B-41F5-B6AA-5AFF9B33A2CB}
+DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT, 
+0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb);
+
+
+// {14782342-93E8-4565-872C-D9A2973D5CBF}
+DEFINE_GUID(MFT_GRAYSCALE_SATURATION, 
+0x14782342, 0x93e8, 0x4565, 0x87, 0x2c, 0xd9, 0xa2, 0x97, 0x3d, 0x5c, 0xbf);
+
+// {E0BADE5D-E4B9-4689-9DBA-E2F00D9CED0E}
+DEFINE_GUID(MFT_GRAYSCALE_CHROMA_ROTATION, 
+0xe0bade5d, 0xe4b9, 0x4689, 0x9d, 0xba, 0xe2, 0xf0, 0xd, 0x9c, 0xed, 0xe);
+
+
+template <class T> void SafeRelease(T **ppT)
+{
+    if (*ppT)
+    {
+        (*ppT)->Release();
+        *ppT = NULL;
+    }
+}
+
+// Function pointer for the function that transforms the image.
+typedef void (*IMAGE_TRANSFORM_FN)(
+    const D2D1::Matrix3x2F& mat,             // Chroma transform matrix.
+    const D2D_RECT_U&       rcDest,          // Destination rectangle for the transformation.
+    BYTE*                   pDest,           // Destination buffer.
+    LONG                    lDestStride,     // Destination stride.
+    const BYTE*             pSrc,            // Source buffer.
+    LONG                    lSrcStride,      // Source stride.
+    DWORD                   dwWidthInPixels, // Image width in pixels.
+    DWORD                   dwHeightInPixels // Image height in pixels.
+    );
+
+// CGrayscale class:
+// Implements a grayscale video effect.
+
+class CGrayscale 
+    : public Microsoft::WRL::RuntimeClass<
+           Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >, 
+           ABI::Windows::Media::IMediaExtension,
+           IMFTransform >
+{
+    InspectableClass(RuntimeClass_GrayscaleTransform_GrayscaleEffect, BaseTrust)
+
+public:
+    CGrayscale();
+
+    ~CGrayscale();
+
+    STDMETHOD(RuntimeClassInitialize)();
+
+    // IMediaExtension
+    STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
+
+    // IMFTransform
+    STDMETHODIMP GetStreamLimits(
+        DWORD   *pdwInputMinimum,
+        DWORD   *pdwInputMaximum,
+        DWORD   *pdwOutputMinimum,
+        DWORD   *pdwOutputMaximum
+    );
+
+    STDMETHODIMP GetStreamCount(
+        DWORD   *pcInputStreams,
+        DWORD   *pcOutputStreams
+    );
+
+    STDMETHODIMP GetStreamIDs(
+        DWORD   dwInputIDArraySize,
+        DWORD   *pdwInputIDs,
+        DWORD   dwOutputIDArraySize,
+        DWORD   *pdwOutputIDs
+    );
+
+    STDMETHODIMP GetInputStreamInfo(
+        DWORD                     dwInputStreamID,
+        MFT_INPUT_STREAM_INFO *   pStreamInfo
+    );
+
+    STDMETHODIMP GetOutputStreamInfo(
+        DWORD                     dwOutputStreamID,
+        MFT_OUTPUT_STREAM_INFO *  pStreamInfo
+    );
+
+    STDMETHODIMP GetAttributes(IMFAttributes** pAttributes);
+
+    STDMETHODIMP GetInputStreamAttributes(
+        DWORD           dwInputStreamID,
+        IMFAttributes   **ppAttributes
+    );
+
+    STDMETHODIMP GetOutputStreamAttributes(
+        DWORD           dwOutputStreamID,
+        IMFAttributes   **ppAttributes
+    );
+
+    STDMETHODIMP DeleteInputStream(DWORD dwStreamID);
+
+    STDMETHODIMP AddInputStreams(
+        DWORD   cStreams,
+        DWORD   *adwStreamIDs
+    );
+
+    STDMETHODIMP GetInputAvailableType(
+        DWORD           dwInputStreamID,
+        DWORD           dwTypeIndex, // 0-based
+        IMFMediaType    **ppType
+    );
+
+    STDMETHODIMP GetOutputAvailableType(
+        DWORD           dwOutputStreamID,
+        DWORD           dwTypeIndex, // 0-based
+        IMFMediaType    **ppType
+    );
+
+    STDMETHODIMP SetInputType(
+        DWORD           dwInputStreamID,
+        IMFMediaType    *pType,
+        DWORD           dwFlags
+    );
+
+    STDMETHODIMP SetOutputType(
+        DWORD           dwOutputStreamID,
+        IMFMediaType    *pType,
+        DWORD           dwFlags
+    );
+
+    STDMETHODIMP GetInputCurrentType(
+        DWORD           dwInputStreamID,
+        IMFMediaType    **ppType
+    );
+
+    STDMETHODIMP GetOutputCurrentType(
+        DWORD           dwOutputStreamID,
+        IMFMediaType    **ppType
+    );
+
+    STDMETHODIMP GetInputStatus(
+        DWORD           dwInputStreamID,
+        DWORD           *pdwFlags
+    );
+
+    STDMETHODIMP GetOutputStatus(DWORD *pdwFlags);
+
+    STDMETHODIMP SetOutputBounds(
+        LONGLONG        hnsLowerBound,
+        LONGLONG        hnsUpperBound
+    );
+
+    STDMETHODIMP ProcessEvent(
+        DWORD              dwInputStreamID,
+        IMFMediaEvent      *pEvent
+    );
+
+    STDMETHODIMP ProcessMessage(
+        MFT_MESSAGE_TYPE    eMessage,
+        ULONG_PTR           ulParam
+    );
+
+    STDMETHODIMP ProcessInput(
+        DWORD               dwInputStreamID,
+        IMFSample           *pSample,
+        DWORD               dwFlags
+    );
+
+    STDMETHODIMP ProcessOutput(
+        DWORD                   dwFlags,
+        DWORD                   cOutputBufferCount,
+        MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
+        DWORD                   *pdwStatus
+    );
+
+
+private:
+    // HasPendingOutput: Returns TRUE if the MFT is holding an input sample.
+    BOOL HasPendingOutput() const { return m_pSample != NULL; }
+
+    // IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier.
+    BOOL IsValidInputStream(DWORD dwInputStreamID) const
+    {
+        return dwInputStreamID == 0;
+    }
+
+    // IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier.
+    BOOL IsValidOutputStream(DWORD dwOutputStreamID) const
+    {
+        return dwOutputStreamID == 0;
+    }
+
+    HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt);
+    HRESULT OnCheckInputType(IMFMediaType *pmt);
+    HRESULT OnCheckOutputType(IMFMediaType *pmt);
+    HRESULT OnCheckMediaType(IMFMediaType *pmt);
+    void    OnSetInputType(IMFMediaType *pmt);
+    void    OnSetOutputType(IMFMediaType *pmt);
+    HRESULT BeginStreaming();
+    HRESULT EndStreaming();
+    HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut);
+    HRESULT OnFlush();
+    HRESULT UpdateFormatInfo();
+
+    CRITICAL_SECTION            m_critSec;
+
+    // Transformation parameters
+    D2D1::Matrix3x2F            m_transform;                // Chroma transform matrix.
+    D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
+
+    // Streaming
+    bool                        m_bStreamingInitialized;
+    IMFSample                   *m_pSample;                 // Input sample.
+    IMFMediaType                *m_pInputType;              // Input media type.
+    IMFMediaType                *m_pOutputType;             // Output media type.
+
+    // Fomat information
+    UINT32                      m_imageWidthInPixels;
+    UINT32                      m_imageHeightInPixels;
+    DWORD                       m_cbImageSize;              // Image size, in bytes.
+
+    IMFAttributes               *m_pAttributes;
+
+    // Image transform function. (Changes based on the media type.)
+    IMAGE_TRANSFORM_FN          m_pTransformFn;
+};
+#endif
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
new file mode 100644
index 000000000..8af8f2c7d
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
@@ -0,0 +1,313 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|ARM">
+      <Configuration>Debug</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|ARM">
+      <Configuration>Release</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and '$(VisualStudioVersion)' == ''">$(VCTargetsPath11)</VCTargetsPath>
+    <ProjectGuid>{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>GrayscaleTransform</RootNamespace>
+    <ProjectName>GrayscaleTransform</ProjectName>
+    <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion>
+    <AppContainerApplication>true</AppContainerApplication>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <PropertyGroup>
+    <DefaultLanguage>en-US</DefaultLanguage>
+  </PropertyGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <GenerateManifest>false</GenerateManifest>
+    <OutDir>$(Configuration)\$(MSBuildProjectName)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
+    <GenerateManifest>false</GenerateManifest>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <GenerateManifest>false</GenerateManifest>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <GenerateManifest>false</GenerateManifest>
+    <OutDir>$(Configuration)\$(MSBuildProjectName)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
+    <GenerateManifest>false</GenerateManifest>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <GenerateManifest>false</GenerateManifest>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(ProjectDir)$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(ProjectDir)$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(ProjectDir)$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(ProjectDir)$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <PreprocessorDefinitions>_WINRT_DLL;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <PrecompiledHeaderFile>
+      </PrecompiledHeaderFile>
+      <PrecompiledHeaderOutputFile>
+      </PrecompiledHeaderOutputFile>
+      <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
+      <CompileAsWinRT>false</CompileAsWinRT>
+      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+    </Link>
+    <CustomBuildStep>
+      <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
+      <Outputs>$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd</Outputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="Grayscale.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="dllmain.cpp" />
+    <ClCompile Include="Grayscale.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Grayscale.def" />
+  </ItemGroup>
+  <ItemGroup>
+    <Midl Include="GrayscaleTransform.idl">
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+      </MetadataFileName>
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+      </MetadataFileName>
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
+      </MetadataFileName>
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
+      </MetadataFileName>
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+      </MetadataFileName>
+      <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+      </MetadataFileName>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <AdditionalMetadataDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(WindowsSDK_MetadataPath)</AdditionalMetadataDirectories>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</EnableWindowsRuntime>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</EnableWindowsRuntime>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</EnableWindowsRuntime>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</EnableWindowsRuntime>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</EnableWindowsRuntime>
+      <EnableWindowsRuntime Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</EnableWindowsRuntime>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).h</HeaderFileName>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).h</HeaderFileName>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">%(Filename).h</HeaderFileName>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">%(Filename).h</HeaderFileName>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).h</HeaderFileName>
+      <HeaderFileName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).h</HeaderFileName>
+    </Midl>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ItemGroup>
+    <_MdMergeOutput Condition="'$(Platform)' == 'Win32'" Include="$(ProjectDir)$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd" />
+    <_MdMergeOutput Condition="'$(Platform)' != 'Win32'" Include="$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)\$(ProjectName).winmd" />
+  </ItemGroup>
+  <Target Name="CopyWinmdArtifactsOutputGroup" Returns="@(CopyWinmdArtifactsOutputGroupOutputs)">
+    <ItemGroup>
+      <CopyWinmdArtifactsOutputGroupOutputs Include="@(_MdMergeOutput)">
+        <TargetPath>$(ProjectName).winmd</TargetPath>
+        <Implementation>$(TargetName)$(TargetExt)</Implementation>
+      </CopyWinmdArtifactsOutputGroupOutputs>
+    </ItemGroup>
+  </Target>
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
new file mode 100644
index 000000000..92c2c9cfe
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Resources">
+      <UniqueIdentifier>bdc52ff6-58cb-464b-bf4f-0c1804b135ff</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Grayscale.def" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="dllmain.cpp" />
+    <ClCompile Include="Grayscale.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Grayscale.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <Midl Include="GrayscaleTransform.idl" />
+  </ItemGroup>
+</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl
new file mode 100644
index 000000000..de81380ec
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl
@@ -0,0 +1,11 @@
+import "Windows.Media.idl";
+
+#include <sdkddkver.h>
+
+namespace GrayscaleTransform
+{
+	[version(NTDDI_WIN8)]
+	runtimeclass GrayscaleEffect 
+    {
+	}
+}
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp
new file mode 100644
index 000000000..ad6767011
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp
@@ -0,0 +1,58 @@
+//////////////////////////////////////////////////////////////////////////
+//
+// dllmain.cpp
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+//////////////////////////////////////////////////////////////////////////
+
+#include <initguid.h>
+#include "Grayscale.h"
+
+using namespace Microsoft::WRL;
+
+namespace Microsoft { namespace Samples {
+    ActivatableClass(CGrayscale);
+}}
+
+BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
+{
+    if( DLL_PROCESS_ATTACH == dwReason )
+    {
+        //
+        //  Don't need per-thread callbacks
+        //
+        DisableThreadLibraryCalls( hInstance );
+
+        Module<InProc>::GetModule().Create();
+    }
+    else if( DLL_PROCESS_DETACH == dwReason )
+    {
+        Module<InProc>::GetModule().Terminate();
+    }
+
+    return TRUE;
+}
+
+HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory )
+{
+    auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule();
+    return module.GetActivationFactory( activatibleClassId, factory );
+}
+
+HRESULT WINAPI DllCanUnloadNow()
+{
+    auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();    
+    return (module.Terminate()) ? S_OK : S_FALSE;
+}
+
+STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv )
+{
+    auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
+    return module.GetClassObject( rclsid, riid, ppv );
+}
diff --git a/samples/winrt/ImageManipulations/C++/Package.appxmanifest b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
new file mode 100644
index 000000000..c72258b0c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
+  <Identity Name="Microsoft.SDKSamples.MediaCapture.CPP" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0" />
+  <Properties>
+    <DisplayName>MediaCapture CPP sample</DisplayName>
+    <PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
+    <Logo>Assets\storeLogo-sdk.png</Logo>
+  </Properties>
+  <Prerequisites>
+    <OSMinVersion>6.2.1</OSMinVersion>
+    <OSMaxVersionTested>6.2.1</OSMaxVersionTested>
+  </Prerequisites>
+  <Resources>
+    <Resource Language="x-generate" />
+  </Resources>
+  <Applications>
+    <Application Id="MediaCapture.App" Executable="$targetnametoken$.exe" EntryPoint="MediaCapture.App">
+      <VisualElements DisplayName="MediaCapture CPP sample" Logo="Assets\squareTile-sdk.png" SmallLogo="Assets\smallTile-sdk.png" Description="MediaCapture CPP sample" ForegroundText="light" BackgroundColor="#00b2f0">
+        <DefaultTile ShortName="MC CPP" ShowName="allLogos" />
+        <SplashScreen Image="Assets\splash-sdk.png" BackgroundColor="#00b2f0" />
+      </VisualElements>
+    </Application>
+  </Applications>
+  <Capabilities>
+    <Capability Name="picturesLibrary" />
+    <Capability Name="musicLibrary" />
+    <Capability Name="videosLibrary" />
+    <DeviceCapability Name="webcam" />
+    <DeviceCapability Name="microphone" />
+  </Capabilities>
+  <Extensions>
+    <Extension Category="windows.activatableClass.inProcessServer">
+      <InProcessServer>
+        <Path>GrayscaleTransform.dll</Path>
+        <ActivatableClass ActivatableClassId="GrayscaleTransform.GrayscaleEffect" ThreadingModel="both" />
+      </InProcessServer>
+    </Extension>
+  </Extensions>
+</Package>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png b/samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..1a1aec25b67aa1dc55663bdc58da2083107eac0d
GIT binary patch
literal 1583
zcmV+~2GIG5P)<h;3K|Lk000e1NJLTq003qH000pP1^@s6FZkIT00001b5ch_0Itp)
z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGmbN~PnbOGLGA9w%&02y>eSaefwW^{L9
za%BKeVQFr3E>1;MAa*k@H7+-&gq_R)00o~(L_t(oN9~visFhU^$9--EX8GC_#TFqg
zGsMa^)1tx*B!f1x#mt4Mtc<dvMP6w{w9{g=*sCOHv)3LiWNQ0j3npzw`@Yh?{(qOb
z@pt&{$GzR49{AwT{btUbIcH|hnVIvtbXon^`8?3x-rgd-Dg0P~9#xApwu$g<fy~q5
z?U?u-ozD~X?O1m95#|bugja=S@ami0fRvPOB>W-#S%BUan9FL&TqXX@G&Z||Ep!@D
z+1O23l5Bln^t!^c!t;TdO&cXe2h?ylf!crt^xI$fp@!Vy;*S+hGz@8aWB)@1vTyg~
zg9k;A3j6(FPi%VoQhH%YU<O8D&MT4GTw~h`+Xwh=v76Q^dSBsW;Z)%;VSsO3^iZ2W
zjQPQvsNXe%-cG+~3fBit*YB|G0P#5092C;cO~P%$wZcil;39{Kzh&$Xxf_JD*^k+<
zaqMrtemwxk2LFo0KT!16vF~m4yJ5qD(xfMoQeSv8jd4w>Ek&vBGx6E9r@~hvn7zcm
zKq$ItKZo&^0P6b#)BmWx9|;=%U;$py`oD{Rsn9L-4AS=tCHDNPvE$9*eMR4%_V4T5
zsIi_xM~Tj&eZhNN*g=>sOl>GIn!stK=+{!dmBwb5jNhxV{nPl>qSq0gsl%8llA)>a
z^*zWhX^i0e_;;cStn+3?V4gBQdhQgs0lyd@ds~G80!@$W;ShbFc;}1$qz+rM56Lq4
zZ<4T2qk*BD$_m{vyJ`IMl1-6Law?oE-mPg4H(<DMLgGIs`k)4kzFe{#CT@n`;tzx8
zdw*NJ?h&x-^i4pk7^3gT(z**p({Yg@m|OJ=hk!adE6G#nsn4Y7e9PbuinTeUl^b36
zUxA}IG4I$yciHz!edpV?hj=*^9x0wXh<TOnPQU#GPH7dS9a51Sh9e00#fkrf8>sJx
zY@GFWO6#KYHG%w3Iw2+Y5V{K!l5Y0c%TgSjrtfK_XimQK=7voK&G}>N4nQqIDZC{q
zT_l>myt<G(I6I1bO}FO3`bzXQN$1gJ8<i}##toYm2Io{bAvFx-aGy6&biS!RPCZ&6
zaO1MwtF*TopPzK^Ec(jC+dKB@{NE(AUQ>aQf)?T3v{;*Hu4qnguZuS$@n05AtLU<{
zk6wHU?4~6LqqoL?G9AnHO;<(1^`-%X*Rm5$V?kPCZ4Ssi0ylwqrwOFCY(tf%GkhbB
z4>jFgHHN)@IH^Z38jm3Ni@-R4MN>fug+&ibYRb|AqqwfLsctOSowtkg+LBQi;Ez;t
z?_@)+FV*yb<Go-Lgs$d14#`KtMFMq_+u~>yO}l!OkPqMe;=Pyl-Pd%FPh;HZwFPfD
z-V)t{ZHeFhZv-ZHQ=Cv7vN&yw)5U3Ak@y7bj>H=$+H*fat8^s#Jwou*NT<VF!vj0c
z9F!e8CiINa954Lbm~WDv8Kx%}XVO`2zbA$6Ei}eU-uHx`c1^qmA-_xF^Ufk*f4}1z
z4wNS6ZfbEX_HbH^mUevs2l$406#Dyvapa~YIZi$eg$IS3w4cynvZSk4bLcrq54DV9
zj-2n~4AFNd-j|{;5qL*Y_dG4_DSC2}XYZuZ+=laxX%TX8D}fgu-}qkG+s8tmh67@T
z)8)9*IkDIS#;0vuL)a_H^0wgd>GPMzd~Vl$Y0Tv~?T3WHpPF3dVVdelQCh9)!ilHE
znj`f6Mai1X;V_&P^3;)=OXQKAC-e;Yg-Lc~@cA!CKCsLFaZo}jZ7Ox5iV?v-#(3j{
z$0>7JYRmA%n{G~}2p=cVO5=QrF-~q1`iD;546buZHb~=iP`rKk5BAprL8a-Swyg5+
z717j~a|LPww}cyt(^d+c{Lv}!1m{qJw8mSFhb0G*zfnncPTFfFU}48-jq#YI2J>Dz
hxT(Obp8Vf?;4d8suiatp%?AJg002ovPDHLkV1jTD8!rF=

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png b/samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..01b3138cf8c040c54f3a200b2052f94a10240ded
GIT binary patch
literal 8991
zcmd6Nc|6qJ-#(KTZA4N@+E597$&zgpB@wcXeYqo*J;vCFN|9_KA%yH($Tov<m*pl)
zWXUqdlARHQF$?pY&*-kczt{8p|NFzMSL4h%@AF=->pDVowAA+PKDwKQg=L@m4OLwh
z7FK`ob8^=X@QEkv^Dy{_)lFCJDobJeu^I3mHoGgguCTBaN9>_nZwLQpce!Eg#=^3{
z9{OR871__n!gA_^y6P2uPm2Y-qk}<T(&7@MztPI!&Yh2XC!|>syl2;iuI5B$Y9`!J
zKd5~?lB?{2<!Y_H6zW}WELFP2g<$B{QxzRWO^d#nG#q7;^YNRt&XrW|Q%5d7l0Dq2
z0%O<SuiY47H8Qke`ksS!LExLmJd4E?R&dV`W4pywM!wsoPwAS8{ge|P6N_^le|qh<
z4WiJj`1>NoclbkFqD;r^+#H?|?Pz0D9~(xP8_p`JGHXA2^k_Z?gVAxavZ|xfXn5Qz
zbz!igproYh&;=u_Qo9ZhT%S*oMa_f9j~_c(4(K}(hpL>=JUl!^l#KJRd($y~e$n$;
z)V35j&ZTv(uV`@MbDTNF9e+^8(a|w==*yQ#c_&>Izgus<G4Zv5fkDv2^Xal($V5rI
z@X#w0(bU=357p!Ha&la0dh-J|rY)6)h3zZR4xc`KDs;+?9?p|{fE$Q2d$}-BW}lhz
zp~%cY=CW|DT;|xVzFQ0LHfB&Cgcq90Zd6=K#F$U)_ouoPU5XlkCaCesNK9)t1-H3c
zRPH{bEC29&upeb2PONG=?50AZv||acg=cD{!%E!nu!X&|GfG`eT~}UT!gsX?QIL_5
zp|ds~0WUYldQ_oB)OY{2G}f>-ndm&QJn<R7h+LkYo_=3gD29^wvQuZmu*kyExq9jP
zNn?=%!1Fy?Z)8VjvoK*{Vf~F^d<(G%i*slCI^c|<fq?<DWdvUTx^P6Cg?DqZ53%Yh
z-o2V%-lMV)X_lnp4)fYr?Q`tO-SSb)jp#F!m9N@^lWmFSW8InWaxu-?NWHXP_UV4R
zl(Iexp8}UhvOa71BB)I|<x%l4gHGy@pR%EW?<9pB`=0AJbEa!x;DLQ#p=iutjZejl
z+UiZ;I8oC{-=4~WZt1~t$5NGN`>Xr}YeCphNIk#%+5^#xS^e&4xIhE>y!!sdT3R8^
zN#xlXiY{-Qh+)3V<-##LIISN$SmBInE-o(aG#{Ni^Zs7vDRTNFs$|W%`04t$A{v6P
zgZA)Z;IW)v8S*+325FtN*dHmLW9&Z5&B6saIXTlU1|fPOQkM%`a>V2=zbne+dBXM9
z5{}w|^)V<=Eu@|c$$K-Kc}FDt%x#fFJ-37--Vv#K69!sMH>Az|^7hL;9n-<<i}#3c
z;9jxG<|M9V$?`Zq%n+3nbd^%pt*AGeh!$O1ofEPw(=M5L{oHg(u=XZh&S@EUDCx<;
z$1iIa^GY6|2BO!#)4Z|})^h(QPAIQ9W)Zt=uv`O2&c<LPd#_oF)lyq=j7=KxJb9sl
zAa?TyeH$wqr}BxtftDMy2(b>_YOkqBmR{06=BM{qSD#L!r3OwRQQ3nk3{h(p7V!Bl
z?U9c`dkR0x9l5}rGj1sZRpb$i52{aCV7pF?5cfR@2;K4K-sc7cJ!tezGpF(!PG#`5
zk39c0q$?5kezRk4a&`}^6Y<qGN$xY?OD@_cy3B`bYn5d5Vzy3JU~QY|$DwijaQ~t0
zyn>Q{$;-=s3VjvK+-j&qQXWP8@OUT3usZ$dU`|ep$ymU@-@~^UEQY`O$2G+AGyA<8
zb|rLW&y(B-z#%%rFq466>C(}HE~glpI>QR85y0Rl!Xw(<$aL=*`jMU^7I&B{PXyXD
zQ*5G|%!X!C;4UKpruW_O806WL0bo6w&|5*T_9Xc!%xW2z2zMpS-s<BOaJ>??*LAUi
z^>e#U1Sng<&TQ5ljd20S2I|6QXq8c~Y?QoLvXd^m?GOdtW(j23zVg~k@w#Eeo1Q~6
zyxz5QwSF|%-ndBS^;SGh3))@gzZJ`eSdPoDYM4_>nMXenj?^4EuMm6<_vLY=aVWgH
zQRo!dO&QigGRe3CCqB32-)#Oma`Ng{kdzhWPoF;Ru|Zu0``A6o%{|{c%U)CvvI~UJ
z1vcB$IgX4IGoRf|3hjVVqJ_0h932a!q@@04hLQ7ifZ;@USL<w7QBIEaq?6TxhAeco
zOcw4+iIB69C!Po@k8$KFhU@_Q9Tt9@hy~p=$eI?__+zoZw8`7sdt}QHowqm~0W^xC
zGh&WWa&*+<up=IiXML)118m3wOL#jtIB05=@T~B-5;t_j2yFAT2VT}+F-b7Kh0l}z
z<QX_DCPTS%_D%B(v9@8`pGm0fWl`$U)YwQ|S+ZAVycE=M06k;$nuaQKTSIemM?PtX
z_mh)%v!X(aR!F?!7Vdi9t3&3}%m}<^>uyWW+q5Z`POjoJq;c&784`J}E<0KC)NaTu
zYxYXpc<15j`zH0zex+7-&p1-t9P|B=TZ9FD<S~Z>V{_xziPBD!#2-K2^UJ!_eYhma
z2lfk4_Jm=^7U$;NgjrAxMMumPy#G`Elo_-W2M)`)A;j+mb8Ibq4cn|43XaEGOJBMT
z1)Izryi$#qvhV$-r>z*o#oR0aMw)CZUG!V@>Fw$oOZ(jLNtWbI#T<H|X9?fh<r}PZ
zXdl)uWIr<`b*<(~2O%rs*;NyYeI{CX$O_lDZvTUgt{`Au<6Smw{9-gn6LOid*PeAR
zrLJv8O0;=Ntjp+Cug{!{;9Sn^fRrhGtGQ@bM{u&T>6`bQ%5Uel(-jsCr}P;SLJy07
z=H|$hmrU+6+xSoR_fA29?}E)J2;?N%jW>psd#^r-VWu|h;17}lC>jTwtI(R`XX@C*
zlmxbHj9mYm|2I1?Fg>`?64x&4ue1~TMIFpP8Pzf5=<Hlk<3rwYOga@ha6)8cigH86
z*C;Q`7tW~~&H@_+<`1_G^?WkA+mX!gzoHrprA_LV@rr@wc5HuKedfxXH`VakwQHW8
zTu^Ta2%vZ=$y~Y=0|#Z=)6-+@<|et7M}h2nIXFz^Iwaj>-tQ1P2K7pf0CqFutJUC4
z&<#Kh<X>Um39SByE4Z6nie~uB`_nxQjV;umGJG8f%#YZyV~4|3dy>bGk-v`|-fwUn
z`prLFKS<SlO&yPoO1^pWLrbfmn~txGh=|~g{Qor87@MA+o|*Oj-!=eU9YNi<Z=W<s
z&>v}nP#0if?MshtCslbSP138}rW^pIDfe9ZYpY?xxOF15{_i`CaN(X(-*3fHB(j}E
z><pFnm<Mp6(B-s{1lauT3lMODhR+hFc6M1{xaYqx-UXSw3sKiW3Su`?2o@Z=E(}(l
zbq=(FAzn_IkM)rbuYP(8Ty%mnnHd9oRMdgcCekxr(F4qrUZ+f@Uv``P))Fh?IMbE!
z11h>*Y-hpU%&H~qEHpeGq?RWnB(SImoq;T<-VT6>?TkW4D}H%X0m{snR2G!`=l7lL
zM_AcfOzZGN{Kt;DYe@d#r0idf=TC3m#8p)EwZFN{{cB`-yLWjhC0FoNm95)#B=6(+
zS#AEwcF1-XzIbL=wtRaJsfDE4_Y%K-JFE*bh6TpD8x%}#VPW|`K4~L2H@ARME@q*E
z>$)w)pC~H5QWDIul||O<*@?nQQ}KVcnpXU;R-=l^$@>o-bmQG35^2yh0Sy|QJ}D-!
z7fLvnKvzi=QfPW^PO_%%w@<-t7JOTy?aW1|$-<|UdX78)5$*2yz2ry__s=CilmpGG
z51}`|q^k6O`C?_?n;*CboTGf=Vqj|ONsTElA(!pFbx$6HAlR^f>52YdM%jhHdjMu*
zu-Jv}96e)OFDL_)t#&|Oz<4YqI1*~{0CnHBlGO(hf$9V#M^qzf`NXRW(#&eOTL@fp
zy5LjM)IxiLl>OxOYi$Q0Xg~zT>{Yl<c@KFtaL)_uSl`k8Wo2d3DB@6^im(FM?5zUG
zz?9I%wMp$1B}Xu(%6%!z%laoDKnGa`c6QzdSGY^uG4$;Tbo&@CD;RIe9_Wj$Y&Yn(
zy(3RT!N;oGwryJ*eI_s<oZ|av$FDF)d@!3*6Y#T9R8;&mmOv?*D*{T8IjZEqjJEae
zcckjXDvdFY($tXM;DV9hGU)&|CK@_@^;X<kG|CS3P&vhf$}*SHkH1Q@;yCCaQ;m&{
z%K$35ig)+*sr;O>b%4W&G84mS8~1)-QKVp<PV$A5On<?+t&At@j=Bpyaa(rg@1<7Q
z2jx;3VmzNzTQt??Ip$<JL>fct(<N}S68zrt<E}i1D=xU9(YUgTioxL;AAvr(j%@E5
zvNQU_gej4Jfkxt$%q0@^ZBg_iq0TL@HcnkUzzXjmy<ZK<zLnOhjb2uv4Ti3+!7b@K
z<!OfFXNHeBb;c2>Cl8HEi$}Gw1iEsV_PxLZAORZvzcUfu;pRp@`N1_cW%ZwAAH1@u
z+<Z+aiX)j?g9*O5R^e^i<@cR@wes#vVWy2`2F*(&&X2QcgIwC=;pwbN=F@(c;x*Q$
zW435}zbP$AQ>k`m&lS9ZI&bn^BdtPv!6rvWGdro3zJbR@_>H-0`lgUW+)t&bd@j`P
zTBCk7c2q|zl@Q=d9WX&$d0l_09m%xZp_wttfexlI`ZHBV>WORgJS=Sw_94T+NRjb9
zMT;=FfxuG`3`#m3z3Ll-Uale1Lq3XRk>HG}H9F2eHaDatlaRRB!I<-5L@~UyG3DL_
z^g(_Zbj6$Sq(W^abe2O7nU~T2^)Mo09m)F)C*HGYu~$&hH>De=Q5HDZl%n)J!r<fG
ztHm+Tz35SNjF4f2{}Qd+=>cv<?6|S~t;_|DCOYYxG|5f&?~bs&_|4}^rE<hR`p~VW
zxRO@#DCq7T1LipYngXNZG5Zt+&pYLHSL{m|T4aj2nH^*KFWkmDylrzsc+SDVnm24s
zTRdSSV`?~?H}tc|LA-c&X^MYQ^QPzeaN9UPIvimXwkYCG_cPCxaIH$AKXxqNOxvBC
zzcKP`ZBA;&Qf8otQQY9IRNWDq|6I)BLz|`FZFeNPWa>kKUva~Hp1$As_-f-)twdY&
z-y9x^8)Hd^wENz;63P{as9bVic#*2)E03@}g%o*t+O|@GEawq;nn!}>AYn0@+Eg^V
zfUD^kEkf%!n|kn~8-=J<t~3(S^_Csh20eZ@>d+68uRa1{S5Q!}mbB=*GsjtHB;Hvj
z^Cc~5TY<^Jju;EVJ#n8V^Rn`DTJIW~z0G<K^$tn~S^8V^<8Q5nroBt4HnJ=7l~+71
zFGe#6-O#(;g)=n_QPdg`CeG>DwS{V#sy&z{gskrw&K++QPQBXK6eXUYrCO~w;Wyc^
zI-WnI)R$j@+P#{5)7O8W!1vs7=>ZOGsP+>MT$0e&HL`P{Zi+SuekXc;=mmk`UjA7h
zu0BEbhj%pjZK9lrhK7c(QX21YE=k_p<i>aTy=RcQ<quohVr_hu5>_wdR7{4<tJ#YC
z{)I-P{<)7KcvD_^3_d)mMQ^To#zpg?4BqP1tHea$S~Iy3>1B<=PZ$_lE&nr`BWYlT
zp&+DNob#&6bn#pxLO)cq&zmNoann<=)uSbUyxy!&tmR&jIwpLOaE1UcHqm>K1{+_d
z7noKoFX^QCR?FGNlONr(TsQU`2s+)cQ9n)%Uri$*j>VZCBHxL?szna*o$Vnf@6O6r
zI$~SOGv+_=y)uW2^*2X#T-l&C_z{eckJEaDyU596(U`1@4eLU72EO7d8=D+8Ovl_G
z@^K^w_{c@Oh*sg$tKl@s8zIfV2Ekx?7`qv_B2sDPq2)L6F&YcbXNvXCC~t57!1q~r
zo`3W?(}$Kz28H-4jJ9Qeo=>hC`Iwl$HQM-6E$w`siJp%lQro&^DdRz!pW=HFVI^YF
zI@*Mo{OR<AteF?&D`6LV#x++r^k@Mw8`uqnMIje{CEssaDN5#RvJs-nAx_8e`ie%`
z?=dDy#e|qQ9*m%ky9lcP-;Z0gRF%nlTfN8G2ulXDJBWBb+~Uk#=OG;9mcvdIGJ;P!
zcl-_A6g8XtQGZ;cPhq%^I_7iqnrj1DV)J#a8tKNseF;Z+tYLiaoIU{_iy>LSJ9w$<
z@pY?}{<7{t=5M;Cl&I(?8G}XqkdzOF;;Gt>rn<3=<$V!d(s{kwKt6CYE^HjPo>Qh}
z70-@BGOVi!X?&HKr9o%(<zs|-QRKMiQO}eR+E=vMB_T6)+$ZUUTyadXV$XV)fghz{
zF`=PwvznbB6@T4^=X#+61}Ze|j3b$|ay?}24C2J51saAR(kUbgnSdr37MR#N<2F31
zXquP(Z@s0$d5QBvxJ|564lFKv0XwYoxl-Ae`~7O(>NvWHtr{yP^+b=Iewv0x*=J3h
zkn8ogE<j7r;?hofHcTupMYf>PQ;YeRl{TFZm3e=Xk&4Q!(Lo>xf}+EbwKUi1nx)7u
z6*Z}`t_q)(R-SDiR&SqKFWoes%?=`;C9XHFrDB7KmQzK%mNVt&i;J+1re=LP6<^mo
znpMXu(SvdH`Hb_0uba?HM2lSq{r0bB&Qpg_XyWVs#gyf^Nd6bxl`f-?GDyB!+h}Oo
zAYq`Qc2$(t8R5@n8~{t`>|b(35BUcKLI5o0pe%~`CIbxXx}L7CzeEs)PcGaDlpn9g
z<q+deH1FCSSO?foN~plcL`YH0;Rr6KOIDO=Y?4jPue(+Rhb4B(yN$n_+;!rjSD@#5
zRt8BS!s1Q!=pEXA<P5!NJ=wlwqF{KKqE;lZSzMsVqrwvS3{YXTQP(ku26$?+ol^9x
zDJtqHw5XxJ)(?5WM7Ek)5cUy-O4P*8Zp!`mGe0H_RuF;+0)Pe=j(6RU6Swr&%)KGS
z<Vu-(06#&nj(X7zB^Te%3(&!j^<5CaxG1p7sL!iVR4RKX!~`c_g#dygx0-M0!hfR`
zUwu<kdq@{V&h-Wz5oPj9TQRV(aVd_n^U;q3%5UjxW{95*l(GvDu&jcRgWwJ>u+Hh}
zY<@-WZh(`wvHt=}fQKyrozRcAw*9c!Nv8e4oab@2<p4u|JrejE6sQ3icCt18lL>va
zOo|EkwYF|^Xu5CyCk2N{=wjh|UT&^Yo^W+JlNY~rX-EMqCMqh5-W)A_OA-qxfYp|c
zps7rD`RbJ%j}4T%I12gH7^XSW!Zn73AmBw-F0|FYn@o-3mGZm)(0$hCi<6U+^GldK
z?Zm}x5QEvbckeeM9$SFL`s{eB63YaiCBO=8g!Ze$MW-S3$zJJ7FTLAV^8ESpx~r!l
zzQ@7}K;3Xb4|l`_sub1FjLk=GXmS}F-`99`p_oFN`o(H0%f10F0g`-5+@gB=&;!%=
zR;>RL$roW^#{UlqyRG<(NRGU+?S0u=;e_9P;Sy6(VggKjIxl>EWZNJP4Zr%EbR0c?
zynNfv{gs09f0%R78Il(~w%m9Egc;?AD8+o+vX|!u1dpE%wyQ$$SQa7_tH&CD>I>VM
z6j(U`WMT&-DwyP{?J2vzCblIi7{Qu(&@caQ?y@B<@Etq0_fPT?0kZ!Akjs1f``LeQ
zAF;ynszZs^DrQ#6X;t}TOECn(fm;OzlW;)MR~lFwsQgP^cuM=pN`=97{=ZNcPHlka
zgZ*&tQ>uWswCFH%8Zg4wiS-S?S=VXB0ED(}PImS#aTBH%!g&$iG4=H6(`B`Y<7F6(
zoV}CNQ%Ht`*w^T&^%iyc#l9{Eif9D)f#d{@>IOYf>g>;KkD~goEfSoYA_O|le};rc
z7MLVtL1$fEz`{_~*Zs#8WVd}vZDIb#cuP$1;?y|A$INU=h^sptL)+SB@O}P+BA!;X
zN4dLquN?IFZ<3sv`ZrMNdH<Uv^A>%50|(u;ElIxbkhsO(t;kxzW;@lH^y`1UgV|W0
zj=<LDF5A1jh84YCo5J~fdwO`B>Y3>nQw&ilPvg6D^Yb6>G=<0hXHP0rjH3Wi)Lsk>
z-C6u(a2i@UAqo`Go6FT2bnoNo{y$S2lp^3|@)8n%EqQMKqFf}B?<KqTW2RL=MmNVC
zJPs8ykX@n1kC<$=Z`Km+Hq_JOw)%&egfSI$pfO*7h?wbc%FZ-3mOzPvBjHX*q~%VY
zhNQ7dro8EN|Lz}7S|yWBO-&R3JM`u=<h8YdcuBjD|Ekqyko3|-DnC_mh%w(^I?Ckt
zyP&}3w;!=O%?)V=BYO@OwC8A{+Xndg_*5WvseD2ia5FWaMU`8B+5r+~|3x#VX2uCR
zkC+nocck=<LrZ~MS#*IFNqR?8kVJiYV9C@EB(}e<N>o>6?sFmVh73~bDWfYx!}{9w
zOU&$mnsMvU#N$BF4A{gV@t~c}&(AND_qR`>-R$o$)Au=BBM{aurmS0E$PA+XZaE6+
z-XDK1Ies=Wv~R3KK+gRi@cQP^mLTQA91m<l7cX710kRESVcpT!Ohx<xE5^Iz2~+ag
zr5R8!VDy-4i}-Sey?9}SLRBQmA<ySsU?%OZR;CyF3e8Kw3!W(g(YJT+v-41H0F?ro
zgzH+z>t8lBLe)^$$^%^U4!OQsjW-4@d?-8nGBmmB{6N$@c;EtuAg=-~1wl9Ylv-Zi
zJK3JZ=Q+J4FEgieL1%h6x^4cip8_-RQ52QT$H(W`nRe}$%u7^q0$hF!nLt7mSs=x`
zdwQ<?Qp~Niro4d2o*(#A5VUH3`isg3I}vIffsW?^1kwMRETaAI9S5Zcu_*E19e!A}
z%VYhAwY(qI{SQ?M|EU)Y%c1P!zmu?|4gX`{HKg(d?%eI-7RRv*T$!`74&<vzdR9h8
zgCTgE`SX%YWh(W}?6%ze{0rJVX^<8PJM?At4O3bR;7j}h?WGGF8k%r}vLhy5`CWq#
zl}a6g{S-o&8i(#j0tT6f^zeB4ubx-AhvuFfF=iXT0FvB;vTW-KHUfJC#TS%kUaAt1
zrr(#bvxA%rh8q0w^1@94#e~q`m;rlRk(%*uRUf=DMac$1l6D-hnd>dsBWaQb!GIPs
z5EbwWLgHW>1%*jrzZjTDA9xcCuuSWAAoOgqp6~@SBs}m&$DrcYlS?K&P53Vm`nP)_
zypdcr*x6}KTU!u${Db`fFy<^A)ERbX@!oy=;@fxqA>*`6Jd_3<q<4(t*P{s#g(OjB
z%DB6WCCu!80?j2<gQbB%gNfq5Kqp9K(>=KZ<nnjzWQF?){XN~?Y}`;Hf_EXzv&42#
zc>8{52n_Lx^C$9%T;FD|^Ybz3RM;q?)GlImWyL0T0zx<}fkz;1bO>m>%QzZ-F~6#+
zKN-F0CG$Z~+g`nQDn-UQxu>r$VvkhqIR{8(;&4%Kv45hYqVm`Pf#7Z7*t^#VNJF#=
zi$2vyEiE?zFu7uVCMrC`?&|*i`!Rm^^)4$O(WK>NXS?9OM(XkF$(-++&~F0RhBw@6
zgNh`dRgcx~yX879<Wa(|($upQjR8genO_f87k$h2pc?gc0`2W#eWjeD@N;qQRS5}4
zE8q*3iM~9K7tH{}r>d8OL5GmJJYAEUzLw|LEZBePv^M;{rQ)qy$mmk(8bp(R^$aE_
z=>vQteC?eg#b1j-Cf)WeBF2fJ88iY`fw8fOCOqfDas3l#=|962`ZDunc<(HFG>CV1
zh!91?*|`YFUf6f(XL3|CZPsV=icB;#G*anJ0%!-U$HGH~;md>dV-2ATZ8C%p;5{Ep
znERe;dm0FqL(R$p%CV;4F{EaxkuS(5N#WvpeF%49cy3CvV3q6mb)Sh?#O~%*QU|=E
zyj(htZXgre**u;RXHhbh>{F;C!|x2n84<~k5I&fsY=PcDnwC8<NPW|CcE4cP8Fi(N
zm9OPqq`PslW#@8ctsB+CkGUfCN_zf$^8P{!Gk|E@cDou&VRK{Q!K@VjS<UY!5DOZ@
zQN6u}rdSW~cLxBu-h$^M#;^|k5>r^4W-f%5V<~7I^6t}-gWzNT4R3@@PaM;G2|k<a
z?*7oD_e}ytw@Q~lJF|qKFUR40E3nwXWbkyY_wh>)3Cskjxe@Iep7Rj3(HcU2GcCI8
zcSk=45w!*DR~Vcznn>jZ6?V%eFYwZh|I)b<o5z*KW&hA2*51LvUHI9GK^a#nc<NT;
zm#@k-JcZbZsW;F<el6zFc$v);F`F5!ri<FhSw5e2=S*T@t-(%y71wO1+_>2|g*>AW
z3#6W=I{pK^A;&XX#4$-HwjPO0=@xZ0q}XWqZeW@bjxi44&ms(cLy87&H{IIoOT(Po
zA?Qay*dle`Dc;wvO+k6{WRhr<v$cqpeJ%F>h271{RT{kE3<0M`#?6n~7&Q2!78dnu
LTB?Ottseaktfbe2

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..5546e8b24a69738114bc17b2b2d493a6872d67ad
GIT binary patch
literal 1248
zcmeAS@N?(olHy`uVBq!ia0vp^av;pX1|+Qw)-3{3k|nMYCBgY=CFO}lsSJ)O`AMk?
zp1FzXsX?iUDV2pMQ*9U+m{T%CB1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+*
zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn
zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxKsVXI%s|1+P|wiV
z#N6CmN5ROz&_Lh7NZ-&%*U;R`*vQJjKmiJrfVLH-q*(>IxIyg#@@$ndN=gc>^!3Zj
z%k|2Q_413-^$jg8EkR}&8R-I5=oVMzl_XZ^<`pZ$OmImpPA<wUD9OyvQvjKmn3P{y
zVygsnDZ~r81-`y;gY$}^0R;>){ffi_eM3D1{oGuTzrd=COM+4n&cLd=IHa;5RX-@T
zIKQ+g85kdF$}r8qu)}W=NFmTQR{lkqz(`5Vami0E%}vcK@pQ3O0?O#6WTse|n3$Sa
zTDmy9nj4$D8X6i}IGH%PI2*Va8n{>*8k#!7%)qAC)y34v)Xdz{*vZAn(9qS;($vJl
z)xyQx%*e^f(b2>Zrq?sCxFj(zITdDaCeU7}UJJZ>t(=Qe6HD@oLh|!-U@0IVBfliS
zI3vG6!8zDeAv`lLCBM8F6gd#Tx}+9mmZhe+73JqDfJ4_R6N~M}u1=N)CT<3nuErMF
zeGSo@LQaV310ACeN*YK>1ttVce;_72;R8AFtdp7t%r8a2jPa$hZ3Y7aqmZYIV@SoV
zH(|GVn+<qcR&l4au9?s$;FiD|)*$$TBb7yh(M?17f~Xaf?~?A6i!+*jIfmYxBwBLB
z?st;hOPlj21<Snnj1<L^6#wNvx>U)puN1)>GjWDYb(7@t?Y2iuo7SC^e(wK3>@~xg
zMI8?7PRhyOSNeDN&u*(nlZ&MfRzH8rq}_NqyH&<=^8B|I4LQ+k9H%eLW)<BNb@!g}
zI)&SFJ&xa;>>+)vZ|V=`jsDXVcc>oTy0n3v?M%&Q3sa2+aW|74&4eCtU0$<efpN3;
zrGv9FMM7P<{0go`>WI7BOyoPGRM@CzI<vhm@N~nUO?ze<?YHaldByP4seRU*mlB=9
pDfJpPcf54uIl(@NeKehcnPFkgthf62xfX-U98Xt2mvv4FO#q_9qtO5W

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/splash-sdk.png b/samples/winrt/ImageManipulations/C++/assets/splash-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..901c3b085a091e7ccd47f98062443553e73909ed
GIT binary patch
literal 5068
zcmd^DX*iqd*H7tm(Ne83tvzCN6C`S>)G{Td{<XBFmDU;&q(o#v#MWwumSR*bZIo#Z
zx>9My9)pICP(!TIQd&%E34(}N-e_yy&h_tq=Dpr8?}s<fhdk$g&iS3+Ip@A}<@a1W
zX>Tnpr6>ge0Hke>!%qVM5&;0f2Jn_m;*}^(UWfQgfpiQ(a>V(NLXiYC;HWpw3k|fv
zB7M=P(Mazw{BLLz06@|k<Afj~>}+8u999Rp=A%Q#28p8q026a^5EA8&CIP+BzL-E$
z5U;WZ1jKlof}9QPAa+5PXg|zx3IXj%v3EjI{87f<AagUI2^l5^z@kY=AQ>AFNQ9A1
zK_78p;`_B_T@di23(4OU^obP0?j+C>M?eD&bRgO&h#>@M2-Sfe(l;_P0t59RP>3!>
zPZz4E4K;!t(t|-Dz|S9$I2*y+2X-26^*NW=G6ngONI@`N-O$ibozO!%ID)S()Y#Z~
z4MR^)TkN4t3=1S7$=ZQLjdcV#nusD`f=C!#AaD&4>4gg>nS#VjKb3$Dva|aWIFR_c
zQR0^Al955WP#uUa7Q0s0M{gqOH2S}3eAS!i6c&WmJ&h*ff(a<`JbX0PgT=l3`$TJw
zVm2@b0!BO(WB?q83dW)XNj7j(kobv?H^v*LZ)BivYz((NW^~Bt7!(RUY@u%fw}il<
z5V$cEYH)NN<7=@7`bK)jhI)pF;D&lo=rQO~OSpjr#K6GP$k4#T0197^wFxAWkbx-l
zdR~k;@8?*9zm0`i63|Ezj^KpD1+4FYlYTf7j_8LA0$Ms60G%;`-ndZW+HgMA3P%$#
zA!u(a0uBrO*j*UrE7||K>QAxW|C^5Kipl7%ZH+Is%KDOc|E=Brx$(uupGOBBC_XO)
z@xhS4pqLB*>{zjZA9W&g#@{61hY*Sv+m5)T0+b}=Bvd41E{U%VaThHi>Y1|RvbI|+
zw@k=ZJvsko2$u+`1`HY(#4C0`53{LTETb$>3x&4;fIUU4nHvFs7-;~Yb`t>D0|3a1
ze+9M}el#z7O8#kXR06D-KRn&=(MxQu1+ANFLH`+J&1((ve~j^EVll1t#Qz!NOY)z2
z{5{5(<UiN)4;WvN|IFhr7*rd;pY8j<Ven}ppR4E^mcFR9@Q%-CI{`SEOBKuD=oMa3
zUz`mggCBHurF6>2tgdVsvny!d+2N)<!~+xQSu*BgV^fj;>KOgOxdVkw-BraF?;GNO
za9OEniGGuBu)1<erx7<iQ-Ld9GLp}Ehx$HRDV|H)A6+O?uHU~0`7S#~8y6#*AES>6
z$>uEcspvWKb+0@@sF06pX&NeVHU5rX6F5-wvI<fc63rhohTF(F4C_U{3Rf_38*geo
zHlTY*XfWPXBaKB(lw?^km({?n*VA?yP9EF-Jgn8z<!1EH`-V}~!4X+u3&M$)@w7?b
zGM~rQvG+OYtP8<cv~Zw1CEF_lJj_B;TUp?x(6dnreK%7U@WUAX4Vhe``3uDu>BVp@
zXDRl~j_4e_Tl^-YaYilOeAiD*|K{A7WFK{->m?vKBL~rCZb32)S%{f#^HRvUdFrq(
zF0A_!TEVVQ%bto6a@0<*o(eD9Z+(q`Yx}O|?v9-S398A59#s`S^kVXz!=CBA<#efc
zsh*F5mcKvl*k8a87xt2+cFx_95oNe*csmMV5oS9BAV0eeD^a=;)cksx&SxE1;xJex
z<n?@GcJYDq7POGhzM9cyq9>3wOC8&0-3NQYL47c*lZlZ|>N#8YC}AlMrn;e9b7ds0
zO=3?fGo`f!A>THu9iij=VC8rhBir(2m&*Q)G18kB4f{i%{Q-Im3^7&J+DvUTXz<&`
z$Q<YW!C$Uk!kN*6kB`avD;39jUS>thwWf3$J|BwodRn6LgnC8PlO<8#n^%8z&Sb8y
zQU82iy-(NBbaZCNYb9~*MYZXxKbI;D#^-uf&J@SvUb9JulO3szm|X#>5Xw)KrOB$j
zVE(B{%LyRk{<XIeH`phxw>LX3n_Y3se%3-NtmJ9(j84SmsymYJRBCNpecmXlOe>fn
z-V&UdsI)Q4u0Qn{UlT7kT2cO{cVd~p>h99dE2$bdxKxv4u*!QqQC`(5x;5Yup=t|T
z37oE2SurUjFOR9RY2?BTh)Pn})*}D*p~z0tfyL(V#qIpi{waKAbK?*l%qvy(Jom7F
zWKfVKtgQDB<TK1z=&|-3rr?sAz!*Fb>0WPQ8z+!qJ)-vc1zPo#b)TZssqlgaQ8mv>
zNr(42u_MpFy7LOPAHSLV!OylId_>z?Ha@2>J1_EFl8J4SiM6syQ!Z{G{5t(i4zEWu
zeq=C=A7LDtROB`+=u4`2wHc9~l=z{ey0vP_o`pFwyW&KJJjvji$(Y=aY7iyS<k<qv
z=6%l4U$;=HeQ7wpOzvhD<X*}_4FuLI!Dmn~x?33;E|Y8fOiqwcv|7&8cRgc8vo~#g
zu8d@{aUA3o>=^|vLO=7Bu6BRl!*};Rl)2P-*Ypn~=+y3I%H7uAD&Encu{-I9<0~hp
z6!VcCa|I~|rA0x+-!}+gb#$Du9$_4KX`v;uZ3u6sbGVKU#!*Qt+sE;<nBJfcynAoK
z=xgFQE2X570QY-?_trKaDBYy7w{j{=2(`aMeKZka%gxz+)MM5)ofb^C8=cRf94uJX
zG>H{f*v7FSZ!RZKar(0Rb1A<a(D0Ag8j~2_Ie$}`e_K90Da9~3II-pKqnT;yr1J93
zDD&vf^0Z#!)dIsKp5|!+4Do&cFX&&hq}m-vM>wH~z2Bvw?@iEVL%fBVvE5Pr(^8w6
zqDY5&m9Q{vb~?+YN;%_%y?W2v22NH#Y9|BR{lvR8O&*_`HmB(<k=n7s$)(1&rR4hN
zRJaYy77zO|4=zXHCv*ruH7uMk9Ywj34eqQ8mjhZ~F!#KQPR~WlxeuJENN%I+uz8xx
zQSy>&$0lW?ORD@txg7$}W<9QLg5|L$UsO*#y?2d=r0jJkz76iRoo$<`Ze(f9^@2+<
zkRs}<#-+pJ!@_fxsUx!5hni{nXODp!C9UEG)1en?!or(t4Y%=m2g)V3#z<T78>_f4
zUzU6NS2(yTyH&pb!zN=-&zZBX1)w}!kYVC)!xt}6of)aJm)u5CO9Je$>7B}fa=RhX
zcOKstJ|PzkwDWemc%%)|7eLW+W)~Q)mpm^k`4etER6a0TDD3@yWkizMc=G7Ck-zXY
z5SHKgvQuc>i<kOH`(_Jw4!n=T^F{M7s#wV-ib(zU2~Qd&&1ZbtM^mc1!r}z!J0SZ<
z*pK`ypVpSeU<qDVe&!yP7!5%rQ+su)J(^c61WF&~j8rx#FV48x$sFuCW3lW+o~YwB
zO76&)?r(kI7b%rIce}x;J-xuO_}Z*BS(o{8Sae+DS&Jy1y~@n7*{F0Kl}8M8?7D~i
zMLdH66L?#-yZQ6hVQRzkAv5`J@dH)DTT`5~s-h>fW|H*prLq>r9QV^A{{eSPX!Xj&
zjbjL_{JknQo-Z^K62j)Qet25D|DLwWIR(SsD`!gUvIU59+vu0Mi4xPVM_N#uWwJOg
z%xoqMuZ{9s&Nw`nzR^%xgMda48S@$-dh$E6xq3s&J79=-!;MO>-CcjPcYt>>hEbhN
zj|`j$6<=be^{Y;+QTY(RByl0KrOHH}g8zli6&;A;-MxNyPoVI*B0EJ}!-4zM7$5cS
zscT1b20hB@9yU$PswIGp+~|u3^>7*n9@B294gJyNvUq&L0UYko>g=}n^y2dE9J};u
z%BWO1L0?FOY4G5Dc9PmOMJsuqnL~HSJge)0AB!EK&5;cVatYQzv1MvQ0&>dok5E@#
zUSIHdoKGb=xXrzFC95c*m4>8tLthj2m?c9v{edPqzL*{jT20(A(zK2%9g`THSn=|F
z2OL37>n!%H^i@;$iQ7`3!$)5|8K7rgnl=oyT6!R9o%D_9c|DEvp(OGV{6*$?{cHuZ
zcJretn4zS$V8>wO6ZYX9fDN?`8M~9GvYgLOVr%X?TkqcMvA-u)(HNr`fxqbw`;|!F
zO0S4iqPph&JUOeHQKo#Z%BlMSyM3t-T>qS`Or}KZt|}E7NySJPnt)EKC~y_e;Rcfz
z@6l)s!Pu?_xz>4wxeJQB3+8pl7qjei6XkcvAe_>#P27?f^`)RO;g^K?N6SmM84UkP
ziIcXMO*m!czt2Y9hg0RoKs|4phJLK!Gy5y8&MMz2Z(#NpX-@w7CfGdtSVGy=>1X5R
z1lL&kunb|Q^}ncD*1DTqOdifoc+8xOA62dzAu?iHCz7{W`Kgx6VYe8Tow~kV{#>Vg
z$fAYTnBA5ldagS&9(#wASn*!&rM;sdvLu^5IOFA@GK!)m(7UxyWMr<U>ND8P7r>gX
zoo!?PdTi=Ccu2O@c;DLmj^X8cXrodE6iRY3siuH`pCZNM85^i+vvPN`I|2vpB~OXm
z>^&=_`21otc*Kr|t>3SE!cE7z%jbK%LVnxttnPy)1I@5)eBbavbkuE`-Ps;L{zN(6
z-Md|>)!697yCYMQ8<jlHD}Td%w)GL^bY~I$061p^Xx&pzbQ~tewlt-=_Q?zLcVUaT
zOMkeV^{t5idgM3i6@x83*)vfI=>lr(mRs4^O3qx3yUWzl0xQ{$ec11uVRs|-cAvhA
z714Q^UzNf3b6XKHA{c7i3Q;o?-P9?&r`p_3g7K5OhCg+3^~0vd_iW{=*t9vlWxfe9
ztfmNqs5Q+Cq$U$?K5lBvDyTP$?Mx%R{&xA4f;5+A3x<K^aOxzE&WSMgbVU`fa0WO1
zqM5qw8yAxv)G0=KB%0FN&dW^}R!8w<?U|^h@hPTXYE;e2SjqD7ILYgT4)eX@-kzco
znEDDpTK~c6`Oa^(@^R{2`P_x$&GhT>47Psqt0!#Uky*9y$Z61r$hz=1>QzG{9d0Z^
zW;>GYm&C3>T<fk>=2&Vb?eonS=roU>(8h^m6LA`gpjizS!|0;ZqDalbgDVS5OZxH)
z7xqd<qSS`GxL8%x{n0VPYDKO&-)DIFNB6N}4f{|@YeG&p$M@XB@Mtx4M4>S3rAA(=
z2C_=Yb1{1xy*PSgpEKpjnjB+*HmiIRWM2r7wFjS7%U2ZG-z%SWG4%z;KPaDnS73ip
zK7Y|2ANAr_^v@UMzowr49b?VwbK-SH`u7<B4<zWl)vXW!`m)S6tDqvawfAc_$L!&S
I7M?Nx1;puR`v3p{

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..126cf70d83e3973f6a4b040fb4af58f546692252
GIT binary patch
literal 2482
zcmd5;Yg7|w8cxLvC|D2`1g$X?C`v99E-?Ybgb5G?fe;OBLNFwQ1WYE*BnA-0T1BWL
zMnSEBiomi}7ez!wj7SZoLW{S9>mp!LQZc9$K@p>LCn)az@bsMBUpvp4neYAPeV_OG
zoin*nt3zyNI?cr4a5kJ!kc+(!ns3YL*wg>BjSsQc0u?(}6$2-!G-3q8F{N-Kgy+b`
z>me>AmZopK4*BD77E&26Ruvl&&XB-zlGv<6N|P%wYm6o^O(~Y7LMnVBv|gqNAPhD%
z67Vu<0D<olL5WZXLCLbv3<QeFSk04Uq)O;gLf{I#e;NZLkV7glK25$sfiltp2ot;v
zY;E2q6Yvu%s?-3&`=DYYqVPd50^xl~6rzOUOTqgBB*4p?Mx%M+sT6=hrclWMl?c!n
zUQ`B!g8y(4FmH%7iNOVfKls9=079}#rDTxF8jXge@gl*<dNM$#)6E=IDiPBlqUj2i
zIE|=4T_zbo2$di*rAh`X@McDFBCJ*g5U@z!ryy5GM0_MxpdSi_m5iJwR+0e{g)Enw
z^P12`Rb1%bVSG{><)tejG8aN&H6p?Kk>oOIjMeVX9hnueXc&=*3~P#b0|-mha!8@#
zfB^*T3rQ-IGAK;84@jZ2*i<hX8vuaiEN>PVL;(Q`NCyBP<|N0bY-zzv7By%&(~AXq
z0RS6d0>M;_jYbLb@ecM{?mcPCQJ^ZZLIO?tm0^BA*wX*hmJx(NVik<=V0gpi1Vkmn
zDi}?MmH40-A3R^Ckir_&+?@Bhf)FCx1WAJtSdO2lE<^SS?<|TJ)0@p^(y=f<o%MTL
z>HktOG8PQkJR1KoDwA8-{F#>@2OkqY9vw)5ofiZ<81CJbt~lJZJ`Tv_rFA|n&f8e#
zZ@W@WORzY<a+c7ld@6T}N0Y}AQj-}4>%u6mJLVvFA)i~7r>AmGH>_)<mDMi{+#Z?_
zY4L#~k;wXL#n{)e+a_>+3VyyBxWv!Q_^*Yg+TjCkuY*?EXJ%C&ZLc_TFUhB@tlPKZ
ztuQIYLNMqid6%PJV$8LS%K7SL_)v<r_OA^GuVpPTc17lNd@J-lscwA}c4C*H&Sre4
zb6%`2C)$<JsU-cPf72t#=7FaJwMn+j41;g-PC?tV_VFy9-dNzDY-t3}!Mz*?c;a|t
z!m~wnMc;kX(KEy_6xTj*sTB$yFRtWwD&p?-W?MrjX$F*zk}6S;cEgykbDd7mlh)RH
zh~IjAJnw1Ni*LI%4)n^kcaLqqz4T?nqvr)%ei%-b#+5F-bD=3LZhY?f8%vkBqteFa
z0^z(Cr_Jtp#;rY52U4NN!?7Vxc2MuVDp!S_vh3Ymm8&j5J>88<3F-zz=d?{D?YBDk
z(@kr0US82Vnfi$6EjP7mr9NXVqdWecyFu9bQ+-vz8~*Jvx9S@}PI#nNetuSS!i8wk
z+2%t+i}JEQOZ7g#c_LBGC{o4ST9^^)NT7?J<gM~SR@~ReoPO1JDRSXv=RUCH1%=C5
zB)K^|uXwb-wxc7j)UYspaBlUb<IEXw5y3I(aAIiaqD{Yt%;`mbOyBdht?5_Jy?BZs
z&f&r}k#<BGAyLztXF4}TpV;=GKhNO_0^Te(Su=N31&qD<^`TYE;L|Ib7lW&(F0)G&
zN%&3joB1h)H0!eoN<p^6^&ZorlBiC{lGIbX&@tD*#fQGoA(5<x`=!ozoC^JABYgu@
zD^cVg`Of>5)0N#T*h;_Wx;TqK{z%zf-s~q+YwB9u^<lf$aNO0o@-FYlV;=kGTGe-k
zB1h+(S~Fb|KYo#Wf=i3>OgKBG`gUUdml{92j!Tihu~5eK)(TydZIShZuokRiT}2N0
zcDc2}bHhff=9HgJPtLf-jEF`G_WFA6JJQ)tb$hmVhTVW;aR_-}cG$zM?sa9##irpc
z<&R9Eq<<E@p3C)^@_B1I@nGZ7bQ$o-<J95UV@H-1*XSCBMfuC@uQ?PtL}xG1ez}%!
z)V%EnY-cI#^;0Im@?2@g>CAi4DOoQ%=KG!OUUvWW#nHkpQ#kO{GHv}x)0)lUe%p1v
zL%`CXz;=(464l$UN(Pd~u6Y!+_QyDFdT=0p(Y!NmdYhq;8m)2hzSOXmU)tVLhkyGc
zF~;%vBmOe}1}F9bBmR~m!XbgLKWR8P+QBib-tiabEv)6`w%^YW{6}_dhW_G+^FC7K
zkvB!3J8O+ct8^=>yBb0}b`Ge|l+VpAZvSFftI+ibddotU*X!`{FA_jPVWDxa^xdUq
zq+T0wnf!A6Rlfo5wU>UwtMlr*`CVPU#q2q2kjo0e5r6pT543r02EiydC0Asaw!_BW
zB<dsf-@b3#7I`^-q%%`&DcJ*7ZjQTBx(Z(9dC2AO?0q*t;;5GO^n!+L^>(j9N38zY
zVSnnVYg@*N=YGSlDqVZC^-JyRY6^JHUNANN_oKml)nKDbi%`78&Lwkq>3n8lOaK(M
z%XIY)`(*v_R>j{Wk6lNV(-IeGdy{*z&OsHogMSnZ|3Tg#&#R$#Tys~HmZY1|0$u&~
z8{Z!cZXd0F3%?F04BZXB^SFofI5YqCEde<bt;SX3Y-gE)E&dM$(HQY6?rfQ3Q}s6I
Qm*&4H4tq6N#ag%hU;S(27ytkO

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png b/samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..2133f177d172d4c79ef1ffaa8088f786a2bdbe8f
GIT binary patch
literal 1550
zcmeAS@N?(olHy`uVBq!ia0vp^Mj*_=1|;R|J2nC-$r9IylHmNblJdl&R0hYC{G?O`
z&)mfH)S%SFl*+=BsWuD@%qf{65hW46K32*3xq68pHF_1f1wh>l3^w)^1&PVosU-?Y
zsp*+{wo31J?^jaDOtDo8H}y5}EpSfF$n>ZxN)4{^3rViZPPR-@vbR&PsjvbXkegbP
zs8ErclUHn2VXFi-*9yo63F|8<fR&VF+bTgE72zA8;GAESs$i;Tpqp%9W}skZsAp(w
zVs37(qhMrUXrOOkq;F`XYiMp|Y-D9%pa2C*K--E^(yW49+@N*=dA3R!B_#z``ugSN
z<$C4Ddih1^`i7R4mLM~XjC6r2bc-wVN)jt{^NN*WCb*;)Cl_TFlw{`TDS%8&Ov*1U
zu~h=P6yk;40$*Ra!Fk2dfC2`Yennz|zM-Cher_(vUtrb6B|)hOXJA!b98y`3svneE
zoL^d$42+L7Wte7Q*x|Pbq!8#DEB~TQV5B7Gxa237=BDPAc)Hjs0cG@3GE=M!%v?=f
z3@n{ojf~A*4Gj$~oJ^ctoDEzI4O}b@4NV<kW?<9nVq$9HZ0P7}?Brr>Xy|HaX=q~T
zXkuhy<YsAPZfRi()9aa6T#}fVoC>oy6KF3~uM1wiR?bDKi6!|(A^G_^uoMuGkzbNu
zoRMFk;2dnK5T2Qrl3!j7iX4bvT~doO%TiO^it=+6z@clEiN$tTLlY-cQ*#SPb7Kqa
zzJ};cAt%K2fsWA!B@Lvc0uutJKM)h1@PQn7)=A9+=9eO1#>h2t<6vN5a`1F<45_&F
zCgNglvw^_UQ1K63?>IoPgvE$SQc<?Che3IQ;2{nJCo3k?OPjxx7<GOYjM|$1GUZ**
z+v;z3KTcX+Ij?*Fg?S<!Oo0mjnNNIfs}ALlt=%a&Ny|e!r`D<5@!X4UpPBC~zUNJ3
zlYZi~tC?AD*TTZ`=V|<`O3v9$6)#dJ=r5fAVb2YnoOXruj>9`RFR@5oEMEQcuh2HP
zp6FYXzh@K|KXK{P|2wZ_Iz!UOKY}UZOO97`J6F2O-)1bnXSiIfU8r#i)0E?L&d-t2
z)c7~uKsr%c^Nr5aQ$j_iEzTP2CUULicAD~e(?KcrHI`iRGF9`Xqr9aHn7pUHd@)Un
zYj5;f1(o7sYHzMT6tnTW>+t@;Wxnk<?*!Lb$E;+zlqz<(vuNppihlN|p5G(t7tMK*
zuv&A<^nbjst9Cv--KA{k&vuDdcNX)Lj+%*m?<d&HUMuPNThSn9Ubg5_(8J0DHzrJ0
zj_E2cQBJzoRkJ!Fd3R&%u|He4+B};vW&f$Iz)<^n+~i)P{8<6^nVwOBLD9eRj{Hmu
zR_P2f<Ju<eEr0o^kjNsDlB0r4HMUKe@^R9Sv>!*_3;D;aQ7@>=7RYwcvWU3HaL8rD
zamEmP#-v^oIY;GJrcGr_YyWP$|7PL>Nd~R3E+*rLwl`M(?ya};313mc{QT!#{=kD~
z*_z*~*><O-WqrJJIrok5mbwM;o$I69qFyy;ymaw@(j&f5{kf0Q8@9ijv;|lfIe_Dr
i%cW5R!Fdwhz{n80oh#+wlyFN>3GM0X=d#Wzp$P!Xu`&Pv

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/tile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/tile-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..cdec0dbdccad7ae5dd0e92e3c3015449fffb7450
GIT binary patch
literal 2665
zcma)8dpwj`AD^(gN@_z1&pSR_@0Ph|CX;bDv1_Dpuf%xfF$Ocwm>HL$5^q~u7S+3&
zTD-Ok5}6Q6nB-Pe79nQGbi)dHH^jK^u&Le8=e6%Xf1Kx>^ZS0kzu!6M_xYW3%GG6$
z)~d~`5D0{plcPNyfmlXV_0O-+RJHCMS4UL8O+p86p&J}1jAZa3gbfo8fB+{Bg9Xtc
z22&LF5VAlZ)B(1;x6qsBOa@^NnlX<-M{#&6HUeQ`6~$wKA&?LVfLLrU1vz|IiUin9
z3ewArhNbcBpdhwmG#_${c5w%zLqKyT(#jIBh$5>5IFOJ5L~%m70&)}uxu8o{_2;KC
zNMHdX451)@56YY73fRGX2rxrqQ6QFx1&BB_j<AzNBAEhsEDnpo;xRZp3P&On@MJ6&
z`0ycB-uTQwGTol~!Ix@8K?VthJTe9o85xO=B%onF3xhK^H=ozQ<54OEN+9A28Br*%
zz+_Ru9uk0jHc!Zgxxl<4BLEH;Qjn@he_sNJ_feKB_^?f?4Z}n+co-ZSJHMnwAdU9d
zP!8uKS|FrDpW^+W!UA^@55mwP0UXW;RR<SnGVh8<w&Oz#A<TD&;n2lhbPa-qupkKL
z0d{U?fESy~gd+tDXc~>|#1#k`To7`yryx~)G@H#N6A9)HW;k;^k$|<q;T&+gY^ioO
zW&|wJ&YoaTu(4g_+QVQt2jU7Bxy(;o!jjziMBwmLp6ww%I|5=-`7j4qSTLErbS&5<
z^*(T!OUHs+l8aFVgPA|pKOFPolqz@TyC0KQHTanJ5LcD!d{t8W)DlV&2u+2Py^VWR
z*PuKx>?KuS)BlTqYX-%Ae=h|P1LEg9mWlnv{$CwipSRw5W!7=Gl{L<lhA{D*wdHO7
zK2hM#N*k$Tw;0xYI4(OXl^`n5Dbm%fZ!TLwL{w=4&k!003(YZq^>v|$c&&wI(fkRs
zU|z&5m=`hsM?z)(;O1{jWK<1uq7yUx#%3OaYE=>Oc0k_VAnz%Ys)BE!w}l;RWk)8z
z(VENsO!gwpvfivAyHe0KY8rXrP=K=c_{hkX#>B^dA*a(?jrF?TX05mq{A2T$rv-;I
z$g)GLQthe-50+`?nAorF8~K&f1xcDT?^m3L8awoS^t+|B+_)o2M|S0bvx#3<n`y|1
zQ#}f!l{ab~Z)T3UoiRLmRM2U8FfQNZ*xLkAuE{_?wdBs>RHK)Q<PAwI!;bN-tGy?l
z`Zg17uWe$l3!k=C80KIbej0EOH9l9Cm`mUmC7dZw=7qQ%gg14(_q-NH+jv0lg=exx
zyXoedR%@vATc|7U?LN}G{f542=+&LLgbVcIJL#^UnbpR;b=lR;pZ#9cUy+HPWUWwo
zq@C<>97{jhg}3G8uH@@X&CJqU`E#W{P30#``^{%(OwJD-=-tyauopL0;VGqI3c5q4
zr*$ObhOaD=K;y>j@OB(*Y&F$>fHn1Sym(M#EK#3=slAk%n1|!amZGMfQyrkraP~!>
z)-W|mGF&kTS}6x41?jgc3I-VXbg1n0kWp%YDJoLz5y0_884jFCy2t_@V*^{WqK&Vj
z#j#K7hFadS*9^0nR!#e8^3SKrl7nC8{Bpi&c{jLW<V~C?HNZL8Yj8Niwzed3h~h53
zQwyegNbNi(?Y^rn{%Tcz*mpNhQ*RG#igfaQL~92c;GPyeZMV(Vz7?^%J2ryW9!+5u
zHMsM>mq)wKWPA5!c}o(GC~7L-m_Cc3yhuqVprfBOTg1$Tmq++%`0NgQG)Qb0okCcS
zk9B*@D2`=mr`HE}>8<&1fBcQj`m7M-x`@t+M|s|8?Qg!+3NgcXlQ8jD%v&B1)xof_
zvtup#a{1X2R~F;h=%WFHf!+0#aD@pljC}qB!EZ!qJ$7e9@Zl7H8MCd!Rj(*Pv;3cG
z%mXw7edE<t`76#l?7S86^1X|XL=qzpObM>MLDMZOdby>zc2ah&@JVyxK?m{O#8snd
zB#U9q_hK$7E?2vRqqBV^4jt&zytD1ruf;jKdWR&rv&!4_1MZjmDJ7le!AZhu7>vQR
ziRvEGNi$i|(y(#Xj$-A#llvm;X70rrh34!dIf$7uw@y^y^HeXtkYnZ^naWn(qCtz-
zRfkyezQXmBx(s)(K7(yCY7o(?6Gf}9*p%~{3*O1hsxMwH+d6PUivpeTLWS#Ui1`h)
zOGVoG;&%DQ#y)xL)3(9rUc+2ZFQ0p;CVlP^Kc4g1q`SM{{bQW6-Q`7Hn^&lZr_L>t
z#!LgqOV2XP*X;0WYFjJkQF7Q(Tf|d!5BC1jHIkC(IW;IO;F=`B;PJKz%Ko~rjCVcv
zvZ7<@FI+af-v2L@hhJkH+H-cbpZ4+lUtE7M<XHWKmPQ>hDOPlqpA&Q6Tso6^`10k(
zB-VRlVRfHXfnwSz-fc%$z3I=vkI#gxDJkFIxg}>XP<oT0*z>@`eQuV@r|{P(a>u6%
zbshAL;`_fWk*`fVne`@i^!iZ$<z7Z-WSUzglU>+wJrA7$N>k51Z_K`RLmbsqYJ5Ae
zpDHirz501}!eNS?kO8L1^C!)ktV)`Jj^<r=O@B1Hau&0^tbnBBkMT)4H+L%I653}n
zcUx-QE0O-LJ$Lg4JdOHt#!n1gAD7k?>`)VJh@*TSEK%<WcAFVF@k>sN(#lz}UAsoG
zRciR3+%kN&g+^=xSy?_x3snMB(~e+cy^QWP;%#Cq>n)f`f3<94`odnN$+D3+?MvMI
zW0MyJYI6zx>iRu%7OIN=he92%^@l>eWF=PB=s(r^zbEmR*TvEjf4XsIX4m^8zOJ*{
V^V80WL-UV6CkGe%d|Utc-vFTWTn+#L

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/windows-sdk.png b/samples/winrt/ImageManipulations/C++/assets/windows-sdk.png
new file mode 100644
index 0000000000000000000000000000000000000000..67268021df6fbd0dfdd5220f669db5e07d83f620
GIT binary patch
literal 2997
zcmV;m3rh5fP)<h;3K|Lk000e1NJLTq000~S000sQ1^@s6NC&>;00009a7bBm000id
z000id0mpBsWB>pPPiaF#P*7-ZbZ>KLZ*U+<Lqi~Na&Km7Y-Iodc-oy)XH-+^7Crag
z^g>IBfRsybQWXdwQbLP>6p<z>Aqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uh<iVD~V
z<RPMtgQJLw%KPDaqifc@_vX$1wbwr9tn;0-&j-K=43<bUQ8j=JsX`tR;Dg7+#^K~H
zK!FM*Z~zbpvt%K2{UZSY_<lS*D<Z%Lz5oGu(+dayz)hRLFdT>f59&ghTmgWD0l;*T
zI7<kC6aYYajzXpYKt=(8otP$50H6c_V9R4-;{Z@C0AMG7=F<Rxo%or10RUT+Ar%3j
zkpLhQWr#!oXgdI`&sK^>09Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p
z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-<?i
z0%4j!F2Z@488U%158(66005wo6%pWr^Zj_v4zAA5HjcIqUoGmt2LB>rV&neh&#Q1i
z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_<lS*MWK+n+1cgf
z<k(8YLR(?VSAG6x!e78w{cQPuJpA|d;J)G{fihizM+Erb!p!tcr5w+a34~(Y=8s4G
zw+sLL9n&JjNn*KJDiq^U5^;`1nvC-@r6P$!k}1U{(*I=Q-z@tBKHoI}uxdU5dyy@u
zU1J0GOD7Ombim^G008p4Z^6_k2m^p<gW=D2|L;HjN1!DDfM!XOaR2~bL?kX$%CkSm
z2mk;?pn)o|K^yeJ7%adB9Ki+L!3+FgHiSYX#KJ-lLJDMn9CBbOtb#%)hRv`YDqt_v
zKpix|QD}yfa1JiQRk#j4a1Z)n2%f<xynzV>LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW
zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_Ifq<Ex{*7`05XF7hP+2Hl!3BQJ=6@fL%FCo
z8iYoo3(#bAF`ADSpqtQgv>H8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X
zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ<AYmRsNLWl*PS{AOARHt#5!wki2?K;t
z!Y3k=s7tgax)J%r7-BLphge7~Bi0g+6E6^Zh(p9TBoc{3GAFr^0!gu?RMHaCM$&Fl
zBk3%un>0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4
z<uv66WtcKSRim0x-Ke2d5jBrmLam{;Qm;{ms1r1GnmNsb7D-E`t)i9F8fX`2_i3-_
zbh;7Ul^#x)&{xvS=|||7=mYe33=M`AgU5(xC>fg=2N-7=cNnjjOr{yriy6mMFgG#l
znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U
zt5vF<Q0r40Q)j6=sE4X&sBct1q<&fbi3VB2Ov6t@q*0);U*o*SAPZv|vv@2aYYnT0
zb%8a+Cb7-ge0D0knEf5Qi#@8Tp*ce{N;6lpQuCB%KL_KOarm5cP6_8Ir<e17iry6O
zDdH&`rZh~sF=bq9s+O0QSgS~@QL9Jmy*94xr=6y~MY~!1fet~(N+(<=M`w@D1)b+p
z*;C!83a1uLJv#NSE~;y#8=<>IcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya?
z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y
zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB
zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt
z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a<fJbF^|4I#xQ~n$Dc=
zKYhjYmgz5NSkDm8*fZm{6U!;YX`NG>(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C
z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB
zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe
zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0
z?2xS?_ve_-k<Mujg;0Lz*3buG=3$G&ehepthlN*$KaOySSQ^nWmo<0M+(UEUMEXRQ
zMBbZcF;6+KElM>iKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$
z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4
z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu
zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu
z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E
ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw
zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX
z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i&
z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01
z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R
z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw
zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD
zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3|
zawq-H%e&ckC+@AhPrP6BK<z=<L*0kfKU@CX*zeqbYQT4(^U>T#_XdT7&;F71j}Joy
zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z
zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot<a{81DF0~rvGr5Xr~8u`lav1h
z1DNytV>2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F}
z0002sNkl<Zc-rigF$%&!5JlgrO^)C(wiWE`>}=C$qwI-NYOoT~TF4nB*YE@uK^dDB
zWR30ww$s-POn&BXW+rPygeRt``M?BN0aGCJxdu1^r8s+Rdsm!&%k_ve0V-e%jKx_a
z&Kh6@6u`k0^$aBgg{A`b{%e|-{MpA6H~>atXo8lmfjMc|h_j1WOH-MBto3b%xo=ah
zD6ZCiGu#1JA7iMs;nIYI&w#sfAynGXP=aR{pby*>2XE7wE-hUGLmy+Pwc&3e3AYq~
rL3F-plJa|oO~TqubZP!GOu=ISd<8xF6%`=M00000NkvXXu0mjfiA9h!

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp b/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp
new file mode 100644
index 000000000..9449fbead
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp
@@ -0,0 +1,452 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+#include "pch.h"
+#include "LayoutAwarePage.h"
+#include "SuspensionManager.h"
+
+using namespace SDKSample::Common;
+
+using namespace Platform;
+using namespace Platform::Collections;
+using namespace Windows::Foundation;
+using namespace Windows::Foundation::Collections;
+using namespace Windows::System;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::ViewManagement;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Interop;
+using namespace Windows::UI::Xaml::Navigation;
+
+/// <summary>
+/// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
+/// </summary>
+LayoutAwarePage::LayoutAwarePage()
+{
+    if (Windows::ApplicationModel::DesignMode::DesignModeEnabled)
+    {
+        return;
+    }
+
+    // Create an empty default view model
+    DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>());
+
+    // When this page is part of the visual tree make two changes:
+    // 1) Map application view state to visual state for the page
+    // 2) Handle keyboard and mouse navigation requests
+    Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded);
+
+    // Undo the same changes when the page is no longer visible
+    Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded);
+}
+
+static DependencyProperty^ _defaultViewModelProperty =
+    DependencyProperty::Register("DefaultViewModel",
+    TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr);
+
+/// <summary>
+/// Identifies the <see cref="DefaultViewModel"/> dependency property.
+/// </summary>
+DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get()
+{
+    return _defaultViewModelProperty;
+}
+
+/// <summary>
+/// Gets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
+/// used as a trivial view model.
+/// </summary>
+IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get()
+{
+    return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty));
+}
+
+/// <summary>
+/// Sets an implementation of <see cref="IObservableMap&lt;String, Object&gt;"/> designed to be
+/// used as a trivial view model.
+/// </summary>
+void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value)
+{
+    SetValue(DefaultViewModelProperty, value);
+}
+
+/// <summary>
+/// Invoked when the page is part of the visual tree
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="e">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+	this->StartLayoutUpdates(sender, e);
+
+	// Keyboard and mouse navigation only apply when occupying the entire window
+	if (this->ActualHeight == Window::Current->Bounds.Height &&
+		this->ActualWidth == Window::Current->Bounds.Width)
+	{
+		// Listen to the window directly so focus isn't required
+		_acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated +=
+			ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this,
+			&LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated);
+		_pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed +=
+			ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this,
+			&LayoutAwarePage::CoreWindow_PointerPressed);
+		_navigationShortcutsRegistered = true;
+	}
+}
+
+/// <summary>
+/// Invoked when the page is removed from visual tree
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="e">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+	if (_navigationShortcutsRegistered)
+	{
+		Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken;
+		Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken;
+		_navigationShortcutsRegistered = false;
+	}
+	StopLayoutUpdates(sender, e);
+}
+
+#pragma region Navigation support
+
+/// <summary>
+/// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
+/// until it reaches the top of the navigation stack.
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="e">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e)
+{
+    (void) sender;	// Unused parameter
+    (void) e;	// Unused parameter
+
+    // Use the navigation frame to return to the topmost page
+    if (Frame != nullptr)
+    {
+        while (Frame->CanGoBack)
+        {
+            Frame->GoBack();
+        }
+    }
+}
+
+/// <summary>
+/// Invoked as an event handler to navigate backward in the navigation stack
+/// associated with this page's <see cref="Frame"/>.
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="e">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e)
+{
+    (void) sender;	// Unused parameter
+    (void) e;	// Unused parameter
+
+    // Use the navigation frame to return to the previous page
+    if (Frame != nullptr && Frame->CanGoBack)
+    {
+        Frame->GoBack();
+    }
+}
+
+/// <summary>
+/// Invoked as an event handler to navigate forward in the navigation stack
+/// associated with this page's <see cref="Frame"/>.
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="e">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e)
+{
+    (void) sender;	// Unused parameter
+    (void) e;	// Unused parameter
+
+    // Use the navigation frame to advance to the next page
+    if (Frame != nullptr && Frame->CanGoForward)
+    {
+        Frame->GoForward();
+    }
+}
+
+/// <summary>
+/// Invoked on every keystroke, including system keys such as Alt key combinations, when
+/// this page is active and occupies the entire window.  Used to detect keyboard navigation
+/// between pages even when the page itself doesn't have focus.
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="args">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args)
+{
+    auto virtualKey = args->VirtualKey;
+
+    // Only investigate further when Left, Right, or the dedicated Previous or Next keys
+    // are pressed
+    if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown ||
+        args->EventType == CoreAcceleratorKeyEventType::KeyDown) &&
+        (virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right ||
+        (int)virtualKey == 166 || (int)virtualKey == 167))
+    {
+        auto coreWindow = Window::Current->CoreWindow;
+        auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down;
+        bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState;
+        bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState;
+        bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState;
+        bool noModifiers = !menuKey && !controlKey && !shiftKey;
+        bool onlyAlt = menuKey && !controlKey && !shiftKey;
+
+        if (((int)virtualKey == 166 && noModifiers) ||
+            (virtualKey == VirtualKey::Left && onlyAlt))
+        {
+            // When the previous key or Alt+Left are pressed navigate back
+            args->Handled = true;
+            GoBack(this, ref new RoutedEventArgs());
+        }
+        else if (((int)virtualKey == 167 && noModifiers) ||
+            (virtualKey == VirtualKey::Right && onlyAlt))
+        {
+            // When the next key or Alt+Right are pressed navigate forward
+            args->Handled = true;
+            GoForward(this, ref new RoutedEventArgs());
+        }
+    }
+}
+
+/// <summary>
+/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
+/// page is active and occupies the entire window.  Used to detect browser-style next and
+/// previous mouse button clicks to navigate between pages.
+/// </summary>
+/// <param name="sender">Instance that triggered the event.</param>
+/// <param name="args">Event data describing the conditions that led to the event.</param>
+void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
+{
+    auto properties = args->CurrentPoint->Properties;
+
+    // Ignore button chords with the left, right, and middle buttons
+    if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed ||
+        properties->IsMiddleButtonPressed) return;
+
+    // If back or foward are pressed (but not both) navigate appropriately
+    bool backPressed = properties->IsXButton1Pressed;
+    bool forwardPressed = properties->IsXButton2Pressed;
+    if (backPressed ^ forwardPressed)
+    {
+        args->Handled = true;
+        if (backPressed) GoBack(this, ref new RoutedEventArgs());
+        if (forwardPressed) GoForward(this, ref new RoutedEventArgs());
+    }
+}
+
+#pragma endregion
+
+#pragma region Visual state switching
+
+/// <summary>
+/// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
+/// <see cref="Control"/> within the page, to indicate that the sender should start receiving
+/// visual state management changes that correspond to application view state changes.
+/// </summary>
+/// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
+/// corresponding to view states.</param>
+/// <param name="e">Event data that describes how the request was made.</param>
+/// <remarks>The current view state will immediately be used to set the corresponding visual state
+/// when layout updates are requested.  A corresponding <see cref="Unloaded"/> event handler
+/// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged.  Instances of
+/// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
+/// events.</remarks>
+/// <seealso cref="DetermineVisualState"/>
+/// <seealso cref="InvalidateVisualState"/>
+void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
+{
+    (void) e;	// Unused parameter
+
+    auto control = safe_cast<Control^>(sender);
+    if (_layoutAwareControls == nullptr)
+    {
+        // Start listening to view state changes when there are controls interested in updates
+        _layoutAwareControls = ref new Vector<Control^>();
+        _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged);
+
+        // Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
+        _this = this;
+    }
+    _layoutAwareControls->Append(control);
+
+    // Set the initial visual state of the control
+    VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false);
+}
+
+void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
+{
+    (void) sender;	// Unused parameter
+    (void) e;	// Unused parameter
+
+    InvalidateVisualState();
+}
+
+/// <summary>
+/// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
+/// <see cref="Control"/>, to indicate that the sender should start receiving visual state
+/// management changes that correspond to application view state changes.
+/// </summary>
+/// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
+/// corresponding to view states.</param>
+/// <param name="e">Event data that describes how the request was made.</param>
+/// <remarks>The current view state will immediately be used to set the corresponding visual state
+/// when layout updates are requested.</remarks>
+/// <seealso cref="StartLayoutUpdates"/>
+void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e)
+{
+    (void) e;	// Unused parameter
+
+    auto control = safe_cast<Control^>(sender);
+    unsigned int index;
+    if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index))
+    {
+        _layoutAwareControls->RemoveAt(index);
+        if (_layoutAwareControls->Size == 0)
+        {
+            // Stop listening to view state changes when no controls are interested in updates
+            Window::Current->SizeChanged -= _windowSizeEventToken;
+            _layoutAwareControls = nullptr;
+            // Last control has received the Unload notification.
+            _this = nullptr;
+        }
+    }
+}
+
+/// <summary>
+/// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
+/// within the page.  The default implementation uses the names of enum values.  Subclasses may
+/// override this method to control the mapping scheme used.
+/// </summary>
+/// <param name="viewState">View state for which a visual state is desired.</param>
+/// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
+/// <seealso cref="InvalidateVisualState"/>
+String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState)
+{
+    switch (viewState)
+    {
+    case ApplicationViewState::Filled:
+        return "Filled";
+    case ApplicationViewState::Snapped:
+        return "Snapped";
+    case ApplicationViewState::FullScreenPortrait:
+        return "FullScreenPortrait";
+    case ApplicationViewState::FullScreenLandscape:
+    default:
+        return "FullScreenLandscape";
+    }
+}
+
+/// <summary>
+/// Updates all controls that are listening for visual state changes with the correct visual
+/// state.
+/// </summary>
+/// <remarks>
+/// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
+/// signal that a different value may be returned even though the view state has not changed.
+/// </remarks>
+void LayoutAwarePage::InvalidateVisualState()
+{
+    if (_layoutAwareControls != nullptr)
+    {
+        String^ visualState = DetermineVisualState(ApplicationView::Value);
+        auto controlIterator = _layoutAwareControls->First();
+        while (controlIterator->HasCurrent)
+        {
+            auto control = controlIterator->Current;
+            VisualStateManager::GoToState(control, visualState, false);
+            controlIterator->MoveNext();
+        }
+    }
+}
+
+#pragma endregion
+
+#pragma region Process lifetime management
+
+/// <summary>
+/// Invoked when this page is about to be displayed in a Frame.
+/// </summary>
+/// <param name="e">Event data that describes how this page was reached.  The Parameter
+/// property provides the group to be displayed.</param>
+void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e)
+{
+    // Returning to a cached page through navigation shouldn't trigger state loading
+    if (_pageKey != nullptr) return;
+
+    auto frameState = SuspensionManager::SessionStateForFrame(Frame);
+    _pageKey = "Page-" + Frame->BackStackDepth;
+
+    if (e->NavigationMode == NavigationMode::New)
+    {
+        // Clear existing state for forward navigation when adding a new page to the
+        // navigation stack
+        auto nextPageKey = _pageKey;
+        int nextPageIndex = Frame->BackStackDepth;
+        while (frameState->HasKey(nextPageKey))
+        {
+            frameState->Remove(nextPageKey);
+            nextPageIndex++;
+            nextPageKey = "Page-" + nextPageIndex;
+        }
+
+        // Pass the navigation parameter to the new page
+        LoadState(e->Parameter, nullptr);
+    }
+    else
+    {
+        // Pass the navigation parameter and preserved page state to the page, using
+        // the same strategy for loading suspended state and recreating pages discarded
+        // from cache
+        LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey)));
+    }
+}
+
+/// <summary>
+/// Invoked when this page will no longer be displayed in a Frame.
+/// </summary>
+/// <param name="e">Event data that describes how this page was reached.  The Parameter
+/// property provides the group to be displayed.</param>
+void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e)
+{
+    auto frameState = SuspensionManager::SessionStateForFrame(Frame);
+    auto pageState = ref new Map<String^, Object^>();
+    SaveState(pageState);
+    frameState->Insert(_pageKey, pageState);
+}
+
+/// <summary>
+/// Populates the page with content passed during navigation.  Any saved state is also
+/// provided when recreating a page from a prior session.
+/// </summary>
+/// <param name="navigationParameter">The parameter value passed to
+/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
+/// </param>
+/// <param name="pageState">A map of state preserved by this page during an earlier
+/// session.  This will be null the first time a page is visited.</param>
+void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
+{
+}
+
+/// <summary>
+/// Preserves state associated with this page in case the application is suspended or the
+/// page is discarded from the navigation cache.  Values must conform to the serialization
+/// requirements of <see cref="SuspensionManager.SessionState"/>.
+/// </summary>
+/// <param name="pageState">An empty map to be populated with serializable state.</param>
+void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState)
+{
+}
+
+#pragma endregion
diff --git a/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h b/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h
new file mode 100644
index 000000000..bd71062fe
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h
@@ -0,0 +1,88 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+#pragma once
+
+#include <collection.h>
+
+namespace SDKSample
+{
+    namespace Common
+    {
+        /// <summary>
+        /// Typical implementation of Page that provides several important conveniences:
+        /// <list type="bullet">
+        /// <item>
+        /// <description>Application view state to visual state mapping</description>
+        /// </item>
+        /// <item>
+        /// <description>GoBack, GoForward, and GoHome event handlers</description>
+        /// </item>
+        /// <item>
+        /// <description>Mouse and keyboard shortcuts for navigation</description>
+        /// </item>
+        /// <item>
+        /// <description>State management for navigation and process lifetime management</description>
+        /// </item>
+        /// <item>
+        /// <description>A default view model</description>
+        /// </item>
+        /// </list>
+        /// </summary>
+        [Windows::Foundation::Metadata::WebHostHidden]
+        public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page
+        {
+        internal:
+            LayoutAwarePage();
+
+        public:
+            void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void InvalidateVisualState();
+            static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty
+            {
+                Windows::UI::Xaml::DependencyProperty^ get();
+            };
+            property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel
+            {
+                Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get();
+                void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value);
+            }
+
+        protected:
+            virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState);
+            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
+            virtual void LoadState(Platform::Object^ navigationParameter,
+                Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
+            virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState);
+
+        private:
+            Platform::String^ _pageKey;
+            bool _navigationShortcutsRegistered;
+            Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel;
+            Windows::Foundation::EventRegistrationToken _windowSizeEventToken,
+                _acceleratorKeyEventToken, _pointerPressedEventToken;
+            Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls;
+            void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
+            void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+            void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
+
+            void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender,
+                Windows::UI::Core::AcceleratorKeyEventArgs^ args);
+            void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender,
+                Windows::UI::Core::PointerEventArgs^ args);
+            LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
+        };
+    }
+}
diff --git a/samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml b/samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml
new file mode 100644
index 000000000..7c3d23877
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml
@@ -0,0 +1,978 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+
+<ResourceDictionary
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+
+    <!-- Non-brush values that vary across themes -->
+    
+    <ResourceDictionary.ThemeDictionaries>
+        <ResourceDictionary x:Key="Default">
+            <x:String x:Key="BackButtonGlyph">&#xE071;</x:String>
+            <x:String x:Key="BackButtonSnappedGlyph">&#xE0BA;</x:String>
+        </ResourceDictionary>
+
+        <ResourceDictionary x:Key="HighContrast">
+            <x:String x:Key="BackButtonGlyph">&#xE0A6;</x:String>
+            <x:String x:Key="BackButtonSnappedGlyph">&#xE0C4;</x:String>
+        </ResourceDictionary>
+    </ResourceDictionary.ThemeDictionaries>
+
+    <!-- RichTextBlock styles -->
+
+    <Style x:Key="BasicRichTextStyle" TargetType="RichTextBlock">
+        <Setter Property="Foreground" Value="{StaticResource ApplicationForegroundThemeBrush}"/>
+        <Setter Property="FontSize" Value="{StaticResource ControlContentThemeFontSize}"/>
+        <Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>
+        <Setter Property="TextTrimming" Value="WordEllipsis"/>
+        <Setter Property="TextWrapping" Value="Wrap"/>
+        <Setter Property="Typography.StylisticSet20" Value="True"/>
+        <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
+    </Style>
+
+    <Style x:Key="BaselineRichTextStyle" TargetType="RichTextBlock" BasedOn="{StaticResource BasicRichTextStyle}">
+        <Setter Property="LineHeight" Value="20"/>
+        <Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
+        <!-- Properly align text along its baseline -->
+        <Setter Property="RenderTransform">
+            <Setter.Value>
+                <TranslateTransform X="-1" Y="4"/>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style x:Key="ItemRichTextStyle" TargetType="RichTextBlock" BasedOn="{StaticResource BaselineRichTextStyle}"/>
+
+    <Style x:Key="BodyRichTextStyle" TargetType="RichTextBlock" BasedOn="{StaticResource BaselineRichTextStyle}">
+        <Setter Property="FontWeight" Value="SemiLight"/>
+    </Style>
+
+    <!-- TextBlock styles -->
+
+    <Style x:Key="BasicTextStyle" TargetType="TextBlock">
+        <Setter Property="Foreground" Value="{StaticResource ApplicationForegroundThemeBrush}"/>
+        <Setter Property="FontSize" Value="{StaticResource ControlContentThemeFontSize}"/>
+        <Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>
+        <Setter Property="TextTrimming" Value="WordEllipsis"/>
+        <Setter Property="TextWrapping" Value="Wrap"/>
+        <Setter Property="Typography.StylisticSet20" Value="True"/>
+        <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
+    </Style>
+
+    <Style x:Key="BaselineTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BasicTextStyle}">
+        <Setter Property="LineHeight" Value="20"/>
+        <Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
+        <!-- Properly align text along its baseline -->
+        <Setter Property="RenderTransform">
+            <Setter.Value>
+                <TranslateTransform X="-1" Y="4"/>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style x:Key="HeaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}">
+        <Setter Property="FontSize" Value="56"/>
+        <Setter Property="FontWeight" Value="Light"/>
+        <Setter Property="LineHeight" Value="40"/>
+        <Setter Property="RenderTransform">
+            <Setter.Value>
+                <TranslateTransform X="-2" Y="8"/>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style x:Key="SubheaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}">
+        <Setter Property="FontSize" Value="26.667"/>
+        <Setter Property="FontWeight" Value="Light"/>
+        <Setter Property="LineHeight" Value="30"/>
+        <Setter Property="RenderTransform">
+            <Setter.Value>
+                <TranslateTransform X="-1" Y="6"/>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style x:Key="TitleTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}">
+        <Setter Property="FontWeight" Value="SemiBold"/>
+    </Style>
+
+    <Style x:Key="ItemTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}"/>
+
+    <Style x:Key="BodyTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}">
+        <Setter Property="FontWeight" Value="SemiLight"/>
+    </Style>
+
+    <Style x:Key="CaptionTextStyle" TargetType="TextBlock" BasedOn="{StaticResource BaselineTextStyle}">
+        <Setter Property="FontSize" Value="12"/>
+        <Setter Property="Foreground" Value="{StaticResource ApplicationSecondaryForegroundThemeBrush}"/>
+    </Style>
+
+    <!-- Button styles -->
+
+    <!--
+        TextButtonStyle is used to style a Button using subheader-styled text with no other adornment.  This
+        style is used in the GroupedItemsPage as a group header and in the FileOpenPickerPage for triggering
+        commands.
+    -->
+    <Style x:Key="TextButtonStyle" TargetType="Button">
+        <Setter Property="MinWidth" Value="0"/>
+        <Setter Property="MinHeight" Value="0"/>
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="Button">
+                    <Grid Background="Transparent">
+                        <TextBlock
+                            x:Name="Text"
+                            Text="{TemplateBinding Content}"
+                            Margin="3,-7,3,10"
+                            TextWrapping="NoWrap"
+                            Style="{StaticResource SubheaderTextStyle}"/>
+                        <Rectangle
+                            x:Name="FocusVisualWhite"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="1.5"/>
+                        <Rectangle
+                            x:Name="FocusVisualBlack"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="0.5"/>
+
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualState x:Name="Normal"/>
+                                <VisualState x:Name="PointerOver">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ApplicationPointerOverForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Pressed">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ApplicationPressedForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Disabled">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonDisabledForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="FocusStates">
+                                <VisualState x:Name="Focused">
+                                    <Storyboard>
+                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetName="FocusVisualWhite" Storyboard.TargetProperty="Opacity"/>
+                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetName="FocusVisualBlack" Storyboard.TargetProperty="Opacity"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Unfocused"/>
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+                    </Grid>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <!--
+        TextRadioButtonStyle is used to style a RadioButton using subheader-styled text with no other adornment.
+        This style is used in the SearchResultsPage to allow selection among filters.
+    -->
+    <Style x:Key="TextRadioButtonStyle" TargetType="RadioButton">
+        <Setter Property="MinWidth" Value="0"/>
+        <Setter Property="MinHeight" Value="0"/>
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="RadioButton">
+                    <Grid Background="Transparent">
+                        <TextBlock
+                            x:Name="Text"
+                            Text="{TemplateBinding Content}"
+                            Margin="3,-7,3,10"
+                            TextWrapping="NoWrap"
+                            Style="{StaticResource SubheaderTextStyle}"/>
+                        <Rectangle
+                            x:Name="FocusVisualWhite"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="1.5"/>
+                        <Rectangle
+                            x:Name="FocusVisualBlack"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="0.5"/>
+
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualState x:Name="Normal"/>
+                                <VisualState x:Name="PointerOver">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ApplicationPointerOverForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Pressed">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ApplicationPressedForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Disabled">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonDisabledForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="FocusStates">
+                                <VisualState x:Name="Focused">
+                                    <Storyboard>
+                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetName="FocusVisualWhite" Storyboard.TargetProperty="Opacity"/>
+                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetName="FocusVisualBlack" Storyboard.TargetProperty="Opacity"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Unfocused"/>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="CheckStates">
+                                <VisualState x:Name="Checked"/>
+                                <VisualState x:Name="Unchecked">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Text" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ApplicationSecondaryForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Indeterminate"/>
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+                    </Grid>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <!--
+        AppBarButtonStyle is used to style a Button for use in an App Bar.  Content will be centered and should fit within
+        the 40-pixel radius glyph provided.  16-point Segoe UI Symbol is used for content text to simplify the use of glyphs
+        from that font.  AutomationProperties.Name is used for the text below the glyph.
+    -->
+    <Style x:Key="AppBarButtonStyle" TargetType="Button">
+        <Setter Property="Foreground" Value="{StaticResource AppBarItemForegroundThemeBrush}"/>
+        <Setter Property="VerticalAlignment" Value="Stretch"/>
+        <Setter Property="FontFamily" Value="Segoe UI Symbol"/>
+        <Setter Property="FontWeight" Value="Normal"/>
+        <Setter Property="FontSize" Value="20"/>
+        <Setter Property="AutomationProperties.ItemType" Value="App Bar Button"/>
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="Button">
+                    <Grid Width="100" Background="Transparent">
+                        <StackPanel VerticalAlignment="Top" Margin="0,14,0,13">
+                            <Grid Width="40" Height="40" Margin="0,0,0,5" HorizontalAlignment="Center">
+                                <TextBlock x:Name="BackgroundGlyph" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemBackgroundThemeBrush}"/>
+                                <TextBlock x:Name="OutlineGlyph" Text="&#xE0A7;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0"/>
+                                <ContentPresenter x:Name="Content" HorizontalAlignment="Center" Margin="-1,-1,0,0" VerticalAlignment="Center"/>
+                            </Grid>
+                            <TextBlock
+                                x:Name="TextLabel"
+                                Text="{TemplateBinding AutomationProperties.Name}"
+                                Margin="0,0,2,0"
+                                FontSize="12"
+                                TextAlignment="Center"
+                                Width="88"
+                                MaxHeight="32"
+                                TextTrimming="WordEllipsis"
+                                Style="{StaticResource BasicTextStyle}"/>
+                        </StackPanel>
+                        <Rectangle
+                                x:Name="FocusVisualWhite"
+                                IsHitTestVisible="False"
+                                Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}"
+                                StrokeEndLineCap="Square"
+                                StrokeDashArray="1,1"
+                                Opacity="0"
+                                StrokeDashOffset="1.5"/>
+                        <Rectangle
+                                x:Name="FocusVisualBlack"
+                                IsHitTestVisible="False"
+                                Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}"
+                                StrokeEndLineCap="Square"
+                                StrokeDashArray="1,1"
+                                Opacity="0"
+                                StrokeDashOffset="0.5"/>
+
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualState x:Name="Normal"/>
+                                <VisualState x:Name="PointerOver">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverBackgroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPointerOverForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Pressed">
+                                    <Storyboard>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="OutlineGlyph"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="0"
+                                            Duration="0"/>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Disabled">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextLabel" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="FocusStates">
+                                <VisualState x:Name="Focused">
+                                    <Storyboard>
+                                        <DoubleAnimation
+                                                Storyboard.TargetName="FocusVisualWhite"
+                                                Storyboard.TargetProperty="Opacity"
+                                                To="1"
+                                                Duration="0"/>
+                                        <DoubleAnimation
+                                                Storyboard.TargetName="FocusVisualBlack"
+                                                Storyboard.TargetProperty="Opacity"
+                                                To="1"
+                                                Duration="0"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Unfocused" />
+                                <VisualState x:Name="PointerFocused" />
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+                    </Grid>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <!-- Standard App Bar buttons -->
+  
+    <Style x:Key="SkipBackAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="SkipBackAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Skip Back"/>
+        <Setter Property="Content" Value="&#xE100;"/>
+    </Style>
+    <Style x:Key="SkipAheadAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="SkipAheadAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Skip Ahead"/>
+        <Setter Property="Content" Value="&#xE101;"/>
+    </Style>
+    <Style x:Key="PlayAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="PlayAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Play"/>
+        <Setter Property="Content" Value="&#xE102;"/>
+    </Style>
+    <Style x:Key="PauseAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="PauseAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Pause"/>
+        <Setter Property="Content" Value="&#xE103;"/>
+    </Style>
+    <Style x:Key="EditAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="EditAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Edit"/>
+        <Setter Property="Content" Value="&#xE104;"/>
+    </Style>
+    <Style x:Key="SaveAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="SaveAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Save"/>
+        <Setter Property="Content" Value="&#xE105;"/>
+    </Style>
+    <Style x:Key="DeleteAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="DeleteAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Delete"/>
+        <Setter Property="Content" Value="&#xE106;"/>
+    </Style>
+    <Style x:Key="DiscardAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="DiscardAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Discard"/>
+        <Setter Property="Content" Value="&#xE107;"/>
+    </Style>
+    <Style x:Key="RemoveAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="RemoveAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Remove"/>
+        <Setter Property="Content" Value="&#xE108;"/>
+    </Style>
+    <Style x:Key="AddAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="AddAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Add"/>
+        <Setter Property="Content" Value="&#xE109;"/>
+    </Style>
+    <Style x:Key="NoAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="NoAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="No"/>
+        <Setter Property="Content" Value="&#xE10A;"/>
+    </Style>
+    <Style x:Key="YesAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="YesAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Yes"/>
+        <Setter Property="Content" Value="&#xE10B;"/>
+    </Style>
+    <Style x:Key="MoreAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="MoreAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="More"/>
+        <Setter Property="Content" Value="&#xE10C;"/>
+    </Style>
+    <Style x:Key="RedoAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="RedoAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Redo"/>
+        <Setter Property="Content" Value="&#xE10D;"/>
+    </Style>
+    <Style x:Key="UndoAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="UndoAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Undo"/>
+        <Setter Property="Content" Value="&#xE10E;"/>
+    </Style>
+    <Style x:Key="HomeAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="HomeAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Home"/>
+        <Setter Property="Content" Value="&#xE10F;"/>
+    </Style>
+    <Style x:Key="OutAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="OutAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Out"/>
+        <Setter Property="Content" Value="&#xE110;"/>
+    </Style>
+    <Style x:Key="NextAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="NextAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Next"/>
+        <Setter Property="Content" Value="&#xE111;"/>
+    </Style>
+    <Style x:Key="PreviousAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="PreviousAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Previous"/>
+        <Setter Property="Content" Value="&#xE112;"/>
+    </Style>
+    <Style x:Key="FavoriteAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="FavoriteAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Favorite"/>
+        <Setter Property="Content" Value="&#xE113;"/>
+    </Style>
+    <Style x:Key="PhotoAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="PhotoAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Photo"/>
+        <Setter Property="Content" Value="&#xE114;"/>
+    </Style>
+    <Style x:Key="SettingsAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="SettingsAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Settings"/>
+        <Setter Property="Content" Value="&#xE115;"/>
+    </Style>
+    <Style x:Key="VideoAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="VideoAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Video"/>
+        <Setter Property="Content" Value="&#xE116;"/>
+    </Style>
+    <Style x:Key="RefreshAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="RefreshAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Refresh"/>
+        <Setter Property="Content" Value="&#xE117;"/>
+    </Style>
+    <Style x:Key="DownloadAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="DownloadAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Download"/>
+        <Setter Property="Content" Value="&#xE118;"/>
+    </Style>
+    <Style x:Key="MailAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="MailAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Mail"/>
+        <Setter Property="Content" Value="&#xE119;"/>
+    </Style>
+    <Style x:Key="SearchAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="SearchAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Search"/>
+        <Setter Property="Content" Value="&#xE11A;"/>
+    </Style>
+    <Style x:Key="HelpAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="HelpAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Help"/>
+        <Setter Property="Content" Value="&#xE11B;"/>
+    </Style>
+    <Style x:Key="UploadAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="UploadAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Upload"/>
+        <Setter Property="Content" Value="&#xE11C;"/>
+    </Style>
+    <Style x:Key="PinAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="PinAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Pin"/>
+        <Setter Property="Content" Value="&#xE141;"/>
+    </Style>
+    <Style x:Key="UnpinAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
+        <Setter Property="AutomationProperties.AutomationId" Value="UnpinAppBarButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Unpin"/>
+        <Setter Property="Content" Value="&#xE196;"/>
+    </Style>
+
+    <!-- Title area styles -->
+
+    <Style x:Key="PageHeaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource HeaderTextStyle}">
+        <Setter Property="TextWrapping" Value="NoWrap"/>
+        <Setter Property="VerticalAlignment" Value="Bottom"/>
+        <Setter Property="Margin" Value="0,0,40,40"/>
+    </Style>
+
+    <Style x:Key="PageSubheaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource SubheaderTextStyle}">
+        <Setter Property="TextWrapping" Value="NoWrap"/>
+        <Setter Property="VerticalAlignment" Value="Bottom"/>
+        <Setter Property="Margin" Value="0,0,0,40"/>
+    </Style>
+
+    <Style x:Key="SnappedPageHeaderTextStyle" TargetType="TextBlock" BasedOn="{StaticResource PageSubheaderTextStyle}">
+        <Setter Property="Margin" Value="0,0,18,40"/>
+    </Style>
+
+    <!--
+        BackButtonStyle is used to style a Button for use in the title area of a page.  Margins appropriate for
+        the conventional page layout are included as part of the style.
+    -->
+    <Style x:Key="BackButtonStyle" TargetType="Button">
+        <Setter Property="MinWidth" Value="0"/>
+        <Setter Property="Width" Value="48"/>
+        <Setter Property="Height" Value="48"/>
+        <Setter Property="Margin" Value="36,0,36,36"/>
+        <Setter Property="VerticalAlignment" Value="Bottom"/>
+        <Setter Property="FontFamily" Value="Segoe UI Symbol"/>
+        <Setter Property="FontWeight" Value="Normal"/>
+        <Setter Property="FontSize" Value="56"/>
+        <Setter Property="AutomationProperties.AutomationId" Value="BackButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Back"/>
+        <Setter Property="AutomationProperties.ItemType" Value="Navigation Button"/>
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="Button">
+                    <Grid x:Name="RootGrid">
+                        <Grid Margin="-1,-16,0,0">
+                            <TextBlock x:Name="BackgroundGlyph" Text="&#xE0A8;" Foreground="{StaticResource BackButtonBackgroundThemeBrush}"/>
+                            <TextBlock x:Name="NormalGlyph" Text="{StaticResource BackButtonGlyph}" Foreground="{StaticResource BackButtonForegroundThemeBrush}"/>
+                            <TextBlock x:Name="ArrowGlyph" Text="&#xE0A6;" Foreground="{StaticResource BackButtonPressedForegroundThemeBrush}" Opacity="0"/>
+                        </Grid>
+                        <Rectangle
+                            x:Name="FocusVisualWhite"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="1.5"/>
+                        <Rectangle
+                            x:Name="FocusVisualBlack"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="0.5"/>
+
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualState x:Name="Normal" />
+                                <VisualState x:Name="PointerOver">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonPointerOverBackgroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="NormalGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonPointerOverForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Pressed">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="ArrowGlyph"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="NormalGlyph"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="0"
+                                            Duration="0"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Disabled">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Visibility">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="FocusStates">
+                                <VisualState x:Name="Focused">
+                                    <Storyboard>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="FocusVisualWhite"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="FocusVisualBlack"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Unfocused" />
+                                <VisualState x:Name="PointerFocused" />
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+                    </Grid>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <!--
+        PortraitBackButtonStyle is used to style a Button for use in the title area of a portrait page.  Margins appropriate
+        for the conventional page layout are included as part of the style.
+    -->
+    <Style x:Key="PortraitBackButtonStyle" TargetType="Button" BasedOn="{StaticResource BackButtonStyle}">
+        <Setter Property="Margin" Value="26,0,26,36"/>
+    </Style>
+
+    <!--
+        SnappedBackButtonStyle is used to style a Button for use in the title area of a snapped page.  Margins appropriate
+        for the conventional page layout are included as part of the style.
+        
+        The obvious duplication here is necessary as the glyphs used in snapped are not merely smaller versions of the same
+        glyph but are actually distinct.
+    -->
+    <Style x:Key="SnappedBackButtonStyle" TargetType="Button">
+        <Setter Property="MinWidth" Value="0"/>
+        <Setter Property="Margin" Value="20,0,0,0"/>
+        <Setter Property="VerticalAlignment" Value="Bottom"/>
+        <Setter Property="FontFamily" Value="Segoe UI Symbol"/>
+        <Setter Property="FontWeight" Value="Normal"/>
+        <Setter Property="FontSize" Value="26.66667"/>
+        <Setter Property="AutomationProperties.AutomationId" Value="BackButton"/>
+        <Setter Property="AutomationProperties.Name" Value="Back"/>
+        <Setter Property="AutomationProperties.ItemType" Value="Navigation Button"/>
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="Button">
+                    <Grid x:Name="RootGrid" Width="36" Height="36" Margin="-3,0,7,33">
+                        <Grid Margin="-1,-1,0,0">
+                            <TextBlock x:Name="BackgroundGlyph" Text="&#xE0D4;" Foreground="{StaticResource BackButtonBackgroundThemeBrush}"/>
+                            <TextBlock x:Name="NormalGlyph" Text="{StaticResource BackButtonSnappedGlyph}" Foreground="{StaticResource BackButtonForegroundThemeBrush}"/>
+                            <TextBlock x:Name="ArrowGlyph" Text="&#xE0C4;" Foreground="{StaticResource BackButtonPressedForegroundThemeBrush}" Opacity="0"/>
+                        </Grid>
+                        <Rectangle
+                            x:Name="FocusVisualWhite"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="1.5"/>
+                        <Rectangle
+                            x:Name="FocusVisualBlack"
+                            IsHitTestVisible="False"
+                            Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}"
+                            StrokeEndLineCap="Square"
+                            StrokeDashArray="1,1"
+                            Opacity="0"
+                            StrokeDashOffset="0.5"/>
+
+                        <VisualStateManager.VisualStateGroups>
+                            <VisualStateGroup x:Name="CommonStates">
+                                <VisualState x:Name="Normal" />
+                                <VisualState x:Name="PointerOver">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonPointerOverBackgroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="NormalGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonPointerOverForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Pressed">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BackButtonForegroundThemeBrush}"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="ArrowGlyph"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="NormalGlyph"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="0"
+                                            Duration="0"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Disabled">
+                                    <Storyboard>
+                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Visibility">
+                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
+                                        </ObjectAnimationUsingKeyFrames>
+                                    </Storyboard>
+                                </VisualState>
+                            </VisualStateGroup>
+                            <VisualStateGroup x:Name="FocusStates">
+                                <VisualState x:Name="Focused">
+                                    <Storyboard>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="FocusVisualWhite"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                        <DoubleAnimation
+                                            Storyboard.TargetName="FocusVisualBlack"
+                                            Storyboard.TargetProperty="Opacity"
+                                            To="1"
+                                            Duration="0"/>
+                                    </Storyboard>
+                                </VisualState>
+                                <VisualState x:Name="Unfocused" />
+                                <VisualState x:Name="PointerFocused" />
+                            </VisualStateGroup>
+                        </VisualStateManager.VisualStateGroups>
+                    </Grid>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <!-- Item templates -->
+
+    <!-- Grid-appropriate 250 pixel square item template as seen in the GroupedItemsPage and ItemsPage -->
+    <DataTemplate x:Key="Standard250x250ItemTemplate">
+        <Grid HorizontalAlignment="Left" Width="250" Height="250">
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
+                <TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0"/>
+                <TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+    <!-- Grid-appropriate 500 by 130 pixel item template as seen in the GroupDetailPage -->
+    <DataTemplate x:Key="Standard500x130ItemTemplate">
+        <Grid Height="110" Width="480" Margin="10">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="Auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
+                <TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Description}" Style="{StaticResource BodyTextStyle}" MaxHeight="60"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+    <!-- List-appropriate 130 pixel high item template as seen in the SplitPage -->
+    <DataTemplate x:Key="Standard130ItemTemplate">
+        <Grid Height="110" Margin="6">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="Auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
+                <TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Description}" Style="{StaticResource BodyTextStyle}" MaxHeight="60"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+    <!--
+        List-appropriate 80 pixel high item template as seen in the SplitPage when Filled, and
+        the following pages when snapped: GroupedItemsPage, GroupDetailPage, and ItemsPage
+    -->
+    <DataTemplate x:Key="Standard80ItemTemplate">
+        <Grid Margin="6">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="Auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="60" Height="60">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel Grid.Column="1" Margin="10,0,0,0">
+                <TextBlock Text="{Binding Title}" Style="{StaticResource ItemTextStyle}" MaxHeight="40"/>
+                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+    <!-- Grid-appropriate 300 by 70 pixel item template as seen in the SearchResultsPage -->
+    <DataTemplate x:Key="StandardSmallIcon300x70ItemTemplate">
+        <Grid Width="300">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="Auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="10,10,0,20" Width="40" Height="40">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel Grid.Column="1" Margin="10,0,10,10">
+                <TextBlock Text="{Binding Title}" Style="{StaticResource BodyTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" Height="40"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+    <!-- List-appropriate 70 pixel high item template as seen in the SearchResultsPage when Snapped -->
+    <DataTemplate x:Key="StandardSmallIcon70ItemTemplate">
+        <Grid Margin="6">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="Auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,0,0,10" Width="40" Height="40">
+                <Image Source="{Binding Image}" Stretch="UniformToFill"/>
+            </Border>
+            <StackPanel Grid.Column="1" Margin="10,-10,0,0">
+                <TextBlock Text="{Binding Title}" Style="{StaticResource BodyTextStyle}" TextWrapping="NoWrap"/>
+                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" Height="40"/>
+            </StackPanel>
+        </Grid>
+    </DataTemplate>
+
+  <!--
+      190x130 pixel item template for displaying file previews as seen in the FileOpenPickerPage
+      Includes an elaborate tooltip to display title and description text
+  -->
+  <DataTemplate x:Key="StandardFileWithTooltip190x130ItemTemplate">
+        <Grid>
+            <Grid Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
+                <Image
+                    Source="{Binding Image}"
+                    Width="190"
+                    Height="130"
+                    HorizontalAlignment="Center"
+                    VerticalAlignment="Center"
+                    Stretch="Uniform"/>
+            </Grid>
+            <ToolTipService.Placement>Mouse</ToolTipService.Placement>
+            <ToolTipService.ToolTip>
+                <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="Auto"/>
+                        <ColumnDefinition Width="*"/>
+                    </Grid.ColumnDefinitions>
+
+                    <Grid Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="20">
+                        <Image
+                            Source="{Binding Image}"
+                            Width="160"
+                            Height="160"
+                            HorizontalAlignment="Center"
+                            VerticalAlignment="Center"
+                            Stretch="Uniform"/>
+                    </Grid>
+                    <StackPanel Width="200" Grid.Column="1" Margin="0,20,20,20">
+                        <TextBlock Text="{Binding Title}" TextWrapping="NoWrap" Style="{StaticResource BodyTextStyle}"/>
+                        <TextBlock Text="{Binding Description}" MaxHeight="140" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" Style="{StaticResource BodyTextStyle}"/>
+                    </StackPanel>
+                </Grid>                    
+            </ToolTipService.ToolTip>
+        </Grid>
+    </DataTemplate>
+
+    <!-- Default to 10-pixel spacing between grid items (after accounting for 4-pixel insets for focus) -->
+
+    <Style TargetType="GridViewItem">
+        <Setter Property="Margin" Value="0,0,2,2" />
+    </Style>
+
+    <!-- ScrollViewer styles -->
+
+    <Style x:Key="HorizontalScrollViewerStyle" TargetType="ScrollViewer">
+        <Setter Property="HorizontalScrollBarVisibility" Value="Auto"/>
+        <Setter Property="VerticalScrollBarVisibility" Value="Disabled"/>
+        <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Enabled" />
+        <Setter Property="ScrollViewer.VerticalScrollMode" Value="Disabled" />
+        <Setter Property="ScrollViewer.ZoomMode" Value="Disabled" />
+    </Style>
+
+    <Style x:Key="VerticalScrollViewerStyle" TargetType="ScrollViewer">
+        <Setter Property="HorizontalScrollBarVisibility" Value="Disabled"/>
+        <Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
+        <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled" />
+        <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled" />
+        <Setter Property="ScrollViewer.ZoomMode" Value="Disabled" />
+    </Style>
+
+    <!-- Page layout roots typically use entrance animations and a theme-appropriate background color -->
+
+    <Style x:Key="LayoutRootStyle" TargetType="Panel">
+        <Setter Property="Background" Value="{StaticResource ApplicationPageBackgroundThemeBrush}"/>
+        <Setter Property="ChildrenTransitions">
+            <Setter.Value>
+                <TransitionCollection>
+                    <EntranceThemeTransition/>
+                </TransitionCollection>
+            </Setter.Value>
+        </Setter>
+    </Style>
+</ResourceDictionary>
diff --git a/samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp b/samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp
new file mode 100644
index 000000000..c1ecf11cf
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp
@@ -0,0 +1,481 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// SuspensionManager.cpp
+// Implementation of the SuspensionManager class
+//
+
+#include "pch.h"
+#include "SuspensionManager.h"
+
+#include <collection.h>
+#include <algorithm>
+
+using namespace SDKSample::Common;
+
+using namespace Concurrency;
+using namespace Platform;
+using namespace Platform::Collections;
+using namespace Windows::Foundation;
+using namespace Windows::Foundation::Collections;
+using namespace Windows::Storage;
+using namespace Windows::Storage::FileProperties;
+using namespace Windows::Storage::Streams;
+using namespace Windows::UI::Xaml;
+using namespace Windows::UI::Xaml::Controls;
+using namespace Windows::UI::Xaml::Interop;
+
+namespace
+{
+    Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>();
+    String^ sessionStateFilename = "_sessionState.dat";
+
+    // Forward declarations for object object read / write support
+    void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object);
+    Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader);
+}
+
+/// <summary>
+/// Provides access to global session state for the current session.  This state is serialized by
+/// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
+/// one of the following: boxed values including integers, floating-point singles and doubles,
+/// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
+/// subject to the same constraints.  Session state should be as compact as possible.
+/// </summary>
+IMap<String^, Object^>^ SuspensionManager::SessionState::get(void)
+{
+    return _sessionState;
+}
+
+/// <summary>
+/// Wrap a WeakReference as a reference object for use in a collection.
+/// </summary>
+private ref class WeakFrame sealed
+{
+private:
+    WeakReference _frameReference;
+
+internal:
+    WeakFrame(Frame^ frame) { _frameReference = frame; }
+    property Frame^ ResolvedFrame
+    {
+        Frame^ get(void) { return _frameReference.Resolve<Frame>(); }
+    };
+};
+
+namespace
+{
+    std::vector<WeakFrame^> _registeredFrames;
+    DependencyProperty^ FrameSessionStateKeyProperty =
+        DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty",
+        TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr);
+    DependencyProperty^ FrameSessionStateProperty =
+        DependencyProperty::RegisterAttached("_FrameSessionStateProperty",
+        TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr);
+}
+
+/// <summary>
+/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
+/// and restored from <see cref="SessionState"/>.  Frames should be registered once
+/// immediately after creation if they will participate in session state management.  Upon
+/// registration if state has already been restored for the specified key
+/// the navigation history will immediately be restored.  Subsequent invocations of
+/// <see cref="RestoreAsync(String)"/> will also restore navigation history.
+/// </summary>
+/// <param name="frame">An instance whose navigation history should be managed by
+/// <see cref="SuspensionManager"/></param>
+/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
+/// store navigation-related information.</param>
+void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey)
+{
+    if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr)
+    {
+        throw ref new FailureException("Frames can only be registered to one session state key");
+    }
+
+    if (frame->GetValue(FrameSessionStateProperty) != nullptr)
+    {
+        throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all");
+    }
+
+    // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
+    // navigation state should be managed
+    frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey);
+    _registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame));
+
+    // Check to see if navigation state can be restored
+    RestoreFrameNavigationState(frame);
+}
+
+/// <summary>
+/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
+/// from <see cref="SessionState"/>.  Any navigation state previously captured will be
+/// removed.
+/// </summary>
+/// <param name="frame">An instance whose navigation history should no longer be
+/// managed.</param>
+void SuspensionManager::UnregisterFrame(Frame^ frame)
+{
+    // Remove session state and remove the frame from the list of frames whose navigation
+    // state will be saved (along with any weak references that are no longer reachable)
+    auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
+    if (SessionState->HasKey(key)) SessionState->Remove(key);
+    _registeredFrames.erase(
+        std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e)
+        {
+            auto testFrame = e->ResolvedFrame;
+            return testFrame == nullptr || testFrame == frame;
+        }),
+        _registeredFrames.end()
+    );
+}
+
+/// <summary>
+/// Provides storage for session state associated with the specified <see cref="Frame"/>.
+/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
+/// their session state saved and restored automatically as a part of the global
+/// <see cref="SessionState"/>.  Frames that are not registered have transient state
+/// that can still be useful when restoring pages that have been discarded from the
+/// navigation cache.
+/// </summary>
+/// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
+/// page-specific state instead of working with frame session state directly.</remarks>
+/// <param name="frame">The instance for which session state is desired.</param>
+/// <returns>A collection of state subject to the same serialization mechanism as
+/// <see cref="SessionState"/>.</returns>
+IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame)
+{
+    auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty));
+
+    if (frameState == nullptr)
+    {
+        auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty));
+        if (frameSessionKey != nullptr)
+        {
+            // Registered frames reflect the corresponding session state
+            if (!_sessionState->HasKey(frameSessionKey))
+            {
+                _sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>());
+            }
+            frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey));
+        }
+        else
+        {
+            // Frames that aren't registered have transient state
+            frameState = ref new Map<String^, Object^>();
+        }
+        frame->SetValue(FrameSessionStateProperty, frameState);
+    }
+    return frameState;
+}
+
+void SuspensionManager::RestoreFrameNavigationState(Frame^ frame)
+{
+    auto frameState = SessionStateForFrame(frame);
+    if (frameState->HasKey("Navigation"))
+    {
+        frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation")));
+    }
+}
+
+void SuspensionManager::SaveFrameNavigationState(Frame^ frame)
+{
+    auto frameState = SessionStateForFrame(frame);
+    frameState->Insert("Navigation", frame->GetNavigationState());
+}
+
+/// <summary>
+/// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
+/// registered with <see cref="RegisterFrame"/> will also preserve their current
+/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
+/// to save its state.
+/// </summary>
+/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
+task<void> SuspensionManager::SaveAsync(void)
+{
+    // Save the navigation state for all registered frames
+    for (auto&& weakFrame : _registeredFrames)
+    {
+        auto frame = weakFrame->ResolvedFrame;
+        if (frame != nullptr) SaveFrameNavigationState(frame);
+    }
+
+    // Serialize the session state synchronously to avoid asynchronous access to shared
+    // state
+    auto sessionData = ref new InMemoryRandomAccessStream();
+    auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0));
+    WriteObject(sessionDataWriter, _sessionState);
+
+    // Once session state has been captured synchronously, begin the asynchronous process
+    // of writing the result to disk
+    return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int)
+    {
+        return sessionDataWriter->FlushAsync();
+    }).then([=](bool flushSucceeded)
+    {
+        (void)flushSucceeded; // Unused parameter
+        return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename,
+            CreationCollisionOption::ReplaceExisting);
+    }).then([=](StorageFile^ createdFile)
+    {
+        return createdFile->OpenAsync(FileAccessMode::ReadWrite);
+    }).then([=](IRandomAccessStream^ newStream)
+    {
+        return RandomAccessStream::CopyAndCloseAsync(
+            sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0));
+    }).then([=](UINT64 copiedBytes)
+    {
+        (void)copiedBytes; // Unused parameter
+        return;
+    });
+}
+
+/// <summary>
+/// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
+/// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
+/// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
+/// state.
+/// </summary>
+/// <param name="version">A version identifer compared to the session state to prevent
+/// incompatible versions of session state from reaching app code.  Saved state with a
+/// different version will be ignored, resulting in an empty <see cref="SessionState"/>
+/// dictionary.</param>
+/// <returns>An asynchronous task that reflects when session state has been read.  The
+/// content of <see cref="SessionState"/> should not be relied upon until this task
+/// completes.</returns>
+task<void> SuspensionManager::RestoreAsync(void)
+{
+    _sessionState->Clear();
+
+    task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename));
+    return getFileTask.then([=](StorageFile^ stateFile)
+    {
+        task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync());
+        return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties)
+        {
+            auto size = unsigned int(stateFileProperties->Size);
+            if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB");
+            task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync());
+            return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream)
+            {
+                auto stateReader = ref new DataReader(stateFileStream);
+                return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead)
+                {
+                    (void)bytesRead; // Unused parameter
+                    // Deserialize the Session State
+                    Object^ content = ReadObject(stateReader);
+                    _sessionState = (Map<String^, Object^>^)content;
+
+                    // Restore any registered frames to their saved state
+                    for (auto&& weakFrame : _registeredFrames)
+                    {
+                        auto frame = weakFrame->ResolvedFrame;
+                        if (frame != nullptr)
+                        {
+                            frame->ClearValue(FrameSessionStateProperty);
+                            RestoreFrameNavigationState(frame);
+                        }
+                    }
+                }, task_continuation_context::use_current());
+            });
+        });
+    });
+}
+
+#pragma region Object serialization for a known set of types
+
+namespace
+{
+    // Codes used for identifying serialized types
+    enum StreamTypes {
+        NullPtrType = 0,
+
+        // Supported IPropertyValue types
+        UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type,
+        SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType,
+
+        // Additional supported types
+        StringToObjectMapType,
+
+        // Marker values used to ensure stream integrity
+        MapEndMarker
+    };
+
+    void WriteString(DataWriter^ writer, String^ string)
+    {
+        writer->WriteByte(StringType);
+        writer->WriteUInt32(writer->MeasureString(string));
+        writer->WriteString(string);
+    }
+
+    void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue)
+    {
+        switch (propertyValue->Type)
+        {
+        case PropertyType::UInt8:
+            writer->WriteByte(UInt8Type);
+            writer->WriteByte(propertyValue->GetUInt8());
+            return;
+        case PropertyType::UInt16:
+            writer->WriteByte(UInt16Type);
+            writer->WriteUInt16(propertyValue->GetUInt16());
+            return;
+        case PropertyType::UInt32:
+            writer->WriteByte(UInt32Type);
+            writer->WriteUInt32(propertyValue->GetUInt32());
+            return;
+        case PropertyType::UInt64:
+            writer->WriteByte(UInt64Type);
+            writer->WriteUInt64(propertyValue->GetUInt64());
+            return;
+        case PropertyType::Int16:
+            writer->WriteByte(Int16Type);
+            writer->WriteUInt16(propertyValue->GetInt16());
+            return;
+        case PropertyType::Int32:
+            writer->WriteByte(Int32Type);
+            writer->WriteUInt32(propertyValue->GetInt32());
+            return;
+        case PropertyType::Int64:
+            writer->WriteByte(Int64Type);
+            writer->WriteUInt64(propertyValue->GetInt64());
+            return;
+        case PropertyType::Single:
+            writer->WriteByte(SingleType);
+            writer->WriteSingle(propertyValue->GetSingle());
+            return;
+        case PropertyType::Double:
+            writer->WriteByte(DoubleType);
+            writer->WriteDouble(propertyValue->GetDouble());
+            return;
+        case PropertyType::Boolean:
+            writer->WriteByte(BooleanType);
+            writer->WriteBoolean(propertyValue->GetBoolean());
+            return;
+        case PropertyType::Char16:
+            writer->WriteByte(Char16Type);
+            writer->WriteUInt16(propertyValue->GetChar16());
+            return;
+        case PropertyType::Guid:
+            writer->WriteByte(GuidType);
+            writer->WriteGuid(propertyValue->GetGuid());
+            return;
+        case PropertyType::String:
+            WriteString(writer, propertyValue->GetString());
+            return;
+        default:
+            throw ref new InvalidArgumentException("Unsupported property type");
+        }
+    }
+
+    void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map)
+    {
+        writer->WriteByte(StringToObjectMapType);
+        writer->WriteUInt32(map->Size);
+        for (auto&& pair : map)
+        {
+            WriteObject(writer, pair->Key);
+            WriteObject(writer, pair->Value);
+        }
+        writer->WriteByte(MapEndMarker);
+    }
+
+    void WriteObject(DataWriter^ writer, Object^ object)
+    {
+        if (object == nullptr)
+        {
+            writer->WriteByte(NullPtrType);
+            return;
+        }
+
+        auto propertyObject = dynamic_cast<IPropertyValue^>(object);
+        if (propertyObject != nullptr)
+        {
+            WriteProperty(writer, propertyObject);
+            return;
+        }
+
+        auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object);
+        if (mapObject != nullptr)
+        {
+            WriteStringToObjectMap(writer, mapObject);
+            return;
+        }
+
+        throw ref new InvalidArgumentException("Unsupported data type");
+    }
+
+    String^ ReadString(DataReader^ reader)
+    {
+        int length = reader->ReadUInt32();
+        String^ string = reader->ReadString(length);
+        return string;
+    }
+
+    IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader)
+    {
+        auto map = ref new Map<String^, Object^>();
+        auto size = reader->ReadUInt32();
+        for (unsigned int index = 0; index < size; index++)
+        {
+            auto key = safe_cast<String^>(ReadObject(reader));
+            auto value = ReadObject(reader);
+            map->Insert(key, value);
+        }
+        if (reader->ReadByte() != MapEndMarker)
+        {
+            throw ref new InvalidArgumentException("Invalid stream");
+        }
+        return map;
+    }
+
+    Object^ ReadObject(DataReader^ reader)
+    {
+        auto type = reader->ReadByte();
+        switch (type)
+        {
+        case NullPtrType:
+            return nullptr;
+        case UInt8Type:
+            return reader->ReadByte();
+        case UInt16Type:
+            return reader->ReadUInt16();
+        case UInt32Type:
+            return reader->ReadUInt32();
+        case UInt64Type:
+            return reader->ReadUInt64();
+        case Int16Type:
+            return reader->ReadInt16();
+        case Int32Type:
+            return reader->ReadInt32();
+        case Int64Type:
+            return reader->ReadInt64();
+        case SingleType:
+            return reader->ReadSingle();
+        case DoubleType:
+            return reader->ReadDouble();
+        case BooleanType:
+            return reader->ReadBoolean();
+        case Char16Type:
+            return (char16_t)reader->ReadUInt16();
+        case GuidType:
+            return reader->ReadGuid();
+        case StringType:
+            return ReadString(reader);
+        case StringToObjectMapType:
+            return ReadStringToObjectMap(reader);
+        default:
+            throw ref new InvalidArgumentException("Unsupported property type");
+        }
+    }
+}
+
+#pragma endregion
diff --git a/samples/winrt/ImageManipulations/C++/common/suspensionmanager.h b/samples/winrt/ImageManipulations/C++/common/suspensionmanager.h
new file mode 100644
index 000000000..65e1180a0
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/common/suspensionmanager.h
@@ -0,0 +1,50 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// SuspensionManager.h
+// Declaration of the SuspensionManager class
+//
+
+#pragma once
+
+#include <ppltasks.h>
+
+namespace SDKSample
+{
+    namespace Common
+    {
+        /// <summary>
+        /// SuspensionManager captures global session state to simplify process lifetime management
+        /// for an application.  Note that session state will be automatically cleared under a variety
+        /// of conditions and should only be used to store information that would be convenient to
+        /// carry across sessions, but that should be disacarded when an application crashes or is
+        /// upgraded.
+        /// </summary>
+        ref class SuspensionManager sealed
+        {
+        internal:
+            static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey);
+            static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame);
+            static Concurrency::task<void> SaveAsync(void);
+            static Concurrency::task<void> RestoreAsync(void);
+            static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState
+            {
+                Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void);
+            };
+            static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame(
+                Windows::UI::Xaml::Controls::Frame^ frame);
+
+        private:
+            static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
+            static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame);
+        };
+    }
+}
diff --git a/samples/winrt/ImageManipulations/C++/pch.cpp b/samples/winrt/ImageManipulations/C++/pch.cpp
new file mode 100644
index 000000000..97389d94c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/pch.cpp
@@ -0,0 +1,16 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// pch.cpp
+// Include the standard header and generate the precompiled header.
+//
+
+#include "pch.h"
diff --git a/samples/winrt/ImageManipulations/C++/pch.h b/samples/winrt/ImageManipulations/C++/pch.h
new file mode 100644
index 000000000..13f9bc34c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/pch.h
@@ -0,0 +1,23 @@
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+
+//
+// pch.h
+// Header for standard system include files.
+//
+
+#pragma once
+
+#include <collection.h>
+#include <ppltasks.h>
+#include <agile.h>
+#include "Common\LayoutAwarePage.h"
+#include "Common\SuspensionManager.h"
+#include "App.xaml.h"
diff --git a/samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml b/samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml
new file mode 100644
index 000000000..ec2c1a713
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml
@@ -0,0 +1,51 @@
+<!--
+//*********************************************************
+//
+// Copyright (c) Microsoft. All rights reserved.
+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
+//
+//*********************************************************
+-->
+<ResourceDictionary
+    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
+    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+
+    <Style x:Key="TitleTextStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI Light" />
+        <Setter Property="FontSize" Value="16" />
+    </Style>
+    <Style x:Key="HeaderTextStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI Semilight" />
+        <Setter Property="FontSize" Value="26.667" />
+        <Setter Property="Margin" Value="0,0,0,25" />
+    </Style>
+    <Style x:Key="H2Style" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI" />
+        <Setter Property="FontSize" Value="14.667" />
+        <Setter Property="Margin" Value="0,0,0,0" />
+    </Style>
+    <Style x:Key="SubheaderTextStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI Semilight" />
+        <Setter Property="FontSize" Value="14.667" />
+        <Setter Property="Margin" Value="0,0,0,5" />
+    </Style>
+    <Style x:Key="BasicTextStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI Light" />
+        <Setter Property="FontSize" Value="16" />
+    </Style>
+    <Style x:Key="SeparatorStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI" />
+        <Setter Property="FontSize" Value="9" />
+    </Style>
+    <Style x:Key="FooterStyle" TargetType="TextBlock">
+        <Setter Property="FontFamily" Value="Segoe UI" />
+        <Setter Property="FontSize" Value="12" />
+        <Setter Property="Margin" Value="0,8,0,0" />
+    </Style>
+    <Style x:Key="HyperlinkStyle" TargetType="HyperlinkButton">
+        <Setter Property="Padding" Value="5"/>
+    </Style>
+</ResourceDictionary>
diff --git a/samples/winrt/ImageManipulations/description.html b/samples/winrt/ImageManipulations/description.html
new file mode 100644
index 000000000..ad1df7d56
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description.html
@@ -0,0 +1,238 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+    <head><link rel="stylesheet" type="text/css" href="description/Combined.css,0:SearchBox,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;amp;hashKey=E778FABBB649835AFE4E73BCAC4F643A" xmlns="http://www.w3.org/1999/xhtml" />
+<link rel="stylesheet" type="text/css" href="description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;amp;hashKey=B88AD897C8197B762EA1BF0238A60A9F" xmlns="http://www.w3.org/1999/xhtml" />
+
+        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+        <title>Media capture using capture device sample</title>
+        <link href="description/Galleries.css" type="text/css" rel="Stylesheet" /><link href="description/Layout.css" type="text/css" rel="Stylesheet" /><link href="description/Brand.css" type="text/css" rel="Stylesheet" /><link href="description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css" type="text/css" rel="Stylesheet" />
+        <link href="description/iframedescription.css" rel="Stylesheet" type="text/css" />
+        <script src="description/offline.js" type="text/javascript"></script>
+        <style type="text/css">
+            #projectInfo {
+                overflow: auto;
+            }
+            #longDesc {
+                clear:both;
+                margin: 25px 0 10px 0;
+            }
+
+            #SampleIndexList{
+                margin-left: 15px;
+            }
+        </style>
+    </head>
+<body>
+    <div id="offlineDescription">
+        <h1>Media capture using capture device sample</h1>
+        <br/>
+        <div id="projectInfo">
+            <div class="section">
+                    <div class="itemBarLong tagsContainer">
+                        <label for="Technologies">Technologies</label>
+                        <div id="Technologies">
+                            Windows Runtime
+                        </div>
+                    </div>
+                    <div class="itemBarLong tagsContainer">
+                        <label for="Topics">Topics</label>
+                        <div id="Topics">
+                            Devices and sensors
+                        </div>
+                    </div>
+                <div class="itemBarLong">
+                    <label for="Platforms">Platforms</label>
+                    <div id="Platforms">
+                        Windows RT
+                    </div>
+                </div>
+                <div class="itemBarLong">
+                    <label for="Requirements">Requirements</label>
+                    <div id="Requirements">
+                        
+                    </div>
+                </div>
+                <div class="itemBar">
+                    <label for="LastUpdated">Primary Language</label>
+                    <div id="LastUpdated">en-US</div>
+                </div>
+                <div class="itemBar">
+                    <label for="LastUpdated">Last Updated</label>
+                    <div id="LastUpdated">4/9/2013</div>
+                </div>
+                <div class="itemBarLong">
+                    <label for="License">License</label>
+                    <div id="License">
+                        <a href="license.rtf">MS-LPL</a></div>
+                </div>
+                <div class="itemBar">
+                    <div class="viewonlinecont">
+                        <a data-link="online" href="http://code.msdn.microsoft.com/windowsapps/Media-Capture-Sample-adf87622">View this sample online</a>
+                    </div>
+                </div>
+            </div>
+        </div>
+        
+                   
+<script type="text/javascript">
+    function initializePage() {
+        var otherTabClass = 'otherTab';
+        var hiddenPreClass = 'hidden';
+
+        var htmlDecode = function(encodedData) {
+            var decodedData = "";
+            if (encodedData) {
+                var div = document.createElement('div');
+                div.innerHTML = encodedData;
+                decodedData = div.firstChild.nodeValue.replace( /\\r\\n/ig , '\r\n');
+            }
+            return decodedData;
+        };
+                
+        Galleries.iterateElem(Galleries.findElem(null, 'div', 'scriptcode'), function (index, scriptBlock) {
+            var titleElem = Galleries.findElem(scriptBlock, 'div', 'title')[0];
+            var labelElems = Galleries.findElem(titleElem, 'span');
+            if (labelElems.length == 0) {
+                labelElems = titleElem;
+            }
+            var languageSpans = Galleries.findElem(scriptBlock, 'span', 'hidden');
+            var pres = Galleries.findElem(scriptBlock, 'pre');
+            if (languageSpans.length > 0 && pres.length > 1) {
+                Galleries.iterateElem(labelElems, function(index, elem) {
+                    var codePre = pres[index];
+                    var labelSpan = elem;
+                    var languageSpan = languageSpans[index];
+                            
+                    elem.code = codePre.innerHTML.replace( /(\r(\n)?)|((\r)?\n)/ig , '\\r\\n');
+                            
+                    codePre.className = codePre.className.replace(hiddenPreClass, '');
+                            
+                    languageSpan.parentNode.removeChild(languageSpan);
+                });
+
+                pres = Galleries.findElem(scriptBlock, 'pre');
+                Galleries.iterateElem(labelElems, function(index, elem) {
+                    var codePre = pres[index];
+                    var labelSpan = elem;
+                    if (index == 0) {
+                        scriptBlock.activeTab = 0;
+                    }
+                    else {
+                        labelSpan.className += otherTabClass;
+                        codePre.className += hiddenPreClass;
+                    }
+                    Galleries.attachEventHandler(labelSpan, 'click', function(e) {
+                        var activeTab = scriptBlock.activeTab;
+                        labelElems[activeTab].className += otherTabClass;
+                        pres[activeTab].className += hiddenPreClass;
+
+                        codePre.className = codePre.className.replace(hiddenPreClass, '');
+                        labelSpan.className = labelSpan.className.replace(otherTabClass, '');
+                        scriptBlock.activeTab = index;
+                    });
+                });
+
+                var preview = Galleries.findElem(scriptBlock, 'div', 'preview');
+                if (preview.length == 0) {
+                    preview.push(pres[pres.length - 1]);
+                }
+                Galleries.iterateElem(preview, function(index, elem) {
+                    elem.parentNode.removeChild(elem);
+                });
+
+                if (window.clipboardData && clipboardData.setData) {
+                    var copyLink = document.createElement('a');
+                    copyLink.href = 'javascript:void(0);';
+                    copyLink.className = 'copyCode';
+                    copyLink.innerHTML = 'Copy Code';
+                    Galleries.attachEventHandler(copyLink, 'click', function (e) {
+                        clipboardData.setData("Text", htmlDecode(labelElems[scriptBlock.activeTab].code));
+                        return false;
+                    });
+                    scriptBlock.insertBefore(copyLink, scriptBlock.childNodes[0]);
+                }
+            }
+        });
+    }
+
+    Galleries.onWindowLoad(function(){
+        initializePage();
+    });
+
+</script>
+<div id="longDesc">
+    
+<div id="mainSection">
+<p>This sample demonstrates how to use the <a href="http://msdn.microsoft.com/library/windows/apps/BR241124">
+<b>MediaCapture</b> </a>API to capture video, audio, and pictures from a capture device, such as a webcam.
+</p>
+<p>Specifically, this sample covers: </p>
+<ul>
+<li>Previewing video from a capture device, such as a webcam, connected to the computer.
+</li><li>Capturing video from a capture device, such as a webcam, connected to the computer.
+</li><li>Taking a picture from a capture device, such as a webcam, connected to the computer.
+</li><li>Enumerating cameras connected to the computer. </li><li>Adding a video effect to a video. </li><li>Recording audio from a capture device connected to the computer. </li></ul>
+<p></p>
+<p>For more information on capturing video in your app, see <a href="http://msdn.microsoft.com/library/windows/apps/Hh465152">
+Quickstart: capturing a photo or video using the camera dialog</a> and <a href="http://msdn.microsoft.com/library/windows/apps/Hh452791">
+Quickstart: capturing video using the MediaCapture API</a>.</p>
+<p class="note"><b>Important</b>&nbsp;&nbsp; </p>
+<p class="note">This sample uses the Media Extension feature of Windows&nbsp;8 to add functionality to the Microsoft Media Foundation pipeline. A Media Extension consists of a hybrid object that implements both Component Object Model (COM) and Windows Runtime
+ interfaces. The COM interfaces interact with the Media Foundation pipeline. The Windows Runtime interfaces activate the component and interact with the Windows Store app.
+</p>
+<p class="note">In most situations, it is recommended that you use Visual C&#43;&#43; with Component Extensions (C&#43;&#43;/CX ) to interact with the Windows Runtime. But in the case of hybrid components that implement both COM and Windows Runtime interfaces, such as Media
+ Extensions, this is not possible. C&#43;&#43;/CX can only create Windows Runtime objects. So, for hybrid objects it is recommended that you use
+<a href="http://go.microsoft.com/fwlink/p/?linkid=243149">Windows Runtime C&#43;&#43; Template Library</a> to interact with the Windows Runtime. Be aware that Windows Runtime C&#43;&#43; Template Library has limited support for implementing COM interfaces.</p>
+<p></p>
+<p>To obtain an evaluation copy of Windows&nbsp;8, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241655">
+Windows&nbsp;8</a>.</p>
+<p>To obtain an evaluation copy of Microsoft Visual Studio&nbsp;2012, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241656">
+Visual Studio&nbsp;2012</a>.</p>
+<h3><a id="related_topics"></a>Related topics</h3>
+<dl><dt><a href="http://go.microsoft.com/fwlink/p/?LinkID=227694">Windows 8 app samples</a>
+</dt><dt><b>Roadmaps</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465134">Adding multimedia</a>
+</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465156">Capturing or rendering audio, video, and images</a>
+</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh767284">Designing UX for apps</a>
+</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR229583">Roadmap for apps using C# and Visual Basic</a>
+</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700360">Roadmap for apps using C&#43;&#43;</a>
+</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465037">Roadmap for apps using JavaScript</a>
+</dt><dt><b>Tasks</b> </dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465152">Quickstart: capturing a photo or video using the camera dialog</a>
+</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh452791">Quickstart: capturing video using the MediaCapture API</a>
+</dt><dt><b>Reference</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR211961"><b>AddEffectAsync</b>
+</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226592"><b>ClearEffectsAsync</b>
+</a></dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR241124"><b>MediaCapture</b>
+</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226581"><b>MediaCaptureSettings</b>
+</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh701026"><b>MediaEncodingProfile</b>
+</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700863"><b>StartRecordToStorageFileAsync</b>
+</a></dt><dt><b>Windows.Media.Capture</b> </dt></dl>
+<h3>Operating system requirements</h3>
+<table>
+<tbody>
+<tr>
+<th>Client</th>
+<td><dt>Windows&nbsp;8 </dt></td>
+</tr>
+<tr>
+<th>Server</th>
+<td><dt>Windows Server&nbsp;2012 </dt></td>
+</tr>
+</tbody>
+</table>
+<h3>Build the sample</h3>
+<p></p>
+<ol>
+<li>Start Visual Studio Express&nbsp;2012 for Windows&nbsp;8 and select <b>File</b> &gt; <b>
+Open</b> &gt; <b>Project/Solution</b>. </li><li>Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio Express&nbsp;2012 for Windows&nbsp;8 Solution (.sln) file.
+</li><li>Press F7 or use <b>Build</b> &gt; <b>Build Solution</b> to build the sample. </li></ol>
+<p></p>
+<h3>Run the sample</h3>
+<p>To debug the app and then run it, press F5 or use <b>Debug</b> &gt; <b>Start Debugging</b>. To run the app without debugging, press Ctrl&#43;F5 or use
+<b>Debug</b> &gt; <b>Start Without Debugging</b>.</p>
+</div>
+
+</div>
+
+
+    </div>
+</body>
+</html>
diff --git a/samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css b/samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css
new file mode 100644
index 000000000..e69de29bb
diff --git a/samples/winrt/ImageManipulations/description/Brand.css b/samples/winrt/ImageManipulations/description/Brand.css
new file mode 100644
index 000000000..98415561e
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/Brand.css
@@ -0,0 +1,3629 @@
+#BodyBackground
+{
+    min-width:0px;
+}
+
+#JelloExpander, .IE7 #JelloExpander, .IE8 #JelloExpander, .IE9 #JelloExpander
+{
+    padding-left:0px;
+    padding-right:0px;
+}
+
+#JelloSizer
+{
+    margin: 0 auto;
+    max-width: 0px;
+    padding: 0;
+    width: 100%;
+}
+
+/* Global Styles */
+body 
+{
+    font-size:0.75em;
+}
+
+h1 
+{
+    font-size: 3em;
+    font-family: 'Segoe UI Light','Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
+    color: #707070;
+    font-weight: normal;
+    padding-top:4px;
+    margin-bottom: 17px;
+    line-height: 1.3;
+    font-weight:100;
+}
+
+h2, h3, h4, h5, h6 
+{
+    font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
+    color:#2a2a2a;
+    font-weight:normal;
+}
+
+a, a:link, a:visited {
+    color: #00749E;
+}
+a:hover {
+    color: #0095c4;
+    text-decoration:none;
+}
+
+/*---------- Masthead -----------*/
+
+.NetworkLogo a {
+    display: none;
+}
+
+/*-------- Start Advertisment --------*/
+
+.advertisment {
+    padding-top:5px;
+}
+
+/*-------- End Advertisment --------*/
+
+
+/*-------- Start LocalTabs Page --------*/
+#GalleriesNavigation {
+    float: right;
+}
+
+.LocalNavigation
+{
+    display:block;
+    overflow: auto;
+    width: auto;
+}
+    .LocalNavigation .HeaderTabs {
+        width: auto;
+    }
+        .LocalNavigation .TabOff a {
+            color:#333;
+        }
+
+        .LocalNavigation .TabOff a:hover {
+            background-color:#E0E7EC;
+            margin-top: 1px;
+            padding: 4px 6px;
+        }
+
+        .LocalNavigation #notificationLink span {
+            color:Red;
+            font-weight:bold;   
+        }
+    
+
+/*-------- End LocalTabs Page --------*/
+
+/*-------- Start SubMenu Page --------*/
+
+.subMenu
+{
+    margin: 0 0 10px 0;
+    color: #FFFFFF;
+    overflow: hidden;
+}
+
+.subMenu a, .subMenu span
+{
+    margin: 5px 5px 0 5px;
+}
+
+.subMenu > h2
+{
+    float: left;
+    margin: 7px 15px 0 0;
+    vertical-align: middle;
+    color: #666;
+    padding-bottom: 5px;
+}
+
+.subMenu .advancedSearchLink
+{
+    float: left;
+    margin: 9px 0 0 15px;
+}
+
+
+
+.subMenu .uploadLink
+{
+    float: right;
+    margin: 5px 5px 0 0;
+    padding: 0 0 0 30px;
+    height: 24px;
+    background: url('../Common/smalluploadicon.png') no-repeat 10px 0;
+    color: #0066E1;
+    cursor: pointer;
+}
+
+.subMenu #searchBoxContainer
+{
+    float: left;
+    width: 400px;
+    padding: 3px 50px;
+}
+
+/*-------- End SubMenu Page --------*/
+
+/*-------- Start SearchBox --------*/
+
+div.searchbox
+{
+    overflow:auto;
+    width:450px;
+    margin:26px 0 14px 0;
+}
+
+.srchbox
+{
+    width: 100%;
+    background: #FFFFFF;
+    padding: 0px 2px;
+    height: 25px;
+    border: 1px solid #ccc;
+    table-layout: auto;
+    margin-bottom:5px;
+}
+
+
+
+.srchbox #searchImageCell input
+{
+    background: transparent url('searchButton.png') no-repeat 0 0;
+    width: 20px;
+    height: 20px;
+    padding-left: 1px;
+    margin-top: 3px;
+}
+
+
+.srchbox #searchImageCell
+{
+    text-align: right;
+    padding: 0px;
+    vertical-align: middle;
+}
+
+.IE7 .srchbox #searchImageCell
+{
+    padding:2px 2px 0 0;
+}
+
+.srchbox #searchImageCell input
+{
+}
+
+
+table.srchbox
+{
+    table-layout: fixed;
+}
+
+.srchbox .stxtcell
+{
+    padding-right: 4px;
+    width:90%;
+}
+
+.srchbox .stxtcell > input
+{
+    margin-right: 4px;
+    height: 26px;
+    line-height:26px;
+    width: 100%;
+    padding: 0px;
+    padding-left: 4px;
+    padding-top: 2px;
+    border: none;
+    font-style: normal !important;
+    outline: none;
+}
+
+.IE7 .srchbox .stxtcell > input
+{
+    height: 20px;
+}
+
+.srchbox .stxtcell > input.stxtinptpassive
+{
+    color: #AAA;
+    font-style: normal !important;
+}
+
+/*-------- End SearchBox --------*/
+
+
+/*-------- Start Search Page --------*/
+
+
+#searchPage #mainContentContainer
+{
+    margin: 0 0 0 243px;
+}
+
+#searchPage .browseFilterBar, #dashboardPage .browseFilterBar
+{    
+    padding: 5px 0 6px 0;
+    
+}
+
+    #searchPage .browseFilterBar a, #dashboardPage .browseFilterBar a
+    {
+        font-weight:normal;
+    }
+
+    #searchPage .browseFilterBar .browseSort, #dashboardPage .browseFilterBar .browseSort
+    {
+        float:right;
+    }
+    
+    #searchPage .browseBreadcrumb
+    {
+        padding-top:3px;
+    }
+
+        #searchPage .browseFilterBar .browseSort select, #dashboardPage .browseFilterBar .browseSort select
+        {
+            height:20px;
+        }        
+        
+        #searchPage .browseFilterBar .browseSort img, #dashboardPage .browseFilterBar .browseSort img
+        {
+            vertical-align:text-top;
+        }
+
+#searchPage h2, #searchPage h3
+{
+    font-size: 1.25em;
+    padding: 2px 0 3px 3px;
+}
+
+#searchPage h2
+{
+    display:inline;
+    clear:none;
+}
+
+ #dashboardsearchbox
+ {
+     width:420px;
+     margin:0;
+     float:left;
+ }
+
+/*-------- End Search Page --------*/
+
+/*-------- Begin Requests Page --------*/
+
+#requestsPage {
+    color:#666;
+}
+
+    #requestsPage h1 {
+        clear:none;
+    }
+    #requestsPage h2, #requestsPage h3
+    {
+        font-size: 1.25em;
+    }
+
+    #requestsPage h2
+    {
+        display:inline;
+        clear:none;
+    }
+
+    #requestsPage h3 
+    {
+        padding: 2px 0 3px 3px;
+    }
+
+    #requestsPage #mainContentContainer
+    {
+        margin: 0 0 0 243px;
+    }
+
+    #requestsPage #mainContentWrapper {
+        float:left;
+        width:100%;
+    }
+    #requestsPage #mainContent {
+        position:relative;
+    }
+
+    #requestsPage #mainContent .subtitle{
+        margin-bottom:5px;
+    }
+
+    #requestsPage #requestsFilterBar {
+        margin-top: 10px;
+        overflow: auto;
+    }
+
+        #requestsPage #requestsFilterBar .requestsCrumb {
+             float: left;
+            margin:10px 0 10px 10px;
+        }
+        #requestsPage #requestsFilterBar .requestsSort {
+            float: right;   
+            margin:10px 0 10px 0;
+        }
+    
+    #requestsPage #Pager {
+        text-align: center; 
+        padding-top: .75em; 
+        padding-bottom: .75em;
+    }
+
+    #requestsPage #requestsRss {
+        float: right;
+        margin: 2px 0 0 3px;
+        cursor: pointer;
+    }  
+    
+    .IE7 #requestsPage #requestsList {
+        padding-top: 10px;
+        margin-top:5px;
+    }
+
+    #requestsPage #requestsList .noResults {
+        padding: 10px 0;
+    }   
+   
+
+/*-------- End Requests Page --------*/
+
+/*--------  Begin Request List Item --------*/
+.requestlistitem td
+{
+    padding: .9em 0 .9em .5em;
+}
+    .requestlistitem .votebox
+    {
+        
+        text-align:center;
+    }
+    
+    .requestlistitem .voteboxcontainer
+    {
+        vertical-align:top;
+        width: 75px;
+    }
+
+    .requestlistitem #votelabel
+    {
+        border-width:1px;
+        border-bottom-style:solid;
+    }
+
+    #myRequestsTab #votenumber,
+    #requestsPage #votenumber
+    {
+        background-color: #777;
+        padding: 6px 10px;
+        color: #fff;
+        margin-bottom: 5px;
+        font-size: 1.6em;
+    }
+    
+    #myRequestsTab .votelink,
+    #requestsPage .votelink 
+    {
+        font-weight:bold;
+        background-color: #eee;
+        padding: 5px 0;
+        width: 75px;
+        float: left;
+    }
+
+    #myRequestsTab .needvote,
+    #requestsPage .needvote
+    {
+        font-weight:bold;
+    }
+
+    #myRequestsTab .alreadyvoted, #myRequestsTab .resolved
+    #requestsPage .alreadyvoted, #requestsPage .resolved
+    {
+        font-weight:bold;
+        color: #666;
+    }
+
+    .requestlistitem .linkform 
+    {
+        width:100%;
+        float:right;
+        margin-top:15px;
+    }
+
+    .requestlistitem .requesttitle 
+    {
+        font-weight:600;
+        margin-bottom:3px;
+    }
+
+    .requestlistitem .requester 
+    {
+        margin-bottom:3px;
+    }
+
+    .requestlistitem .hidden 
+    {
+        display:none;
+    }
+    
+    .requestlistitem .requestSummary div
+    {
+        margin-bottom:0.25em;
+    }
+    
+    .requestlistitem .requestSummary 
+    {
+        line-height: 1.45em;
+        width: 80%;
+    }
+    .requestlistitem .requestInfo
+    {
+        padding:1.2em 0 0 2.5em;
+        vertical-align:top;
+        width:15%;
+        line-height: 1.45em;
+    }
+    
+    .requestlinks > td
+    {
+        padding-bottom: 16px;
+    }
+    
+    .requestlinks div 
+    {
+        float:right;
+    }
+
+    .requestlistitem .textbox 
+    {
+        width:95%;
+    }
+    
+
+
+/*--------  End Request List Item --------*/
+
+
+/*--------  Begin New Request Form --------*/
+#newrequest {
+    margin-top:5px;
+    background:#F8F8F8;
+    border-width:1px;
+    border-style:solid;
+    border-color:#E8E8E8;
+    padding:5px;
+}
+
+#newrequest > div:first-child {
+    font-weight:bold;
+}
+
+#newrequest .itemheading {
+    margin-top:5px;
+}
+
+#newrequest textarea {
+    width:95%;
+}
+
+#newrequest .field-validation-error {
+    display:block;
+    color:Red;
+    font-weight:bold;
+}
+#newrequest #submit {
+    margin-top:5px;
+}
+
+/*--------  End New Request Form --------*/
+
+/*-------- Request Description Page ------*/
+
+.reqDescPage #mainContent {
+    overflow: auto;
+}
+.reqDescPage #header {
+    float: left;
+    width: 100%;
+}
+
+.reqDescPage {
+    color: #000 !important;
+}
+
+.reqDescPage #sideNav {
+    background-color: #fff;
+}
+
+.reqDescPage #header td {
+    vertical-align: bottom;
+}
+
+.reqDescPage #header #votenumber {
+    width: 50px;
+    padding: 6px 12px;
+    text-align: center;
+    float: left;
+}
+
+.reqDescPage #header .requestTitle {
+    margin: 0 0 5px 10px;
+    width: 85%;
+}
+
+.reqDescPage #header .requestTitle h1 {
+    margin-bottom: 0px;
+    font-size: 2em;
+}
+
+.reqDescPage #headerLinks {
+
+}
+
+.reqDescPage .votelink 
+{
+    text-align: center;
+    float: left;
+}
+
+#requestsPage #headerLinks .assignlink
+{
+    font-weight:bold;
+    background-color: #eee;
+    padding: 5px 10px;
+    float: left;
+    margin-left: 10px;
+}
+
+.reqDescPage #projectInfo {
+    clear: both;
+}
+
+.reqDescPage #solutions {
+    clear: both;
+    padding-top: 30px;
+}
+
+.reqDescPage .solutionItems {
+    clear: both;
+}
+
+.reqDescPage .solutionHeader {
+    border-bottom: 1px solid #ccc;
+}
+
+.reqDescPage .solutionAddContainer {
+    padding-top: 15px;
+    float: left;
+}
+
+.reqDescPage #SubmittedProjectLinkUrl {
+    width: 400px;
+}
+
+.reqDescPage .solutionItem {
+    margin-top: 25px;
+    padding: 0 5px 5px 0;
+    float: left;
+}
+.reqDescPage .solutionItemDetails {
+    float: left;
+    width: 535px;
+}
+
+.reqDescPage .solutionItemLinks {
+    margin-top: 10px;
+    clear: both;
+    float: left;
+    width: 100%;
+}
+
+.reqDescPage .solutionItemLinks a {
+    float: left;
+    margin-right: 10px;
+    font-weight:bold;
+    background-color: #eee;
+    padding: 5px 10px;
+}
+
+.reqDescPage .solutionItem .itemTitle {
+    font-size: 1.2em;
+    padding-bottom: 5px;
+}
+
+.reqDescPage .tagsContainer label {
+    display: none;
+}
+
+.reqDescPage .solutionItem  .summaryBox {
+    padding: .25em 0 .25em 0;
+    clear: both;
+    line-height: 1.45;
+}
+
+.reqDescPage .solutionsection {
+    float: left;
+    margin-left: 20px;
+}
+.reqDescPage .completedSolution {
+    font-size: 1.25em;
+    padding-top: 4px;
+}
+
+.reqDescPage .requestDescriptionCont, .reqDescPage .requestDicussions {
+    padding-top: 30px;
+    clear: both;
+    overflow: auto;
+}
+
+.reqDescPage .requestDescription {
+    padding-top: 10px;
+    line-height: 1.45;
+}
+
+.reqDescPage .requestDicussionsAsk {
+    padding: 10px 0;
+}
+
+.reqDescPage .watermark {
+        color:Gray;
+    }
+
+
+/*--------  Begin Extra Actions Section --------*/
+#extraActions
+{
+    float: right;
+    width: 300px;
+    vertical-align: top;
+}
+
+    #extraActions .section
+    {
+        padding: 0 0 10px 0;
+        overflow:auto;
+    }
+ 
+        #extraActions .section a
+        {
+            font-weight:bold;
+        }
+/*--------  End Extra Actions Section --------*/
+
+/*--------  Begin Contribute --------*/
+
+
+#contributeSection a
+{
+    font-size:1.1em;
+}
+
+#contributeSection, #sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
+{
+    background-color:#fff;
+    margin: 0 0 9px 0;
+    padding-left: 0px;
+}
+
+#sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
+{
+    font-size:1.65em;
+    margin-top:42px;
+}
+
+#sideNav #contributeSection, #contributeSection
+{
+    padding:0 0 41px 0;
+}
+
+#projectPage .sidebar #contributeSection
+{
+    margin: 10px 0 10px 0;
+    padding:0 0 5px 0;
+    
+}
+
+#sideNav #contributeSection > div, .sidebar #contributeSection > div, #contributeSection > div
+{
+    padding: 0 0 2px 0;
+    overflow:auto;
+}
+
+#sideNav #contributeSection img, #contributeSection img
+{
+    float: left;
+    width: 25px;
+}
+
+#sideNav #contributeSection .contributeAction, .sidebar #contributeSection .contributeAction, #contributeSection .contributeAction
+{
+    padding:17px 0 0 0;
+}
+
+    #contributeSection .contributeAction img
+    {        
+        background-color:#00749e;
+        margin-right:9px;
+    }
+    
+    #contributeSection .contributeAction img:hover
+    {
+        background-color:#0095C4;
+    }
+    
+    #contributeSection .contributeAction a
+    {
+        display:block;
+        line-height: 1.8;
+    }
+
+#uploadLink, #exclamationLink, #myContributionsLink
+{
+    display:block;
+    line-height: 1.8;
+}
+
+#myContributionsLink span 
+{
+    color: red;    
+}
+
+#feedbackLink
+{
+    background: url("FeedbackIcon.png") no-repeat;
+    width: 40px;
+    height: 40px;
+}
+
+.itemRow .affiliationLink, #editorPicksSection .affiliationLink
+{
+    background: url("../common/MicrosoftLogo.png") no-repeat;
+    width: 82px;
+    height: 18px;
+}
+
+
+#contributeSection a+div
+{
+         
+}
+
+.IE7 #contributeSection a+div
+{
+    float:left;
+}
+/*--------  End Contribute --------*/
+
+
+/*--------  Begin Directory List Footer --------*/
+
+#directoryListFooter {
+    padding:5px;
+    margin-top:10px;
+    margin-bottom:10px;
+    border:1px solid #E6E6E6;
+    background-color:#F8F8F8;
+    width:438px;
+}
+
+#directoryListFooter h4 
+{
+    font-size:1em;
+}
+
+/*--------  End Directory List Footer --------*/
+
+/*--------  Begin Editors Picks --------*/
+#editorPicksSection ul
+{
+    padding-left:0px;
+    line-height:135%;
+}
+
+    #editorPicksSection ul li
+    {
+        clear: left;
+        padding-top: 10px;
+        list-style:none;
+    }
+    #editorPicksSection ul li:first-child {
+        padding-top: 0;
+    }
+        
+        #editorPicksSection a {
+            font-weight: normal !important;
+        }
+        
+        #editorPicksSection ul li .thumbnail
+        {
+            float: left;
+            padding: 3px;
+            max-width: 60px;
+        }
+        
+            #editorPicksSection ul li .thumbnail img {
+                max-width: 60px;
+            }
+/*--------  End Editors Picks --------*/
+
+/*--------  Begin Side Nav Section --------*/
+
+#sideNav
+{
+    width: 215px;
+    margin-left: 0;
+    vertical-align: top;
+    float: left;
+}
+
+    #sideNav #sideNavHeader
+    {
+        margin-bottom: 10px;
+        padding-left: 12px;
+    }
+
+    #sideNav #sideNavHeader a
+    {
+        margin-right:3px;
+    }
+
+    #sideNav .section
+    {
+        padding: 0 10px 18px 10px;
+    }
+        #sideNav .section h3
+        {
+            
+            padding: 2px 0 3px 3px;
+        }
+
+        #sideNav .section ul
+        {
+        }
+
+        #sideNav .section ul li
+        {
+            padding: 4px 0 2px;
+            margin-left: 3px;
+            margin-right: 3px;
+        }        
+
+
+        #sideNav .section form > div
+        {
+            padding: 4px 0 0 0;
+            border-bottom: none;
+            margin: 0 3px 0 3px;
+            color: #3A3E43;
+        }
+            .IE8 #sideNav .section ul li > div.itemText
+            {
+                word-wrap: break-word;
+                width: 225px;
+            }
+            #sideNav .section ul li > div.itemCount
+            {
+                color: #3A3E43;
+            }
+        #sideNav .section a
+        {
+            font-weight: normal;    
+        }
+
+        #sideNav .section a:hover
+        {
+            text-decoration: underline;
+        }
+
+/*--------  End Side Nav Section --------*/
+
+
+
+/*-------- Start Dashboard Page --------*/
+
+#dashboardPage {
+    padding-top:5px;
+    clear:both;
+}
+#dashboardPage .contributions .tabContents {
+    padding: 5px 5px 10px 0;
+    clear:both;
+}
+    #dashboardPage .contributions .noContributions {
+        clear:both;
+    }
+#dashboardPage #mainContentWrapper {
+    float:left;
+    width:100%;
+}
+
+#dashboardPage #detailsSection {
+    float:left;
+    margin-left:-100%;
+    width:240px;
+    padding: 0 0 18px 10px;
+}
+
+.IE7 #dashboardPage #detailsSection {
+    width:auto;
+    min-width: 300px;
+    max-width: 300px;
+}
+.IE7 #dashboardPage #detailsSection .itemBar {
+    width: 270px;
+}
+
+#dashboardPage #detailsSection h3 {
+    word-wrap:break-word;
+}
+
+#dashboardPage #mainContent {
+    margin:0 0 0 250px;
+    position:relative;
+}
+
+#dashboardPage .dashboardEvenRow
+{
+    background-color: #ececec;
+}
+#dashboardPage .dashboardPadding
+{
+    padding-bottom: 4px;
+}
+#dashboardPage .dashboardCell
+{
+    width: 100%;
+    vertical-align: top;
+    padding: 1em 0.5em 0.5em 0.5em;
+    word-wrap: break-word;
+}
+#dashboardPage .projectManagement
+{
+    width: 24em;
+    padding: 0em 1em 0em 1em;
+    vertical-align: top;
+    text-align: right;
+    float: right;
+}
+
+#dashboardPage #subscriptionsLink 
+{
+    position:absolute;
+    right:5px;
+}
+
+#dashboardPage .itemDelete
+{
+    vertical-align:top;
+    padding-top:.8em;
+    width:30px;
+}
+
+#dashboardPage .itemDeleteText
+{
+    border-style:solid;
+    border-width:thin;
+    border-collapse:collapse;
+    padding-bottom:2px;
+    padding-left:4px;
+    padding-right:4px;
+    color:Gray
+}
+
+#dashboardPage #myRequestsTab .requestTabHeaders
+{
+    font-weight:normal;
+    border-bottom: solid 1px #CCC;
+    padding-bottom: 10px;
+    padding-top: 10px;
+    float: left;
+    width: 100%;
+}
+
+#dashboardPage #myRequestsTab .requestTabHeaders div:first-child
+{
+    border: 0;
+}
+
+#dashboardPage #myRequestsTab .requestTabHeaders div
+{
+    padding: 2px 9px 3px 9px;
+    font-size: 0.9em;
+    line-height: 125%;
+    color:#00749E;
+    border-left: solid 1px #555;
+    cursor: pointer;
+    float: left;
+    text-align: center;
+}
+
+#dashboardPage #myRequestsTab .requestTabHeaders div.currentRequest
+{
+    background-color:#fff;
+    cursor: default;
+    border-bottom:none;
+    margin-bottom:-2px;
+    color:#000;    
+}
+
+#dashboardPage #myRequestsTab .requestTabHeaders div.currentRequest a {
+    color: #000;
+}
+
+
+#dashboardPage #myRequestsTab .requestTabHeaders div a
+{
+    text-decoration:none;
+}
+
+#dashboardPage #myRequestsTab .requestTabContents
+{
+    clear: both;
+}
+
+#dashboardPage #myRequestsTab .requestTabContents .noResults {
+    padding-top: 20px;
+}
+
+/*-------- End Dashboard Page --------*/
+
+/*-------- Start Upload Page --------*/
+
+#UploadPage
+{
+    margin-left:10px;
+    max-width:925px;
+}
+
+    #UploadPage .watermark {
+        color:Gray;
+    }
+
+    #UploadPage .projectTypeChoice   {
+    }
+
+        #UploadPage .projectTypeChoice > div {
+            padding: 20px 10px 20px 10px;
+            border: 1px solid darkgrey;
+            cursor: pointer;
+            height: 200px;
+            float: left;
+        }
+
+        #UploadPage .projectTypeChoice > div + div
+        {
+            margin: 0 0 0 5px;
+        }
+
+        #UploadPage .projectTypeChoice div.current
+        {
+            background-color: #E9E9E9;
+            cursor: default;
+        }
+
+            #UploadPage .projectTypeChoice div.choice {
+                font-size: large;
+                font-weight: bold;
+                padding: 0 0 10px 0;
+            }
+
+            #UploadPage .projectTypeChoice div.description {
+                padding: 0 0 0 17px;
+            }
+
+            #UploadPage .projectTypeChoice #genericSampleUploadDescription {
+                padding-top: 5px;
+            }
+
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription .logos {
+                    overflow: auto;    
+                }
+
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription .vslogo {
+                    background: url(../samples/vslogo.png) no-repeat;
+                    width: 125px;
+                    height: 18px;
+                }
+
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription .javalogo {
+                    background: url(../samples/javalogo.png) no-repeat;
+                    width: 33px;
+                    height: 60px;
+                    float: left;
+                }                
+                
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription .phplogo {
+                    background: url(../samples/phplogo.png) no-repeat;
+                    width: 65px;
+                    height: 35px;
+                    float: left;
+                    margin: 15px 0 0 10px;
+                }                
+                
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription .nodejslogo {
+                    background: url(../samples/nodejslogo.png) no-repeat;
+                    width: 90px;
+                    height: 25px;
+                    float: left;
+                    margin: 18px 0 0 10px;
+                }
+
+                #UploadPage .projectTypeChoice #genericSampleUploadDescription > div+div {
+                    margin-top: 10px;
+                }
+
+    #UploadPage .projectTypeContents {
+        clear: left;
+        padding: 10px 0 0 0;
+    }
+
+        #UploadPage .projectTypeContents .instruction > div+div {
+            padding-top: 5px;
+        }
+   #UploadPage #libraryContainer {
+       margin: 5px 0 0 0;
+       display: none;
+   }
+    #UploadPage fieldset
+    {
+        margin: 10px 0 30px 5px;
+    }
+
+        #UploadPage fieldset > *
+        {
+            margin-left:10px;
+        }
+
+        #UploadPage .fieldsetStyleContainer {
+            margin: 10px 0 0 5px;
+        }
+
+        #UploadPage fieldset h2,
+        #UploadPage .fieldsetStyleContainer h2
+        {   
+            font-family: 'Segoe UI Semibold','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;
+            font-size: 17px;
+            font-weight: bold;
+            color: #3A3E43;
+            border-bottom: 2px solid #EFEFEF;
+            width: 100%;
+            padding-bottom: 3px;
+            margin-left:0px;
+            margin-bottom:8px;
+        }
+
+        .IE7 #UploadPage fieldset h2,
+        .IE7 #UploadPage .fieldsetStyleContainer h2
+        {
+            margin-left:-10px;
+        }
+
+        #UploadPage fieldset .field-validation-error
+        {
+            clear:left;
+            display:block;
+            margin-top:4px;
+        }
+
+        #UploadPage fieldset .required
+        {
+            margin-left: 3px;
+        }
+
+        #UploadPage fieldset .instruction,
+        #UploadPage .fieldsetStyleContainer .description,
+        #UploadPage .fieldsetStyleContainer .instruction
+        {
+            color: #3A3E43;
+            margin:0 0 10px 0;
+        }
+
+        #UploadPage fieldset .faqLink
+        {
+            margin: 0 0 10px 0;
+        }
+
+        #UploadPage fieldset label 
+        {
+            display:block;
+        }
+
+        #UploadPage fieldset input[type=text]
+        {
+            width:60%;
+        }
+
+        #UploadPage fieldset input[type=checkbox]
+        {
+            float:left;
+            clear:left;
+            margin-right:5px;
+        }
+
+        #UploadPage fieldset input[type=radio]
+        {
+            float:left;
+            clear:left;
+            margin-right:5px;
+        }
+
+        #UploadPage fieldset#richDescription textarea 
+        {
+            width:70%;
+            height:600px;
+        }
+          
+        #UploadPage fieldset#summary textarea 
+        {
+            width:60%;
+            height:100px;
+            margin-top: 10px;
+            margin-left: -30px;
+        }
+
+        .IE #UploadPage fieldset#summary textarea, .IE9 #UploadPage fieldset#summary textarea
+        {
+            margin-left: -30px;
+            overflow: auto;
+        }
+
+        .FF #UploadPage fieldset#summary textarea
+        {
+            margin-left: -30px;
+        }
+
+        #UploadPage fieldset#summary #SummaryReadOnly 
+        {
+            width:60%;
+            margin-top: 10px;
+            padding-top: 5px;
+            color: #909082;
+        }
+
+        #UploadPage fieldset#summary #SummaryCharCount 
+        {
+            width:60%;
+            text-align: right;
+        }
+                
+        #UploadPage fieldset#options label 
+        {
+            margin-bottom:10px;
+        }
+        
+	    #UploadPage fieldset#license label
+	    {
+            margin-bottom:10px;
+        }        
+        
+        #UploadPage input[type="text"].tagInput, #UploadPage input[type="text"].listInput
+        {
+            width:40%;
+            float:left;
+        }
+
+        #UploadPage .addedTags, #UploadPage .addedProjects
+        {
+            margin-bottom:15px;
+            width: 500px;
+
+        }
+            #UploadPage .addedTags .tag, #UploadPage .addedProjects .projectTitle
+            {
+                position:relative;
+                overflow:hidden;
+            }
+
+                #UploadPage .addedTags .tag  label, #UploadPage .addedProjects .projectTitle  label 
+                {
+                    float:left;
+                    width: 450px;
+                }
+            
+                #UploadPage .addedTags .tag  a, #UploadPage .addedProjects .projectTitle  a 
+                {
+                    position:absolute;
+                    text-align:right;
+                    right:0px;
+                }
+         
+        .fileManager .fileUploadProgressIndicator
+        {
+            width: 500px;
+        }
+
+        .fileManager .uploadProcessingWarning {
+            margin-top: 5px;
+        }
+
+        .fileManager .fileUploadProgressIndicator .throbber
+        {
+            font-weight: bold;
+            background: url('./progressIndicatorWhite.gif') no-repeat 10px 0;
+            padding: 7px 10px 5px 60px;
+            height: 25px;
+            margin-left: -10px;
+        }
+
+        .fileManager #uploadFrame, .fileManager .uploadFrame
+        {
+            width:100%;
+        }
+
+            .fileManager .addLabel + a 
+            {
+                margin-left:25px;
+            }
+
+        .fileManager fieldset label {
+            display: block;
+        }
+
+        .fileManager .unlocalizedFiles {
+            color:#808080;
+        }
+
+        .fileManager .filesContainer 
+        {
+            margin-bottom:15px;
+            width: 500px;
+
+        }
+
+            .fileManager .filesContainer .file
+            {
+                position:relative;
+                overflow:hidden;
+            }
+
+                .fileManager .filesContainer .file .title {
+                    border-bottom: 1px solid #000000;
+                    padding-bottom: 3px;
+                    margin-top: 10px;
+                    margin-bottom: 10px;
+                }
+
+                    .fileManager .filesContainer .file .title .manageLinks
+                    {
+                        float: right;
+                    }
+                    
+                .fileManager .filesContainer .file .version {
+                        padding: 0 0 20px 10px;
+                }
+
+                    .fileManager .filesContainer .file .version label {
+                        float: left;
+                        font-weight: bold;
+                    }
+
+                    .fileManager .filesContainer .file .version span {
+                        float: left;
+                        margin-left: 5px;
+                    }
+
+                .fileManager .filesContainer .file .language {
+                    clear: left;
+                    padding: 0 0 5px 10px;
+                }
+
+                    .fileManager .filesContainer .file .language label {
+                        font-weight: bold;
+                    }
+
+                    .fileManager .filesContainer .file .language label + label {
+                        font-weight: normal;
+                        padding-left: 10px;
+                    }
+
+                    .fileManager .filesContainer .file .language div {
+                        padding-left: 20px;
+                    }
+                    
+                    .file .requirements {
+                        clear: left;
+                        padding: 0 0 0 10px;
+                    }
+
+                    .file .requirements label {
+                        font-weight: bold;
+                    }
+                    
+                    .file .requirements > div {
+                        padding-left: 20px;
+                    }
+                    
+                    .file .requirements .requirementsContent {
+                        padding-top: 5px;
+                        padding-bottom: 10px;
+                    }
+                    
+                    .file .requirements .requirementsContent label {
+                        font-style: italic;
+                        font-weight: normal;
+                    }
+                    
+                    .file .requirements .requirementsContent > div 
+                    {
+                       margin-bottom:4px;
+                       position:relative;
+                    }
+                    
+                    .requirementsContent .requirementsRemove {
+                        float:right;
+                        position:absolute;
+                        right:0px;
+                    }
+                    
+                    .requirements .requirementsAddError {
+                        color:#ff0000;
+                    }
+                    
+                    .requirements .reqBrowseButton {
+                        margin-left : 10px;
+                    }
+                    
+                    #UploadPage fieldset .requirements input[type="text"] {
+                        margin-right: 10px;
+                        width: 70%;
+                    }
+                    
+                    .reqBrowsefade
+                    {
+                        position: absolute;
+                        background-color: #aaaaaa;
+                    }
+                    .reqBrowse
+                    {
+                        background-color: #f4f4f4;
+                        border:1px solid #000000;
+                        -border-radius: 5px;
+                        -moz-border-radius: 5px;
+                        -webkit-border-radius: 5px;
+                        padding:15px;
+                        position: absolute;
+                        display: block;
+                    }
+
+                   .reqBrowsebuttons
+                    {
+                       text-align:right;
+                       position:absolute;
+                       right:10px;
+                       bottom:5px;
+                    }
+                    .reqBrowsebuttons > button
+                    {
+                        color: Blue;
+                        border: none;
+                        background: none;
+                        font-weight: bold;
+                        cursor:pointer;
+                    }
+
+                    .reqBrowseclose
+                    {
+                        display:none;
+                    }
+
+                    .reqBrowseDialog
+                    {
+                        width: 700px;
+                        clear:both;
+                        overflow:hidden;
+                        padding-bottom: 20px;
+                    }
+                    
+                    .reqBrowseDialog > h2 
+                    {
+                        border-bottom: 1px solid #000000;
+                        padding-bottom: 5px;
+                    }
+                    .reqBrowseDialog > p 
+                    {
+                        margin: 15px 0 15px 0;
+                    }
+                    
+                    .reqBrowseSearchCont
+                    {
+                        width: 100%;
+                        background: white;
+                        padding: 0px 2px;
+                        -moz-border-radius: 2px;
+                        border-radius: 2px;
+                        border: 1px solid #888;
+                        margin-bottom: 5px;
+                        height: 29px;
+                    }
+                    .reqBrowseSearchCont .rbboxcont
+                    {
+                        width:90%;
+                        float:left;
+                        margin-top: 2px;
+                    }
+                    
+                    .reqBrowseSearchCont input
+                    {
+                        border:none;
+                        outline:none;
+                        border-color: transparent;
+                    }
+                    .reqBrowseSearchBox
+                    {
+                        margin-right: 4px;
+                        height: 20px;
+                        line-height: 20px;
+                        width: 100%;
+                        padding-left: 4px;
+                        padding-top: 2px;
+                    }
+                    
+                    .reqBrowseSearchBoxDefault
+                    {
+                        color: #AAA;
+                    }
+                    .reqBrowseSearchCont .rbbtncont
+                    {
+                        float: right;
+                        margin-top: 4px;
+                    }
+                    .reqBrowseSearchBtn
+                    {
+                        background: transparent url('searchButton.png') no-repeat 0 0;
+                        width: 22px;
+                        height: 22px;
+                        float:left;
+                        cursor:pointer;
+                    }
+                    
+                    .reqBrowseTabs
+                    {
+                        border-bottom: 5px solid #E8E8E8;
+                        margin:3px 0;
+                        overflow:auto;
+                    }
+                    
+                    .reqBrowseTabs .reqBrowseTabsR
+                    {
+                        color:#fff !important;
+                    }
+                    
+                    .reqBrowseTabs .reqBrowseTabsHighlight
+                    {
+                        color:#000 !important;
+                        background-color:#E8E8E8;
+                    }
+                    
+                    .reqBrowseTabs a
+                    {
+                        padding:5px 12px;
+                        color:#fff;
+                        background-color:#888;
+                        font-weight:bold;
+                        float:left;
+                        margin: 0 4px 0px 0;
+                    }
+                    
+                    .reqBrowsePager td
+                    {
+                        text-align:center;
+                    }
+                    .reqBrowseDialog #Pager
+                    {
+                        margin: 5px 0 15px 0;
+                    }
+                    
+                    .reqBrowseContent
+                    {
+                        height:310px;
+                        overflow:auto;
+                        clear:both;
+                        position:relative;
+                    }
+                    
+                    .reqBrowsePager
+                    {
+                        width:700px;
+                        margin:0 auto;
+                    }
+                    
+                    .reqBrowseContentError
+                    {
+                        color:#ff0000;
+                        margin:5px;
+                    }
+                    .reqBrowseContent .requirementItem
+                    {
+                        border-bottom: 2px solid #E8E8E8;
+                        padding: 4px 0 6px 0;
+                        overflow:auto;
+                    }
+                    .reqBrowseContent .section1
+                    {
+                       float:left;
+                       width:75%;
+                       padding-left:25px;
+                       position:relative;
+                    }
+                    
+                    .reqBrowseContent .section1 input
+                    {
+                        position:absolute;
+                        left:0px;
+                    }
+                    
+                    .reqBrowseContent .title
+                    {
+                        font-weight:bold;
+                    }
+                    .reqBrowseContent .section2
+                    {
+                        float:right;
+                    }
+
+
+    .progressIndicatorfade
+    {
+        position: absolute;
+        background-color: #FFFFFF;
+    }
+    .progressIndicator
+    {
+        background-color: #f4f4f4;
+        border: 1px solid #000000;
+        -border-radius: 5px;
+        -moz-border-radius: 5px;
+        -webkit-border-radius: 5px;
+        padding: 15px;
+        position: absolute;
+        display: block;
+        max-width: 70%;
+        max-height: 70%;
+    }
+    #progressIndicator .progressIndicatorclose
+    {
+        display: none;
+    }
+
+    #progressIndicatorContent
+    {
+        font-weight: bold;
+        padding: 7px 10px 0 10px;
+        height: 25px;
+    }
+   
+
+/*-------- End Upload Page --------*/
+
+/* --- 
+   --- Homepage ---
+   --- */
+p
+{
+    margin: 0 0 1px 0;
+}
+#homePageHeader
+{
+    float: left;
+    margin-bottom: 1em;
+    width: 100%;
+}
+
+.tagline {
+    font-size: x-small;
+    position: relative;
+    top: -11px;
+}
+
+.logo
+{
+    float: left;
+    width: 455px;
+    height: 70px;
+    font-weight: bold;
+    font-size: 22px;
+    margin: 0 10px 0 0;
+    color: #3A3E43;
+}
+.logo > img
+{
+    float: right;
+}
+.logo > div
+{
+    color: #3A3E43;
+    font-weight: bold;
+    font-size: 22px;
+}
+
+.welcomeInfo
+{
+    float: left;
+    width: 700px;
+}
+.welcomeInfo h2
+{
+    font-size: 16px;
+}
+.welcomeInfo p
+{
+    margin: 5px 0 0 0;
+}
+
+#siteActions > div
+{
+    border: 1px solid #BBBBBB;
+    padding: 15px 5px 0 65px;
+    height: 55px;
+    background-repeat: no-repeat;
+    background-position: 10px 10px;
+}
+#siteActions a, #siteActions p
+{
+    margin-top: 5px;
+}
+
+#siteActions .label a
+{
+    font-size: 1.25em;
+    font-weight: bold;
+    margin-bottom: 3px;
+}
+
+#myGalleryBox
+{
+    background-image: url("MyGalleryIcon.png");
+}
+
+#findActions
+{
+    float: right;
+    padding: 10px;
+    width: 225px;
+    height: 50px;
+    border: 1px solid #BBBBBB;
+    margin: 0 10px 0 0;
+}
+
+#findBox div:first-child
+{
+    margin: 0 0 5px 0;
+    font-weight: bold;
+}
+
+#legalDisclaimer
+{
+    margin: 0 0 10px;
+    color: #798072;
+    font-size: 0.8em;
+}
+
+#siteActions
+{
+    float: right;
+    width: 200px;
+}
+#siteActions > div
+{
+    margin-bottom: 10px;
+}
+.homePageProjects
+{
+    width: 100%;
+    float: left;
+}
+.homePageProjects > div
+{
+    padding-left: 1.5em;
+}
+.homePageProjects > div:first-child
+{
+    padding-left: 0;
+}
+
+.homePageProjects .projectList ul
+{
+    padding: 0;
+    margin: 0;
+}
+.homePageProjects li
+{
+    margin-top: .5em;
+    padding-bottom: 0.5em;
+    list-style-type: none;
+}
+.homePageProjects .itemRow a, .homePageProjects .itemRow a:hover
+{
+    color: #0054A6;
+}
+
+.projectList > a:first-child
+{
+    margin-left: 1px;
+    float: right;
+}
+.projectList > a, .projectList > a:hover
+{
+    color: #5BAEDB;
+}
+.projectListTitle
+{
+    height: 27px;
+    font-size: 16px;
+    font-weight: bold;
+    line-height: 125%;
+    background: #E8E8E8;
+    padding: 5px 5px 5px 25px;
+}
+.homePageListPager
+{
+    text-align: right;
+    margin-bottom: -.5em;
+}
+
+.recentlyAddedProjects
+{
+    float: left;
+    width: 32%;
+}
+.mostPopularProjects
+{
+    float: right;
+    width: 32%;
+}
+.highestRankedProjects
+{
+    overflow: hidden;
+}
+* html .highestRankedProjects
+{
+    float: left;
+}
+* html .highestRankedProjects > div
+{
+    width: 100%;
+}
+
+#Pager
+{
+    text-align:left;
+}
+
+/* Impromptu warning style */
+.ipWarningfade
+{
+    position: absolute;
+    background-color: #aaaaaa;
+}
+div.ipWarning
+{
+    width: 400px;
+    position: absolute;
+    border-radius: 10px;
+    -moz-border-radius: 10px;
+    -webkit-border-radius: 10px;
+    padding: 20px 0 20px 20px;
+    background-color: #FCE5E6;
+    border: solid 2px #EE1F25;
+}
+.ipWarningcontainer
+{
+    font-weight: bold;
+}
+.ipWarningclose
+{
+    display: none;
+}
+.ipWarningmessage div
+{
+    position: relative;
+}
+.ipWarningmessage div div + div
+{
+    text-align: center;
+    padding-right: 20px;
+}
+.ipWarningmessage div div:first-child div
+{
+    margin-left: 50px;
+}
+.ipWarningmessage div div:first-child img
+{
+    position: absolute;
+    margin: -20px 0 0 0;
+    top: 35%;
+}
+.ipWarningbuttons
+{
+    text-align: center;
+    margin: 20px 0 0 0;
+}
+.ipWarning button
+{
+    padding: 4px 8px 4px 8px;
+    margin: 2px;
+    font-weight: bold;
+    border: solid 1px #A6A3A6;
+    color: #FFFFFF;
+    background: #B8BABC;
+    filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#B8BABC',EndColorStr='#949699');
+}
+
+#eyebrow
+{
+    width: 100%;
+}
+#siteMessage .unsupportedLocale {
+    margin: 10px 0 0 243px;
+    border: solid 1px #CCC;
+    background: #FCFEC5;
+    padding: 5px;
+}
+
+#Footer
+{
+    width: 100%;
+    height: auto;
+}
+
+.clear
+{
+    clear: both;
+}
+
+#buildVersion
+{
+    clear: both;
+    margin-left: auto;
+    margin-right: auto;
+    padding-right: 26px;
+    padding-top: 8px;
+    text-align: right;
+}
+
+#page
+{
+    clear: both;
+    padding-top: 10px;
+}
+
+#page h1
+{
+    padding: 10px 0px;
+}
+
+#ownerBar
+{
+    background: #EFEFEF;
+    border: 2px solid #7FCBF5;
+    text-align: left;
+    color: Black;
+    margin: 10px 0 20px 0;
+    padding: 5px;
+    word-spacing: 0px;
+    font-size: medium;
+}
+
+#ownerBar a
+{
+    color: Blue;
+    padding: 0 5px 0 5px;
+}
+
+
+
+
+/*-------- Start Tab Control --------*/
+
+.tabHeaders
+{
+    font-weight:normal;
+    text-transform: uppercase;
+    border-bottom: solid 1px #CCC;
+    float: left;
+    width: 100%;
+}
+
+.tabHeaders div
+{
+    padding: 7px 19px 8px 19px;
+    font-size: 0.9em;
+    line-height: 125%;
+    color:#00749E;
+    cursor: pointer;
+    float: left;
+    text-align: center;
+}
+
+.tabHeaders div.current
+{
+    background-color:#fff;
+    cursor: default;
+    border: 1px solid #CCC;
+    border-bottom:none;
+    margin-bottom:-2px;
+    color:#000;    
+}
+
+.tabHeaders div a
+{
+    text-decoration:none;
+}
+
+.tabContents
+{
+    clear: both;
+}
+
+#MainContent .tabHeaders div.current a
+{
+    color:#000;
+}
+
+.tabContents div.current
+{
+    display: block;
+}
+/*-------- End Tab Control --------*/
+
+.itemContainer
+{
+    width: 100%;
+}
+.itemRow .itemTitle
+{
+    padding-bottom: 5px;
+    font-size:1.1em;
+}
+
+.itemRow .itemBody, .itemRow .itemInfo
+{
+    padding:15px 17px 16px 0;
+}
+.itemRow .itemDescription
+{
+    overflow: hidden;
+    max-height: 80px;
+}
+.itemRow .itemBody
+{
+    vertical-align: top;
+    line-height: 1.4;
+}
+.itemRow .itemBody a.officialMicrosoftLabel
+{
+    color: #ACACAC;
+}
+.itemRow .itemInfo
+{
+    vertical-align: top;
+    padding-left: .5em;
+    line-height: 1.4;
+    width: 10em;
+    text-align:right;
+}
+
+.IE7 .itemRow .itemInfo
+{
+    width:11em;
+}
+
+.itemRow .itemInfo .ratingStars
+{
+    float: left;
+}
+.itemRow .itemInfo .ratingCount
+{
+    padding: 0 0 0 5px;
+    float: left;
+}
+.itemRow .ratingInfo
+{
+    text-align: center;
+}
+
+.itemRow .affiliationLink, #editorPicksSection .affiliationLink
+{
+    position: relative;
+    top: 3px;
+}
+
+#editorPicksSection a.officialMicrosoftLabel
+{
+    color: #ACACAC;
+}
+
+.itemRow .tagsContainer label {
+    display:none;
+}
+
+.editorPickedItem
+{
+    background-color:#F8F8F8;
+}
+
+.editorPickedText
+{
+    font-size:1.25em;
+    padding-bottom:2px;
+}
+.editorPickedItem > td 
+{
+    border-top:6px solid #fff;    
+}
+
+.dirSubHeading
+{
+    margin-bottom:15px;
+}
+
+#searchPage .dirSubHeading h2 
+{
+    line-height:1.4;
+    font-size:1.1em;
+}
+
+#searchPage .dirSubHeading h2 span
+{
+    padding-top:5px;
+    display:block;
+}
+
+#searchPage .dirSubHeading h1, #searchPage .dirSubHeading h2
+{
+    clear:none;
+    padding-left:0px;    
+}
+
+.dirSubHeading .dirSubLinks
+{
+    font-size:1.2em;
+    padding-top:5px;
+}
+
+
+.summaryBox
+{
+    padding: .25em 0 .25em 0;
+    clear: both;
+    line-height:1.45;
+}
+
+/*-------- Start Rating Stars --------*/
+
+.RatingStar
+{
+    width: 11px;
+    height: 11px;
+    padding: 0 8px 0 0;
+    background-position: center;
+    float: left;
+}
+
+.FilledRatingStar, .HalfRatingStar, .EmptyRatingStar, .FilledRatingStarHover
+{
+    width: 11px;
+    height: 11px;
+    padding: 0px 1px 0px 0px;
+    margin-top: 2px;
+}
+
+.FilledRatingStar
+{
+    background: url(../samples/fullStar.png) no-repeat;    
+}
+
+.ownerRating .FilledRatingStar
+{
+    background: url(../samples/fullStar.png) no-repeat;
+}
+
+.FilledRatingStarHover
+{
+    background: url(../samples/fullStarHover.png) no-repeat;
+    
+}
+
+.HalfRatingStar
+{
+    background: url(../samples/halfStar.png) no-repeat;
+   
+}
+
+.EmptyRatingStar
+{
+    background: url(../samples/emptyStar.png) no-repeat;
+    
+}
+
+.EditStarMode .RatingStar
+{
+    cursor: pointer;
+}
+
+
+
+/*-------- End Rating Stars --------*/
+
+.discussionFormTable
+{
+    width: 100%;
+    table-layout: fixed;
+}
+
+
+#ReviewsTabPane .seeAllLink, #DiscussionsTabPane .seeAllLink
+{
+    margin-top: 10px;
+    text-align: center;
+}
+
+/*-------- Start DiscussionsTab --------*/
+
+.threadActions
+{
+    text-align: right;
+    margin-top: 10px;
+    float: right;
+}
+
+#DiscussionsTabPane .reply, #DiscussionsTabPane .toggleDiscussion
+{
+    cursor: pointer;
+}
+
+
+#defaultDicussionText, #newDiscussion
+{
+    padding-top: 10px;
+}
+#DiscussionsTabPane .posts
+{
+    display: block;
+}
+#DiscussionsTabPane .threadHeader .left
+{
+    float: left;
+}
+#DiscussionsTabPane .threadHeader .right
+{
+    float: right;
+}
+#DiscussionsTabPane .normal
+{
+    font-weight: normal;
+}
+
+#DiscussionsTabPane .threadHeader
+{
+    position: relative;
+    background-color: #ECECEC;
+    padding: 4px 10px 4px 10px;
+}
+
+#DiscussionsTabPane .threadHeader .title
+{
+    color: #000000;
+    font-weight: bold;
+    margin-bottom: .7em;
+}
+#DiscussionsTabPane .threadHeader .label
+{
+    color: #000000;
+}
+#DiscussionsTabPane .postMeta
+{
+    color: #666666;
+}
+#DiscussionsTabPane .threadHeader .value
+{
+    font-weight: bold;
+    color: #000000;
+}
+
+#DiscussionsTabPane .reply
+{
+    font-weight: normal;
+    cursor: hand;
+}
+
+#DiscussionsTabPane ul li
+{
+    list-style-type: none;
+    list-style-image: none;
+    padding-bottom: 10px;
+}
+
+#DiscussionsTabPane ul
+{
+    padding-left: 0px;
+    margin-left: 0px;
+    padding-right: 2px;
+}
+
+.IE #reviewList .right
+{
+    margin-right: -1em;
+}
+
+#newDiscussion
+{
+    margin: 0 0 15px 0;
+}
+#newDiscussion #Title
+{
+    width: 50%;
+}
+#newDiscussion textarea
+{
+    width: 99%;
+    height: 10em;
+}
+
+#DiscussionsTabPane
+{
+    margin-left: 0px;
+    padding: 0 1em 1em 1em;
+}
+
+
+.postMeta
+{
+    float: right;
+}
+
+.postReply
+{
+    cursor: hand;
+    float: right;
+    font-weight: bold;
+}
+
+.postSaveReply
+{
+    display: none;
+}
+
+.postSaveReply textarea
+{
+    width: 99%;
+    margin-bottom: 4px;
+    height: 8em;
+}
+
+.toggleDiscussion
+{
+    cursor: hand;
+}
+
+.saveReplyErrorMessage
+{
+    display: none;
+    margin: 0 0 4px 0;
+    color: Red;
+    font-weight: bold;
+}
+
+#discussionListItem .avatar
+{
+    float: left;
+    padding: 5px;
+    vertical-align: middle;
+}
+
+#discussionListItem .discussion
+{
+    margin-left: 55px;
+    padding: 0 5px 5px 5px;
+    vertical-align: top;
+}
+
+.IE7 #discussionListItem .avatar
+{
+    margin-top: 15px;
+}
+
+
+/*-------- End DiscussionsTab --------*/
+
+
+.flotChart
+{
+    height: 300px;
+}
+
+#projectMenuBarTop
+{
+    padding: 10px 0 20px 0;
+    font-weight: bold;
+    font-size: 25px;
+}
+.dayHeader
+{
+    font-weight: bold;
+}
+
+/*-------- Start StatsPage --------*/
+#statsPage
+{
+    border: none;
+    background-color: Transparent;
+    margin-top: 1em;
+}
+
+#statsPage .rangeBox
+{
+    padding: 5px;
+    background-color: #ECECEC;
+    border: solid 1px #C2C2C2;
+    float: left;
+}
+#statsPage .statBox
+{
+    margin-top: 1em;
+    margin-bottom: 10px;
+    overflow: hidden;
+    display: none;
+}
+#statsPage .statBox h3
+{
+    font-size: 1.1em;
+    display: inline;
+}
+
+#statsPage #statMessage
+{
+    margin-top: 1em;
+    display: none;
+}
+
+#statsPage #statDownloadBox img {
+    float: left;
+}
+
+#statsPage .statDownloadLink {
+    padding-left: 5px;
+    vertical-align: middle;
+}
+
+#pointTooltip
+{
+    border: solid #000000 1px;
+    height: 35px;
+    background-color: #EEEEEE;
+    position: absolute;
+    display: none;
+    text-align: center;
+    padding: 9px;
+    border-radius: 4px;
+    -moz-border-radius: 4px;
+    -webkit-border-radius: 4px;
+    z-index: 1000;
+    white-space: nowrap;
+}
+
+.flotChart
+{
+    height: 300px;
+}
+
+/*-------- End StatsPage --------*/
+
+
+/***************************************************************/
+/* TagAutoComplete Styles */
+/***************************************************************/
+.AutoCompletePanel
+{
+    font-size: 95%;
+    border: solid .1em #999;
+    background-color: #f0f0f0;
+    padding: .15em;
+}
+
+.AutoCompletePanel div.Row
+{
+    color: #000;
+    cursor: pointer;
+    background-color: transparent;
+    padding: .15em .25em;
+    text-align: left;
+}
+
+.AutoCompletePanel div.Selected
+{
+    color: #fff;
+    background-color: #6D6D6D;
+}
+
+
+/*-------- Start Subscription Form --------*/
+
+#subscribeForm
+{
+    background-color: #D3D3D1;
+    border: 1px solid #000000;
+    -border-radius: 5px;
+    -moz-border-radius: 5px;
+    -webkit-border-radius: 5px;
+    padding: 15px;
+    position: absolute;
+    display: block;
+}
+
+#subscribeForm .subscribeFormbuttons
+{
+    text-align: right;
+    margin-top: 10px;
+}
+#subscribeForm .subscribeFormbuttons > button
+{
+    color: Blue;
+    border: none;
+    background: none;
+    font-weight: bold;
+    cursor: pointer;
+}
+
+#subscribeForm .subscribeFormclose
+{
+    display: none;
+}
+
+#subscribeForm table
+{
+    margin-bottom: 15px;
+}
+
+#subscribeForm table th
+{
+    text-align: left;
+    font-weight: bold;
+    border-bottom: 1px solid #000000;
+}
+
+#subscribeForm table td
+{
+    padding: 5px 10px 5px 20px;
+}
+
+#subscribeForm .rowHeading td
+{
+    font-weight: bold;
+    border-bottom: 1px solid #FFFFFF;
+}
+
+#subscribeForm table tr td:first-child
+{
+    padding: 5px 40px 5px 0;
+}
+
+
+/*-------- End Subscription Form --------*/
+
+/*-------- Start Tag Browser --------*/
+
+.tagBrowserfade
+{
+    position: absolute;
+    background-color: #aaaaaa;
+}
+#tagBrowser
+{
+    background-color: #f4f4f4;
+    border:1px solid #000000;
+    -border-radius: 5px;
+    -moz-border-radius: 5px;
+    -webkit-border-radius: 5px;
+    padding:15px;
+    position: absolute;
+    display: block;
+}
+
+#tagBrowser .tagBrowserbuttons
+{
+   text-align:right;
+   margin-top: 10px;
+}
+#tagBrowser .tagBrowserbuttons > button
+{
+    color: Blue;
+    border: none;
+    background: none;
+    font-weight: bold;
+    cursor:pointer;
+}
+
+#tagBrowser .tagBrowserclose
+{
+    display:none;
+}
+
+.tagBrowserContainer {
+    width: 450px;
+}
+
+.tagBrowserContainer h2 {
+    border-bottom: 1px solid #000000;
+    padding-bottom: 5px;
+}
+.tagBrowserContainer > p {
+    margin: 15px 0 15px 0;
+}
+
+.tagBrowserContainer .tags {
+    margin: 5px;
+    height: 225px;
+    overflow-y: scroll;
+}
+
+
+/*-------- End Tag Browser --------*/
+
+/*-------- Start List Filter Box --------*/
+
+div#filterInputBox
+{
+    overflow:auto;
+    min-width:225px;
+}
+
+.filterBox
+{
+    width: 100%;
+    background: #FFFFFF;
+    padding: 0px 2px;
+    height: 25px;
+    -moz-border-radius: 2px;
+    border-radius: 2px;
+    border: 1px solid #888888;
+    table-layout: auto;
+    margin-bottom:5px;
+}
+
+    .filterBox #filterImageCell
+    {
+        text-align: right;
+        padding: 0px;
+        vertical-align: middle;
+    }
+
+    .IE7 .filterBox #filterImageCell
+    {
+        padding:2px 2px 0 0;
+    }
+
+        .filterBox #filterImg
+        {
+            background: transparent url('searchButton.png') no-repeat 0 0;
+            width: 22px;
+            height: 22px;
+        }
+
+table.filterBox
+{
+    table-layout: fixed;
+}
+
+    .filterBox .stxtcell
+    {
+        padding-right: 4px;
+        width:90%;
+    }
+
+        .filterBox .stxtcell > input
+        {
+            margin-right: 4px;
+            height: 26px;
+            line-height:26px;
+            width: 100%;
+            padding: 0px;
+            padding-left: 4px;
+            padding-top: 2px;
+            border: none;
+        }
+
+        .IE7 .filterBox .stxtcell > input
+        {
+            height: 20px;
+        }
+
+            .filterBox .stxtcell > input.stxtinptpassive
+            {
+                color: #ACACAC;
+            }
+
+/*-------- End List Filter Box --------*/
+
+/*-------- Start Notifications --------*/
+
+#notificationsSummaryBox
+{
+    font-weight: bold;
+    padding: .5em;
+}
+
+
+.notificationsByDay, .notifications
+{
+    /*list-style: none;*/
+}
+
+.dayHeader
+{
+    border-bottom: 1px solid silver;
+    margin-top: 1em;
+    padding-bottom: .5em;
+}
+
+.notifications
+{
+    margin-top: .5em;
+}
+
+ul.notifications li
+{
+    line-height: 1.5em;
+}
+
+ul.notifications li.unread
+{
+    font-weight: bold;
+}
+
+ul.notifications li ol, ul.notifications li ul
+{
+    margin-left: 1.5em;
+}
+
+/*-------- End Notifications --------*/
+
+/*-------- Start ProjectDetailsPage --------*/
+
+#projectPage #projectInfo
+{
+    position: relative;
+    margin-top: 5px;
+    height: 100%;
+}
+#projectInfo .section
+{
+    float: left;
+    margin-bottom: 0px;
+    height: 100%;
+}
+
+    #projectInfo .section .itemBar, #projectInfo .section .itemBarLong
+    {
+        clear: both;
+        padding: 7px 0 7px 0;
+        overflow:auto;
+    }
+    
+     #projectInfo .section .itemBarLong:first-child
+     {
+         padding-top:3px;
+     }
+    
+    .IE7 #projectInfo .section .itemBar, .IE7 #projectInfo .section .itemBarLong
+    {
+        padding-top: 5px;
+    }
+
+    #projectInfo .section .itemBar > label, #projectInfo .section .itemBarLong > label
+    {
+        width: 130px;
+        float: left;
+        text-transform: capitalize;
+    }
+
+    #projectInfo .section .itemBar div#yourRating {
+        float:left;
+    }    
+    
+    #projectInfo .section .itemBar div.RatingStar {
+        margin:2px 1px 0 0;
+    }
+
+    #projectInfo .section .itemBar div#RatingCount {
+        padding: 0 0 0 3px;
+    }    
+    
+    #projectInfo .section .itemBar .ratingsWithCountContainer img {
+       vertical-align:top;
+       float:left;
+       padding-right: 4px;
+    }
+
+    #projectInfo .section .itemBar > span, #projectInfo .section .itemBarLong > span, #projectPage .section .itemBar > div
+    {
+        float: left;
+    }
+
+    #projectInfo .section .itemBar, #projectInfo .section .itemBarLong {
+        width: 100%;
+    }
+
+    #projectInfo .section .itemBar > span {
+        float: none;
+    }
+
+    #projectInfo .section .itemBar > span .shareThisItem {
+        white-space: nowrap;
+    }
+    
+    #projectInfo .section .itemBarLong div
+    {
+        margin-left: 130px;
+        padding: 0;
+    }
+    
+     #projectInfo .section .viewonlinecont
+     {
+         background-color:#d3d3d3;
+         padding:5px 10px;
+         margin-top:10px;
+         float:left;
+         font-weight:bold;
+     }
+
+#projectInfo #sectionLeft
+{
+    width: 50%;
+}
+#projectInfo #sectionRight
+{
+    width: 50%;
+}
+.IE7 #projectInfo #sectionRight
+{
+    width: auto;
+}
+
+#projectPage h2.projectSummary
+{    
+    font-weight:normal;
+    font-size: 1.1em;
+    margin-bottom: 11px;
+    line-height:1.4;
+    word-wrap: break-word;
+}
+
+.IE7 #projectPage h2.projectSummary
+{
+    font-family: 'Segoe UI' , 'Lucida Grande' ,Verdana,Arial,Helvetica,sans-serif;
+}
+
+.IE #projectPage .projectTitle, .IE9 #projectPage .projectTitle
+{
+    width: 100%; 
+}
+
+#projectPage #reportAbuse
+{
+    float: left;
+    font-size: x-small;
+}
+
+#projectPage .hiddenSidebar {
+    display: none;
+}
+
+#projectPage .fullProjectBody {
+    margin-left:-275px;
+}
+
+.IE8 #projectPage #userCard {
+    float: left;
+    height: auto;
+}
+
+#projectPage #userCard .avatar img {
+    max-width: 100px;
+    max-height: 100px;
+}
+
+#projectDetails
+{
+    overflow:hidden;
+}
+
+#projectBody
+{
+    width: 100%;
+    overflow:hidden;
+}
+
+    #projectDetails > div:first-child
+    {
+        margin: 5px 0 0 260px;
+    }
+ 
+    #projectBody > div:first-child
+    {
+        margin: 20px 0 0 260px;
+    }
+
+    .IE7 #projectContent .tabHeaders
+    {
+        overflow:hidden;
+        margin-bottom:-20px;
+    }
+
+#projectPage .sidebar
+{
+    float: left;
+    width: 215px;
+    margin-right: -250px;
+}
+
+    #projectPage .sidebar .section
+    {
+        margin: 20px 0 10px 0;
+    }
+
+        #projectPage .sidebar .section .titleBar h3
+        {
+            padding: 0 0 2px 0;
+        }
+
+        #projectPage .sidebar .section .itemBarRight
+        {
+            min-height: 21px;
+            position: relative;
+            padding-top: 5px;
+        }
+
+        #projectPage .sidebar .section .titleBar
+        {
+            margin-bottom: 5px;
+        }
+
+        #projectPage .sidebar .section .authorItem
+        {
+            padding: 0 0 5px 10px;
+        }
+
+            #projectPage .sidebar .section .authorItem a
+            {
+                display:block;
+                float:left;
+                max-width:170px;
+            }
+
+            #projectPage .sidebar .section .authorItem > div
+            {
+                float:right;
+            }
+
+    #projectPage .sidebar #advertisement
+    {
+        margin-top: 20px;
+    }
+
+    #projectPage .sidebar #advertisement .label
+    {
+        text-align: center;    
+    }
+
+    #projectPage .sidebar #moreFromAuthor 
+    {
+        width:225px;
+        margin: 20px 0 10px 0;
+        float:left;
+    }
+    
+    #projectPage .sidebar  #moreFromAuthor .bottomBar {
+        padding: 5px 0px 5px 25px;
+        text-align: right;
+    }
+
+#projectPage #Collections {
+    min-height:22px;
+    min-width:169px;
+}
+
+#projectPage #Collections .bevelButton {
+    background-color: #8CC63F;
+}
+
+#projectPage .bevelButton
+{
+    font-weight: bold;
+    border-radius: 3px;
+    -moz-border-radius: 3px;
+    -webkit-border-radius: 3px;
+    color: white;
+    padding: 2px 10px 3px;
+    text-align: center;
+}
+
+#projectPage #DiscussionsTabPane .bevelButton
+{
+    font-weight: normal;
+    color: black;
+    padding: 1px 10px 1px;
+}
+
+#projectPage #Downloads {
+    padding: 0 0 8px 0;
+    float: left;
+}
+    #projectPage #Downloads > div:first-child {
+        float: left;
+        margin: 15px 0 0 0;
+        height:35px;
+        line-height:1.6;
+        width: 130px;
+    }
+    #projectPage #Downloads label 
+    {
+        font-size:1.25em;
+    }
+    #projectPage #Downloads input
+    {
+        min-width: 100px;
+        padding: 3px 10px 3px 10px;
+        margin: 3px 10px 0 10px;
+        font-weight: bold;
+        float: left;
+    }
+    
+    #projectPage #Downloads .button
+    {
+        background-color:#007494;
+        color:#fff;
+        padding:5px 15px;
+        margin: 15px 15px 0 0;
+        float:left;
+    }
+    
+    #projectPage #Downloads .button:hover 
+    {
+        background-color:#0095c4;
+        text-decoration:none;
+    }
+
+#projectPage #projectBody .attachments {
+    margin: 0 0 15px 0;
+}
+
+    #projectPage #projectBody .attachments label {
+        float: left;
+    }
+
+        #projectPage #projectBody .attachments .files a, #projectPage #projectBody .attachments .files span {
+            float: left;
+            padding: 0 5px 0 5px;
+        }
+
+#publishBar
+{
+    border: 1px solid #707070;
+    background-color: #F8F8F8;
+    margin-top: 10px;
+}
+
+#sourceItem {
+    height: 610px;
+}
+    #sourceItem > div:first-child {
+        padding: 20px 5px 0 15px;
+        font-weight: bold;
+    }
+    #sourceItem > div+div {
+        height: 560px;
+        padding: 10px;
+        overflow: auto;
+    }
+    #sourceItem .copyCode {
+        font-weight: normal;
+        margin: 0 15px 0 0;
+        float: right;
+    }
+
+.sourceList {
+    height: 600px;
+    padding: 5px;
+    border-top: 1px solid #CCC;
+    margin-top: -1px;
+}
+
+        .sourceList .sourceListTabHeader
+        {
+            margin:20px 10px;
+        }
+        .sourceList .sourceListTabs
+        {
+            margin-bottom:20px;
+            border-bottom: 1px solid #CCC;
+            float:left;
+            width:100%;
+        }
+        .sourceList .sourceListTabs .languageTab {
+            padding:5px 10px 5px 10px;
+            font-weight: bold;
+            float: left;
+            margin: 0 3px 0px 0;
+            color:#00749E;
+        }
+        .sourceList .sourceListTabs .languageTab:hover 
+        {
+            color: #0095C4;
+        }
+
+        .sourceList .sourceListTabs .selectedLanguage {
+            background-color: #fff;
+            color: #000;
+            border: 1px solid #ccc;
+            border-bottom:none;
+            margin-bottom:-2px;
+        }
+
+        .sourceList .sourceListTabs .unselectedLanguage {
+            cursor: pointer;
+        }
+
+        .sourceList .endTabs {
+            clear: both;
+        }
+
+    .sourceList .sourceListContent {
+        padding-top: 5px;
+    }
+
+
+.sbfc,
+.sbfe
+{
+    white-space: nowrap;
+	text-indent: 20px;
+	cursor: pointer;
+	padding: .2em 0em .2em 0em;
+	background-repeat: no-repeat;
+	background-position: left center;
+	font-weight: bold;
+	text-decoration: none !important;
+}
+
+.sbfc 
+{
+	background-image: url(../samples/node_closed.gif);
+}
+
+.sbfe
+{
+    white-space: nowrap;
+	background-image: url(../samples/node_opened.gif);
+}
+
+.ndbf
+{
+    white-space: nowrap;
+	text-indent:20px;
+}
+
+.sbf
+{
+    white-space: nowrap;
+	background: url(../samples/bullet.gif) no-repeat 4px -1px;
+	cursor: pointer;
+	text-indent: 20px;
+    white-space: nowrap;
+	padding: .1em 0em .1em 0em;
+}
+
+.sbsf,
+.sbf:hover
+{
+	color: #000;
+	text-decoration: none !important;
+	
+}
+
+.sbsf
+{
+	color: #000 !important;
+	background-color: rgb(232, 232, 232);
+}
+
+.sbf:hover
+{
+	color: #ce8b10;
+}
+
+/*-------- Translate --------*/
+.translatePage {
+    width: 900px;
+}
+.translatePage .fileManager {
+    margin-bottom:20px;
+}
+.translatePage .fileManager h4 {
+    margin-top:10px;
+}
+.translatePage #formContainer {
+    width: 100%;
+}
+.translatePage .formLabel {
+    width: 300px;
+    padding: 5px;
+}
+ .translatePage .textInput {
+    width: 425px;
+}
+.translatePage TEXTAREA.richText {
+    height: 600px;
+    width: 620px;
+}
+.translatePage TEXTAREA.unadornedEditor {
+    height: 600px;
+}
+.translatePage .formWideLabel, .translatePage .richText {
+    padding: 5px;
+}
+.translatePage .formWideLabel, .translatePage .unadornedEditor {
+    width: 750px;
+    padding: 5px;
+}
+.translatePage #languageSelection {
+    margin: 15px;
+    display: inline-block;
+}
+
+.translateTab, .translateTabSelected {
+    font-weight: bold;
+    float: left;
+    text-align: center;
+    margin: 10px;
+    padding: 7px;
+    background: #E8E8E8;
+    white-space: nowrap;
+    cursor: pointer;
+}
+
+.translateTabSelected
+{
+    color: White;
+    background: Gray;
+}
+
+.translateTabSelected .translateLabel, .translateTab .translateLabel
+{
+    white-space: nowrap;  
+    float: left;  
+    padding: 0 5px 0 5px;
+}
+
+.translateTab #deleteLanguage, .translateTab #moreLanguages
+{
+    padding-left: 10px;
+}
+
+.translateLabel #deleteLanguage {
+    color: #FFFFFF;
+}
+/*-------- End Translate --------*/
+/*-------- Begin Eula --------*/
+
+
+#eulaPagefade
+{
+    position: absolute;
+    background-color: #FFFFFF;
+}
+
+#eulaPage
+{
+    background-color: #f4f4f4;
+    border: 1px solid #000000;
+    -border-radius: 5px;
+    -moz-border-radius: 5px;
+    -webkit-border-radius: 5px;
+    padding: 15px;
+    display: block;
+    max-width: 70%;
+}
+
+#eulaPage .eulaPageclose
+{
+    text-align: right;
+}
+
+#eulaPage .eulaPagemessage
+{
+    overflow: auto;
+    max-height: 350px;
+}
+
+    #eulaPage .eulaPagemessage h1
+    {
+        margin: 0 0 5px 0;
+    }
+
+#eulaPage .eulaPagebuttons
+{
+    text-align: right;
+    margin-top: 10px;
+}
+#eulaPage .eulaPagebuttons > button
+{
+    color: Blue;
+    border: none;
+    background: none;
+    font-weight: bold;
+    cursor: pointer;
+}
+
+
+        #eulaPage #eula #documentText
+        {
+            line-height: normal;
+        }
+
+/*-------- End DocumentView --------*/
+/*-------- Begin FAQ --------*/
+
+#FAQPage #TableOfContents h2
+{
+    padding: 5px;
+    border-bottom: 2px solid #EFEFEF;
+    margin: 0 0 10px 0;
+    max-width: 70%;
+}
+
+#FAQPage .FAQSection
+{
+    padding: 10px 0px;
+    width: 70%;
+}
+
+    #FAQPage .FAQSection h2
+    {
+        padding: 5px;
+        border-bottom: 2px solid #EFEFEF;
+    }
+
+    #FAQPage .FAQSection h3
+    {
+        padding: 5px;
+    }
+
+    #FAQPage .FAQSection ul, #FAQPage .FAQSection ol
+    {
+        margin: 0;
+    }
+
+    #FAQPage .FAQSection #description > div
+    {
+        overflow: auto;
+        padding-left: 10px;
+    }
+
+        #FAQPage .FAQSection #description img
+        {
+            float: left;
+        }
+
+        #FAQPage .FAQSection #description div > div
+        {
+            padding-top: 10px;
+            float: left;
+        }
+
+    #FAQPage .FAQSection > div > div
+    {
+        padding: 0 15px;
+    }
+
+    #FAQPage #Reputation th, #FAQPage #Reputation td
+    {
+        padding-left: 20px;
+    }
+    
+/*-------- End FAQ --------*/
+/*-------- Begin DocumentView --------*/
+
+#documentView #documentText
+{
+    line-height: normal;
+}
+
+/*-------- End DocumentView --------*/
+
+.Opera wbr:after
+{
+    content: "\00200B"; 
+}
+
+
+.IE9 wbr:after
+{
+    content: "\00200B"; 
+}
+
+.IE8 wbr {
+  width: 0px;
+  display: inline-block;
+  overflow: hidden;
+}
+
+/*-------- Begin FileManager --------*/
+
+.uploadControlNoError 
+        {
+            height:30px
+        }
+.uploadControlWithError 
+        {
+            height:80px;
+        }
+/*-------- End FileManager --------*/
+
+/*-------- Begin User Card --------*/
+#userCard .titleBar {
+    border-bottom: solid 5px #E8E8E8;
+    margin: 10px 0 5px 0;
+}
+    #userCard .titleBar h3
+    {
+        font-size: 1.0em;
+        font-weight: bold;
+        line-height: 125%;
+        padding: 0 0 2px 0;
+    }
+
+#userCard .userFeed {
+    float: right;
+}
+   
+#userCard .bio {
+    max-width:300px;
+    white-space: normal;
+}
+        
+#userCard .avatar
+{
+    padding: 5px 5px 10px 5px;
+    margin: 0 0 3px 0;
+    text-align: center;
+}
+
+#userCard .itemBar {
+    padding: 5px;
+}
+
+    #userCard .itemBar label
+    {
+        float: left;
+        text-transform: capitalize;
+    }
+
+    #userCard .itemBar label+span {
+        display: block;
+        margin-left: 100px;
+    }
+
+#userCard .collapsableSidebar {
+    clear:both;
+    width:100%;
+    margin-top: 5px;
+}
+
+/* Profile Overrides */
+#userCard
+{
+    padding: 0 0 10px 0
+}
+
+#userCard .profile-usercard
+{
+    width:225px;
+}
+
+#userCard .profile-usercard, #userCard .profile-inline, #userCard .profile-inline-header
+{
+    border:0px;
+    background-color:#fff;
+}
+
+#userCard .profile-userimage-large
+{
+    margin-bottom:10px;
+    border:none;
+    width:auto;
+    height:auto;
+}
+
+#userCard .profile-inline .profile-inline-header-details 
+{
+    width:100%;
+    display:block;
+    clear:both;
+    margin-left:0px;
+}
+
+
+    
+/*-------- End User Card --------*/
+/*-------- Begin Description Progress Meter --------*/
+
+#descriptionProgressMeter {
+    float: right; 
+    border-top: 1px solid #DADADA; 
+    border-left: 1px solid #DADADA; 
+    width: 210px;
+    padding-left: 7px;
+}
+
+    #descriptionProgressMeter h4 {
+        font-weight: bold;
+    }
+
+    #descriptionProgressMeter #progressGraphic {
+        border: 1px solid #888888;
+        width: 205px;        
+        margin: 10px 0;
+        background-color: #E9E9E9;
+        padding: 1px 0 0 1px;
+    }
+
+        #descriptionProgressMeter #progressGraphic div {
+            background-image: url("../common/progress_meter.png");
+            padding-left: 5px;
+        }
+
+    #descriptionProgressMeter #progressText {
+        font-weight: bold;
+        margin: 5px 0;
+        
+    }
+            
+    #descriptionProgressMeter #goodDescriptionText  p+p {    
+        padding: 5px 0;
+    }
+
+        #descriptionProgressMeter #goodDescriptionText > div {
+            margin-top: 5px;
+            width: 150px;
+            border-radius: 5px;
+            -moz-border-radius: 5px;
+            -webkit-border-radius: 5px;
+            overflow: auto;
+        }
+
+            #descriptionProgressMeter #goodDescriptionText div img {
+                float: left;
+            }
+
+            #descriptionProgressMeter #goodDescriptionText div div {    
+                margin: 7px 0 5px 10px;
+            }
+
+/*-------- End Description Progress Indicator --------*/
+
+/*-------- Start Sample Pack Tab View --------*/
+.SamplePackTab #headerBar
+{    
+    padding: 15px 5px 20px 5px;
+    font-weight: bold
+}
+    .SamplePackTab #headerBar .reportCount
+    {
+        padding-top: 2px;
+    }
+    .SamplePackTab #headerBar .samplePackSort
+    {
+        float: right;
+        color: #666;
+    }
+/*-------- End Sample Pack Tab View --------*/
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/description/Combined.css b/samples/winrt/ImageManipulations/description/Combined.css
new file mode 100644
index 000000000..e69de29bb
diff --git a/samples/winrt/ImageManipulations/description/Galleries.css b/samples/winrt/ImageManipulations/description/Galleries.css
new file mode 100644
index 000000000..ac2e94ee8
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/Galleries.css
@@ -0,0 +1,418 @@
+/* ***************************************************
+Galleries.css   - Common Structure
+
+This is where we define common layout for structures that are truly close to common across the different
+Galleries sites.  To make sure this works we need to follow certain conventions.
+
+1. Define each logical structure in its own section with its own comment block that gives the section
+a Name, Description and defines the root element if one exists (i.e #someElement). Also, mark the closing block.
+
+2. Indent styles in a section to represent if it is a child of a previous element.
+i.e.      #someDiv{
+            }
+                #someDiv ul {
+                }
+ 
+3. Do not include brand specific information here like colors and fonts unless they are *really* common.
+
+4. If there is an element that you know will be overridden in each brand stylesheet still include it here with an empty definition. 
+This will aid in knowing what section to override and what selectors to use.
+
+i.e.    #someSction a {
+        }
+
+5.  When you add a new section also update the Table of Contents below so that we have a quick overview of the sections
+
+ *****************************************************/
+ 
+/****************************************************
+Table of Contents
+
+    Global - global classes
+
+    FileAttachmentDisplay - The list of attached files under the editor
+    Eyebrow - The breadcrumb control at the top of the master page
+    Pager - The common paging control, used for browsing pages of search results
+    Profile User Card - Elements in the profile usercard control
+    SideNav - The navigation side bar that contains the search filters
+
+
+*****************************************************/
+
+/********************************
+Name: Global
+Root: none
+Description: truly global classes
+********************************/
+body {
+    text-align: left;
+    direction: ltr;
+}
+
+img.rss {
+    background: url(../../../GlobalResources/Images/Rss.png) no-repeat;
+    background-position: 0px 0px;
+    height: 17px;
+    width: 17px;
+}
+/* End Global Section */
+
+/********************************
+Name: FileAttachmentDisplay
+Root: #fileAttachmentDisplay
+Description: The list of attached files under the editor
+********************************/
+#fileAttachmentDisplay {
+}
+    #fileAttachmentDisplay .attachment {
+        margin-right: 10px;
+        float: left;
+    }
+
+        #fileAttachmentDisplay .attachment .displayAttachment {
+            padding: 0px 0 13px 0;
+            float: left;
+        }
+
+        #fileAttachmentDisplay .attachment .removeAttachment {
+            background-image: url('/Content/Common/delete.png');
+            display: block;
+            width: 16px;
+            height: 16px;
+            float: left;
+        }
+/* End FileAttachmentDisplay Section */
+
+
+/********************************
+Name: Eyebrow
+Root: .EyebrowContainer
+Description: The breadcrumb control at the top of the master page
+********************************/
+.EyebrowContainer {
+}
+    .EyebrowContainer div.EyebrowElement{
+        display:inline;
+    }
+
+    .EyebrowContainer .EyebrowElement{
+        font-weight:normal
+    }
+    .EyebrowContainer .EyebrowLeafLink{
+        color:#000;
+    }
+/* End Eyebrow Section */
+
+/********************************
+Name: Pager
+Root: #Pager
+Description: The common paging control, used for browsing pages of search results
+********************************/
+#Pager {
+}
+    #Pager div{
+        display:inline;
+    }
+/* End Pager Section */
+
+/********************************
+
+Name: Profile User Card
+Root: #dashboardPage #userCard
+Description: Elements in the profile usercard control
+
+********************************/
+    #dashboardPage #userCard .profile-usercard-inline {
+        margin: 5px 0 10px 0;
+    }
+
+   /* #dashboardPage #userCard .profile-usercard {
+        width: 288px;
+    }
+/* End Profile User Card Section */
+
+/********************************
+
+Name: Discussion 
+Root: #DiscussionsTabPane
+Description: Defines the layout of the dicussion 
+
+
+********************************/
+#DiscussionsTabPane {
+}
+
+    #DiscussionsTabPane .itemHidden
+    {
+        background: lightgrey;
+    }
+
+    #discussionListItem {
+    }
+
+        .discussion .postActions
+        {
+            float: right;
+        }
+
+        #discussionListItem .postItem
+        {
+            white-space: pre-wrap;
+            word-wrap: break-word;
+            font-size:1em;
+        }
+
+/* End Discussion Section */
+
+
+/********************************
+
+Name: SearchDefaultLocale
+Root: .searchDefaultLocale
+Description: Defines the layout of the include english result checkbox on the Browse Page
+
+
+********************************/
+.searchDefaultLocale
+{
+    float: right;
+    margin: 20px 0 0 5px;
+}
+    .searchDefaultLocale input
+    {
+        vertical-align:top;
+    }
+    .searchDefaultLocale span
+    {
+        margin-left: -3px;
+    }
+/*-------- End SearchDefaultLocale --------*/
+
+
+/********************************
+
+Name: SideNav
+Root: #sideNav
+Description: Defines the layout of the naviation elements on the side of the Browse Page
+             These represent the different filters like Code Language, Category and Tag
+
+
+********************************/
+
+#sideNav {
+    width: 250px;
+    vertical-align:top;
+    background-color:#eee;
+}
+    #sideNav h3 {
+    }
+
+    #sideNav .section {
+        padding: 0 0 10px 0;
+        position: relative;
+    }
+
+        #sideNav .section a {
+        }
+
+        #sideNav .section a:hover {
+        }
+
+        #sideNav .section > div {
+            padding:5px 5px 5px 0;
+            line-height:150%;
+        }
+
+        #sideNav .section ul {
+            list-style-type:none;
+            padding:0px;
+            margin:0px;
+        }
+
+            #sideNav .section ul  li {
+                position: relative;
+                padding: 5px 5px 5px 0;
+            }
+    
+                #sideNav .section ul li .selectedFilter {
+                    float: left;
+                    padding-right: 5px;
+                }
+
+        #sideNav .section div.itemCount {
+            float: right;
+        }
+
+        #sideNav .section form input[ type = "checkbox"] {
+            margin: 0px 4px 0px 0px;
+            vertical-align: middle; 
+        }
+/* End SideNav Section */
+
+/*----------- Contribution Logos *******/
+.contributionLogo {
+    float: left;
+    position: relative;
+    margin-right: 6px;
+}
+
+.logo_visualstudio {
+    background: transparent url('../common/logos/visualstudio.png') no-repeat;
+    width: 23px;
+    height: 12px;
+    margin-top: 3px;
+}
+.logo_allinonecode {
+    background: transparent url('../common/logos/1code.png') no-repeat;
+    width: 14px;
+    height: 16px;
+}
+.logo_exchange {
+    background: transparent url('../common/logos/exchange.png') no-repeat;
+    width: 14px;
+    height: 16px;
+}
+.logo_ie {
+    background: transparent url('../common/logos/ie.png') no-repeat;
+    width: 16px;
+    height: 16px;
+}
+.logo_office {
+    background: transparent url('../common/logos/office.png') no-repeat;
+    width: 17px;
+    height: 16px;
+}
+.logo_windows {
+    background: transparent url('../common/logos/windows.png') no-repeat;
+    width: 17px;
+    height: 16px;
+    }
+.logo_azure {
+    background: transparent url('../common/logos/windowsazuredark.png') no-repeat;
+    width: 16px;
+    height: 16px;
+}
+
+.logo_windowsphone {
+    background: transparent url('../common/logos/windowsphone.png') no-repeat;
+    width: 16px;
+    height: 16px;
+    }
+
+    .contributionLogoTip {
+        position: absolute;
+        display: none;
+        border: solid 1px #CCC;
+        color: #333;
+        background-color: #F0F0F0;
+        font-size: 11px;
+        font-family: "Segoe UI",Sans-Serif;
+        box-shadow: 3px 3px 5px #888;
+        -moz-box-shadow: 3px 3px 5px #888;
+        z-index: 1003;
+        padding: 5px;
+        min-width: 250px;
+    }
+
+/*----------- End Contribution Logos *******/
+
+.clear
+{
+    clear: both;
+}
+
+.customcontributionLogoTip {
+        position: absolute;
+        display: none;
+        border: solid 1px #CCC;
+        background-color: white;
+        color: #333;
+        font-size: 11px;
+        font-family: "Segoe UI",Sans-Serif;
+        box-shadow: 3px 3px 5px #888;
+        -moz-box-shadow: 3px 3px 5px #888;
+        z-index: 1004;
+        padding: 5px;
+        min-width: 250px;
+}
+
+.customcontributionTittle {
+    font-size: 14px;
+    margin-left: 90px;
+}
+
+.customcontributionDiscription {
+    font-size: 13px;
+    margin: 10px 5px;
+    text-align: justify;
+}
+
+.customcontribution {
+    float: left;
+    position: relative;
+    margin-right: 6px;
+}
+
+.customcontributionLink {
+    margin-left: 5px;
+}
+
+.customcontributionlogo {
+    float: left;
+    padding: 0 10px;
+    margin: 0;
+    width: 70px;
+    height: 70px;
+    background-repeat: no-repeat; 
+}
+
+
+.logo_azure_large {
+    background-image:  url('../common/logos/windowsazure_large.png');
+}
+.logo_visualstudio_large {
+    background-image:  url('../common/logos/visualstudio_large.png');
+}
+.logo_exchange_large {
+    background-image:  url('../common/logos/exchange_large.png');
+}
+.logo_ie_large {
+    background-image:  url('../common/logos/ie_large.png');
+}
+.logo_office_large {
+    background-image:  url('../common/logos/office_large.png');
+}
+.logo_windows_large {
+    background-image:  url('../common/logos/windows_large.png');
+}
+.logo_windowsphone_large {
+    background-image:  url('../common/logos/windowsphone_large.png');
+}
+
+/* Custome Header */
+.dirSubHeading .windowssdk .container
+{
+    background: #FF3300 url('wpappsbackground.png') no-repeat;    
+    color: white;
+    padding: 8px 10px 18px 170px;   
+}
+
+.dirSubHeading .windowssdk .container h1, .dirSubHeading .windowssdk .container h2 {
+    color: white !important;
+}
+
+.dirSubHeading .windowssdk .container p {
+    margin: 20px 0 0 0 !important;
+}
+
+.dirSubHeading .windowssdk .container a {
+    background-color:#ffd800;
+    color: #2a2a2a !important; 
+    cursor:pointer; 
+    font-size:13px; 
+    font-family:'Segoe UI Semibold','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif; 
+    padding:4px 12px 6px;
+}
+
+
+
diff --git a/samples/winrt/ImageManipulations/description/Layout.css b/samples/winrt/ImageManipulations/description/Layout.css
new file mode 100644
index 000000000..625f77763
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/Layout.css
@@ -0,0 +1,147 @@
+#container {
+    min-height: 768px;
+}
+
+#leftSubHeaderContainer
+{
+    margin-top:20px;
+}
+
+#title h1
+{
+    font-size:25px;
+}
+
+#subtitle h2
+{
+    font-size:15px;
+}
+
+#subtitle
+{
+    margin-left:10px;
+}
+
+
+#formContainer
+{
+    margin-left:10px;
+    margin-top:30px;
+}
+
+.formLabel
+{
+    float:left;
+    width: 250px;
+}
+
+.formRow
+{
+    clear:both;
+    padding: 10px 0 10px 10px; 
+}
+
+
+.formRecaptchaRow
+{
+    clear:both;
+    float:left;
+    margin-top:20px;
+    margin-left:10px; 
+    margin-bottom:20px;   
+}
+
+.formSubmitRow
+{
+    clear:both;
+    margin-top:20px;
+    margin-left:300px; 
+    margin-bottom:20px;
+}
+
+.formControl {
+    width:300px;
+    float:left;
+}
+.formControl .textInput
+{
+    width:300px;
+}
+
+.formControl textarea
+{
+    width:425px;
+    height:100px;
+}
+
+.formControl .tag
+{
+    width:425px;
+}
+
+.formControl .richText
+{
+    margin-top:10px;
+    width:500px;
+    height:440px;
+}
+
+.formWideLabel
+{
+    width:500px;
+}
+
+.formBigLabel
+{
+    margin-top:20px;
+    font-size:20px;
+}
+
+.formControlBelow
+{
+    clear:both;
+    margin-top:10px;
+    width:500px;
+}
+
+.required
+{
+    color: Red;
+}
+.helpText
+{
+    color: #9D9D9D;
+    font-style: italic;
+}
+
+#agreementSummary
+{
+    clear:both;
+    margin-top:10px;
+    width:800px;
+}
+
+.field-validation-error, .validation-summary-errors
+{
+    color: #FF0000;
+    font-weight: bold;
+}
+
+.tinyMCETemplate {
+    position: relative;
+    left: 400px;
+    width: 300px;
+    max-height: 300px;
+    overflow: auto;
+}
+
+.IE6 .tinyMCETemplate {
+    left: 25px;
+}
+
+.ownerBar {
+    padding: 5px;
+}
+.ownerBar .ownerBarOptions {
+    float: right;
+}
diff --git a/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css b/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
new file mode 100644
index 000000000..e3f039dfb
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
@@ -0,0 +1,303 @@
+/*Global*/
+h1 {
+    font-size: 36px;
+    font-family: 'Segoe UI Light';
+    color: #707070;
+    font-weight: normal;
+    margin-bottom: 17px !important;
+}
+
+h2, h3, h4, h5, h6, #searchPage h3 {
+    font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
+    font-weight:normal;
+    color: #2A2A2A !important;
+}
+
+a, a:link, a:visited {
+    color: #0095c4;
+}
+
+body {
+    color:#707070;
+}
+
+.profile-usercard {
+    color:#707070 !important;
+}
+
+/*temporary setting to override msdn_windows.css
+can remove once conflicting settings are removed from that file*/
+
+
+.LocalNavigation, .LocalNavigation .TabOn, .LocalNavigation .TabOn:hover, .LocalNavigation .TabOff, .LocalNavigation .TabOff a:hover {
+    display: block;
+    background-color:transparent !important;
+    color: #0095c4;
+}
+
+.LocalNavigation .TabOff a {
+color:#707070 ;
+}
+
+/*End Global*/
+
+.EyebrowContainer 
+{
+    margin-bottom: 0 !important;
+}
+
+#sideNav
+{
+    width: 215px !important;
+}
+
+#searchPage #mainContentContainer
+{
+    margin-right:0 !important;
+    margin-left:243px !important;
+}
+
+#searchPage .dirSubHeading h2 
+{
+    font-size: 14px !important;
+    font-weight: normal !important;
+    color: #454545 !important;
+    line-height: 1.45;
+}
+
+#searchPage #directoryListFooter, #searchPage #Pager {
+    font-size: 14px;
+}
+
+#searchPage h2, #searchPage h3
+{
+    font-size: 1.25em  !important;
+}
+
+#sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
+{
+    font-size: 1.65em !important;
+}
+
+.subMenu > h2
+{
+    font-family: 'Segoe UI Light','Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
+    font-weight:normal;
+    font-size:30px;
+    margin: 15px 10px 5px 0;
+    padding-bottom:0px;
+}
+
+.itemRow {
+}
+    .itemRow .itemBody, .itemRow .itemInfo {
+        padding: 18px 17px 20px 0;
+         font-size: 14px;
+         line-height: 1.45em;
+    }
+
+    .itemRow .itemTitle {
+        font-weight: normal;
+    }
+
+    .itemRow .summaryBox{
+        color: #454545;
+    }
+
+    .Samples #MainContent .itemRow .itemTitle a {
+        font-weight: 600 !important;
+        line-height: 1.45;
+    }
+    #MainContent a.officialMicrosoftLabel
+    {
+        color: #ACACAC;
+    }
+
+
+.tabContents {
+    border-top-width:0px;
+}
+   
+#UploadPage {
+    margin: 0px 0px 0px 10px;
+}
+    #UploadPage h1 {
+        padding: 0;
+        font-size: 22px;
+    }
+    #UploadPage h2 {
+        color:#F39700 !important;
+    }
+
+    #UploadPage #uploadPageInstruction {
+        margin-top:10px;
+    }
+        
+    #UploadPage fieldset {
+        margin-left:0px;
+    }
+
+    #UploadPage fieldset h2 {
+        font-weight:normal;
+    }
+
+    #UploadPage fieldset#uploadsForm{
+        margin-top:25px;
+    }
+    
+    #UploadPage fieldset#summary textarea {
+        margin-left:0px;
+    }
+
+    #UploadPage .projectTypeChoice > div {
+        height: 250px;
+    }
+
+#sideNav {
+}
+
+    #sideNav .section h3 {
+        background-color: transparent;
+
+    }
+
+    #sideNav .section UL LI {
+        border-bottom-width: 0px;
+    }
+
+    #sideNav .section form > div {
+        border-bottom: none;
+        color: #707070;
+    }
+        #sideNav .section ul li > div.itemCount
+        {
+            color: #707070;
+        }
+
+
+#searchPage {
+}
+
+    #searchPage h2, #searchPage h3 {
+        text-transform:none;
+        background-color:transparent;
+        font-weight:normal;
+        font-size:1.2em;
+    }
+
+    #searchPage .browseFilterBar {
+        background-color:transparent;
+        border-width:0px;
+        font-weight:normal;
+    }
+
+#requestsPage {
+    padding-top:15px;
+}
+    #requestsPage .tabHeaders {
+        overflow: visible;
+    }
+
+    #requestsPage #requestsList {
+        border: none;
+    }
+
+
+    #requestsPage h2, #requestsPage h3 {
+        text-transform:none;
+        background-color:transparent;
+        font-weight:normal;
+        font-size:1.2em;
+    }
+
+    .reqBrowseContent .title {
+        font-weight: bold !important;
+        color:#000 !important;
+        font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
+    }
+
+    .reqDescPage #header #votenumber {
+        height: 30px;
+        padding: 9px 12px 3px 12px;
+    }
+
+#extraActions {
+}
+    #extraActions .section
+    {
+        margin-bottom: 10px;
+    }
+    #extraActions .section a
+    {
+        font-weight:normal;
+    }
+
+    #extraActions #contributeSection div img {
+        width:0px;
+    }
+
+
+
+#projectPage {
+}
+
+    #projectPage .projectTitle {
+        color: #707070;
+        margin: 5px 0px 15px 0px;
+    }
+
+    #projectPage h2.projectSummary, #projectPage #projectInfo, #projectPage .tabHeaders {
+        font-size: 14px !important;
+        line-height: 1.45em;
+        color: #454545 !important;
+        font-weight: normal !important;
+    }
+
+    #projectPage #projectInfo a {
+        color: #00749e;
+    }
+
+    #projectPage #Downloads a, #projectPage #Downloads label {
+        font-size: 14px;
+    }
+
+    #projectPage #reportAbuse {
+        font-size: 1em;
+    }
+
+    #projectPage #publishBar a, #projectPage #publishBar a:visited {
+        color: #0095c4;
+        font-weight: normal;
+    }
+
+    #projectPage #Collections .bevelButton{
+        background-color: #F8F8F8;
+        color: #0095C4;
+        border: 1px solid #707070;
+    }
+
+    #projectPage #DiscussionsTabPane .threadHeader .title {
+        font-weight:bold !important;
+        color:Black !important;#F8F8F8;
+        font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
+    }
+
+    #projectPage .sidebar .section .titleBar h3 {
+        font-weight:normal;
+        font-size:1.2em;
+    }
+
+#LocalNav {
+}
+
+    #LocalNav.HeaderTabs {
+        margin-left:11px;
+    }
+
+
+#searchPage .dirSubHeading h1
+{
+    margin-bottom:17px !important;
+}
+
+
diff --git a/samples/winrt/ImageManipulations/description/iframedescription.css b/samples/winrt/ImageManipulations/description/iframedescription.css
new file mode 100644
index 000000000..9abc9cdb3
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/iframedescription.css
@@ -0,0 +1,179 @@
+body {
+    color: #000000;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 0.813em;
+    font-style: normal;
+    word-wrap: break-word;
+}
+
+/*BEGIN HEADERS*/
+.h1, h1 {
+    color: #3A3E43;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 1.4em;
+    font-weight: bold;
+    margin: 0;
+}
+
+.h2, h2 {
+    color: #3A3E43;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 1.2em;
+    font-weight: bold;
+}
+.h3, h3 {
+    color: #3A3E43;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 1.077em;
+    font-weight: bold;
+}
+.h4, h4 {
+    color: #3A3E43;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 1em;
+    font-weight: bold;
+}
+h4.subHeading {
+    margin-bottom: 7px;
+    margin-top: 13px;
+}
+/*END HEADERS*/
+
+/*BEGIN LINKS*/
+a:link {
+    color: #00749E;
+    text-decoration: none;
+}
+a:hover {
+    text-decoration: underline;
+}
+a:visited {
+    color: #960BB4;
+    text-decoration: none;
+}
+a:focus {
+    outline: 1px dotted #000000;
+}
+
+a.libraryLink:link {
+    text-decoration:none;
+    border-bottom:1px dotted;
+}
+
+/*END LINKS*/
+
+/*BEGIN IMAGES*/
+img {
+    border: 0 none;
+}
+/*END IMAGES*/
+
+/*BEGIN TABLE*/
+.title table {
+    color: #000000;
+    font-family: 'Segoe UI',Verdana,Arial;
+    font-size: 1.077em;
+    font-style: normal;
+}
+table {
+    border-collapse: collapse;
+}
+
+table, table th, table td {
+    border:1px solid #BBBBBB;
+}
+/*END TABLE*/
+
+/*BEGIN LIST*/
+ul {
+    list-style-type: disc;
+    margin-left:40px;
+    padding-left: 0;
+}
+ul li {
+    padding-bottom: 10px;
+}
+ol {
+    margin-left:40px;
+    padding-left: 0;
+}
+ol li {
+    padding-bottom: 10px;
+}
+/*END LIST*/
+
+.scriptcode {
+    position: relative;
+    padding: 8px 8px 8px 8px;
+    background: #FFFFFF;
+    font-size: 12px;
+    line-height: 125%;
+    font-weight:normal;
+}
+.scriptcode pre 
+{ 
+    white-space: pre-wrap !important;       /* css-3 */
+    word-wrap: break-word !important;       /* Internet Explorer 5.5+ */
+    margin:0 0 10px 0 !important;
+    padding: 10px;
+    border-top: solid 2px #D0D2D2;
+    border-bottom: solid 2px #D0D2D2;
+    border-left: solid 1px #D0D2D2;
+    border-right: solid 1px #D0D2D2;
+}
+            
+.scriptcode .title { 
+    color:#E66A38;
+    font-size: 12px;
+    font-weight:bold;
+    margin: 0;
+    min-height: 23px;
+}
+.scriptcode .title > span:first-child {
+    border-left: solid 1px #D0D2D2;
+}
+.scriptcode .title > span {
+    padding: 4px 8px 4px 8px;
+    display: inline-block;
+    border-top: 1px solid #D0D2D2;
+    border-right: 1px solid #D0D2D2;
+    border-collapse: collapse;
+    text-align: center;
+    background: white;
+}
+.scriptcode .title > span.otherTab {
+    color: #1364C4;
+    background: #EFF5FF;
+    cursor: pointer;
+}
+
+.scriptcode .hidden {
+    display: none !important;
+    visibility: hidden !important;
+}
+
+.scriptcode  .copyCode {
+    padding: 8px 2px 0 2px !important;
+    margin-right: 15px;
+    position: absolute !important;
+    right: 0 !important;
+    top: 17px;
+    display:block !important;
+    background: #FFFFFF;
+}
+.scriptcode .pluginLinkHolder {
+    display: none;
+}
+.scriptcode .pluginEditHolderLink {
+    display: none;
+}
+
+.Opera wbr
+{
+    display: inline-block;
+}
+
+.IE9 wbr:after
+{
+content: "\00200B"; 
+}
diff --git a/samples/winrt/ImageManipulations/description/offline.js b/samples/winrt/ImageManipulations/description/offline.js
new file mode 100644
index 000000000..f5d07c8af
--- /dev/null
+++ b/samples/winrt/ImageManipulations/description/offline.js
@@ -0,0 +1,52 @@
+var Galleries = Galleries || { };
+
+(function() {
+
+    function findElem(parent, tagName, className) {
+        var elemToSearch = (parent) ?  parent : document.body;
+        var tagMatch = elemToSearch.getElementsByTagName(tagName);
+        var evaluator = function(elem) {
+            return (className) ? (elem.className.indexOf(className) > -1) : true;
+        };
+
+        return findArrayElem(tagMatch, evaluator);
+    }
+
+    function findArrayElem(array, evaluator) {
+        var newArray = new Array();
+        for (var count = 0; count < array.length; count++) {
+            if (evaluator(array[count])) {
+                newArray.push(array[count]);
+            }
+        }
+        return newArray;
+    }
+
+    function iterateElem(elems, delegate) {
+        for(var count = 0; count < elems.length; count++) {
+            delegate(count, elems[count]);
+        }
+    }
+
+    function isHidden(elem) {
+        return (elem.offsetHeight === 0 && elem.offsetWidth === 0) || elem.style && elem.style.display === "none";
+    }
+    
+    function onWindowLoad(callback) {
+        attachEventHandler(null, 'load', callback);
+    }
+ 
+    function attachEventHandler(elem, event, callback) {
+        var elemToAttach = (elem) ? elem : window;
+        if (document.addEventListener) {
+			elemToAttach.addEventListener(event, callback, false);
+		} else if ( document.attachEvent ) {
+			elemToAttach.attachEvent('on' + event, callback);
+		}
+    }
+
+    Galleries.findElem = findElem;
+    Galleries.iterateElem = iterateElem;
+    Galleries.attachEventHandler = attachEventHandler;
+    Galleries.onWindowLoad = onWindowLoad;
+})();
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/license.rtf b/samples/winrt/ImageManipulations/license.rtf
new file mode 100644
index 000000000..690a7ad07
--- /dev/null
+++ b/samples/winrt/ImageManipulations/license.rtf
@@ -0,0 +1,25 @@
+{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 MS Shell Dlg;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs16\f2\cf0 \cf0\ql{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
+{\fs40\f2 {\ltrch MICROSOFT LIMITED PUBLIC LICENSE version 1.1}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 \line {\ltrch ----------------------}\line \li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch This license governs use of code marked as \ldblquote sample\rdblquote  or \ldblquote example\rdblquote  available on this web site without a license agreement, as provided under the section above titled \ldblquote NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEB SITE.\rdblquote  If you use such code (the \ldblquote software\rdblquote ), you accept this license. If you do not accept the license, do not use the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch 1. Definitions}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch The terms \ldblquote reproduce,\rdblquote  \ldblquote reproduction,\rdblquote  \ldblquote derivative works,\rdblquote  and \ldblquote distribution\rdblquote  have the same meaning here as under U.S. copyright law. }\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch A \ldblquote contribution\rdblquote  is the original software, or any additions or changes to the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch A \ldblquote contributor\rdblquote  is any person that distributes its contribution under this license.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch \ldblquote Licensed patents\rdblquote  are a contributor\rquote s patent claims that read directly on its contribution.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch 2. Grant of Rights}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch 3. Conditions and Limitations}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (A) No Trademark License- This license does not grant you rights to use any contributors\rquote  name, logo, or trademarks.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (E) The software is licensed \ldblquote as-is.\rdblquote  You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 {\ltrch (F) Platform Limitation - The licenses granted in sections 2(A) and 2(B) extend only to the software or derivative works that you create that run directly on a Microsoft Windows operating system product, Microsoft run-time technology (such as the .NET Framework or Silverlight), or Microsoft application platform (such as Microsoft Office or Microsoft Dynamics).}\li0\ri0\sa0\sb0\fi0\ql\par}
+{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
+}
+}
\ No newline at end of file

From 9e06287121155f1312cc64a23a5e56bf08ffcfad Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 24 Jun 2013 02:32:57 -0700
Subject: [PATCH 32/75] Windows RT sample updated.

Unused scenarious removed.
Grey scale convertion replaced with cv::Canny call.
---
 platforms/scripts/cmake_winrt.cmd             |   2 +-
 platforms/winrt/arm.winrt.toolchain.cmake     |  13 +-
 .../ImageManipulations/C++/AudioCapture.xaml  |  62 --
 .../C++/AudioCapture.xaml.cpp                 | 366 ------------
 .../C++/AudioCapture.xaml.h                   |  70 ---
 .../ImageManipulations/C++/BasicCapture.xaml  |  87 ---
 .../C++/BasicCapture.xaml.cpp                 | 535 ------------------
 .../C++/BasicCapture.xaml.h                   |  88 ---
 .../ImageManipulations/C++/Constants.cpp      |   2 -
 .../winrt/ImageManipulations/C++/Constants.h  |   2 +-
 .../ImageManipulations/C++/MainPage.xaml      |   6 +-
 .../C++/MediaCapture.vcxproj                  | 160 +++++-
 .../C++/MediaCapture.vcxproj.filters          |  25 +-
 .../MediaExtensions/Grayscale/Grayscale.cpp   | 250 +-------
 .../C++/MediaExtensions/Grayscale/Grayscale.h |  34 +-
 .../Grayscale/Grayscale.vcxproj               |  20 +-
 16 files changed, 221 insertions(+), 1501 deletions(-)
 delete mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml
 delete mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
 delete mode 100644 samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
 delete mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml
 delete mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
 delete mode 100644 samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h

diff --git a/platforms/scripts/cmake_winrt.cmd b/platforms/scripts/cmake_winrt.cmd
index aafed7d09..c6d8cb8e0 100644
--- a/platforms/scripts/cmake_winrt.cmd
+++ b/platforms/scripts/cmake_winrt.cmd
@@ -3,4 +3,4 @@ cd build
 
 rem call "C:\Program Files\Microsoft Visual Studio 11.0\VC\bin\x86_arm\vcvarsx86_arm.bat"
 
-cmake.exe -GNinja -DCMAKE_BUILD_TYPE=Release -DWITH_FFMPEG=OFF -DBUILD_opencv_gpu=OFF -DBUILD_opencv_python=OFF -DCMAKE_TOOLCHAIN_FILE=..\..\winrt\arm.winrt.toolchain.cmake ..\..\..
+cmake.exe -GNinja -DWITH_TBB=ON -DBUILD_TBB=ON -DCMAKE_BUILD_TYPE=Release -DWITH_FFMPEG=OFF -DBUILD_opencv_gpu=OFF -DBUILD_opencv_python=OFF -DCMAKE_TOOLCHAIN_FILE=..\..\winrt\arm.winrt.toolchain.cmake ..\..\..
diff --git a/platforms/winrt/arm.winrt.toolchain.cmake b/platforms/winrt/arm.winrt.toolchain.cmake
index b34056cd5..ac9af117d 100644
--- a/platforms/winrt/arm.winrt.toolchain.cmake
+++ b/platforms/winrt/arm.winrt.toolchain.cmake
@@ -3,4 +3,15 @@ set(CMAKE_SYSTEM_PROCESSOR "arm-v7a")
 
 set(CMAKE_FIND_ROOT_PATH "${CMAKE_SOURCE_DIR}/platforms/winrt")
 set(CMAKE_REQUIRED_DEFINITIONS -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
-add_definitions(-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
\ No newline at end of file
+add_definitions(-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
+
+set(CMAKE_CXX_FLAGS           ""                    CACHE STRING "c++ flags")
+set(CMAKE_C_FLAGS             ""                    CACHE STRING "c flags")
+
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ZW -EHsc -GS")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -GS")
+
+
+set(CMAKE_SHARED_LINKER_FLAGS "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"                    CACHE STRING "shared linker flags")
+set(CMAKE_MODULE_LINKER_FLAGS "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"                    CACHE STRING "module linker flags")
+set(CMAKE_EXE_LINKER_FLAGS    "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"  CACHE STRING "executable linker flags")
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml
deleted file mode 100644
index be65bcd8c..000000000
--- a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml
+++ /dev/null
@@ -1,62 +0,0 @@
-<!--
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
--->
-
-<common:LayoutAwarePage
-    x:Class="SDKSample.MediaCapture.AudioCapture"
-    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-    xmlns:local="using:$rootsnamespace$"
-    xmlns:common="using:SDKSample.Common"
-    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
-    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-    mc:Ignorable="d">
-
-    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
-        <Grid.RowDefinitions>
-            <RowDefinition Height="Auto"/>
-            <RowDefinition Height="*"/>
-        </Grid.RowDefinitions>
-        <Grid x:Name="Input" Grid.Row="0">
-            <Grid.RowDefinitions>
-                <RowDefinition Height="Auto"/>
-                <RowDefinition Height="*"/>
-            </Grid.RowDefinitions>
-          <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left"  >
-            This scenario shows how to do an audio only capture using the default microphone. Click on StartRecord to start recording.
-          </TextBlock>
-          <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
-            <Button x:Name="btnStartDevice3" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>            
-            <Button x:Name="btnStartStopRecord3" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>            
-          </StackPanel>
-        </Grid>
-
-        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
-          <StackPanel>
-            <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Audio' />
-            <Canvas x:Name='playbackCanvas3' Width='320' Height ='240' >
-              <MediaElement  x:Name='playbackElement3'	  Width="320"  Height="240" Margin="10,5,10,5"/>
-            </Canvas>
-          </StackPanel>
-        </Grid>
-
-        <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts -->
-        <VisualStateManager.VisualStateGroups>
-            <VisualStateGroup>
-                <VisualState x:Name="FullScreenLandscape"/>
-                <VisualState x:Name="Filled"/>
-                <VisualState x:Name="FullScreenPortrait"/>
-                <VisualState x:Name="Snapped"/>
-            </VisualStateGroup>
-        </VisualStateManager.VisualStateGroups>
-    </Grid>
-
-</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
deleted file mode 100644
index 37fc379d3..000000000
--- a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
-
-//
-// AudioCapture.xaml.cpp
-// Implementation of the AudioCapture class
-//
-
-#include "pch.h"
-#include "AudioCapture.xaml.h"
-#include <ppl.h>
-using namespace concurrency;
-
-using namespace SDKSample::MediaCapture;
-
-using namespace Windows::UI::Xaml;
-using namespace Windows::UI::Xaml::Navigation;
-using namespace Windows::UI::Xaml::Data;
-using namespace Windows::System;
-using namespace Windows::Foundation;
-using namespace Platform;
-using namespace Windows::UI;
-using namespace Windows::UI::Core;
-using namespace Windows::UI::Xaml;
-using namespace Windows::UI::Xaml::Controls;
-using namespace Windows::UI::Xaml::Data;
-using namespace Windows::UI::Xaml::Media;
-using namespace Windows::Storage;
-using namespace Windows::Media::MediaProperties;
-using namespace Windows::Storage::Streams;
-using namespace Windows::System;
-using namespace Windows::UI::Xaml::Media::Imaging;
-
-
-AudioCapture::AudioCapture()
-{
-    InitializeComponent();
-    ScenarioInit();
-}
-
-/// <summary>
-/// Invoked when this page is about to be displayed in a Frame.
-/// </summary>
-/// <param name="e">Event data that describes how this page was reached.  The Parameter
-/// property is typically used to configure the page.</param>
-void AudioCapture::OnNavigatedTo(NavigationEventArgs^ e)
-{
-    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
-    // as NotifyUser()
-    rootPage = MainPage::Current;
-    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AudioCapture::SoundLevelChanged);
-}
-
-void AudioCapture::OnNavigatedFrom(NavigationEventArgs^ e)
-{
-    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
-    // as NotifyUser()
-    Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
-}
-
-void  AudioCapture::ScenarioInit()
-{
-    try
-    {
-        rootPage = MainPage::Current;
-        btnStartDevice3->IsEnabled = true;
-        btnStartStopRecord3->IsEnabled = false;
-        m_bRecording = false;
-        playbackElement3->Source = nullptr;
-        m_bSuspended = false;
-        ShowStatusMessage("");
-    }
-    catch (Exception ^e)
-    {
-        ShowExceptionMessage(e);
-    }
-
-}
-
-void AudioCapture::ScenarioReset()
-{
-    ScenarioInit();
-}
-
-
-void AudioCapture::SoundLevelChanged(Object^ sender, Object^ e)
-{
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
-    {    
-        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
-        {
-            ScenarioReset();
-        }
-        else
-        {
-            if (m_bRecording)
-            {
-                ShowStatusMessage("Stopping Record on invisibility");
-
-                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                {
-                    try
-                    {
-                        recordTask.get();
-                        m_bRecording = false;
-                    }catch (Exception ^e)
-                    {
-                        ShowExceptionMessage(e);
-                    }
-                });
-            }
-        }
-    })));
-}
-
-void AudioCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
-{
-    try
-    {
-        if (m_bRecording)
-        {
-            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this](){
-                try
-                {
-                    ShowStatusMessage("Stopping Record on exceeding max record duration");
-                    EnableButton(false, "StartStopRecord");
-                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
-                        }
-                        catch (Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                        }
-                    });
-
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-
-            })));
-        }
-    }
-    catch (Exception ^e)
-    {
-        m_bRecording = false;
-        SwitchRecordButtonContent();
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-    }
-}
-
-void AudioCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
-{
-    String ^message = "Fatal error: " + currentFailure->Message;
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, 
-        ref new Windows::UI::Core::DispatchedHandler([this, message]()
-    {
-        ShowStatusMessage(message);
-    })));
-}
-
-void AudioCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        EnableButton(false, "StartDevice");
-        ShowStatusMessage("Starting device");
-        auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
-        m_mediaCaptureMgr = mediaCapture;
-        auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings();
-        settings->StreamingCaptureMode = Windows::Media::Capture::StreamingCaptureMode::Audio;
-        create_task(mediaCapture->InitializeAsync()).then([this](task<void> initTask)
-        {
-            try
-            {
-                initTask.get();
-
-                auto mediaCapture = m_mediaCaptureMgr.Get();
-                EnableButton(true, "StartPreview");
-                EnableButton(true, "StartStopRecord");
-                EnableButton(true, "TakePhoto");
-                ShowStatusMessage("Device initialized successful");
-                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AudioCapture::RecordLimitationExceeded);
-                mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AudioCapture::Failed);
-            }
-            catch (Exception ^ e)
-            {
-                ShowExceptionMessage(e);
-            }
-        });
-    }
-    catch (Platform::Exception^ e)
-    {
-        ShowExceptionMessage(e);
-    }
-}
-
-void AudioCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        String ^fileName;
-        EnableButton(false, "StartStopRecord");
-
-        if (!m_bRecording)
-        {
-            ShowStatusMessage("Starting Record");
-
-            fileName = AUDIO_FILE_NAME;
-
-            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
-            {
-                try
-                {
-                    this->m_recordStorageFile = fileTask.get();
-                    ShowStatusMessage("Create record file successful");
-
-                    MediaEncodingProfile^ recordProfile= nullptr;
-                    recordProfile = MediaEncodingProfile::CreateM4a(Windows::Media::MediaProperties::AudioEncodingQuality::Auto);
-
-                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = true;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-
-                            ShowStatusMessage("Start Record successful");
-
-
-                        }catch (Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                        }
-                    });
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-            }
-            );
-        }
-        else
-        {
-            ShowStatusMessage("Stopping Record");
-
-            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void>)
-            {
-                try
-                {
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    SwitchRecordButtonContent();
-
-                    ShowStatusMessage("Stop record successful");
-                    if (!m_bSuspended)
-                    {
-                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
-                        {
-                            try
-                            {
-                                ShowStatusMessage("Record file opened");
-                                auto stream = streamTask.get();
-                                ShowStatusMessage(this->m_recordStorageFile->Path);
-                                playbackElement3->AutoPlay = true;
-                                playbackElement3->SetSource(stream, this->m_recordStorageFile->FileType);
-                                playbackElement3->Play();
-                            }
-                            catch (Exception ^e)
-                            {
-                                ShowExceptionMessage(e);
-                                m_bRecording = false;
-                                SwitchRecordButtonContent();
-                                EnableButton(true, "StartStopRecord");
-                            }
-                        });
-                    }
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-            });
-        }
-    }
-    catch (Platform::Exception^ e)
-    {
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-        m_bRecording = false;
-        SwitchRecordButtonContent();
-    }
-}
-
-
-void AudioCapture::ShowStatusMessage(Platform::String^ text)
-{
-    rootPage->NotifyUser(text, NotifyType::StatusMessage);
-}
-
-void AudioCapture::ShowExceptionMessage(Platform::Exception^ ex)
-{
-    rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
-}
-
-void AudioCapture::SwitchRecordButtonContent()
-{
-    {
-        if (m_bRecording)
-        {
-            btnStartStopRecord3->Content="StopRecord";
-        }
-        else
-        {
-            btnStartStopRecord3->Content="StartRecord";
-        }
-    }
-}
-void AudioCapture::EnableButton(bool enabled, String^ name)
-{
-    if (name->Equals("StartDevice"))
-    {
-        btnStartDevice3->IsEnabled = enabled;
-    }
-
-    else if (name->Equals("StartStopRecord"))
-    {
-        btnStartStopRecord3->IsEnabled = enabled;
-    }
-
-}
-
diff --git a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
deleted file mode 100644
index b75efdc72..000000000
--- a/samples/winrt/ImageManipulations/C++/AudioCapture.xaml.h
+++ /dev/null
@@ -1,70 +0,0 @@
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
-
-//
-// AudioCapture.xaml.h
-// Declaration of the AudioCapture class
-//
-
-#pragma once
-
-#include "pch.h"
-#include "AudioCapture.g.h"
-#include "MainPage.xaml.h"
-
-#define AUDIO_FILE_NAME "audio.mp4"
-
-namespace SDKSample
-{
-    namespace MediaCapture
-    {
-        /// <summary>
-        /// An empty page that can be used on its own or navigated to within a Frame.
-        /// </summary>
-    	[Windows::Foundation::Metadata::WebHostHidden]
-        public ref class AudioCapture sealed
-        {
-        public:
-            AudioCapture();
-    
-        protected:
-            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
-            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
-        private:
-            MainPage^ rootPage;
-    
-            void ScenarioInit();
-            void ScenarioReset();
-    
-            void SoundLevelChanged(Object^ sender, Object^ e);
-            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
-            void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
-    
-            void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void ShowStatusMessage(Platform::String^ text);
-            void ShowExceptionMessage(Platform::Exception^ ex);
-    
-            void EnableButton(bool enabled, Platform::String ^name);
-            void SwitchRecordButtonContent();
-    
-            Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
-            Windows::Storage::StorageFile^ m_photoStorageFile;
-            Windows::Storage::StorageFile^ m_recordStorageFile;
-            bool m_bRecording;
-            bool m_bSuspended;
-            Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
-        };
-    }
-}
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml
deleted file mode 100644
index 2cc0b0a5f..000000000
--- a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml
+++ /dev/null
@@ -1,87 +0,0 @@
-<!--
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
--->
-
-<common:LayoutAwarePage
-    x:Class="SDKSample.MediaCapture.BasicCapture"
-    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-    xmlns:local="using:$rootsnamespace$"
-    xmlns:common="using:SDKSample.Common"
-    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
-    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-    mc:Ignorable="d">
-
-    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">
-        <Grid.RowDefinitions>
-            <RowDefinition Height="Auto"/>
-            <RowDefinition Height="*"/>
-        </Grid.RowDefinitions>
-        <Grid x:Name="Input" Grid.Row="0">
-            <Grid.RowDefinitions>
-              <RowDefinition Height="Auto"/>
-              <RowDefinition Height="Auto"/>
-                <RowDefinition Height="*"/>
-            </Grid.RowDefinitions>
-            <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" >
-              This scenario demonstrates how to use the MediaCapture API to preview the camera stream, record a video, and take a picture using default initialization settings.
-              You can also adjust the brightness and contrast.
-            </TextBlock>
-            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
-              <Button x:Name="btnStartDevice1" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>
-              <Button x:Name="btnStartPreview1" Click="btnStartPreview_Click" IsEnabled="true"  Margin="0,0,10,0">StartPreview</Button>
-              <Button x:Name="btnStartStopRecord1" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>
-              <Button x:Name="btnTakePhoto1" Click="btnTakePhoto_Click" IsEnabled="false"  Margin="0,0,10,0">TakePhoto</Button>                        
-            </StackPanel>
-          <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="2">
-            <TextBlock TextWrapping="Wrap" Text="Brightness" Style="{StaticResource BasicTextStyle}"  Margin="0,0,10,0" VerticalAlignment="Center"/>
-            <Slider x:Name="sldBrightness"   IsEnabled="False" ValueChanged="sldBrightness_ValueChanged"  Width="207" Margin="0,0,10,0"/>
-            <TextBlock TextWrapping="Wrap" Text="Contrast" Style="{StaticResource BasicTextStyle}"  Margin="0,0,10,0" VerticalAlignment="Center" />
-            <Slider x:Name="sldContrast"   IsEnabled="False" ValueChanged="sldContrast_ValueChanged"  Width="207"  Margin="0,0,10,0"/>
-          </StackPanel>
-        </Grid>
-
-        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
-          <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
-            <StackPanel>
-              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Preview' />
-              <Canvas x:Name="previewCanvas1" Width="320"  Height="240" Background="Gray">
-                <CaptureElement x:Name="previewElement1" Width="320" Height="240" />
-              </Canvas>
-            </StackPanel>
-            <StackPanel>
-              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Video' />
-              <Canvas x:Name='playbackCanvas1' Width='320' Height ='240' >
-                <MediaElement  x:Name='playbackElement1'	  Width="320"  Height="240" />
-              </Canvas>
-            </StackPanel>
-            <StackPanel>
-              <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Images' />
-              <Canvas x:Name="imageCanvas1" Width='320' Height ='240' >
-                <Image x:Name="imageElement1"  Width="320"   Height="240"/>
-              </Canvas>
-            </StackPanel>
-          </StackPanel>
-
-        </Grid>
-
-        <!-- Add Storyboards to the visual states below as necessary for supporting the various layouts -->
-        <VisualStateManager.VisualStateGroups>
-            <VisualStateGroup>
-                <VisualState x:Name="FullScreenLandscape"/>
-                <VisualState x:Name="Filled"/>
-                <VisualState x:Name="FullScreenPortrait"/>
-                <VisualState x:Name="Snapped"/>
-            </VisualStateGroup>
-        </VisualStateManager.VisualStateGroups>
-    </Grid>
-
-</common:LayoutAwarePage>
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
deleted file mode 100644
index f385fa9a7..000000000
--- a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.cpp
+++ /dev/null
@@ -1,535 +0,0 @@
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
-
-//
-// BasicCapture.xaml.cpp
-// Implementation of the BasicCapture class
-//
-
-#include "pch.h"
-#include "BasicCapture.xaml.h"
-#include "ppl.h"
-
-using namespace Windows::System;
-using namespace Windows::Foundation;
-using namespace Platform;
-using namespace Windows::UI;
-using namespace Windows::UI::Core;
-using namespace Windows::UI::Xaml;
-using namespace Windows::UI::Xaml::Controls;
-using namespace Windows::UI::Xaml::Navigation;
-using namespace Windows::UI::Xaml::Data;
-using namespace Windows::UI::Xaml::Media;
-using namespace Windows::Storage;
-using namespace Windows::Media::MediaProperties;
-using namespace Windows::Storage::Streams;
-using namespace Windows::System;
-using namespace Windows::UI::Xaml::Media::Imaging;
-
-using namespace SDKSample::MediaCapture;
-using namespace concurrency;
-
-
-BasicCapture::BasicCapture()
-{
-    InitializeComponent();
-    ScenarioInit();
-}
-
-/// <summary>
-/// Invoked when this page is about to be displayed in a Frame.
-/// </summary>
-/// <param name="e">Event data that describes how this page was reached.  The Parameter
-/// property is typically used to configure the page.</param>
-void BasicCapture::OnNavigatedTo(NavigationEventArgs^ e)
-{
-    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
-    // as NotifyUser()
-    rootPage = MainPage::Current;
-    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &BasicCapture::SoundLevelChanged);
-}
-
-void BasicCapture::OnNavigatedFrom(NavigationEventArgs^ e)
-{
-    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
-    // as NotifyUser()
-
-    Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken;
-    m_currentScenarioLoaded = false;
-}
-
-
-void  BasicCapture::ScenarioInit()
-{
-    try
-    {
-        btnStartDevice1->IsEnabled = true;
-        btnStartPreview1->IsEnabled = false;
-        btnStartStopRecord1->IsEnabled = false;
-        m_bRecording = false;
-        m_bPreviewing = false;
-        btnStartStopRecord1->Content = "StartRecord";
-        btnTakePhoto1->IsEnabled = false;
-        previewElement1->Source = nullptr;
-        playbackElement1->Source = nullptr;
-        imageElement1->Source= nullptr;
-        sldBrightness->IsEnabled = false;
-        sldContrast->IsEnabled = false;
-        m_bSuspended = false;
-        previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
-
-    }
-    catch (Exception ^e)
-    {
-        ShowExceptionMessage(e);
-    }
-
-}
-
-void BasicCapture::ScenarioReset()
-{
-    previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
-    ScenarioInit();
-}
-
-void BasicCapture::SoundLevelChanged(Object^ sender, Object^ e)
-{
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
-    {    
-        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
-        {
-            ScenarioReset();
-        }
-        else
-        {
-            if (m_bRecording)
-            {
-                ShowStatusMessage("Stopping Record on invisibility");
-
-                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                {
-                    m_bRecording = false;
-                });
-            }
-            if (m_bPreviewing)
-            {
-                ShowStatusMessage("Stopping Preview on invisibility");
-
-                create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
-                {
-                    try
-                    {
-                        previewTask.get();
-                        m_bPreviewing = false;
-                    }
-                    catch (Exception ^e)
-                    {
-                        ShowExceptionMessage(e);
-                    }
-                });
-            }
-        }
-    })));
-}
-
-void BasicCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
-{
-    try
-    {
-        if (m_bRecording)
-        {
-            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this](){
-                try
-                {
-                    ShowStatusMessage("Stopping Record on exceeding max record duration");
-                    EnableButton(false, "StartStopRecord");
-                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
-                        }
-                        catch (Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                        }
-                    });
-
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-
-            })));
-        }
-    }
-    catch (Exception ^e)
-    {
-        m_bRecording = false;
-        SwitchRecordButtonContent();
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-    }
-}
-
-void BasicCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
-{
-    String ^message = "Fatal error: " + currentFailure->Message;
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
-        ref new Windows::UI::Core::DispatchedHandler([this, message]()
-    {
-        ShowStatusMessage(message);
-    })));
-}
-
-void BasicCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        EnableButton(false, "StartDevice");
-        ShowStatusMessage("Starting device");
-        auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
-        m_mediaCaptureMgr = mediaCapture;
-        create_task(mediaCapture->InitializeAsync()).then([this](task<void> initTask)
-        {
-            try
-            {
-                initTask.get();
-
-                auto mediaCapture = m_mediaCaptureMgr.Get();
-                EnableButton(true, "StartPreview");
-                EnableButton(true, "StartStopRecord");
-                EnableButton(true, "TakePhoto");
-                ShowStatusMessage("Device initialized successful");
-                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &BasicCapture::RecordLimitationExceeded);
-                mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &BasicCapture::Failed);
-            }
-            catch (Exception ^ e)
-            {
-                ShowExceptionMessage(e);
-            }
-        }
-        );
-    }
-    catch (Platform::Exception^ e)
-    {
-        ShowExceptionMessage(e);
-    }
-}
-
-void BasicCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    m_bPreviewing = false;
-    try
-    {
-        ShowStatusMessage("Starting preview");
-        EnableButton(false, "StartPreview");
-        auto mediaCapture = m_mediaCaptureMgr.Get();
-
-        previewCanvas1->Visibility = Windows::UI::Xaml::Visibility::Visible;
-        previewElement1->Source = mediaCapture;
-        create_task(mediaCapture->StartPreviewAsync()).then([this](task<void> previewTask)
-        {
-            try
-            {
-                previewTask.get();
-                auto mediaCapture = m_mediaCaptureMgr.Get();
-                m_bPreviewing = true;
-                ShowStatusMessage("Start preview successful");
-                if(mediaCapture->VideoDeviceController->Brightness)
-                {
-                    SetupVideoDeviceControl(mediaCapture->VideoDeviceController->Brightness, sldBrightness);
-                }
-                if(mediaCapture->VideoDeviceController->Contrast)
-                {                
-                    SetupVideoDeviceControl(mediaCapture->VideoDeviceController->Contrast, sldContrast);
-                }
-
-            }catch (Exception ^e)
-            {
-                ShowExceptionMessage(e);
-            }
-        });
-    }
-    catch (Platform::Exception^ e)
-    {
-        m_bPreviewing = false;
-        previewElement1->Source = nullptr;
-        EnableButton(true, "StartPreview");
-        ShowExceptionMessage(e);
-    }
-}
-
-void BasicCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        ShowStatusMessage("Taking photo");
-        EnableButton(false, "TakePhoto");
-
-        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> getFileTask) 
-        {
-            try
-            {
-                this->m_photoStorageFile = getFileTask.get();
-                ShowStatusMessage("Create photo file successful");
-                ImageEncodingProperties^ imageProperties = ImageEncodingProperties::CreateJpeg();
-
-                create_task(m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, this->m_photoStorageFile)).then([this](task<void> photoTask)
-                {
-                    try
-                    {
-                        photoTask.get();
-                        EnableButton(true, "TakePhoto");
-                        ShowStatusMessage("Photo taken");
-
-                        task<IRandomAccessStream^>(this->m_photoStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> getStreamTask)
-                        {
-                            try
-                            {
-                                auto photoStream = getStreamTask.get();
-                                ShowStatusMessage("File open successful");
-                                auto bmpimg = ref new BitmapImage();
-
-                                bmpimg->SetSource(photoStream);
-                                imageElement1->Source = bmpimg;
-                            }
-                            catch (Exception^ e)
-                            {
-                                ShowExceptionMessage(e);
-                                EnableButton(true, "TakePhoto");
-                            }
-                        });
-                    }
-                    catch (Platform::Exception ^ e)
-                    {
-                        ShowExceptionMessage(e);
-                        EnableButton(true, "TakePhoto");
-                    }
-                });
-            }
-            catch (Exception^ e)
-            {
-                ShowExceptionMessage(e);
-                EnableButton(true, "TakePhoto");
-            }
-        });
-    }
-    catch (Platform::Exception^ e)
-    {
-        ShowExceptionMessage(e);
-        EnableButton(true, "TakePhoto");
-    }
-}
-
-void BasicCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        String ^fileName;
-        EnableButton(false, "StartStopRecord");
-
-        if (!m_bRecording)
-        {
-            ShowStatusMessage("Starting Record");
-
-            fileName = VIDEO_FILE_NAME;
-
-            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName,Windows::Storage::CreationCollisionOption::GenerateUniqueName )).then([this](task<StorageFile^> fileTask)
-            {
-                try
-                {
-                    this->m_recordStorageFile = fileTask.get();
-                    ShowStatusMessage("Create record file successful");
-
-                    MediaEncodingProfile^ recordProfile= nullptr;
-                    recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
-
-                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = true;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-
-                            ShowStatusMessage("Start Record successful");
-                        }
-                        catch (Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                        }
-                    });
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-            }
-            );
-        }
-        else
-        {
-            ShowStatusMessage("Stopping Record");
-
-            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-            {
-                try
-                {
-                    recordTask.get();
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    SwitchRecordButtonContent();
-
-                    ShowStatusMessage("Stop record successful");
-                    if (!m_bSuspended)
-                    {
-                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
-                        {
-                            try
-                            {
-                                auto stream = streamTask.get();
-                                ShowStatusMessage("Record file opened");
-                                ShowStatusMessage(this->m_recordStorageFile->Path);
-                                playbackElement1->AutoPlay = true;
-                                playbackElement1->SetSource(stream, this->m_recordStorageFile->FileType);
-                                playbackElement1->Play();
-                            }
-                            catch (Exception ^e)
-                            {
-                                ShowExceptionMessage(e);
-                                m_bRecording = false;
-                                EnableButton(true, "StartStopRecord");
-                                SwitchRecordButtonContent();
-                            }
-                        });
-                    }
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    SwitchRecordButtonContent();
-                    ShowExceptionMessage(e);
-                }
-            });
-        }
-    }
-    catch (Platform::Exception^ e)
-    {
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-        SwitchRecordButtonContent();
-        m_bRecording = false;
-    }
-}
-
-void BasicCapture::SetupVideoDeviceControl(Windows::Media::Devices::MediaDeviceControl^ videoDeviceControl, Slider^ slider)
-{
-    try
-    {		
-        if ((videoDeviceControl->Capabilities)->Supported)
-        {
-            slider->IsEnabled = true;
-            slider->Maximum = videoDeviceControl->Capabilities->Max;
-            slider->Minimum = videoDeviceControl->Capabilities->Min;
-            slider->StepFrequency = videoDeviceControl->Capabilities->Step;
-            double controlValue = 0;
-            if (videoDeviceControl->TryGetValue(&controlValue))
-            {
-                slider->Value = controlValue;
-            }
-        }
-        else
-        {
-            slider->IsEnabled = false;
-        }
-    }
-    catch (Platform::Exception^ e)
-    {
-        ShowExceptionMessage(e);
-    }
-}
-
-// VideoDeviceControllers
-void BasicCapture::sldBrightness_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
-{
-    bool succeeded = m_mediaCaptureMgr->VideoDeviceController->Brightness->TrySetValue(sldBrightness->Value);
-    if (!succeeded)
-    {
-        ShowStatusMessage("Set Brightness failed");
-    }
-}
-
-void BasicCapture::sldContrast_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs ^e)
-{
-    bool succeeded = m_mediaCaptureMgr->VideoDeviceController->Contrast->TrySetValue(sldContrast->Value);
-    if (!succeeded)
-    {
-        ShowStatusMessage("Set Contrast failed");
-    }
-}
-
-void BasicCapture::ShowStatusMessage(Platform::String^ text)
-{
-    rootPage->NotifyUser(text, NotifyType::StatusMessage);
-}
-
-void BasicCapture::ShowExceptionMessage(Platform::Exception^ ex)
-{
-    rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
-}
-
-void BasicCapture::SwitchRecordButtonContent()
-{
-    if (m_bRecording)
-    {
-        btnStartStopRecord1->Content="StopRecord";
-    }
-    else
-    {
-        btnStartStopRecord1->Content="StartRecord";
-    }
-}
-void BasicCapture::EnableButton(bool enabled, String^ name)
-{
-    if (name->Equals("StartDevice"))
-    {
-        btnStartDevice1->IsEnabled = enabled;
-    }
-    else if (name->Equals("StartPreview"))
-    {
-        btnStartPreview1->IsEnabled = enabled;
-    }
-    else if (name->Equals("StartStopRecord"))
-    {
-        btnStartStopRecord1->IsEnabled = enabled;
-    }
-    else if (name->Equals("TakePhoto"))
-    {
-        btnTakePhoto1->IsEnabled = enabled;
-    }
-}
-
diff --git a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h b/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h
deleted file mode 100644
index 28129efb7..000000000
--- a/samples/winrt/ImageManipulations/C++/BasicCapture.xaml.h
+++ /dev/null
@@ -1,88 +0,0 @@
-//*********************************************************
-//
-// Copyright (c) Microsoft. All rights reserved.
-// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
-// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
-// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
-// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
-//
-//*********************************************************
-
-//
-// BasicCapture.xaml.h
-// Declaration of the BasicCapture class
-//
-
-#pragma once
-
-#include "pch.h"
-#include "BasicCapture.g.h"
-#include "MainPage.xaml.h"
-
-using namespace Windows::UI::Xaml;
-using namespace Windows::UI::Xaml::Controls;
-using namespace Windows::Graphics::Display;
-using namespace Windows::UI::ViewManagement;
-using namespace Windows::Devices::Enumeration;
-#define VIDEO_FILE_NAME "video.mp4"
-#define PHOTO_FILE_NAME "photo.jpg"
-namespace SDKSample
-{
-    namespace MediaCapture
-    {
-        /// <summary>
-        /// An empty page that can be used on its own or navigated to within a Frame.
-        /// </summary>
-    	[Windows::Foundation::Metadata::WebHostHidden]
-        public ref class BasicCapture sealed
-        {
-        public:
-            BasicCapture();
-    
-        protected:
-            virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
-            virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
-    
-        private:
-            MainPage^ rootPage;
-            void ScenarioInit();
-            void ScenarioReset();
-    
-            void Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
-            void Resuming(Object^ sender, Object^ e);
-    
-            void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-            void SoundLevelChanged(Object^ sender, Object^ e);
-            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
-            void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
-    
-    
-            void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-    
-            void SetupVideoDeviceControl(Windows::Media::Devices::MediaDeviceControl^ videoDeviceControl, Slider^ slider);
-            void sldBrightness_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
-            void sldContrast_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
-    
-            void ShowStatusMessage(Platform::String^ text);
-            void ShowExceptionMessage(Platform::Exception^ ex);
-    
-            void EnableButton(bool enabled, Platform::String ^name);
-            void SwitchRecordButtonContent();
-    
-            Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCaptureMgr;
-            Windows::Storage::StorageFile^ m_photoStorageFile;
-            Windows::Storage::StorageFile^ m_recordStorageFile;
-            bool m_bRecording;
-            bool m_bEffectAdded;
-            bool m_bSuspended;
-            bool m_bPreviewing;
-            Windows::UI::Xaml::WindowVisibilityChangedEventHandler ^m_visbilityHandler;
-            Windows::Foundation::EventRegistrationToken m_eventRegistrationToken;
-            bool m_currentScenarioLoaded;
-        };
-    }
-}
diff --git a/samples/winrt/ImageManipulations/C++/Constants.cpp b/samples/winrt/ImageManipulations/C++/Constants.cpp
index 873b98381..a26634272 100644
--- a/samples/winrt/ImageManipulations/C++/Constants.cpp
+++ b/samples/winrt/ImageManipulations/C++/Constants.cpp
@@ -18,7 +18,5 @@ Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Sc
 {
     // The format here is the following:
     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
-    { "Video preview, record and take pictures", "SDKSample.MediaCapture.BasicCapture" },
     { "Enumerate cameras and add a video effect", "SDKSample.MediaCapture.AdvancedCapture" },
-    { "Audio Capture", "SDKSample.MediaCapture.AudioCapture" }
 };
diff --git a/samples/winrt/ImageManipulations/C++/Constants.h b/samples/winrt/ImageManipulations/C++/Constants.h
index 917f66487..143f06960 100644
--- a/samples/winrt/ImageManipulations/C++/Constants.h
+++ b/samples/winrt/ImageManipulations/C++/Constants.h
@@ -26,7 +26,7 @@ namespace SDKSample
         {
             Platform::String^ get()
             {
-                return ref new Platform::String(L"MediaCapture CPP sample");
+                return ref new Platform::String(L"OpenCV Image Manipulations sample");
             }
         }
 
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml b/samples/winrt/ImageManipulations/C++/MainPage.xaml
index d830e3cf0..82d5494b6 100644
--- a/samples/winrt/ImageManipulations/C++/MainPage.xaml
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml
@@ -36,7 +36,7 @@
 
 
     <Grid x:Name="LayoutRoot" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
-        
+
         <Grid x:Name="ContentRoot" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="100,20,100,20">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
@@ -47,7 +47,7 @@
             <!-- Header -->
             <StackPanel Orientation="Horizontal" Grid.Row="0">
                 <Image x:Name="WindowsLogo" Stretch="None" Source="Assets/windows-sdk.png" AutomationProperties.Name="Windows Logo" HorizontalAlignment="Left" Grid.Column="0"/>
-                <TextBlock  Text="Windows 8 SDK Samples" VerticalAlignment="Bottom" Style="{StaticResource TitleTextStyle}" TextWrapping="Wrap" Grid.Column="1"/>
+                <TextBlock VerticalAlignment="Bottom" Style="{StaticResource TitleTextStyle}" TextWrapping="Wrap" Grid.Column="1" Text="OpenCV for Windows RT"/>
             </StackPanel>
             <ScrollViewer x:Name="MainScrollViewer" Grid.Row="1" ZoomMode="Disabled" IsTabStop="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Padding="0,0,0,20" >
                 <Grid>
@@ -92,7 +92,7 @@
                             <TextBlock x:Name="DescriptionText" Margin="0,5,0,0" Text="Description:" Style="{StaticResource SubheaderTextStyle}" Grid.Row="1" Grid.Column="1"/>
                             <!-- Input Scenarios -->
                             <UserControl x:Name="InputSection" Margin="0,5,0,0" IsTabStop="False" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top"/>
-                                
+
                             <!-- Output section -->
                             <TextBlock Text="Output" Grid.Row="5"  Margin="0,25,0,20" Style="{StaticResource H2Style}" Grid.ColumnSpan="2"/>
                             <TextBlock x:Name="StatusBlock" Grid.Row="6" Margin="0,0,0,5" Grid.ColumnSpan="2"/>
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
index d2f255d1b..84b6d3df5 100644
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
@@ -101,14 +101,6 @@
       <DependentUpon>AdvancedCapture.xaml</DependentUpon>
       <SubType>Code</SubType>
     </ClInclude>
-    <ClInclude Include="AudioCapture.xaml.h">
-      <DependentUpon>AudioCapture.xaml</DependentUpon>
-      <SubType>Code</SubType>
-    </ClInclude>
-    <ClInclude Include="BasicCapture.xaml.h">
-      <DependentUpon>BasicCapture.xaml</DependentUpon>
-      <SubType>Code</SubType>
-    </ClInclude>
     <ClInclude Include="Constants.h" />
     <ClInclude Include="MainPage.xaml.h">
       <DependentUpon>MainPage.xaml</DependentUpon>
@@ -127,12 +119,6 @@
     <Page Include="AdvancedCapture.xaml">
       <SubType>Designer</SubType>
     </Page>
-    <Page Include="AudioCapture.xaml">
-      <SubType>Designer</SubType>
-    </Page>
-    <Page Include="BasicCapture.xaml">
-      <SubType>Designer</SubType>
-    </Page>
     <Page Include="Common\StandardStyles.xaml">
       <SubType>Designer</SubType>
     </Page>
@@ -156,14 +142,6 @@
     <ClCompile Include="App.xaml.cpp">
       <DependentUpon>App.xaml</DependentUpon>
     </ClCompile>
-    <ClCompile Include="AudioCapture.xaml.cpp">
-      <DependentUpon>AudioCapture.xaml</DependentUpon>
-      <SubType>Code</SubType>
-    </ClCompile>
-    <ClCompile Include="BasicCapture.xaml.cpp">
-      <DependentUpon>BasicCapture.xaml</DependentUpon>
-      <SubType>Code</SubType>
-    </ClCompile>
     <ClCompile Include="Common\LayoutAwarePage.cpp" />
     <ClCompile Include="Constants.cpp" />
     <ClCompile Include="Common\SuspensionManager.cpp" />
@@ -194,6 +172,144 @@
       <Project>{ba69218f-da5c-4d14-a78d-21a9e4dec669}</Project>
     </ProjectReference>
   </ItemGroup>
+  <ItemGroup>
+    <None Include="..\..\..\..\build\install\bin\opencv_calib3d245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_contrib245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_core245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_features2d245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_flann245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_highgui245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_imgproc245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_legacy245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_ml245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_nonfree245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_objdetect245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_photo245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_stitching245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_superres245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_ts245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_video245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+    <None Include="..\..\..\..\build\install\bin\opencv_videostab245.dll">
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
+      <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
+    </None>
+  </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
index 5f6124c2b..403e5ea1f 100644
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
@@ -40,9 +40,7 @@
     <Page Include="Sample-Utils\SampleTemplateStyles.xaml">
       <Filter>Sample-Utils</Filter>
     </Page>
-    <Page Include="BasicCapture.xaml" />
     <Page Include="AdvancedCapture.xaml" />
-    <Page Include="AudioCapture.xaml" />
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="MainPage.xaml.h" />
@@ -56,8 +54,6 @@
     </ClInclude>
     <ClInclude Include="Constants.h" />
     <ClInclude Include="AdvancedCapture.xaml.h" />
-    <ClInclude Include="AudioCapture.xaml.h" />
-    <ClInclude Include="BasicCapture.xaml.h" />
   </ItemGroup>
   <ItemGroup>
     <ClCompile Include="App.xaml.cpp" />
@@ -71,8 +67,6 @@
     </ClCompile>
     <ClCompile Include="Constants.cpp" />
     <ClCompile Include="AdvancedCapture.xaml.cpp" />
-    <ClCompile Include="AudioCapture.xaml.cpp" />
-    <ClCompile Include="BasicCapture.xaml.cpp" />
   </ItemGroup>
   <ItemGroup>
     <Filter Include="Assets">
@@ -85,4 +79,23 @@
       <UniqueIdentifier>{54f287f8-e4cb-4f47-97d0-4c469de6992e}</UniqueIdentifier>
     </Filter>
   </ItemGroup>
+  <ItemGroup>
+    <None Include="..\..\..\..\build\install\bin\opencv_calib3d245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_contrib245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_core245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_features2d245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_flann245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_highgui245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_imgproc245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_legacy245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_ml245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_nonfree245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_objdetect245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_photo245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_stitching245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_superres245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_ts245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_video245.dll" />
+    <None Include="..\..\..\..\build\install\bin\opencv_videostab245.dll" />
+  </ItemGroup>
 </Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
index 687386ece..d41fa3481 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
@@ -8,6 +8,9 @@
 #include "Grayscale.h"
 #include "bufferlock.h"
 
+#include "opencv2\core\core.hpp"
+#include "opencv2\imgproc\imgproc.hpp"
+
 #pragma comment(lib, "d2d1")
 
 using namespace Microsoft::WRL;
@@ -80,16 +83,12 @@ NOTES ON THE MFT IMPLEMENTATION
 
 
 // Video FOURCC codes.
-const DWORD FOURCC_YUY2 = '2YUY'; 
-const DWORD FOURCC_UYVY = 'YVYU'; 
 const DWORD FOURCC_NV12 = '21VN'; 
 
 // Static array of media types (preferred and accepted).
 const GUID g_MediaSubtypes[] =
 {
-    MFVideoFormat_NV12,
-    MFVideoFormat_YUY2,
-    MFVideoFormat_UYVY
+    MFVideoFormat_NV12
 };
 
 HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage);
@@ -102,27 +101,6 @@ inline T clamp(const T& val, const T& minVal, const T& maxVal)
     return (val < minVal ? minVal : (val > maxVal ? maxVal : val));
 }
 
-
-// TransformChroma:
-// Apply the transforms to calculate the output chroma values.
-
-void TransformChroma(const D2D1::Matrix3x2F& mat, BYTE *pu, BYTE *pv)
-{
-    // Normalize the chroma values to [-112, 112] range
-
-    D2D1_POINT_2F pt = { static_cast<float>(*pu) - 128, static_cast<float>(*pv) - 128 };
-
-    pt = mat.TransformPoint(pt);
-
-    // Clamp to valid range.
-    clamp(pt.x, -112.0f, 112.0f);
-    clamp(pt.y, -112.0f, 112.0f);
-
-    // Map back to [16...240] range.
-    *pu = static_cast<BYTE>(pt.x + 128.0f);
-    *pv = static_cast<BYTE>(pt.y + 128.0f);
-}
-
 //-------------------------------------------------------------------
 // Functions to convert a YUV images to grayscale.
 //
@@ -141,144 +119,6 @@ void TransformChroma(const D2D1::Matrix3x2F& mat, BYTE *pu, BYTE *pv)
 // dwHeightInPixels  Frame height, in pixels.
 //-------------------------------------------------------------------
 
-// Convert UYVY image.
-
-void TransformImage_UYVY(
-    const D2D1::Matrix3x2F& mat,
-    const D2D_RECT_U& rcDest,
-    _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest, 
-    _In_ LONG lDestStride, 
-    _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
-    _In_ LONG lSrcStride, 
-    _In_ DWORD dwWidthInPixels, 
-    _In_ DWORD dwHeightInPixels)
-{
-    DWORD y = 0;
-    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
-
-    // Lines above the destination rectangle.
-    for ( ; y < rcDest.top; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels * 2);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-
-    // Lines within the destination rectangle.
-    for ( ; y < y0; y++)
-    {
-        WORD *pSrc_Pixel = (WORD*)pSrc;
-        WORD *pDest_Pixel = (WORD*)pDest;
-
-        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
-        {
-            // Byte order is U0 Y0 V0 Y1
-            // Each WORD is a byte pair (U/V, Y)
-            // Windows is little-endian so the order appears reversed.
-
-            if (x >= rcDest.left && x < rcDest.right)
-            {
-                BYTE u = pSrc_Pixel[x] & 0x00FF;
-                BYTE v = pSrc_Pixel[x+1] & 0x00FF;
-
-                TransformChroma(mat, &u, &v);
-
-                pDest_Pixel[x] = (pSrc_Pixel[x] & 0xFF00) | u;
-                pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0xFF00) | v;
-            }
-            else
-            {
-#pragma warning(push)
-#pragma warning(disable: 6385) 
-#pragma warning(disable: 6386) 
-                pDest_Pixel[x] = pSrc_Pixel[x];
-                pDest_Pixel[x+1] = pSrc_Pixel[x+1];
-#pragma warning(pop)
-            }
-        }
-
-        pDest += lDestStride;
-        pSrc += lSrcStride;
-    }
-
-    // Lines below the destination rectangle.
-    for ( ; y < dwHeightInPixels; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels * 2);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-}
-
-
-// Convert YUY2 image.
-
-void TransformImage_YUY2(
-    const D2D1::Matrix3x2F& mat,
-    const D2D_RECT_U& rcDest,
-    _Inout_updates_(_Inexpressible_(lDestStride * dwHeightInPixels)) BYTE *pDest, 
-    _In_ LONG lDestStride, 
-    _In_reads_(_Inexpressible_(lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
-    _In_ LONG lSrcStride, 
-    _In_ DWORD dwWidthInPixels, 
-    _In_ DWORD dwHeightInPixels)
-{
-    DWORD y = 0;
-    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
-
-    // Lines above the destination rectangle.
-    for ( ; y < rcDest.top; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels * 2);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-
-    // Lines within the destination rectangle.
-    for ( ; y < y0; y++)
-    {
-        WORD *pSrc_Pixel = (WORD*)pSrc;
-        WORD *pDest_Pixel = (WORD*)pDest;
-
-        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
-        {
-            // Byte order is Y0 U0 Y1 V0
-            // Each WORD is a byte pair (Y, U/V)
-            // Windows is little-endian so the order appears reversed.
-
-            if (x >= rcDest.left && x < rcDest.right)
-            {
-                BYTE u = pSrc_Pixel[x] >> 8;
-                BYTE v = pSrc_Pixel[x+1] >> 8;
-
-                TransformChroma(mat, &u, &v);
-
-                pDest_Pixel[x] = (pSrc_Pixel[x] & 0x00FF) | (u<<8);
-                pDest_Pixel[x+1] = (pSrc_Pixel[x+1] & 0x00FF) | (v<<8);
-            }
-            else
-            {
-#pragma warning(push)
-#pragma warning(disable: 6385) 
-#pragma warning(disable: 6386) 
-                pDest_Pixel[x] = pSrc_Pixel[x];
-                pDest_Pixel[x+1] = pSrc_Pixel[x+1];
-#pragma warning(pop)
-            }
-        }
-        pDest += lDestStride;
-        pSrc += lSrcStride;
-    }
-
-    // Lines below the destination rectangle.
-    for ( ; y < dwHeightInPixels; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels * 2);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-}
-
 // Convert NV12 image
 
 void TransformImage_NV12(
@@ -307,7 +147,8 @@ void TransformImage_NV12(
 
     // Lines above the destination rectangle.
     DWORD y = 0;
-    const DWORD y0 = min(rcDest.bottom, dwHeightInPixels);
+
+    const DWORD y0 = rcDest.bottom < dwHeightInPixels ? rcDest.bottom : dwHeightInPixels;
 
     for ( ; y < rcDest.top/2; y++)
     {
@@ -323,13 +164,8 @@ void TransformImage_NV12(
         {
             if (x >= rcDest.left && x < rcDest.right)
             {
-                BYTE u = pSrc[x];
-                BYTE v = pSrc[x+1];
-
-                TransformChroma(mat, &u, &v);
-
-                pDest[x] = u;
-                pDest[x+1] = v;
+                pDest[x] = 0;
+                pDest[x+1] = 0;
             }
             else
             {
@@ -351,9 +187,9 @@ void TransformImage_NV12(
 }
 
 CGrayscale::CGrayscale() :
-    m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL), m_pTransformFn(NULL),
+    m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL),
     m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
-    m_transform(D2D1::Matrix3x2F::Identity()), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
+	m_TransformType(Preview), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
     m_pAttributes(NULL)
 {
     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
@@ -1516,10 +1352,8 @@ HRESULT CGrayscale::BeginStreaming()
 
         // Get the chroma transformations.
 
-        float scale = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_SATURATION, 0.0f);
-        float angle = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_CHROMA_ROTATION, 0.0f);
-
-        m_transform = D2D1::Matrix3x2F::Scale(scale, scale) * D2D1::Matrix3x2F::Rotation(angle);
+        // float scale = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_SATURATION, 0.0f);
+        // float angle = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_CHROMA_ROTATION, 0.0f);
 
         m_bStreamingInitialized = true;
     }
@@ -1563,42 +1397,36 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
     HRESULT hr = GetDefaultStride(m_pInputType, &lDefaultStride);
     if (FAILED(hr))
     {
-        goto done;
+        return hr;
     }
 
     // Lock the input buffer.
     hr = inputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pSrc, &lSrcStride);
     if (FAILED(hr))
     {
-        goto done;
+        return hr;
     }
 
     // Lock the output buffer.
     hr = outputLock.LockBuffer(lDefaultStride, m_imageHeightInPixels, &pDest, &lDestStride);
     if (FAILED(hr))
     {
-        goto done;
-    }
-
-    // Invoke the image transform function.
-    assert (m_pTransformFn != NULL);
-    if (m_pTransformFn)
-    {
-        (*m_pTransformFn)(m_transform, m_rcDest, pDest, lDestStride, pSrc, lSrcStride,
-            m_imageWidthInPixels, m_imageHeightInPixels);
-    }
-    else
-    {
-        hr = E_UNEXPECTED;
-        goto done;
+        return hr;
     }
 
+     //(*m_pTransformFn)(m_transform, m_rcDest, pDest, lDestStride, pSrc, lSrcStride,
+     //       m_imageWidthInPixels, m_imageHeightInPixels);
 
+	cv::Mat InputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pSrc, lSrcStride);
+	cv::Mat InputGreyScale(InputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+	cv::Mat OutputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pDest, lDestStride);
+	OutputFrame.setTo(cv::Scalar(128));
+	cv::Mat OutputGreyScale(OutputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+	cv::Canny(InputGreyScale, OutputGreyScale, 80, 90);
+	
     // Set the data size on the output buffer.
     hr = pOut->SetCurrentLength(m_cbImageSize);
 
-    // The VideoBufferLock class automatically unlocks the buffers.
-done:
     return hr;
 }
 
@@ -1626,8 +1454,6 @@ HRESULT CGrayscale::UpdateFormatInfo()
     m_imageHeightInPixels = 0;
     m_cbImageSize = 0;
 
-    m_pTransformFn = NULL;
-
     if (m_pInputType != NULL)
     {
         hr = m_pInputType->GetGUID(MF_MT_SUBTYPE, &subtype);
@@ -1635,19 +1461,7 @@ HRESULT CGrayscale::UpdateFormatInfo()
         {
             goto done;
         }
-        if (subtype == MFVideoFormat_YUY2)
-        {
-            m_pTransformFn = TransformImage_YUY2;
-        }
-        else if (subtype == MFVideoFormat_UYVY)
-        {
-            m_pTransformFn = TransformImage_UYVY;
-        }
-        else if (subtype == MFVideoFormat_NV12)
-        {
-            m_pTransformFn = TransformImage_NV12;
-        }
-        else
+		if (subtype != MFVideoFormat_NV12)
         {
             hr = E_UNEXPECTED;
             goto done;
@@ -1678,20 +1492,6 @@ HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage)
 
     switch (fcc)
     {
-    case FOURCC_YUY2:
-    case FOURCC_UYVY:
-        // check overflow
-        if ((width > MAXDWORD / 2) || (width * 2 > MAXDWORD / height))
-        {
-            hr = E_INVALIDARG;
-        }
-        else
-        {   
-            // 16 bpp
-            *pcbImage = width * height * 2;
-        }
-        break;
-
     case FOURCC_NV12:
         // check overflow
         if ((height/2 > MAXDWORD - height) || ((height + height/2) > MAXDWORD / width))
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
index b83223bce..96b4b1b96 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
@@ -42,15 +42,14 @@ DEFINE_GUID(CLSID_GrayscaleMFT,
 DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT, 
 0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb);
 
-
-// {14782342-93E8-4565-872C-D9A2973D5CBF}
-DEFINE_GUID(MFT_GRAYSCALE_SATURATION, 
-0x14782342, 0x93e8, 0x4565, 0x87, 0x2c, 0xd9, 0xa2, 0x97, 0x3d, 0x5c, 0xbf);
-
-// {E0BADE5D-E4B9-4689-9DBA-E2F00D9CED0E}
-DEFINE_GUID(MFT_GRAYSCALE_CHROMA_ROTATION, 
-0xe0bade5d, 0xe4b9, 0x4689, 0x9d, 0xba, 0xe2, 0xf0, 0xd, 0x9c, 0xed, 0xe);
-
+enum ProcessingType
+{
+	Preview,
+	GrayScale,
+	Canny,
+	Zoom,
+	Sepia
+};
 
 template <class T> void SafeRelease(T **ppT)
 {
@@ -61,18 +60,6 @@ template <class T> void SafeRelease(T **ppT)
     }
 }
 
-// Function pointer for the function that transforms the image.
-typedef void (*IMAGE_TRANSFORM_FN)(
-    const D2D1::Matrix3x2F& mat,             // Chroma transform matrix.
-    const D2D_RECT_U&       rcDest,          // Destination rectangle for the transformation.
-    BYTE*                   pDest,           // Destination buffer.
-    LONG                    lDestStride,     // Destination stride.
-    const BYTE*             pSrc,            // Source buffer.
-    LONG                    lSrcStride,      // Source stride.
-    DWORD                   dwWidthInPixels, // Image width in pixels.
-    DWORD                   dwHeightInPixels // Image height in pixels.
-    );
-
 // CGrayscale class:
 // Implements a grayscale video effect.
 
@@ -244,7 +231,7 @@ private:
     CRITICAL_SECTION            m_critSec;
 
     // Transformation parameters
-    D2D1::Matrix3x2F            m_transform;                // Chroma transform matrix.
+	ProcessingType              m_TransformType;
     D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
 
     // Streaming
@@ -259,8 +246,5 @@ private:
     DWORD                       m_cbImageSize;              // Image size, in bytes.
 
     IMFAttributes               *m_pAttributes;
-
-    // Image transform function. (Changes based on the media type.)
-    IMAGE_TRANSFORM_FN          m_pTransformFn;
 };
 #endif
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
index 8af8f2c7d..c7e905936 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
@@ -123,13 +123,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
-      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
+      <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib;opencv_core245.lib;opencv_imgproc245.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(ProjectDir)$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
@@ -146,13 +147,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
@@ -169,13 +171,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
@@ -192,13 +195,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(ProjectDir)$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
@@ -215,13 +219,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>
@@ -238,13 +243,14 @@
       </PrecompiledHeaderOutputFile>
       <AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
       <CompileAsWinRT>false</CompileAsWinRT>
-      <AdditionalIncludeDirectories>$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common;</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(OPENCV_DIR)\include;$(ProjectDir);$(IntermediateOutputPath);%(AdditionalIncludeDirectories);$(ProjectDir)\..\Common</AdditionalIncludeDirectories>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
       <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
       <Command>mdmerge -metadata_dir "$(WindowsSDK_MetadataPath)" -o "$(SolutionDir)$(Platform)\$(Configuration)\$(MSBuildProjectName)" -i "$(MSBuildProjectDirectory)" -v -partial</Command>

From de9f659f1e37d798ff22c8b9a1c3a13f68bdde12 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 10 Jun 2013 11:48:53 -0700
Subject: [PATCH 33/75] Several transforms added to sample IMFTransform.

---
 .../C++/AdvancedCapture.xaml                  |   3 +-
 .../C++/AdvancedCapture.xaml.cpp              |  45 +++---
 .../C++/AdvancedCapture.xaml.h                |   1 +
 .../ImageManipulations/C++/MainPage.xaml      |  12 +-
 .../MediaExtensions/Grayscale/Grayscale.cpp   | 153 ++++++++++++------
 .../C++/MediaExtensions/Grayscale/Grayscale.h |  22 +--
 6 files changed, 146 insertions(+), 90 deletions(-)

diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
index 4e6ebfd30..e6266adb9 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
@@ -40,7 +40,8 @@
                 <Button x:Name="btnTakePhoto2" Click="btnTakePhoto_Click" IsEnabled="false"  Margin="0,0,10,0">TakePhoto</Button>
             </StackPanel>
             <StackPanel Orientation="Horizontal" Grid.Row="2" Margin="0,10,0,0">
-                <CheckBox x:Name="chkAddRemoveEffect" Margin="0,0,10,0" Content="Grayscale Effect"  IsEnabled="False" Checked="chkAddRemoveEffect_Checked" Unchecked="chkAddRemoveEffect_Unchecked"/>
+                <CheckBox x:Name="chkAddRemoveEffect" Margin="0,0,10,0" Content="Add Effect"  IsEnabled="False" Checked="chkAddRemoveEffect_Checked" Unchecked="chkAddRemoveEffect_Unchecked"/>
+                <ComboBox Width="120"/>
             </StackPanel>
         </Grid>
 
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
index dc59acc2e..15890ba6b 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
@@ -122,7 +122,7 @@ void AdvancedCapture::ScenarioReset()
 void AdvancedCapture::SoundLevelChanged(Object^ sender, Object^ e)
 {
     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
-    {    
+    {
         if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
         {
             ScenarioReset();
@@ -220,7 +220,7 @@ void AdvancedCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCap
 void AdvancedCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
 {
     String ^message = "Fatal error" + currentFailure->Message;
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, 
+    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
         ref new Windows::UI::Core::DispatchedHandler([this, message]()
     {
         ShowStatusMessage(message);
@@ -325,7 +325,7 @@ void AdvancedCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::
         EnableButton(false, "TakePhoto");
         auto currentRotation = GetCurrentPhotoRotation();
 
-        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(TEMP_PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this, currentRotation](task<StorageFile^> getFileTask) 
+        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(TEMP_PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this, currentRotation](task<StorageFile^> getFileTask)
         {
             try
             {
@@ -520,7 +520,7 @@ void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender
              }
          });
     }
- 
+
     btnStartDevice2->IsEnabled = true;
     btnStartPreview2->IsEnabled = false;
     btnStartStopRecord2->IsEnabled = false;
@@ -581,12 +581,12 @@ void AdvancedCapture::EnumerateWebcamsAsync()
 }
 
 void AdvancedCapture::AddEffectToImageStream()
-{    
+{
     auto mediaCapture = m_mediaCaptureMgr.Get();
     Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
 
     if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
-        (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical) && 
+        (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical) &&
         (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::RecordPhotoStreamsIdentical))
     {
         Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
@@ -596,13 +596,13 @@ void AdvancedCapture::AddEffectToImageStream()
             Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::IMediaEncodingProperties^>^ supportedPropsList = mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo);
             {
                 unsigned int i = 0;
-                while (i<  supportedPropsList->Size)
+                while (i < supportedPropsList->Size)
                 {
                     Windows::Media::MediaProperties::IMediaEncodingProperties^ props = supportedPropsList->GetAt(i);
 
                     String^ s = props->Type;
                     if(props->Type->Equals("Video"))
-                    {                                                    
+                    {
                         task<void>(mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Windows::Media::Capture::MediaStreamType::Photo,props)).then([this](task<void> changeTypeTask)
                         {
                             try
@@ -616,7 +616,7 @@ void AdvancedCapture::AddEffectToImageStream()
                                     {
                                         effectTask3.get();
                                         m_bEffectAddedToPhoto = true;
-                                        ShowStatusMessage("Adding effect to photo stream successful");                                                                    
+                                        ShowStatusMessage("Adding effect to photo stream successful");
                                         chkAddRemoveEffect->IsEnabled = true;
 
                                     }
@@ -633,8 +633,7 @@ void AdvancedCapture::AddEffectToImageStream()
                             {
                                 ShowExceptionMessage(e);
                                 chkAddRemoveEffect->IsEnabled = true;
-                                chkAddRemoveEffect->IsChecked = false;																	
-
+                                chkAddRemoveEffect->IsChecked = false;
                             }
 
                         });
@@ -686,8 +685,8 @@ void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windo
                 auto mediaCapture = m_mediaCaptureMgr.Get();
                 Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
 
-                ShowStatusMessage("Add effect successful to preview stream successful");                
-                if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) && 
+                ShowStatusMessage("Add effect successful to preview stream successful");
+                if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
                     (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical))
                 {
                     Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord);
@@ -703,14 +702,14 @@ void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windo
                                 m_bEffectAddedToRecord = true;
                                 AddEffectToImageStream();
                                 chkAddRemoveEffect->IsEnabled = true;
-                            } 
+                            }
                             catch(Exception ^e)
                             {
                                 ShowExceptionMessage(e);
                                 chkAddRemoveEffect->IsEnabled = true;
                                 chkAddRemoveEffect->IsChecked = false;
                             }
-                        }); 						
+                        });
                     }
                     else
                     {
@@ -718,7 +717,7 @@ void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windo
                         chkAddRemoveEffect->IsEnabled = true;
                     }
 
-                }                
+                }
                 else
                 {
                     AddEffectToImageStream();
@@ -777,7 +776,7 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                                     {
                                         ShowExceptionMessage(e);
                                         chkAddRemoveEffect->IsEnabled = true;
-                                        chkAddRemoveEffect->IsChecked = true;				
+                                        chkAddRemoveEffect->IsChecked = true;
                                     }
 
                                 });
@@ -791,7 +790,7 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                         {
                             ShowExceptionMessage(e);
                             chkAddRemoveEffect->IsEnabled = true;
-                            chkAddRemoveEffect->IsChecked = true;				
+                            chkAddRemoveEffect->IsChecked = true;
 
                         }
 
@@ -813,7 +812,7 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                         {
                             ShowExceptionMessage(e);
                             chkAddRemoveEffect->IsEnabled = true;
-                            chkAddRemoveEffect->IsChecked = true;				
+                            chkAddRemoveEffect->IsChecked = true;
                         }
 
                     });
@@ -821,7 +820,7 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                 else
                 {
                     chkAddRemoveEffect->IsEnabled = true;
-                    chkAddRemoveEffect->IsChecked = true;	
+                    chkAddRemoveEffect->IsChecked = true;
                 }
             }
             catch (Exception ^e)
@@ -1032,3 +1031,9 @@ Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup(
     }
 }
 
+
+
+void SDKSample::MediaCapture::AdvancedCapture::EffectType_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
+{
+
+}
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
index 83556b95e..4784900d7 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
@@ -98,6 +98,7 @@ namespace SDKSample
             bool m_bRotateVideoOnOrientationChange;
             bool m_bReversePreviewRotation;
             Windows::Foundation::EventRegistrationToken m_orientationChangedEventToken;
+            void EffectType_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
         };
     }
 }
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml b/samples/winrt/ImageManipulations/C++/MainPage.xaml
index 82d5494b6..e0ed0d79c 100644
--- a/samples/winrt/ImageManipulations/C++/MainPage.xaml
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml
@@ -116,17 +116,7 @@
                     <ColumnDefinition Width="Auto"/>
                     <ColumnDefinition Width="*"/>
                 </Grid.ColumnDefinitions>
-                <Image Grid.Row="0"  Source="Assets/microsoft-sdk.png" AutomationProperties.Name="Microsoft Logo" Stretch="None" HorizontalAlignment="Left"/>
-                <TextBlock Style="{StaticResource FooterStyle}" Text="© Microsoft Corporation. All rights reserved." TextWrapping="Wrap" Grid.Row="1" HorizontalAlignment="Left"/>
-                <StackPanel x:Name="FooterPanel" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right">
-                    <HyperlinkButton Content="Terms of use" Tag="http://www.microsoft.com/About/Legal/EN/US/IntellectualProperty/Copyright/default.aspx"
-                        Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
-                    <TextBlock Text="|" Style="{StaticResource SeparatorStyle}" VerticalAlignment="Center"/>
-                    <HyperlinkButton Content="Trademarks" Tag="http://www.microsoft.com/About/Legal/EN/US/IntellectualProperty/Trademarks/EN-US.aspx"
-                        Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
-                    <TextBlock Text="|"  Style="{StaticResource SeparatorStyle}" VerticalAlignment="Center"/>
-                    <HyperlinkButton Content="Privacy Statement" Tag="http://privacy.microsoft.com" Click="Footer_Click" FontSize="12" Style="{StaticResource HyperlinkStyle}"/>
-                </StackPanel>
+                <StackPanel x:Name="FooterPanel" Orientation="Horizontal" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right"/>
             </Grid>
 
 
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
index d41fa3481..e853d4627 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
@@ -30,9 +30,9 @@ MFT_GRAYSCALE_DESTINATION_RECT (type = blob, UINT32[4] array)
 
 MFT_GRAYSCALE_SATURATION (type = double)
 
-    Sets the saturation level. The nominal range is [0...1]. Values beyond 1.0f 
+    Sets the saturation level. The nominal range is [0...1]. Values beyond 1.0f
     result in supersaturated colors. Values below 0.0f create inverted colors.
-    
+
 MFT_GRAYSCALE_CHROMA_ROTATION (type = double)
 
     Rotates the chroma values of each pixel. The attribue value is the angle of
@@ -45,7 +45,7 @@ as a scaling transform.
 
 NOTES ON THE MFT IMPLEMENTATION
 
-1. The MFT has fixed streams: One input stream and one output stream. 
+1. The MFT has fixed streams: One input stream and one output stream.
 
 2. The MFT supports the following formats: UYVY, YUY2, NV12.
 
@@ -56,34 +56,34 @@ NOTES ON THE MFT IMPLEMENTATION
 5. If both types are set, no type can be set until the current type is cleared.
 
 6. Preferred input types:
- 
+
      (a) If the output type is set, that's the preferred type.
-     (b) Otherwise, the preferred types are partial types, constructed from the 
+     (b) Otherwise, the preferred types are partial types, constructed from the
          list of supported subtypes.
- 
+
 7. Preferred output types: As above.
 
-8. Streaming: 
- 
-    The private BeingStreaming() method is called in response to the 
-    MFT_MESSAGE_NOTIFY_BEGIN_STREAMING message. 
+8. Streaming:
+
+    The private BeingStreaming() method is called in response to the
+    MFT_MESSAGE_NOTIFY_BEGIN_STREAMING message.
 
     If the client does not send MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, the MFT calls
-    BeginStreaming inside the first call to ProcessInput or ProcessOutput. 
+    BeginStreaming inside the first call to ProcessInput or ProcessOutput.
 
     This is a good approach for allocating resources that your MFT requires for
-    streaming. 
-    
-9. The configuration attributes are applied in the BeginStreaming method. If the 
-   client changes the attributes during streaming, the change is ignored until 
-   streaming is stopped (either by changing the media types or by sending the 
+    streaming.
+
+9. The configuration attributes are applied in the BeginStreaming method. If the
+   client changes the attributes during streaming, the change is ignored until
+   streaming is stopped (either by changing the media types or by sending the
    MFT_MESSAGE_NOTIFY_END_STREAMING message) and then restarted.
-   
+
 */
 
 
 // Video FOURCC codes.
-const DWORD FOURCC_NV12 = '21VN'; 
+const DWORD FOURCC_NV12 = '21VN';
 
 // Static array of media types (preferred and accepted).
 const GUID g_MediaSubtypes[] =
@@ -124,11 +124,11 @@ inline T clamp(const T& val, const T& minVal, const T& maxVal)
 void TransformImage_NV12(
     const D2D1::Matrix3x2F& mat,
     const D2D_RECT_U& rcDest,
-    _Inout_updates_(_Inexpressible_(2 * lDestStride * dwHeightInPixels)) BYTE *pDest, 
-    _In_ LONG lDestStride, 
+    _Inout_updates_(_Inexpressible_(2 * lDestStride * dwHeightInPixels)) BYTE *pDest,
+    _In_ LONG lDestStride,
     _In_reads_(_Inexpressible_(2 * lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
-    _In_ LONG lSrcStride, 
-    _In_ DWORD dwWidthInPixels, 
+    _In_ LONG lSrcStride,
+    _In_ DWORD dwWidthInPixels,
     _In_ DWORD dwHeightInPixels)
 {
     // NV12 is planar: Y plane, followed by packed U-V plane.
@@ -189,7 +189,7 @@ void TransformImage_NV12(
 CGrayscale::CGrayscale() :
     m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL),
     m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
-	m_TransformType(Preview), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
+    m_TransformType(Preview), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
     m_pAttributes(NULL)
 {
     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
@@ -786,12 +786,12 @@ HRESULT CGrayscale::GetInputStatus(
         return MF_E_INVALIDSTREAMNUMBER;
     }
 
-    // If an input sample is already queued, do not accept another sample until the 
+    // If an input sample is already queued, do not accept another sample until the
     // client calls ProcessOutput or Flush.
 
-    // NOTE: It is possible for an MFT to accept more than one input sample. For 
-    // example, this might be required in a video decoder if the frames do not 
-    // arrive in temporal order. In the case, the decoder must hold a queue of 
+    // NOTE: It is possible for an MFT to accept more than one input sample. For
+    // example, this might be required in a video decoder if the frames do not
+    // arrive in temporal order. In the case, the decoder must hold a queue of
     // samples. For the video effect, each sample is transformed independently, so
     // there is no reason to queue multiple input samples.
 
@@ -902,12 +902,12 @@ HRESULT CGrayscale::ProcessMessage(
     case MFT_MESSAGE_SET_D3D_MANAGER:
         // Sets a pointer to the IDirect3DDeviceManager9 interface.
 
-        // The pipeline should never send this message unless the MFT sets the MF_SA_D3D_AWARE 
+        // The pipeline should never send this message unless the MFT sets the MF_SA_D3D_AWARE
         // attribute set to TRUE. Because this MFT does not set MF_SA_D3D_AWARE, it is an error
         // to send the MFT_MESSAGE_SET_D3D_MANAGER message to the MFT. Return an error code in
         // this case.
 
-        // NOTE: If this MFT were D3D-enabled, it would cache the IDirect3DDeviceManager9 
+        // NOTE: If this MFT were D3D-enabled, it would cache the IDirect3DDeviceManager9
         // pointer for use during streaming.
 
         hr = E_NOTIMPL;
@@ -972,7 +972,7 @@ HRESULT CGrayscale::ProcessInput(
     // The client must set input and output types before calling ProcessInput.
     if (!m_pInputType || !m_pOutputType)
     {
-        hr = MF_E_NOTACCEPTING;   
+        hr = MF_E_NOTACCEPTING;
         goto done;
     }
 
@@ -1016,7 +1016,7 @@ HRESULT CGrayscale::ProcessOutput(
 
     // This MFT does not accept any flags for the dwFlags parameter.
 
-    // The only defined flag is MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER. This flag 
+    // The only defined flag is MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER. This flag
     // applies only when the MFT marks an output stream as lazy or optional. But this
     // MFT has no lazy or optional streams, so the flag is not valid.
 
@@ -1266,7 +1266,7 @@ HRESULT CGrayscale::OnCheckMediaType(IMFMediaType *pmt)
         goto done;
     }
 
-    // Reject single-field media types. 
+    // Reject single-field media types.
     UINT32 interlace = MFGetAttributeUINT32(pmt, MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
     if (interlace == MFVideoInterlace_FieldSingleUpper  || interlace == MFVideoInterlace_FieldSingleLower)
     {
@@ -1350,10 +1350,13 @@ HRESULT CGrayscale::BeginStreaming()
             goto done;
         }
 
-        // Get the chroma transformations.
+        // Get the effect type
+        UINT32 effect = MFGetAttributeUINT32(m_pAttributes, MFT_IMAGE_EFFECT, 1);
 
-        // float scale = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_SATURATION, 0.0f);
-        // float angle = (float)MFGetAttributeDouble(m_pAttributes, MFT_GRAYSCALE_CHROMA_ROTATION, 0.0f);
+        if ((effect >= 0) && (effect < InvalidEffect))
+        {
+            m_TransformType = (ProcessingType)effect;
+        }
 
         m_bStreamingInitialized = true;
     }
@@ -1363,7 +1366,7 @@ done:
 }
 
 
-// End streaming. 
+// End streaming.
 
 // This method is called if the client sends an MFT_MESSAGE_NOTIFY_END_STREAMING
 // message, or when the media type changes. In general, it should be called whenever
@@ -1414,16 +1417,72 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
         return hr;
     }
 
-     //(*m_pTransformFn)(m_transform, m_rcDest, pDest, lDestStride, pSrc, lSrcStride,
-     //       m_imageWidthInPixels, m_imageHeightInPixels);
+    cv::Mat InputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pSrc, lSrcStride);
+    cv::Mat InputGreyScale(InputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+    cv::Mat OutputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pDest, lDestStride);
+
+    switch (m_TransformType)
+    {
+    case Preview:
+        {
+            InputFrame.copyTo(OutputFrame);
+        } break;
+    case GrayScale:
+        {
+            OutputFrame.setTo(cv::Scalar(128));
+            cv::Mat OutputGreyScale(OutputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+            InputGreyScale.copyTo(OutputGreyScale);
+        } break;
+    case Canny:
+        {
+            OutputFrame.setTo(cv::Scalar(128));
+            cv::Mat OutputGreyScale(OutputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+            cv::Canny(InputGreyScale, OutputGreyScale, 80, 90);
+
+        } break;
+    case Sobel:
+        {
+            OutputFrame.setTo(cv::Scalar(128));
+            cv::Mat OutputGreyScale(OutputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
+            cv::Sobel(InputGreyScale, OutputGreyScale, CV_8U, 1, 1);
+        } break;
+    case Histogram:
+        {
+            const int mHistSizeNum = 25;
+            const int channels[3][1] = {{0}, {1}, {2}};
+            const int mHistSize[] = {25};
+            const float baseRabge[] = {0.f,256.f};
+            const float* ranges[] = {baseRabge};
+            const cv::Scalar mColorsRGB[] = { cv::Scalar(200, 0, 0, 255), cv::Scalar(0, 200, 0, 255),
+                                        cv::Scalar(0, 0, 200, 255) };
+
+            cv::Mat BgrFrame;
+            cv::cvtColor(InputFrame, BgrFrame, cv::COLOR_YUV420sp2BGR);
+            int thikness = (int) (BgrFrame.cols / (mHistSizeNum + 10) / 5);
+            if(thikness > 5) thikness = 5;
+            int offset = (int) ((BgrFrame.cols - (5*mHistSizeNum + 4*10)*thikness)/2);
+
+            // RGB
+            for (int c=0; c<3; c++)
+            {
+                std::vector<int> hist;
+                cv::calcHist(&BgrFrame, 1, channels[c], cv::Mat(), hist, 1, mHistSize, ranges);
+                cv::normalize(hist, hist, BgrFrame.rows/2, 0, cv::NORM_INF);
+                for(int h=0; h<mHistSizeNum; h++) {
+                    cv::Point mP1, mP2;
+                    mP1.x = mP2.x = offset + (c * (mHistSizeNum + 10) + h) * thikness;
+                    mP1.y = BgrFrame.rows-1;
+                    mP2.y = mP1.y - 2 - (int)hist[h];
+                    cv::line(BgrFrame, mP1, mP2, mColorsRGB[c], thikness);
+                }
+            }
+
+            cv::cvtColor(BgrFrame, OutputFrame, cv::COLOR_BGR2YUV_I420);
+        } break;
+    default:
+        break;
+    }
 
-	cv::Mat InputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pSrc, lSrcStride);
-	cv::Mat InputGreyScale(InputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
-	cv::Mat OutputFrame(m_imageHeightInPixels + m_imageHeightInPixels/2, m_imageWidthInPixels, CV_8UC1, pDest, lDestStride);
-	OutputFrame.setTo(cv::Scalar(128));
-	cv::Mat OutputGreyScale(OutputFrame, cv::Range(0, m_imageHeightInPixels), cv::Range(0, m_imageWidthInPixels));
-	cv::Canny(InputGreyScale, OutputGreyScale, 80, 90);
-	
     // Set the data size on the output buffer.
     hr = pOut->SetCurrentLength(m_cbImageSize);
 
@@ -1461,7 +1520,7 @@ HRESULT CGrayscale::UpdateFormatInfo()
         {
             goto done;
         }
-		if (subtype != MFVideoFormat_NV12)
+        if (subtype != MFVideoFormat_NV12)
         {
             hr = E_UNEXPECTED;
             goto done;
@@ -1511,7 +1570,7 @@ HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage)
     return hr;
 }
 
-// Get the default stride for a video format. 
+// Get the default stride for a video format.
 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
 {
     LONG lStride = 0;
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
index 96b4b1b96..a6a6aa2f1 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
@@ -37,18 +37,18 @@ DEFINE_GUID(CLSID_GrayscaleMFT,
 
 
 // Configuration attributes
+// {698649BE-8EAE-4551-A4CB-3EC98FBD3D86}
+DEFINE_GUID(MFT_IMAGE_EFFECT,
+0x698649be, 0x8eae, 0x4551, 0xa4, 0xcb, 0x3e, 0xc9, 0x8f, 0xbd, 0x3d, 0x86);
 
-// {7BBBB051-133B-41F5-B6AA-5AFF9B33A2CB}
-DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT, 
-0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb);
 
 enum ProcessingType
 {
-	Preview,
-	GrayScale,
-	Canny,
-	Zoom,
-	Sepia
+    GrayScale,
+    Canny,
+    Sobel,
+    Histogram,
+    InvalidEffect
 };
 
 template <class T> void SafeRelease(T **ppT)
@@ -63,9 +63,9 @@ template <class T> void SafeRelease(T **ppT)
 // CGrayscale class:
 // Implements a grayscale video effect.
 
-class CGrayscale 
+class CGrayscale
     : public Microsoft::WRL::RuntimeClass<
-           Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >, 
+           Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
            ABI::Windows::Media::IMediaExtension,
            IMFTransform >
 {
@@ -231,7 +231,7 @@ private:
     CRITICAL_SECTION            m_critSec;
 
     // Transformation parameters
-	ProcessingType              m_TransformType;
+    ProcessingType              m_TransformType;
     D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
 
     // Streaming

From bf22567c09ce2eba16cc5ac179a44b9822ef4283 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Fri, 14 Jun 2013 15:01:09 -0700
Subject: [PATCH 34/75] Transform selection implemented in sample GUI.

Gistogram output does not work propertly due color conversion problems.
---
 .../C++/AdvancedCapture.xaml                  |  39 +-
 .../C++/AdvancedCapture.xaml.cpp              | 505 ++++--------------
 .../C++/AdvancedCapture.xaml.h                |  10 +-
 .../winrt/ImageManipulations/C++/App.xaml.cpp |   2 +
 .../ImageManipulations/C++/MainPage.xaml.cpp  |  12 +-
 .../C++/MediaCapture.vcxproj                  |   4 +-
 .../MediaExtensions/Grayscale/Grayscale.cpp   |  66 ++-
 .../C++/MediaExtensions/Grayscale/Grayscale.h |   2 +-
 .../C++/Package.appxmanifest                  |   3 -
 9 files changed, 149 insertions(+), 494 deletions(-)

diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
index e6266adb9..07db96f27 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
@@ -33,38 +33,31 @@
             </Grid.RowDefinitions>
             <TextBlock TextWrapping="Wrap" Grid.Row="0"  Text="This scenario shows how to enumerate cameras in the system. Choose a camera from the list to preview, record or take a photo from the chosen camera.  You can add the gray scale effect using the checkbox provided." Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left"/>
             <StackPanel Orientation="Horizontal" Grid.Row="1" Margin="0,10,0,0">
-                <ListBox x:Name="EnumedDeviceList2" SelectionChanged="lstEnumedDevices_SelectionChanged" ></ListBox>
-                <Button x:Name="btnStartDevice2" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0">StartDevice</Button>
-                <Button x:Name="btnStartPreview2" Click="btnStartPreview_Click" IsEnabled="true"  Margin="0,0,10,0">StartPreview</Button>
-                <Button x:Name="btnStartStopRecord2" Click="btnStartStopRecord_Click" IsEnabled="false"  Margin="0,0,10,0">StartRecord</Button>
-                <Button x:Name="btnTakePhoto2" Click="btnTakePhoto_Click" IsEnabled="false"  Margin="0,0,10,0">TakePhoto</Button>
-            </StackPanel>
-            <StackPanel Orientation="Horizontal" Grid.Row="2" Margin="0,10,0,0">
-                <CheckBox x:Name="chkAddRemoveEffect" Margin="0,0,10,0" Content="Add Effect"  IsEnabled="False" Checked="chkAddRemoveEffect_Checked" Unchecked="chkAddRemoveEffect_Unchecked"/>
-                <ComboBox Width="120"/>
+                <ListBox x:Name="EnumedDeviceList2" SelectionChanged="lstEnumedDevices_SelectionChanged" />
+                <Button x:Name="btnStartDevice2" Click="btnStartDevice_Click" IsEnabled="true"  Margin="0,0,10,0" Content="StartDevice"/>
+                <Button x:Name="btnStartPreview2" Click="btnStartPreview_Click" IsEnabled="true"  Margin="0,0,10,0" Content="StartPreview"/>
+                <ComboBox x:Name="EffectTypeCombo" Width="120" SelectedIndex="0">
+                    <ComboBoxItem Content="Preview"/>
+                    <ComboBoxItem Content="Grayscale"/>
+                    <ComboBoxItem Content="Canny"/>
+                    <ComboBoxItem Content="Sobel"/>
+                    <ComboBoxItem Content="Histogram"/>
+                </ComboBox>
+                <Button Content="Apply" HorizontalAlignment="Stretch" VerticalAlignment="Top" Click="Button_Click"/>
             </StackPanel>
+            <StackPanel x:Name="EffectTypeCombo1" Orientation="Horizontal" Grid.Row="1" Margin="324,5,-324,7"/>
         </Grid>
 
         <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
             <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
                 <StackPanel>
                     <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Preview' />
-                    <Canvas x:Name="previewCanvas2" Width="320"  Height="240" Background="Gray">
-                        <CaptureElement x:Name="previewElement2" Width="320" Height="240" />
-                    </Canvas>
-                </StackPanel>
-                <StackPanel>
-                    <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Video' />
-                    <Canvas x:Name='playbackCanvas2' Width='320' Height ='240' >
-                        <MediaElement  x:Name='playbackElement2'	  Width="320"  Height="240" />
-                    </Canvas>
-                </StackPanel>
-                <StackPanel>
-                    <TextBlock Style="{StaticResource BasicTextStyle}"  HorizontalAlignment='Center'  VerticalAlignment='Center'  TextAlignment='Center'	Text='Captured Images' />
-                    <Canvas x:Name="imageCanvas2" Width='320' Height ='240' >
-                        <Image x:Name="imageElement2"  Width="320"   Height="240"/>
+                    <Canvas x:Name="previewCanvas2" Background="Gray">
+                        <CaptureElement x:Name="previewElement2" />
                     </Canvas>
                 </StackPanel>
+                <StackPanel/>
+                <StackPanel/>
             </StackPanel>
         </Grid>
 
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
index 15890ba6b..066891dac 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
@@ -23,6 +23,7 @@ using namespace Windows::UI::Xaml::Navigation;
 using namespace Windows::UI::Xaml::Data;
 using namespace Windows::System;
 using namespace Windows::Foundation;
+using namespace Windows::Foundation::Collections;
 using namespace Platform;
 using namespace Windows::UI;
 using namespace Windows::UI::Core;
@@ -80,7 +81,6 @@ void AdvancedCapture::OnNavigatedTo(NavigationEventArgs^ e)
     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
     // as NotifyUser()
     rootPage = MainPage::Current;
-    m_eventRegistrationToken = Windows::Media::MediaControl::SoundLevelChanged += ref new EventHandler<Object^>(this, &AdvancedCapture::SoundLevelChanged);
 
     m_orientationChangedEventToken = Windows::Graphics::Display::DisplayProperties::OrientationChanged += ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(this, &AdvancedCapture::DisplayProperties_OrientationChanged);
 }
@@ -96,18 +96,12 @@ void  AdvancedCapture::ScenarioInit()
     rootPage = MainPage::Current;
     btnStartDevice2->IsEnabled = true;
     btnStartPreview2->IsEnabled = false;
-    btnStartStopRecord2->IsEnabled = false;
     m_bRecording = false;
     m_bPreviewing = false;
     m_bEffectAdded = false;
-    btnStartStopRecord2->Content = "StartRecord";
-    btnTakePhoto2->IsEnabled = false;
     previewElement2->Source = nullptr;
-    playbackElement2->Source = nullptr;
-    imageElement2->Source= nullptr;
     ShowStatusMessage("");
-    chkAddRemoveEffect->IsChecked = false;
-    chkAddRemoveEffect->IsEnabled = false;
+    EffectTypeCombo->IsEnabled = false;
     previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
     EnumerateWebcamsAsync();
     m_bSuspended = false;
@@ -119,104 +113,6 @@ void AdvancedCapture::ScenarioReset()
     ScenarioInit();
 }
 
-void AdvancedCapture::SoundLevelChanged(Object^ sender, Object^ e)
-{
-    create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
-    {
-        if(Windows::Media::MediaControl::SoundLevel != Windows::Media::SoundLevel::Muted)
-        {
-            ScenarioReset();
-        }
-        else
-        {
-            if (m_bRecording)
-            {
-                ShowStatusMessage("Stopping Record on invisibility");
-
-                create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                {
-                    try
-                    {
-                        recordTask.get();
-                        m_bRecording = false;
-                    }
-                    catch (Exception ^e)
-                    {
-                        ShowExceptionMessage(e);
-                    }
-                });
-            }
-            if (m_bPreviewing)
-            {
-                ShowStatusMessage("Stopping Preview on invisibility");
-
-                create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask)
-                {
-                    try
-                    {
-                        previewTask.get();
-                        m_bPreviewing = false;
-
-                    }catch (Exception ^e)
-                    {
-                        ShowExceptionMessage(e);
-                    }
-                });
-            }
-        }
-    })));
-}
-
-void AdvancedCapture::RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject)
-{
-    try
-    {
-        if (m_bRecording)
-        {
-            create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
-            {
-                try
-                {
-                    ShowStatusMessage("Stopping Record on exceeding max record duration");
-                    EnableButton(false, "StartStopRecord");
-                    create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                            ShowStatusMessage("Stopped record on exceeding max record duration:" + m_recordStorageFile->Path);
-                        }
-                        catch (Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            m_bRecording = false;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                        }
-                    });
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    SwitchRecordButtonContent();
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-            })));
-        }
-    }
-    catch (Exception ^e)
-    {
-        m_bRecording = false;
-        SwitchRecordButtonContent();
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-    }
-}
-
 void AdvancedCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure)
 {
     String ^message = "Fatal error" + currentFailure->Message;
@@ -267,8 +163,7 @@ void AdvancedCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI
                 EnableButton(true, "StartStopRecord");
                 EnableButton(true, "TakePhoto");
                 ShowStatusMessage("Device initialized successful");
-                chkAddRemoveEffect->IsEnabled = true;
-                mediaCapture->RecordLimitationExceeded += ref new Windows::Media::Capture::RecordLimitationExceededEventHandler(this, &AdvancedCapture::RecordLimitationExceeded);
+                EffectTypeCombo->IsEnabled = true;
                 mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AdvancedCapture::Failed);
             }
             catch (Exception ^ e)
@@ -317,192 +212,6 @@ void AdvancedCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::U
     }
 }
 
-void AdvancedCapture::btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        ShowStatusMessage("Taking photo");
-        EnableButton(false, "TakePhoto");
-        auto currentRotation = GetCurrentPhotoRotation();
-
-        task<StorageFile^>(KnownFolders::PicturesLibrary->CreateFileAsync(TEMP_PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this, currentRotation](task<StorageFile^> getFileTask)
-        {
-            try
-            {
-                auto tempPhotoStorageFile = getFileTask.get();
-                ShowStatusMessage("Create photo file successful");
-                ImageEncodingProperties^ imageProperties = ImageEncodingProperties::CreateJpeg();
-
-                create_task(m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, tempPhotoStorageFile)).then([this,tempPhotoStorageFile,currentRotation](task<void> photoTask)
-                {
-                    try
-                    {
-                        photoTask.get();
-
-                        ReencodePhotoAsync(tempPhotoStorageFile, currentRotation).then([this] (task<StorageFile^> reencodeImageTask)
-                        {
-                            try
-                            {
-                                auto photoStorageFile = reencodeImageTask.get();
-
-                                EnableButton(true, "TakePhoto");
-                                ShowStatusMessage("Photo taken");
-
-                                task<IRandomAccessStream^>(photoStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> getStreamTask)
-                                {
-                                    try
-                                    {
-                                        auto photoStream = getStreamTask.get();
-                                        ShowStatusMessage("File open successful");
-                                        auto bmpimg = ref new BitmapImage();
-
-                                        bmpimg->SetSource(photoStream);
-                                        imageElement2->Source = bmpimg;
-                                    }
-                                    catch (Exception^ e)
-                                    {
-                                        ShowExceptionMessage(e);
-                                        EnableButton(true, "TakePhoto");
-                                    }
-                                });
-                            }
-                            catch (Platform::Exception ^ e)
-                            {
-                                ShowExceptionMessage(e);
-                                EnableButton(true, "TakePhoto");
-                            }
-                        });
-                    }
-                    catch (Platform::Exception ^ e)
-                    {
-                        ShowExceptionMessage(e);
-                        EnableButton(true, "TakePhoto");
-                    }
-                });
-            }
-            catch (Exception^ e)
-            {
-                ShowExceptionMessage(e);
-                EnableButton(true, "TakePhoto");
-
-            }
-        });
-    }
-    catch (Platform::Exception^ e)
-    {
-        ShowExceptionMessage(e);
-        EnableButton(true, "TakePhoto");
-    }
-}
-
-void AdvancedCapture::btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        String ^fileName;
-        EnableButton(false, "StartStopRecord");
-
-        if (!m_bRecording)
-        {
-            ShowStatusMessage("Starting Record");
-
-            fileName = VIDEO_FILE_NAME;
-
-            PrepareForVideoRecording();
-
-            task<StorageFile^>(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](task<StorageFile^> fileTask)
-            {
-                try
-                {
-                    this->m_recordStorageFile = fileTask.get();
-                    ShowStatusMessage("Create record file successful");
-
-                    MediaEncodingProfile^ recordProfile= nullptr;
-                    recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
-
-                    create_task(m_mediaCaptureMgr->StartRecordToStorageFileAsync(recordProfile, this->m_recordStorageFile)).then([this](task<void> recordTask)
-                    {
-                        try
-                        {
-                            recordTask.get();
-                            m_bRecording = true;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-
-                            ShowStatusMessage("Start Record successful");
-                        }
-                        catch (Exception ^e)
-                        {
-                            m_bRecording = true;
-                            SwitchRecordButtonContent();
-                            EnableButton(true, "StartStopRecord");
-                            ShowExceptionMessage(e);
-                        }
-                    });
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    ShowExceptionMessage(e);
-                }
-            });
-        }
-        else
-        {
-            ShowStatusMessage("Stopping Record");
-
-            create_task(m_mediaCaptureMgr->StopRecordAsync()).then([this](task<void> recordTask)
-            {
-                try
-                {
-                    recordTask.get();
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    SwitchRecordButtonContent();
-
-                    ShowStatusMessage("Stop record successful");
-                    if (!m_bSuspended)
-                    {
-                        task<IRandomAccessStream^>(this->m_recordStorageFile->OpenAsync(FileAccessMode::Read)).then([this](task<IRandomAccessStream^> streamTask)
-                        {
-                            try
-                            {
-                                auto stream = streamTask.get();
-                                ShowStatusMessage("Record file opened");
-                                ShowStatusMessage(this->m_recordStorageFile->Path);
-                                playbackElement2->AutoPlay = true;
-                                playbackElement2->SetSource(stream, this->m_recordStorageFile->FileType);
-                                playbackElement2->Play();
-                            }
-                            catch (Exception ^e)
-                            {
-                                ShowExceptionMessage(e);
-                                m_bRecording = false;
-                                EnableButton(true, "StartStopRecord");
-                                SwitchRecordButtonContent();
-                            }
-                        });
-                    }
-                }
-                catch (Exception ^e)
-                {
-                    m_bRecording = false;
-                    EnableButton(true, "StartStopRecord");
-                    SwitchRecordButtonContent();
-                    ShowExceptionMessage(e);
-                }
-            });
-        }
-    }
-    catch (Platform::Exception^ e)
-    {
-        EnableButton(true, "StartStopRecord");
-        ShowExceptionMessage(e);
-        m_bRecording = false;
-        SwitchRecordButtonContent();
-    }
-}
 void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
 {
      if ( m_bPreviewing )
@@ -523,15 +232,9 @@ void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender
 
     btnStartDevice2->IsEnabled = true;
     btnStartPreview2->IsEnabled = false;
-    btnStartStopRecord2->IsEnabled = false;
     m_bRecording = false;
-    btnStartStopRecord2->Content = "StartRecord";
-    btnTakePhoto2->IsEnabled = false;
     previewElement2->Source = nullptr;
-    playbackElement2->Source = nullptr;
-    imageElement2->Source= nullptr;
-    chkAddRemoveEffect->IsEnabled = false;
-    chkAddRemoveEffect->IsChecked = false;
+    EffectTypeCombo->IsEnabled = false;
     m_bEffectAdded = false;
     m_bEffectAddedToRecord = false;
     m_bEffectAddedToPhoto = false;
@@ -617,14 +320,13 @@ void AdvancedCapture::AddEffectToImageStream()
                                         effectTask3.get();
                                         m_bEffectAddedToPhoto = true;
                                         ShowStatusMessage("Adding effect to photo stream successful");
-                                        chkAddRemoveEffect->IsEnabled = true;
+                                        EffectTypeCombo->IsEnabled = true;
 
                                     }
                                     catch(Exception ^e)
                                     {
                                         ShowExceptionMessage(e);
-                                        chkAddRemoveEffect->IsEnabled = true;
-                                        chkAddRemoveEffect->IsChecked = false;
+                                        EffectTypeCombo->IsEnabled = true;
                                     }
                                 });
 
@@ -632,8 +334,7 @@ void AdvancedCapture::AddEffectToImageStream()
                             catch(Exception ^e)
                             {
                                 ShowExceptionMessage(e);
-                                chkAddRemoveEffect->IsEnabled = true;
-                                chkAddRemoveEffect->IsChecked = false;
+                                EffectTypeCombo->IsEnabled = true;
                             }
 
                         });
@@ -654,14 +355,13 @@ void AdvancedCapture::AddEffectToImageStream()
                     effectTask3.get();
                     m_bEffectAddedToPhoto = true;
                     ShowStatusMessage("Adding effect to photo stream successful");
-                    chkAddRemoveEffect->IsEnabled = true;
+                    EffectTypeCombo->IsEnabled = true;
 
                 }
                 catch(Exception ^e)
                 {
                     ShowExceptionMessage(e);
-                    chkAddRemoveEffect->IsEnabled = true;
-                    chkAddRemoveEffect->IsChecked = false;
+                    EffectTypeCombo->IsEnabled = true;
                 }
             });
         }
@@ -669,82 +369,15 @@ void AdvancedCapture::AddEffectToImageStream()
 }
 
 
-
 void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
 {
-    try
-    {
-        chkAddRemoveEffect->IsEnabled = false;
-        m_bEffectAdded = true;
-        create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask)
-        {
-            try
-            {
-                effectTask.get();
-
-                auto mediaCapture = m_mediaCaptureMgr.Get();
-                Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
-
-                ShowStatusMessage("Add effect successful to preview stream successful");
-                if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
-                    (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical))
-                {
-                    Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord);
-                    Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties  = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props);
-                    if(!videoEncodingProperties->Subtype->Equals("H264")) //Cant add an effect to an H264 stream
-                    {
-                        task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask2)
-                        {
-                            try
-                            {
-                                effectTask2.get();
-                                ShowStatusMessage("Add effect successful to record stream successful");
-                                m_bEffectAddedToRecord = true;
-                                AddEffectToImageStream();
-                                chkAddRemoveEffect->IsEnabled = true;
-                            }
-                            catch(Exception ^e)
-                            {
-                                ShowExceptionMessage(e);
-                                chkAddRemoveEffect->IsEnabled = true;
-                                chkAddRemoveEffect->IsChecked = false;
-                            }
-                        });
-                    }
-                    else
-                    {
-                        AddEffectToImageStream();
-                        chkAddRemoveEffect->IsEnabled = true;
-                    }
-
-                }
-                else
-                {
-                    AddEffectToImageStream();
-                    chkAddRemoveEffect->IsEnabled = true;
-                }
-            }
-            catch (Exception ^e)
-            {
-                ShowExceptionMessage(e);
-                chkAddRemoveEffect->IsEnabled = true;
-                chkAddRemoveEffect->IsChecked = false;
-            }
-        });
-    }
-    catch (Platform::Exception ^e)
-    {
-        ShowExceptionMessage(e);
-        chkAddRemoveEffect->IsEnabled = true;
-        chkAddRemoveEffect->IsChecked = false;
-    }
 }
 
 void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
 {
     try
     {
-        chkAddRemoveEffect->IsEnabled = false;
+        EffectTypeCombo->IsEnabled = false;
         m_bEffectAdded = false;
         create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> effectTask)
         {
@@ -775,8 +408,7 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                                     catch(Exception ^e)
                                     {
                                         ShowExceptionMessage(e);
-                                        chkAddRemoveEffect->IsEnabled = true;
-                                        chkAddRemoveEffect->IsChecked = true;
+                                        EffectTypeCombo->IsEnabled = true;
                                     }
 
                                 });
@@ -784,14 +416,12 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                             else
                             {
                             }
-                            chkAddRemoveEffect->IsEnabled = true;
+                            EffectTypeCombo->IsEnabled = true;
                         }
                         catch(Exception ^e)
                         {
                             ShowExceptionMessage(e);
-                            chkAddRemoveEffect->IsEnabled = true;
-                            chkAddRemoveEffect->IsChecked = true;
-
+                            EffectTypeCombo->IsEnabled = true;
                         }
 
                     });
@@ -811,31 +441,27 @@ void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Win
                         catch(Exception ^e)
                         {
                             ShowExceptionMessage(e);
-                            chkAddRemoveEffect->IsEnabled = true;
-                            chkAddRemoveEffect->IsChecked = true;
+                            EffectTypeCombo->IsEnabled = true;
                         }
 
                     });
                 }
                 else
                 {
-                    chkAddRemoveEffect->IsEnabled = true;
-                    chkAddRemoveEffect->IsChecked = true;
+                    EffectTypeCombo->IsEnabled = true;
                 }
             }
             catch (Exception ^e)
             {
                 ShowExceptionMessage(e);
-                chkAddRemoveEffect->IsEnabled = true;
-                chkAddRemoveEffect->IsChecked = true;
+                EffectTypeCombo->IsEnabled = true;
             }
         });
     }
     catch (Platform::Exception ^e)
     {
         ShowExceptionMessage(e);
-        chkAddRemoveEffect->IsEnabled = true;
-        chkAddRemoveEffect->IsChecked = true;
+        EffectTypeCombo->IsEnabled = true;
     }
 }
 
@@ -849,18 +475,6 @@ void AdvancedCapture::ShowExceptionMessage(Platform::Exception^ ex)
     rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
 }
 
-void AdvancedCapture::SwitchRecordButtonContent()
-{
-    if (m_bRecording)
-    {
-        btnStartStopRecord2->Content="StopRecord";
-    }
-    else
-    {
-        btnStartStopRecord2->Content="StartRecord";
-    }
-}
-
 void AdvancedCapture::EnableButton(bool enabled, String^ name)
 {
     if (name->Equals("StartDevice"))
@@ -871,14 +485,6 @@ void AdvancedCapture::EnableButton(bool enabled, String^ name)
     {
         btnStartPreview2->IsEnabled = enabled;
     }
-    else if (name->Equals("StartStopRecord"))
-    {
-        btnStartStopRecord2->IsEnabled = enabled;
-    }
-    else if (name->Equals("TakePhoto"))
-    {
-        btnTakePhoto2->IsEnabled = enabled;
-    }
 }
 
 task<Windows::Storage::StorageFile^> AdvancedCapture::ReencodePhotoAsync(
@@ -1032,8 +638,79 @@ Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup(
 }
 
 
-
-void SDKSample::MediaCapture::AdvancedCapture::EffectType_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
+void SDKSample::MediaCapture::AdvancedCapture::EffectTypeCombo_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
 {
-
+}
+
+
+void SDKSample::MediaCapture::AdvancedCapture::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
+{
+    try
+    {
+        create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> cleanTask)
+        {
+            m_bEffectAdded = true;
+            int index = EffectTypeCombo->SelectedIndex;
+            PropertySet^ props = ref new PropertySet();
+            props->Insert(L"{698649BE-8EAE-4551-A4CB-3EC98FBD3D86}", index);
+            create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"GrayscaleTransform.GrayscaleEffect", props)).then([this](task<void> effectTask)
+            {
+                try
+                {
+                    effectTask.get();
+
+                    auto mediaCapture = m_mediaCaptureMgr.Get();
+                    Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic;
+
+                    ShowStatusMessage("Add effect successful to preview stream successful");
+                    if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) &&
+                        (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical))
+                    {
+                        Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord);
+                        Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties  = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props);
+                        if(!videoEncodingProperties->Subtype->Equals("H264")) //Cant add an effect to an H264 stream
+                        {
+                            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask2)
+                            {
+                                try
+                                {
+                                    effectTask2.get();
+                                    ShowStatusMessage("Add effect successful to record stream successful");
+                                    m_bEffectAddedToRecord = true;
+                                    AddEffectToImageStream();
+                                    EffectTypeCombo->IsEnabled = true;
+                                }
+                                catch(Exception ^e)
+                                {
+                                    ShowExceptionMessage(e);
+                                    EffectTypeCombo->IsEnabled = true;
+                                }
+                            });
+                        }
+                        else
+                        {
+                            AddEffectToImageStream();
+                            EffectTypeCombo->IsEnabled = true;
+                        }
+
+                    }
+                    else
+                    {
+                        AddEffectToImageStream();
+                        EffectTypeCombo->IsEnabled = true;
+                    }
+                }
+                catch (Exception ^e)
+                {
+                    ShowExceptionMessage(e);
+                    EffectTypeCombo->IsEnabled = true;
+                }
+            });
+        });
+    }
+    catch (Platform::Exception ^e)
+    {
+        ShowExceptionMessage(e);
+        EffectTypeCombo->IsEnabled = true;
+    }
 }
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
index 4784900d7..fb754de32 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
@@ -49,18 +49,12 @@ namespace SDKSample
             void ScenarioInit();
             void ScenarioReset();
 
-            void SoundLevelChanged(Object^ sender, Object^ e);
-            void RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^ mediaCapture);
             void Failed(Windows::Media::Capture::MediaCapture ^ mediaCapture, Windows::Media::Capture::MediaCaptureFailedEventArgs ^ args);
 
             void btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
 
             void btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
 
-            void btnStartStopRecord_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-
-            void btnTakePhoto_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-
             void lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
             void EnumerateWebcamsAsync();
 
@@ -72,7 +66,6 @@ namespace SDKSample
             void ShowExceptionMessage(Platform::Exception^ ex);
 
             void EnableButton(bool enabled, Platform::String ^name);
-            void SwitchRecordButtonContent();
 
             task<Windows::Storage::StorageFile^> ReencodePhotoAsync(
                 Windows::Storage::StorageFile ^tempStorageFile,
@@ -98,7 +91,8 @@ namespace SDKSample
             bool m_bRotateVideoOnOrientationChange;
             bool m_bReversePreviewRotation;
             Windows::Foundation::EventRegistrationToken m_orientationChangedEventToken;
-            void EffectType_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
+            void EffectTypeCombo_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
+            void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
         };
     }
 }
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml.cpp b/samples/winrt/ImageManipulations/C++/App.xaml.cpp
index ef733a1cc..a24a4f9c0 100644
--- a/samples/winrt/ImageManipulations/C++/App.xaml.cpp
+++ b/samples/winrt/ImageManipulations/C++/App.xaml.cpp
@@ -15,10 +15,12 @@
 
 #include "pch.h"
 #include "MainPage.xaml.h"
+#include "AdvancedCapture.xaml.h"
 #include "Common\SuspensionManager.h"
 
 using namespace SDKSample;
 using namespace SDKSample::Common;
+using namespace SDKSample::MediaCapture;
 
 using namespace Concurrency;
 using namespace Platform;
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp b/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
index 070278191..bd897fcc0 100644
--- a/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
+++ b/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
@@ -93,7 +93,7 @@ void MainPage::InvalidateSize()
         {
             // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
             // and the LayoutRoot's margins
-            InputSection->Width = ((availableWidth) - 
+            InputSection->Width = ((availableWidth) -
                 (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
         }
         else
@@ -161,7 +161,7 @@ void MainPage::PopulateScenarios()
 }
 
 /// <summary>
-/// This method is responsible for loading the individual input and output sections for each scenario.  This 
+/// This method is responsible for loading the individual input and output sections for each scenario.  This
 /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
 /// and output sections into the respective UserControl on the main page.
 /// </summary>
@@ -185,7 +185,7 @@ void MainPage::LoadScenario(String^ scenarioName)
     if (input == nullptr)
     {
         // Malformed input section.
-        NotifyUser("Cannot load scenario input section for " + scenarioName + 
+        NotifyUser("Cannot load scenario input section for " + scenarioName +
             "  Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage);
         return;
     }
@@ -193,7 +193,7 @@ void MainPage::LoadScenario(String^ scenarioName)
     if (output == nullptr)
     {
         // Malformed output section.
-        NotifyUser("Cannot load scenario output section for " + scenarioName + 
+        NotifyUser("Cannot load scenario output section for " + scenarioName +
             "  Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage);
         return;
     }
@@ -222,7 +222,7 @@ void MainPage::LoadScenario(String^ scenarioName)
     else
     {
         // Malformed Scenario file.
-        NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" + 
+        NotifyUser("Cannot load scenario: " + scenarioName + ".  Make sure root tag in the '" +
             scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage);
     }
 }
@@ -284,7 +284,7 @@ void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
 /// session.  This will be null the first time a page is visited.</param>
 void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState)
 {
-    (void) navigationParameter;	// Unused parameter
+    (void) navigationParameter;    // Unused parameter
 
     PopulateScenarios();
 
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
index 84b6d3df5..88cb45670 100644
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
@@ -122,9 +122,7 @@
     <Page Include="Common\StandardStyles.xaml">
       <SubType>Designer</SubType>
     </Page>
-    <Page Include="MainPage.xaml">
-      <SubType>Designer</SubType>
-    </Page>
+    <Page Include="MainPage.xaml" />
     <Page Include="Sample-Utils\SampleTemplateStyles.xaml">
       <SubType>Designer</SubType>
     </Page>
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
index e853d4627..87121ef29 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
@@ -189,7 +189,7 @@ void TransformImage_NV12(
 CGrayscale::CGrayscale() :
     m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL),
     m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
-    m_TransformType(Preview), m_rcDest(D2D1::RectU()), m_bStreamingInitialized(false),
+    m_TransformType(Preview), m_bStreamingInitialized(false),
     m_pAttributes(NULL)
 {
     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
@@ -219,7 +219,32 @@ STDMETHODIMP CGrayscale::RuntimeClassInitialize()
 //-------------------------------------------------------------------
 HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
 {
-    return S_OK;
+    HRESULT hr = S_OK;
+
+    if (!pConfiguration)
+        return hr;
+
+    HSTRING key;
+    WindowsCreateString(L"{698649BE-8EAE-4551-A4CB-3EC98FBD3D86}", 38, &key);
+    Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting;
+    pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting));
+    boolean found;
+    spSetting->HasKey(key, &found);
+
+    if (found)
+    {
+        IInspectable* value;
+        spSetting->Lookup(key, &value);
+
+        Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IReference<int>> ref;
+        value->QueryInterface(IID_PPV_ARGS(&ref));
+        int effect = InvalidEffect;
+        ref->get_Value(&effect);
+        if ((effect >= 0) && (effect < InvalidEffect))
+        {
+            m_TransformType = (ProcessingType)effect;
+        }
+    }
 }
 
 // IMFTransform methods. Refer to the Media Foundation SDK documentation for details.
@@ -1327,41 +1352,10 @@ HRESULT CGrayscale::BeginStreaming()
 
     if (!m_bStreamingInitialized)
     {
-        // Get the configuration attributes.
-
-        // Get the destination rectangle.
-
-        RECT rcDest;
-        hr = m_pAttributes->GetBlob(MFT_GRAYSCALE_DESTINATION_RECT, (UINT8*)&rcDest, sizeof(rcDest), NULL);
-        if (hr == MF_E_ATTRIBUTENOTFOUND || !ValidateRect(rcDest))
-        {
-            // The client did not set this attribute, or the client provided an invalid rectangle.
-            // Default to the entire image.
-
-            m_rcDest = D2D1::RectU(0, 0, m_imageWidthInPixels, m_imageHeightInPixels);
-            hr = S_OK;
-        }
-        else if (SUCCEEDED(hr))
-        {
-            m_rcDest = D2D1::RectU(rcDest.left, rcDest.top, rcDest.right, rcDest.bottom);
-        }
-        else
-        {
-            goto done;
-        }
-
-        // Get the effect type
-        UINT32 effect = MFGetAttributeUINT32(m_pAttributes, MFT_IMAGE_EFFECT, 1);
-
-        if ((effect >= 0) && (effect < InvalidEffect))
-        {
-            m_TransformType = (ProcessingType)effect;
-        }
-
         m_bStreamingInitialized = true;
+        hr = S_OK;
     }
 
-done:
     return hr;
 }
 
@@ -1465,14 +1459,14 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
             // RGB
             for (int c=0; c<3; c++)
             {
-                std::vector<int> hist;
+                cv::Mat hist;
                 cv::calcHist(&BgrFrame, 1, channels[c], cv::Mat(), hist, 1, mHistSize, ranges);
                 cv::normalize(hist, hist, BgrFrame.rows/2, 0, cv::NORM_INF);
                 for(int h=0; h<mHistSizeNum; h++) {
                     cv::Point mP1, mP2;
                     mP1.x = mP2.x = offset + (c * (mHistSizeNum + 10) + h) * thikness;
                     mP1.y = BgrFrame.rows-1;
-                    mP2.y = mP1.y - 2 - (int)hist[h];
+                    mP2.y = mP1.y - 2 - hist.at<float>(h);
                     cv::line(BgrFrame, mP1, mP2, mColorsRGB[c], thikness);
                 }
             }
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
index a6a6aa2f1..a1030160b 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
@@ -44,6 +44,7 @@ DEFINE_GUID(MFT_IMAGE_EFFECT,
 
 enum ProcessingType
 {
+    Preview,
     GrayScale,
     Canny,
     Sobel,
@@ -232,7 +233,6 @@ private:
 
     // Transformation parameters
     ProcessingType              m_TransformType;
-    D2D_RECT_U                  m_rcDest;                   // Destination rectangle for the effect.
 
     // Streaming
     bool                        m_bStreamingInitialized;
diff --git a/samples/winrt/ImageManipulations/C++/Package.appxmanifest b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
index c72258b0c..5b4bbd232 100644
--- a/samples/winrt/ImageManipulations/C++/Package.appxmanifest
+++ b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
@@ -22,9 +22,6 @@
     </Application>
   </Applications>
   <Capabilities>
-    <Capability Name="picturesLibrary" />
-    <Capability Name="musicLibrary" />
-    <Capability Name="videosLibrary" />
     <DeviceCapability Name="webcam" />
     <DeviceCapability Name="microphone" />
   </Capabilities>

From b0854c605adec7c227a90c776418e8ef32412609 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 19 Jun 2013 03:57:26 -0700
Subject: [PATCH 35/75] Windows RT sample improved.

Corrent histogram output on YUV image implemented;
Some code refactoring done.
---
 .../C++/AdvancedCapture.xaml.cpp              | 111 +------
 .../C++/AdvancedCapture.xaml.h                |   3 -
 .../ImageManipulations/C++/MediaCapture.sln   |   2 +-
 .../C++/MediaCapture.vcxproj                  |  10 +-
 .../C++/MediaCapture.vcxproj.filters          | 101 -------
 .../Grayscale/Grayscale.vcxproj.filters       |  22 --
 .../OcvTransform/OcvImageManipulations.h      |  92 ++++++
 .../OcvImageManipulations.idl}                |   4 +-
 .../OcvTransform.cpp}                         | 284 +++++-------------
 .../OcvTransform.def}                         |   0
 .../OcvTransform.h}                           |  17 +-
 .../OcvTransform.vcxproj}                     |  24 +-
 .../{Grayscale => OcvTransform}/dllmain.cpp   |   4 +-
 .../C++/Package.appxmanifest                  |   8 +-
 .../C++/assets/microsoft-sdk.png              | Bin 1583 -> 0 bytes
 .../C++/assets/opencv-logo-150.png            | Bin 0 -> 4609 bytes
 .../C++/assets/opencv-logo-30.png             | Bin 0 -> 1099 bytes
 .../C++/assets/placeholder-sdk.png            | Bin 8991 -> 0 bytes
 .../C++/assets/smallTile-sdk.png              | Bin 1248 -> 0 bytes
 .../C++/assets/squareTile-sdk.png             | Bin 2482 -> 0 bytes
 .../C++/assets/storeLogo-sdk.png              | Bin 1550 -> 0 bytes
 .../C++/assets/tile-sdk.png                   | Bin 2665 -> 0 bytes
 22 files changed, 194 insertions(+), 488 deletions(-)
 delete mode 100644 samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
 delete mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
 create mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale/GrayscaleTransform.idl => OcvTransform/OcvImageManipulations.idl} (59%)
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale/Grayscale.cpp => OcvTransform/OcvTransform.cpp} (82%)
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale/Grayscale.def => OcvTransform/OcvTransform.def} (100%)
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale/Grayscale.h => OcvTransform/OcvTransform.h} (95%)
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale/Grayscale.vcxproj => OcvTransform/OcvTransform.vcxproj} (96%)
 rename samples/winrt/ImageManipulations/C++/MediaExtensions/{Grayscale => OcvTransform}/dllmain.cpp (96%)
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/opencv-logo-150.png
 create mode 100644 samples/winrt/ImageManipulations/C++/assets/opencv-logo-30.png
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png
 delete mode 100644 samples/winrt/ImageManipulations/C++/assets/tile-sdk.png

diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
index 066891dac..cff0a5a79 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
@@ -313,7 +313,7 @@ void AdvancedCapture::AddEffectToImageStream()
                                 changeTypeTask.get();
                                 ShowStatusMessage("Change type on photo stream successful");
                                 //Now add the effect on the image pin
-                                task<void>(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
+                                task<void>(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask3)
                                 {
                                     try
                                     {
@@ -348,7 +348,7 @@ void AdvancedCapture::AddEffectToImageStream()
         else
         {
             //Add the effect to the image pin if the type is already "Video"
-            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask3)
+            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask3)
             {
                 try
                 {
@@ -368,103 +368,6 @@ void AdvancedCapture::AddEffectToImageStream()
     }
 }
 
-
-void AdvancedCapture::chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-}
-
-void AdvancedCapture::chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
-{
-    try
-    {
-        EffectTypeCombo->IsEnabled = false;
-        m_bEffectAdded = false;
-        create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> effectTask)
-        {
-            try
-            {
-                effectTask.get();
-                ShowStatusMessage("Remove effect from video preview stream successful");
-                if(m_bEffectAddedToRecord)
-                {
-                    task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoRecord)).then([this](task<void> effectTask)
-                    {
-                        try
-                        {
-                            effectTask.get();
-                            ShowStatusMessage("Remove effect from video record stream successful");
-                            m_bEffectAddedToRecord = false;
-                            if(m_bEffectAddedToPhoto)
-                            {
-                                task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
-                                {
-                                    try
-                                    {
-                                        effectTask.get();
-                                        ShowStatusMessage("Remove effect from Photo stream successful");
-                                        m_bEffectAddedToPhoto = false;
-
-                                    }
-                                    catch(Exception ^e)
-                                    {
-                                        ShowExceptionMessage(e);
-                                        EffectTypeCombo->IsEnabled = true;
-                                    }
-
-                                });
-                            }
-                            else
-                            {
-                            }
-                            EffectTypeCombo->IsEnabled = true;
-                        }
-                        catch(Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            EffectTypeCombo->IsEnabled = true;
-                        }
-
-                    });
-
-                }
-                else if(m_bEffectAddedToPhoto)
-                {
-                    task<void>(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Photo)).then([this](task<void> effectTask)
-                    {
-                        try
-                        {
-                            effectTask.get();
-                            ShowStatusMessage("Remove effect from Photo stream successful");
-                            m_bEffectAddedToPhoto = false;
-
-                        }
-                        catch(Exception ^e)
-                        {
-                            ShowExceptionMessage(e);
-                            EffectTypeCombo->IsEnabled = true;
-                        }
-
-                    });
-                }
-                else
-                {
-                    EffectTypeCombo->IsEnabled = true;
-                }
-            }
-            catch (Exception ^e)
-            {
-                ShowExceptionMessage(e);
-                EffectTypeCombo->IsEnabled = true;
-            }
-        });
-    }
-    catch (Platform::Exception ^e)
-    {
-        ShowExceptionMessage(e);
-        EffectTypeCombo->IsEnabled = true;
-    }
-}
-
 void AdvancedCapture::ShowStatusMessage(Platform::String^ text)
 {
     rootPage->NotifyUser(text, NotifyType::StatusMessage);
@@ -637,12 +540,6 @@ Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup(
     }
 }
 
-
-void SDKSample::MediaCapture::AdvancedCapture::EffectTypeCombo_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
-{
-}
-
-
 void SDKSample::MediaCapture::AdvancedCapture::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
 {
     try
@@ -653,7 +550,7 @@ void SDKSample::MediaCapture::AdvancedCapture::Button_Click(Platform::Object^ se
             int index = EffectTypeCombo->SelectedIndex;
             PropertySet^ props = ref new PropertySet();
             props->Insert(L"{698649BE-8EAE-4551-A4CB-3EC98FBD3D86}", index);
-            create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"GrayscaleTransform.GrayscaleEffect", props)).then([this](task<void> effectTask)
+            create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"OcvTransform.OcvImageManipulations", props)).then([this](task<void> effectTask)
             {
                 try
                 {
@@ -670,7 +567,7 @@ void SDKSample::MediaCapture::AdvancedCapture::Button_Click(Platform::Object^ se
                         Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties  = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props);
                         if(!videoEncodingProperties->Subtype->Equals("H264")) //Cant add an effect to an H264 stream
                         {
-                            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"GrayscaleTransform.GrayscaleEffect", nullptr)).then([this](task<void> effectTask2)
+                            task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask2)
                             {
                                 try
                                 {
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
index fb754de32..94fa87c61 100644
--- a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
+++ b/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
@@ -58,8 +58,6 @@ namespace SDKSample
             void lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
             void EnumerateWebcamsAsync();
 
-            void chkAddRemoveEffect_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
-            void chkAddRemoveEffect_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
             void AddEffectToImageStream();
 
             void ShowStatusMessage(Platform::String^ text);
@@ -91,7 +89,6 @@ namespace SDKSample
             bool m_bRotateVideoOnOrientationChange;
             bool m_bReversePreviewRotation;
             Windows::Foundation::EventRegistrationToken m_orientationChangedEventToken;
-            void EffectTypeCombo_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
             void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
         };
     }
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.sln b/samples/winrt/ImageManipulations/C++/MediaCapture.sln
index 7b99bce31..e1f9aa385 100644
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.sln
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.sln
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
 # Visual Studio 11 Express for Windows 8
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MediaCapture", "MediaCapture.vcxproj", "{C5B886A7-8300-46FF-B533-9613DE2AF637}"
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GrayscaleTransform", "MediaExtensions\Grayscale\Grayscale.vcxproj", "{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GrayscaleTransform", "MediaExtensions\OcvTransform\OcvTransform.vcxproj", "{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}"
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
index 88cb45670..f4eceef61 100644
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
+++ b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
@@ -156,17 +156,13 @@
     </ClCompile>
   </ItemGroup>
   <ItemGroup>
-    <Image Include="Assets\microsoft-sdk.png" />
-    <Image Include="Assets\placeholder-sdk.png" />
-    <Image Include="Assets\smallTile-sdk.png" />
+    <Image Include="assets\opencv-logo-150.png" />
+    <Image Include="assets\opencv-logo-30.png" />
     <Image Include="Assets\splash-sdk.png" />
-    <Image Include="Assets\squareTile-sdk.png" />
-    <Image Include="Assets\storeLogo-sdk.png" />
-    <Image Include="Assets\tile-sdk.png" />
     <Image Include="Assets\windows-sdk.png" />
   </ItemGroup>
   <ItemGroup>
-    <ProjectReference Include="MediaExtensions\Grayscale\Grayscale.vcxproj">
+    <ProjectReference Include="MediaExtensions\OcvTransform\OcvTransform.vcxproj">
       <Project>{ba69218f-da5c-4d14-a78d-21a9e4dec669}</Project>
     </ProjectReference>
   </ItemGroup>
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters b/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
deleted file mode 100644
index 403e5ea1f..000000000
--- a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj.filters
+++ /dev/null
@@ -1,101 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Image Include="Assets\microsoft-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\placeholder-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\smallTile-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\splash-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\squareTile-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\storeLogo-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\tile-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-    <Image Include="Assets\windows-sdk.png">
-      <Filter>Assets</Filter>
-    </Image>
-  </ItemGroup>
-  <ItemGroup>
-    <ApplicationDefinition Include="App.xaml" />
-  </ItemGroup>
-  <ItemGroup>
-    <AppxManifest Include="Package.appxmanifest" />
-  </ItemGroup>
-  <ItemGroup>
-    <Page Include="MainPage.xaml" />
-    <Page Include="Common\StandardStyles.xaml">
-      <Filter>Common</Filter>
-    </Page>
-    <Page Include="Sample-Utils\SampleTemplateStyles.xaml">
-      <Filter>Sample-Utils</Filter>
-    </Page>
-    <Page Include="AdvancedCapture.xaml" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="MainPage.xaml.h" />
-    <ClInclude Include="pch.h" />
-    <ClInclude Include="App.xaml.h" />
-    <ClInclude Include="Common\SuspensionManager.h">
-      <Filter>Common</Filter>
-    </ClInclude>
-    <ClInclude Include="Common\LayoutAwarePage.h">
-      <Filter>Common</Filter>
-    </ClInclude>
-    <ClInclude Include="Constants.h" />
-    <ClInclude Include="AdvancedCapture.xaml.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="App.xaml.cpp" />
-    <ClCompile Include="MainPage.xaml.cpp" />
-    <ClCompile Include="pch.cpp" />
-    <ClCompile Include="Common\LayoutAwarePage.cpp">
-      <Filter>Common</Filter>
-    </ClCompile>
-    <ClCompile Include="Common\SuspensionManager.cpp">
-      <Filter>Common</Filter>
-    </ClCompile>
-    <ClCompile Include="Constants.cpp" />
-    <ClCompile Include="AdvancedCapture.xaml.cpp" />
-  </ItemGroup>
-  <ItemGroup>
-    <Filter Include="Assets">
-      <UniqueIdentifier>{132eec18-b164-4b15-a746-643880e9c5d9}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Common">
-      <UniqueIdentifier>{476b4177-f316-4458-8e13-cab3dc2381c5}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Sample-Utils">
-      <UniqueIdentifier>{54f287f8-e4cb-4f47-97d0-4c469de6992e}</UniqueIdentifier>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\..\..\..\build\install\bin\opencv_calib3d245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_contrib245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_core245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_features2d245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_flann245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_highgui245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_imgproc245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_legacy245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_ml245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_nonfree245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_objdetect245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_photo245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_stitching245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_superres245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_ts245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_video245.dll" />
-    <None Include="..\..\..\..\build\install\bin\opencv_videostab245.dll" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters b/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
deleted file mode 100644
index 92c2c9cfe..000000000
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj.filters
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Resources">
-      <UniqueIdentifier>bdc52ff6-58cb-464b-bf4f-0c1804b135ff</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="Grayscale.def" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="dllmain.cpp" />
-    <ClCompile Include="Grayscale.cpp" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="Grayscale.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <Midl Include="GrayscaleTransform.idl" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
new file mode 100644
index 000000000..5fce7322c
--- /dev/null
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
@@ -0,0 +1,92 @@
+
+
+/* this ALWAYS GENERATED file contains the definitions for the interfaces */
+
+
+ /* File created by MIDL compiler version 8.00.0595 */
+/* at Wed Jun 19 03:47:25 2013
+ */
+/* Compiler settings for C:\Users\ASMORK~1\AppData\Local\Temp\OcvImageManipulations.idl-2e8e757e:
+    Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 8.00.0595 
+    protocol : dce , ms_ext, c_ext, robust
+    error checks: allocation ref bounds_check enum stub_data 
+    VC __declspec() decoration level: 
+         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
+         DECLSPEC_UUID(), MIDL_INTERFACE()
+*/
+/* @@MIDL_FILE_HEADING(  ) */
+
+#pragma warning( disable: 4049 )  /* more than 64k source lines */
+
+
+/* verify that the <rpcndr.h> version is high enough to compile this file*/
+#ifndef __REQUIRED_RPCNDR_H_VERSION__
+#define __REQUIRED_RPCNDR_H_VERSION__ 475
+#endif
+
+#include "rpc.h"
+#include "rpcndr.h"
+
+#ifndef __RPCNDR_H_VERSION__
+#error this stub requires an updated version of <rpcndr.h>
+#endif // __RPCNDR_H_VERSION__
+
+
+#ifndef __OcvImageManipulations_h__
+#define __OcvImageManipulations_h__
+
+#if defined(_MSC_VER) && (_MSC_VER >= 1020)
+#pragma once
+#endif
+
+#if defined(__cplusplus)
+#if defined(__MIDL_USE_C_ENUM)
+#define MIDL_ENUM enum
+#else
+#define MIDL_ENUM enum class
+#endif
+#endif
+
+
+/* Forward Declarations */ 
+
+/* header files for imported files */
+#include "Windows.Media.h"
+
+#ifdef __cplusplus
+extern "C"{
+#endif 
+
+
+/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
+/* [local] */ 
+
+#pragma warning(push)
+#pragma warning(disable:4001) 
+#pragma once
+#pragma warning(pop)
+#ifndef RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
+#define RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
+extern const __declspec(selectany) WCHAR RuntimeClass_OcvTransform_OcvImageManipulations[] = L"OcvTransform.OcvImageManipulations";
+#endif
+
+
+/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
+/* [local] */ 
+
+
+
+extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_c_ifspec;
+extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_s_ifspec;
+
+/* Additional Prototypes for ALL interfaces */
+
+/* end of Additional Prototypes */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.idl
similarity index 59%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.idl
index de81380ec..120ef7dbb 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/GrayscaleTransform.idl
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.idl
@@ -2,10 +2,10 @@ import "Windows.Media.idl";
 
 #include <sdkddkver.h>
 
-namespace GrayscaleTransform
+namespace OcvTransform
 {
 	[version(NTDDI_WIN8)]
-	runtimeclass GrayscaleEffect 
+	runtimeclass OcvImageManipulations 
     {
 	}
 }
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.cpp
similarity index 82%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.cpp
index 87121ef29..bf9812815 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.cpp
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.cpp
@@ -5,49 +5,23 @@
 //
 // Copyright (c) Microsoft Corporation. All rights reserved.
 
-#include "Grayscale.h"
+#include "OcvTransform.h"
 #include "bufferlock.h"
 
 #include "opencv2\core\core.hpp"
 #include "opencv2\imgproc\imgproc.hpp"
 
-#pragma comment(lib, "d2d1")
-
 using namespace Microsoft::WRL;
 
 /*
 
 This sample implements a video effect as a Media Foundation transform (MFT).
 
-The video effect manipulates chroma values in a YUV image. In the default setting,
-the entire image is converted to grayscale. Optionally, the application may set any
-of the following attributes:
-
-MFT_GRAYSCALE_DESTINATION_RECT (type = blob, UINT32[4] array)
-
-    Sets the destination rectangle for the effect. Pixels outside the destination
-    rectangle are not altered.
-
-MFT_GRAYSCALE_SATURATION (type = double)
-
-    Sets the saturation level. The nominal range is [0...1]. Values beyond 1.0f
-    result in supersaturated colors. Values below 0.0f create inverted colors.
-
-MFT_GRAYSCALE_CHROMA_ROTATION (type = double)
-
-    Rotates the chroma values of each pixel. The attribue value is the angle of
-    rotation in degrees. The result is a shift in hue.
-
-The effect is implemented by treating the chroma value of each pixel as a vector [u,v],
-and applying a transformation matrix to the vector. The saturation parameter is applied
-as a scaling transform.
-
-
 NOTES ON THE MFT IMPLEMENTATION
 
 1. The MFT has fixed streams: One input stream and one output stream.
 
-2. The MFT supports the following formats: UYVY, YUY2, NV12.
+2. The MFT supports NV12 format only.
 
 3. If the MFT is holding an input sample, SetInputType and SetOutputType both fail.
 
@@ -82,18 +56,13 @@ NOTES ON THE MFT IMPLEMENTATION
 */
 
 
-// Video FOURCC codes.
-const DWORD FOURCC_NV12 = '21VN';
-
 // Static array of media types (preferred and accepted).
 const GUID g_MediaSubtypes[] =
 {
     MFVideoFormat_NV12
 };
 
-HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage);
 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride);
-bool ValidateRect(const RECT& rc);
 
 template <typename T>
 inline T clamp(const T& val, const T& minVal, const T& maxVal)
@@ -101,92 +70,7 @@ inline T clamp(const T& val, const T& minVal, const T& maxVal)
     return (val < minVal ? minVal : (val > maxVal ? maxVal : val));
 }
 
-//-------------------------------------------------------------------
-// Functions to convert a YUV images to grayscale.
-//
-// In all cases, the same transformation is applied to the 8-bit
-// chroma values, but the pixel layout in memory differs.
-//
-// The image conversion functions take the following parameters:
-//
-// mat               Transfomation matrix for chroma values.
-// rcDest            Destination rectangle.
-// pDest             Pointer to the destination buffer.
-// lDestStride       Stride of the destination buffer, in bytes.
-// pSrc              Pointer to the source buffer.
-// lSrcStride        Stride of the source buffer, in bytes.
-// dwWidthInPixels   Frame width in pixels.
-// dwHeightInPixels  Frame height, in pixels.
-//-------------------------------------------------------------------
-
-// Convert NV12 image
-
-void TransformImage_NV12(
-    const D2D1::Matrix3x2F& mat,
-    const D2D_RECT_U& rcDest,
-    _Inout_updates_(_Inexpressible_(2 * lDestStride * dwHeightInPixels)) BYTE *pDest,
-    _In_ LONG lDestStride,
-    _In_reads_(_Inexpressible_(2 * lSrcStride * dwHeightInPixels)) const BYTE* pSrc,
-    _In_ LONG lSrcStride,
-    _In_ DWORD dwWidthInPixels,
-    _In_ DWORD dwHeightInPixels)
-{
-    // NV12 is planar: Y plane, followed by packed U-V plane.
-
-    // Y plane
-    for (DWORD y = 0; y < dwHeightInPixels; y++)
-    {
-        CopyMemory(pDest, pSrc, dwWidthInPixels);
-        pDest += lDestStride;
-        pSrc += lSrcStride;
-    }
-
-    // U-V plane
-
-    // NOTE: The U-V plane has 1/2 the number of lines as the Y plane.
-
-    // Lines above the destination rectangle.
-    DWORD y = 0;
-
-    const DWORD y0 = rcDest.bottom < dwHeightInPixels ? rcDest.bottom : dwHeightInPixels;
-
-    for ( ; y < rcDest.top/2; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-
-    // Lines within the destination rectangle.
-    for ( ; y < y0/2; y++)
-    {
-        for (DWORD x = 0; (x + 1) < dwWidthInPixels; x += 2)
-        {
-            if (x >= rcDest.left && x < rcDest.right)
-            {
-                pDest[x] = 0;
-                pDest[x+1] = 0;
-            }
-            else
-            {
-                pDest[x] = pSrc[x];
-                pDest[x+1] = pSrc[x+1];
-            }
-        }
-        pDest += lDestStride;
-        pSrc += lSrcStride;
-    }
-
-    // Lines below the destination rectangle.
-    for ( ; y < dwHeightInPixels/2; y++)
-    {
-        memcpy(pDest, pSrc, dwWidthInPixels);
-        pSrc += lSrcStride;
-        pDest += lDestStride;
-    }
-}
-
-CGrayscale::CGrayscale() :
+OcvImageManipulations::OcvImageManipulations() :
     m_pSample(NULL), m_pInputType(NULL), m_pOutputType(NULL),
     m_imageWidthInPixels(0), m_imageHeightInPixels(0), m_cbImageSize(0),
     m_TransformType(Preview), m_bStreamingInitialized(false),
@@ -195,7 +79,7 @@ CGrayscale::CGrayscale() :
     InitializeCriticalSectionEx(&m_critSec, 3000, 0);
 }
 
-CGrayscale::~CGrayscale()
+OcvImageManipulations::~OcvImageManipulations()
 {
     SafeRelease(&m_pInputType);
     SafeRelease(&m_pOutputType);
@@ -205,7 +89,7 @@ CGrayscale::~CGrayscale()
 }
 
 // Initialize the instance.
-STDMETHODIMP CGrayscale::RuntimeClassInitialize()
+STDMETHODIMP OcvImageManipulations::RuntimeClassInitialize()
 {
     // Create the attribute store.
     return MFCreateAttributes(&m_pAttributes, 3);
@@ -217,7 +101,7 @@ STDMETHODIMP CGrayscale::RuntimeClassInitialize()
 // SetProperties
 // Sets the configuration of the effect
 //-------------------------------------------------------------------
-HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
+HRESULT OcvImageManipulations::SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
 {
     HRESULT hr = S_OK;
 
@@ -237,14 +121,16 @@ HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IProper
         spSetting->Lookup(key, &value);
 
         Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IReference<int>> ref;
-        value->QueryInterface(IID_PPV_ARGS(&ref));
+        hr = value->QueryInterface(IID_PPV_ARGS(&ref));
         int effect = InvalidEffect;
-        ref->get_Value(&effect);
+        hr = ref->get_Value(&effect);
         if ((effect >= 0) && (effect < InvalidEffect))
         {
             m_TransformType = (ProcessingType)effect;
         }
     }
+
+	return hr;
 }
 
 // IMFTransform methods. Refer to the Media Foundation SDK documentation for details.
@@ -254,7 +140,7 @@ HRESULT CGrayscale::SetProperties(ABI::Windows::Foundation::Collections::IProper
 // Returns the minimum and maximum number of streams.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetStreamLimits(
+HRESULT OcvImageManipulations::GetStreamLimits(
     DWORD   *pdwInputMinimum,
     DWORD   *pdwInputMaximum,
     DWORD   *pdwOutputMinimum,
@@ -283,7 +169,7 @@ HRESULT CGrayscale::GetStreamLimits(
 // Returns the actual number of streams.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetStreamCount(
+HRESULT OcvImageManipulations::GetStreamCount(
     DWORD   *pcInputStreams,
     DWORD   *pcOutputStreams
 )
@@ -307,7 +193,7 @@ HRESULT CGrayscale::GetStreamCount(
 // Returns stream IDs for the input and output streams.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetStreamIDs(
+HRESULT OcvImageManipulations::GetStreamIDs(
     DWORD   dwInputIDArraySize,
     DWORD   *pdwInputIDs,
     DWORD   dwOutputIDArraySize,
@@ -328,7 +214,7 @@ HRESULT CGrayscale::GetStreamIDs(
 // Returns information about an input stream.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetInputStreamInfo(
+HRESULT OcvImageManipulations::GetInputStreamInfo(
     DWORD                     dwInputStreamID,
     MFT_INPUT_STREAM_INFO *   pStreamInfo
 )
@@ -375,7 +261,7 @@ HRESULT CGrayscale::GetInputStreamInfo(
 // Returns information about an output stream.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetOutputStreamInfo(
+HRESULT OcvImageManipulations::GetOutputStreamInfo(
     DWORD                     dwOutputStreamID,
     MFT_OUTPUT_STREAM_INFO *  pStreamInfo
 )
@@ -424,7 +310,7 @@ HRESULT CGrayscale::GetOutputStreamInfo(
 // Returns the attributes for the MFT.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetAttributes(IMFAttributes** ppAttributes)
+HRESULT OcvImageManipulations::GetAttributes(IMFAttributes** ppAttributes)
 {
     if (ppAttributes == NULL)
     {
@@ -446,7 +332,7 @@ HRESULT CGrayscale::GetAttributes(IMFAttributes** ppAttributes)
 // Returns stream-level attributes for an input stream.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetInputStreamAttributes(
+HRESULT OcvImageManipulations::GetInputStreamAttributes(
     DWORD           dwInputStreamID,
     IMFAttributes   **ppAttributes
 )
@@ -461,7 +347,7 @@ HRESULT CGrayscale::GetInputStreamAttributes(
 // Returns stream-level attributes for an output stream.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetOutputStreamAttributes(
+HRESULT OcvImageManipulations::GetOutputStreamAttributes(
     DWORD           dwOutputStreamID,
     IMFAttributes   **ppAttributes
 )
@@ -475,7 +361,7 @@ HRESULT CGrayscale::GetOutputStreamAttributes(
 // DeleteInputStream
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::DeleteInputStream(DWORD dwStreamID)
+HRESULT OcvImageManipulations::DeleteInputStream(DWORD dwStreamID)
 {
     // This MFT has a fixed number of input streams, so the method is not supported.
     return E_NOTIMPL;
@@ -486,7 +372,7 @@ HRESULT CGrayscale::DeleteInputStream(DWORD dwStreamID)
 // AddInputStreams
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::AddInputStreams(
+HRESULT OcvImageManipulations::AddInputStreams(
     DWORD   cStreams,
     DWORD   *adwStreamIDs
 )
@@ -501,7 +387,7 @@ HRESULT CGrayscale::AddInputStreams(
 // Returns a preferred input type.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetInputAvailableType(
+HRESULT OcvImageManipulations::GetInputAvailableType(
     DWORD           dwInputStreamID,
     DWORD           dwTypeIndex, // 0-based
     IMFMediaType    **ppType
@@ -549,7 +435,7 @@ HRESULT CGrayscale::GetInputAvailableType(
 // Returns a preferred output type.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetOutputAvailableType(
+HRESULT OcvImageManipulations::GetOutputAvailableType(
     DWORD           dwOutputStreamID,
     DWORD           dwTypeIndex, // 0-based
     IMFMediaType    **ppType
@@ -594,7 +480,7 @@ HRESULT CGrayscale::GetOutputAvailableType(
 // SetInputType
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::SetInputType(
+HRESULT OcvImageManipulations::SetInputType(
     DWORD           dwInputStreamID,
     IMFMediaType    *pType, // Can be NULL to clear the input type.
     DWORD           dwFlags
@@ -656,7 +542,7 @@ done:
 // SetOutputType
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::SetOutputType(
+HRESULT OcvImageManipulations::SetOutputType(
     DWORD           dwOutputStreamID,
     IMFMediaType    *pType, // Can be NULL to clear the output type.
     DWORD           dwFlags
@@ -718,7 +604,7 @@ done:
 // Returns the current input type.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetInputCurrentType(
+HRESULT OcvImageManipulations::GetInputCurrentType(
     DWORD           dwInputStreamID,
     IMFMediaType    **ppType
 )
@@ -755,7 +641,7 @@ HRESULT CGrayscale::GetInputCurrentType(
 // Returns the current output type.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetOutputCurrentType(
+HRESULT OcvImageManipulations::GetOutputCurrentType(
     DWORD           dwOutputStreamID,
     IMFMediaType    **ppType
 )
@@ -793,7 +679,7 @@ HRESULT CGrayscale::GetOutputCurrentType(
 // Query if the MFT is accepting more input.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetInputStatus(
+HRESULT OcvImageManipulations::GetInputStatus(
     DWORD           dwInputStreamID,
     DWORD           *pdwFlags
 )
@@ -840,7 +726,7 @@ HRESULT CGrayscale::GetInputStatus(
 // Query if the MFT can produce output.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::GetOutputStatus(DWORD *pdwFlags)
+HRESULT OcvImageManipulations::GetOutputStatus(DWORD *pdwFlags)
 {
     if (pdwFlags == NULL)
     {
@@ -869,7 +755,7 @@ HRESULT CGrayscale::GetOutputStatus(DWORD *pdwFlags)
 // Sets the range of time stamps that the MFT will output.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::SetOutputBounds(
+HRESULT OcvImageManipulations::SetOutputBounds(
     LONGLONG        hnsLowerBound,
     LONGLONG        hnsUpperBound
 )
@@ -884,7 +770,7 @@ HRESULT CGrayscale::SetOutputBounds(
 // Sends an event to an input stream.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::ProcessEvent(
+HRESULT OcvImageManipulations::ProcessEvent(
     DWORD              dwInputStreamID,
     IMFMediaEvent      *pEvent
 )
@@ -900,7 +786,7 @@ HRESULT CGrayscale::ProcessEvent(
 // ProcessMessage
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::ProcessMessage(
+HRESULT OcvImageManipulations::ProcessMessage(
     MFT_MESSAGE_TYPE    eMessage,
     ULONG_PTR           ulParam
 )
@@ -965,7 +851,7 @@ HRESULT CGrayscale::ProcessMessage(
 // Process an input sample.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::ProcessInput(
+HRESULT OcvImageManipulations::ProcessInput(
     DWORD               dwInputStreamID,
     IMFSample           *pSample,
     DWORD               dwFlags
@@ -1030,7 +916,7 @@ done:
 // Process an output sample.
 //-------------------------------------------------------------------
 
-HRESULT CGrayscale::ProcessOutput(
+HRESULT OcvImageManipulations::ProcessOutput(
     DWORD                   dwFlags,
     DWORD                   cOutputBufferCount,
     MFT_OUTPUT_DATA_BUFFER  *pOutputSamples, // one per stream
@@ -1150,7 +1036,7 @@ done:
 // dwTypeIndex: Index into the list of peferred media types.
 // ppmt:        Receives a pointer to the media type.
 
-HRESULT CGrayscale::OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt)
+HRESULT OcvImageManipulations::OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt)
 {
     if (dwTypeIndex >= ARRAYSIZE(g_MediaSubtypes))
     {
@@ -1188,7 +1074,7 @@ done:
 
 // Validate an input media type.
 
-HRESULT CGrayscale::OnCheckInputType(IMFMediaType *pmt)
+HRESULT OcvImageManipulations::OnCheckInputType(IMFMediaType *pmt)
 {
     assert(pmt != NULL);
 
@@ -1217,7 +1103,7 @@ HRESULT CGrayscale::OnCheckInputType(IMFMediaType *pmt)
 
 // Validate an output media type.
 
-HRESULT CGrayscale::OnCheckOutputType(IMFMediaType *pmt)
+HRESULT OcvImageManipulations::OnCheckOutputType(IMFMediaType *pmt)
 {
     assert(pmt != NULL);
 
@@ -1247,7 +1133,7 @@ HRESULT CGrayscale::OnCheckOutputType(IMFMediaType *pmt)
 
 // Validate a media type (input or output)
 
-HRESULT CGrayscale::OnCheckMediaType(IMFMediaType *pmt)
+HRESULT OcvImageManipulations::OnCheckMediaType(IMFMediaType *pmt)
 {
     BOOL bFoundMatchingSubtype = FALSE;
 
@@ -1307,7 +1193,7 @@ done:
 //
 // Prerequisite: The input type was already validated.
 
-void CGrayscale::OnSetInputType(IMFMediaType *pmt)
+void OcvImageManipulations::OnSetInputType(IMFMediaType *pmt)
 {
     // if pmt is NULL, clear the type.
     // if pmt is non-NULL, set the type.
@@ -1328,7 +1214,7 @@ void CGrayscale::OnSetInputType(IMFMediaType *pmt)
 //
 // Prerequisite: The output type was already validated.
 
-void CGrayscale::OnSetOutputType(IMFMediaType *pmt)
+void OcvImageManipulations::OnSetOutputType(IMFMediaType *pmt)
 {
     // If pmt is NULL, clear the type. Otherwise, set the type.
 
@@ -1346,7 +1232,7 @@ void CGrayscale::OnSetOutputType(IMFMediaType *pmt)
 // This method is called if the client sends the MFT_MESSAGE_NOTIFY_BEGIN_STREAMING
 // message, or when the client processes a sample, whichever happens first.
 
-HRESULT CGrayscale::BeginStreaming()
+HRESULT OcvImageManipulations::BeginStreaming()
 {
     HRESULT hr = S_OK;
 
@@ -1366,7 +1252,7 @@ HRESULT CGrayscale::BeginStreaming()
 // message, or when the media type changes. In general, it should be called whenever
 // the streaming parameters need to be reset.
 
-HRESULT CGrayscale::EndStreaming()
+HRESULT OcvImageManipulations::EndStreaming()
 {
     m_bStreamingInitialized = false;
     return S_OK;
@@ -1376,7 +1262,7 @@ HRESULT CGrayscale::EndStreaming()
 
 // Generate output data.
 
-HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
+HRESULT OcvImageManipulations::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
 {
     BYTE *pDest = NULL;         // Destination buffer.
     LONG lDestStride = 0;       // Destination stride.
@@ -1447,10 +1333,17 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
             const int mHistSize[] = {25};
             const float baseRabge[] = {0.f,256.f};
             const float* ranges[] = {baseRabge};
-            const cv::Scalar mColorsRGB[] = { cv::Scalar(200, 0, 0, 255), cv::Scalar(0, 200, 0, 255),
-                                        cv::Scalar(0, 0, 200, 255) };
+            
+			const cv::Scalar mColorsY[] = { cv::Scalar(76), cv::Scalar(149), cv::Scalar(29) };
+			const cv::Scalar mColorsUV[] = { cv::Scalar(84, 255), cv::Scalar(43, 21), cv::Scalar(255, 107) };
 
+			cv::Mat OutputY(m_imageHeightInPixels, m_imageWidthInPixels, CV_8UC1, pDest, lDestStride);
+			cv::Mat OutputUV(m_imageHeightInPixels/2, m_imageWidthInPixels/2,
+							 CV_8UC2, pDest+m_imageHeightInPixels*lDestStride, lDestStride);
             cv::Mat BgrFrame;
+
+			InputFrame.copyTo(OutputFrame);
+
             cv::cvtColor(InputFrame, BgrFrame, cv::COLOR_YUV420sp2BGR);
             int thikness = (int) (BgrFrame.cols / (mHistSizeNum + 10) / 5);
             if(thikness > 5) thikness = 5;
@@ -1464,14 +1357,20 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
                 cv::normalize(hist, hist, BgrFrame.rows/2, 0, cv::NORM_INF);
                 for(int h=0; h<mHistSizeNum; h++) {
                     cv::Point mP1, mP2;
-                    mP1.x = mP2.x = offset + (c * (mHistSizeNum + 10) + h) * thikness;
+					// Draw on Y plane
+					mP1.x = mP2.x = offset + (c * (mHistSizeNum + 10) + h) * thikness;
                     mP1.y = BgrFrame.rows-1;
-                    mP2.y = mP1.y - 2 - hist.at<float>(h);
-                    cv::line(BgrFrame, mP1, mP2, mColorsRGB[c], thikness);
-                }
-            }
+                    mP2.y = mP1.y - 2 - (int)hist.at<float>(h);
+					cv::line(OutputY, mP1, mP2, mColorsY[c], thikness);
 
-            cv::cvtColor(BgrFrame, OutputFrame, cv::COLOR_BGR2YUV_I420);
+					// Draw on UV planes
+                    mP1.x /= 2;
+                    mP1.y /= 2;
+					mP2.x /= 2;
+                    mP2.y /= 2;
+					cv::line(OutputUV, mP1, mP2, mColorsUV[c], thikness/2);
+                }
+            }            
         } break;
     default:
         break;
@@ -1486,7 +1385,7 @@ HRESULT CGrayscale::OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut)
 
 // Flush the MFT.
 
-HRESULT CGrayscale::OnFlush()
+HRESULT OcvImageManipulations::OnFlush()
 {
     // For this MFT, flushing just means releasing the input sample.
     SafeRelease(&m_pSample);
@@ -1497,7 +1396,7 @@ HRESULT CGrayscale::OnFlush()
 // Update the format information. This method is called whenever the
 // input type is set.
 
-HRESULT CGrayscale::UpdateFormatInfo()
+HRESULT OcvImageManipulations::UpdateFormatInfo()
 {
     HRESULT hr = S_OK;
 
@@ -1526,8 +1425,8 @@ HRESULT CGrayscale::UpdateFormatInfo()
             goto done;
         }
 
-        // Calculate the image size (not including padding)
-        hr = GetImageSize(subtype.Data1, m_imageWidthInPixels, m_imageHeightInPixels, &m_cbImageSize);
+        // Calculate the image size for YUV NV12 image(not including padding)
+		m_cbImageSize = (m_imageHeightInPixels + m_imageHeightInPixels/2)*m_imageWidthInPixels;
     }
 
 done:
@@ -1535,35 +1434,6 @@ done:
 }
 
 
-// Calculate the size of the buffer needed to store the image.
-
-// fcc: The FOURCC code of the video format.
-
-HRESULT GetImageSize(DWORD fcc, UINT32 width, UINT32 height, DWORD* pcbImage)
-{
-    HRESULT hr = S_OK;
-
-    switch (fcc)
-    {
-    case FOURCC_NV12:
-        // check overflow
-        if ((height/2 > MAXDWORD - height) || ((height + height/2) > MAXDWORD / width))
-        {
-            hr = E_INVALIDARG;
-        }
-        else
-        {
-            // 12 bpp
-            *pcbImage = width * (height + (height/2));
-        }
-        break;
-
-    default:
-        hr = E_FAIL;    // Unsupported type.
-    }
-    return hr;
-}
-
 // Get the default stride for a video format.
 HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
 {
@@ -1614,23 +1484,3 @@ HRESULT GetDefaultStride(IMFMediaType *pType, LONG *plStride)
     return hr;
 }
 
-
-// Validate that a rectangle meets the following criteria:
-//
-//  - All coordinates are non-negative.
-//  - The rectangle is not flipped (top > bottom, left > right)
-//
-// These are the requirements for the destination rectangle.
-
-bool ValidateRect(const RECT& rc)
-{
-    if (rc.left < 0 || rc.top < 0)
-    {
-        return false;
-    }
-    if (rc.left > rc.right || rc.top > rc.bottom)
-    {
-        return false;
-    }
-    return true;
-}
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.def
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.def
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.def
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.h
similarity index 95%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.h
index a1030160b..118f6e432 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.h
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.h
@@ -18,14 +18,11 @@
 #include <strsafe.h>
 #include <assert.h>
 
-// Note: The Direct2D helper library is included for its 2D matrix operations.
-#include <D2d1helper.h>
-
 #include <wrl\implements.h>
 #include <wrl\module.h>
 #include <windows.media.h>
 
-#include "GrayscaleTransform.h"
+#include "OcvImageManipulations.h"
 
 // CLSID of the MFT.
 DEFINE_GUID(CLSID_GrayscaleMFT,
@@ -38,7 +35,7 @@ DEFINE_GUID(CLSID_GrayscaleMFT,
 
 // Configuration attributes
 // {698649BE-8EAE-4551-A4CB-3EC98FBD3D86}
-DEFINE_GUID(MFT_IMAGE_EFFECT,
+DEFINE_GUID(OCV_IMAGE_EFFECT,
 0x698649be, 0x8eae, 0x4551, 0xa4, 0xcb, 0x3e, 0xc9, 0x8f, 0xbd, 0x3d, 0x86);
 
 
@@ -61,21 +58,21 @@ template <class T> void SafeRelease(T **ppT)
     }
 }
 
-// CGrayscale class:
+// OcvImageManipulations class:
 // Implements a grayscale video effect.
 
-class CGrayscale
+class OcvImageManipulations
     : public Microsoft::WRL::RuntimeClass<
            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
            ABI::Windows::Media::IMediaExtension,
            IMFTransform >
 {
-    InspectableClass(RuntimeClass_GrayscaleTransform_GrayscaleEffect, BaseTrust)
+    InspectableClass(RuntimeClass_OcvTransform_OcvImageManipulations, BaseTrust)
 
 public:
-    CGrayscale();
+    OcvImageManipulations();
 
-    ~CGrayscale();
+    ~OcvImageManipulations();
 
     STDMETHOD(RuntimeClassInitialize)();
 
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.vcxproj
similarity index 96%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.vcxproj
index c7e905936..fbe768cc9 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/Grayscale.vcxproj
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.vcxproj
@@ -30,8 +30,8 @@
     <VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and '$(VisualStudioVersion)' == ''">$(VCTargetsPath11)</VCTargetsPath>
     <ProjectGuid>{BA69218F-DA5C-4D14-A78D-21A9E4DEC669}</ProjectGuid>
     <Keyword>Win32Proj</Keyword>
-    <RootNamespace>GrayscaleTransform</RootNamespace>
-    <ProjectName>GrayscaleTransform</ProjectName>
+    <RootNamespace>OcvTransform</RootNamespace>
+    <ProjectName>OcvTransform</ProjectName>
     <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion>
     <AppContainerApplication>true</AppContainerApplication>
   </PropertyGroup>
@@ -129,7 +129,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib;opencv_core245.lib;opencv_imgproc245.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -153,7 +153,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -177,7 +177,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -201,7 +201,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -225,7 +225,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -249,7 +249,7 @@
       <SubSystem>Console</SubSystem>
       <AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies);mf.lib;mfuuid.lib;mfplat.lib</AdditionalDependencies>
       <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <ModuleDefinitionFile>Grayscale.def</ModuleDefinitionFile>
+      <ModuleDefinitionFile>OcvTransform.def</ModuleDefinitionFile>
       <AdditionalLibraryDirectories>$(OPENCV_DIR)\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
     </Link>
     <CustomBuildStep>
@@ -258,17 +258,17 @@
     </CustomBuildStep>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClInclude Include="Grayscale.h" />
+    <ClInclude Include="OcvTransform.h" />
   </ItemGroup>
   <ItemGroup>
     <ClCompile Include="dllmain.cpp" />
-    <ClCompile Include="Grayscale.cpp" />
+    <ClCompile Include="OcvTransform.cpp" />
   </ItemGroup>
   <ItemGroup>
-    <None Include="Grayscale.def" />
+    <None Include="OcvTransform.def" />
   </ItemGroup>
   <ItemGroup>
-    <Midl Include="GrayscaleTransform.idl">
+    <Midl Include="OcvImageManipulations.idl">
       <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
       </MetadataFileName>
       <MetadataFileName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/dllmain.cpp
similarity index 96%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp
rename to samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/dllmain.cpp
index ad6767011..d11bceaf0 100644
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/Grayscale/dllmain.cpp
+++ b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/dllmain.cpp
@@ -12,12 +12,12 @@
 //////////////////////////////////////////////////////////////////////////
 
 #include <initguid.h>
-#include "Grayscale.h"
+#include "OcvTransform.h"
 
 using namespace Microsoft::WRL;
 
 namespace Microsoft { namespace Samples {
-    ActivatableClass(CGrayscale);
+	ActivatableClass(OcvImageManipulations);
 }}
 
 BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved )
diff --git a/samples/winrt/ImageManipulations/C++/Package.appxmanifest b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
index 5b4bbd232..9d63dea7c 100644
--- a/samples/winrt/ImageManipulations/C++/Package.appxmanifest
+++ b/samples/winrt/ImageManipulations/C++/Package.appxmanifest
@@ -15,8 +15,8 @@
   </Resources>
   <Applications>
     <Application Id="MediaCapture.App" Executable="$targetnametoken$.exe" EntryPoint="MediaCapture.App">
-      <VisualElements DisplayName="MediaCapture CPP sample" Logo="Assets\squareTile-sdk.png" SmallLogo="Assets\smallTile-sdk.png" Description="MediaCapture CPP sample" ForegroundText="light" BackgroundColor="#00b2f0">
-        <DefaultTile ShortName="MC CPP" ShowName="allLogos" />
+      <VisualElements DisplayName="OCV Image Manipulations" Logo="assets\opencv-logo-150.png" SmallLogo="assets\opencv-logo-30.png" Description="OpenCV Image Manipulations sample" ForegroundText="light" BackgroundColor="#00b2f0">
+        <DefaultTile ShortName="Ocv ImageManipulations" ShowName="allLogos" />
         <SplashScreen Image="Assets\splash-sdk.png" BackgroundColor="#00b2f0" />
       </VisualElements>
     </Application>
@@ -28,8 +28,8 @@
   <Extensions>
     <Extension Category="windows.activatableClass.inProcessServer">
       <InProcessServer>
-        <Path>GrayscaleTransform.dll</Path>
-        <ActivatableClass ActivatableClassId="GrayscaleTransform.GrayscaleEffect" ThreadingModel="both" />
+        <Path>OcvTransform.dll</Path>
+        <ActivatableClass ActivatableClassId="OcvTransform.OcvImageManipulations" ThreadingModel="both" />
       </InProcessServer>
     </Extension>
   </Extensions>
diff --git a/samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png b/samples/winrt/ImageManipulations/C++/assets/microsoft-sdk.png
deleted file mode 100644
index 1a1aec25b67aa1dc55663bdc58da2083107eac0d..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 1583
zcmV+~2GIG5P)<h;3K|Lk000e1NJLTq003qH000pP1^@s6FZkIT00001b5ch_0Itp)
z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGmbN~PnbOGLGA9w%&02y>eSaefwW^{L9
za%BKeVQFr3E>1;MAa*k@H7+-&gq_R)00o~(L_t(oN9~visFhU^$9--EX8GC_#TFqg
zGsMa^)1tx*B!f1x#mt4Mtc<dvMP6w{w9{g=*sCOHv)3LiWNQ0j3npzw`@Yh?{(qOb
z@pt&{$GzR49{AwT{btUbIcH|hnVIvtbXon^`8?3x-rgd-Dg0P~9#xApwu$g<fy~q5
z?U?u-ozD~X?O1m95#|bugja=S@ami0fRvPOB>W-#S%BUan9FL&TqXX@G&Z||Ep!@D
z+1O23l5Bln^t!^c!t;TdO&cXe2h?ylf!crt^xI$fp@!Vy;*S+hGz@8aWB)@1vTyg~
zg9k;A3j6(FPi%VoQhH%YU<O8D&MT4GTw~h`+Xwh=v76Q^dSBsW;Z)%;VSsO3^iZ2W
zjQPQvsNXe%-cG+~3fBit*YB|G0P#5092C;cO~P%$wZcil;39{Kzh&$Xxf_JD*^k+<
zaqMrtemwxk2LFo0KT!16vF~m4yJ5qD(xfMoQeSv8jd4w>Ek&vBGx6E9r@~hvn7zcm
zKq$ItKZo&^0P6b#)BmWx9|;=%U;$py`oD{Rsn9L-4AS=tCHDNPvE$9*eMR4%_V4T5
zsIi_xM~Tj&eZhNN*g=>sOl>GIn!stK=+{!dmBwb5jNhxV{nPl>qSq0gsl%8llA)>a
z^*zWhX^i0e_;;cStn+3?V4gBQdhQgs0lyd@ds~G80!@$W;ShbFc;}1$qz+rM56Lq4
zZ<4T2qk*BD$_m{vyJ`IMl1-6Law?oE-mPg4H(<DMLgGIs`k)4kzFe{#CT@n`;tzx8
zdw*NJ?h&x-^i4pk7^3gT(z**p({Yg@m|OJ=hk!adE6G#nsn4Y7e9PbuinTeUl^b36
zUxA}IG4I$yciHz!edpV?hj=*^9x0wXh<TOnPQU#GPH7dS9a51Sh9e00#fkrf8>sJx
zY@GFWO6#KYHG%w3Iw2+Y5V{K!l5Y0c%TgSjrtfK_XimQK=7voK&G}>N4nQqIDZC{q
zT_l>myt<G(I6I1bO}FO3`bzXQN$1gJ8<i}##toYm2Io{bAvFx-aGy6&biS!RPCZ&6
zaO1MwtF*TopPzK^Ec(jC+dKB@{NE(AUQ>aQf)?T3v{;*Hu4qnguZuS$@n05AtLU<{
zk6wHU?4~6LqqoL?G9AnHO;<(1^`-%X*Rm5$V?kPCZ4Ssi0ylwqrwOFCY(tf%GkhbB
z4>jFgHHN)@IH^Z38jm3Ni@-R4MN>fug+&ibYRb|AqqwfLsctOSowtkg+LBQi;Ez;t
z?_@)+FV*yb<Go-Lgs$d14#`KtMFMq_+u~>yO}l!OkPqMe;=Pyl-Pd%FPh;HZwFPfD
z-V)t{ZHeFhZv-ZHQ=Cv7vN&yw)5U3Ak@y7bj>H=$+H*fat8^s#Jwou*NT<VF!vj0c
z9F!e8CiINa954Lbm~WDv8Kx%}XVO`2zbA$6Ei}eU-uHx`c1^qmA-_xF^Ufk*f4}1z
z4wNS6ZfbEX_HbH^mUevs2l$406#Dyvapa~YIZi$eg$IS3w4cynvZSk4bLcrq54DV9
zj-2n~4AFNd-j|{;5qL*Y_dG4_DSC2}XYZuZ+=laxX%TX8D}fgu-}qkG+s8tmh67@T
z)8)9*IkDIS#;0vuL)a_H^0wgd>GPMzd~Vl$Y0Tv~?T3WHpPF3dVVdelQCh9)!ilHE
znj`f6Mai1X;V_&P^3;)=OXQKAC-e;Yg-Lc~@cA!CKCsLFaZo}jZ7Ox5iV?v-#(3j{
z$0>7JYRmA%n{G~}2p=cVO5=QrF-~q1`iD;546buZHb~=iP`rKk5BAprL8a-Swyg5+
z717j~a|LPww}cyt(^d+c{Lv}!1m{qJw8mSFhb0G*zfnncPTFfFU}48-jq#YI2J>Dz
hxT(Obp8Vf?;4d8suiatp%?AJg002ovPDHLkV1jTD8!rF=

diff --git a/samples/winrt/ImageManipulations/C++/assets/opencv-logo-150.png b/samples/winrt/ImageManipulations/C++/assets/opencv-logo-150.png
new file mode 100644
index 0000000000000000000000000000000000000000..ea685d651ace9ce7ed2463b84bbff6ea2d891f9c
GIT binary patch
literal 4609
zcmV+c68`OpP)<h;3K|Lk000e1NJLTq005Q%005Q<1^@s6JOOdy00001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L04^f{04^f|c%?sf00007bV*G`2i*n}
z3K|J({%<J&01<&nL_t(|+U=ctkQ~)@hriqVMCdJE5>g2XSww<@1dJVIOJMBShDvZ1
zwi5>zR3gB3IVvS~z)((6Nq{OVDa8rIl&cbA62~@ncqD;}9SlN_LV=8Mcm+{NmJ|@M
z=z)YJ*wyY%pOZhjd!}c0c6T24_Vmo&qiXePHQRgpp5HyMd+s^l$&)8fo;-Q-<jIpG
z(kkD32neB9VODZUbng$LtCnX>RqCGV6A%(1#6-ZDrSL(8PXus@!crgrdMbXbU?5aD
zDzG(xM}bES>`ee>JhrAD9ZP*JaD~8w3a<*N##j8cXzF_vmq__%Rp1?grv&~agp*Uh
z!&9e{lz+WKU}FV<CIV5dSLJiI2wW*J-E*J=Rb9#kI$7bx7*IBVR1e_3Dqz%0u+A~a
zLpV#}XDKz8C8*Nsb-%!$dCs&yumXWw({@mcFG&IHgWmpXPf#ruIIfc$;VruaHfZcX
zdVsZofv&JtpwLRSR|BXLuX4NkuuuN&DS>ZDj-}Lis!?IN=VDGlrSNxc1gbG%3V}6V
zE#^%9h46s3C#cdv*5MGAd9LOsoN!;B?WsD!6$&iz+-<$YTHgtv(y`k^r+AgvI`y}z
zoz>qY`;gDKGmqMO6JFu4!YtE)$pji*_jkc(+c8@rXwwNd3R@Lso6gNp(EvWJ@PT%G
z!M0?Iz(v55W(uS}DGU!oe}9|3XwYVWLZQn<pkfMuN)7b&!L42ux*zNf714%{r9{me
z__{)`SA}k+)}VnCrkW?La8C$pd%VQ5Pa)iy5vX*mzYuM^#COe7V#X@*(_K{#aCnK;
z9H0oIvA(5nvSUwB<5ZSIz_)-cz+MA`F|c|K%v4xu;9B5gDdsz!Pk|e|U?ZNaPU^WC
zWg2W3_}oMeM8&^PSNMB{<1RPA<7ba5^n@M`R@K2Hj<-=p1lCmpPmSZ7EwIydc10Lx
zo_ewas@bj>7Vj|*3oL8`REhL50(ZJx00J94BJ2U{5?5KA3Sj|GNo+YwYI~!)TL?!y
zBJ45hFC1<3s=(?-CDlYWn8I@o)uB(Tu_UqnSKO@rJ8Xig0$?Y`NASggJ-E&r@OGHw
z!UKF)9iLDR;buoF{Cgf1&4X%*BQNlQjK)9cVEkM1&bQo0-VL1VNSa)o(fI#a?LYHW
zS1NqU01J4ZgT0gO-7uJeZHU58js54&%{%jQ4J?VSg~tAhe<>qrg~HYt3^v!t46h2C
z99#gWT4o9guV(cQUGPSnjc9Xy^r;6{(;x^OZ0;V-_%((c2}BR9oXuX)&hu=5!JH>L
zwuA9LYI6qTXU)w};&uUjmY*rpyee$kfIndDu68w1(b`Phb%8S+I3LH22UgRx*EU}i
z&dcKEW21eIgXbReUSabC-02{|xX5+!jpSUKfzMd>YSqAg53J_tB^OK&;GbNo!#IW&
z0GC_#YK_8x2Uhb8+U>wbQQ$&>nNE}E;a?p+dWQ#=9R@w)z|QIc9yK^io0(_ea&;3H
zc*0kru>-7I9c7QIz?W>PL<L4DR%<@!Fh%)9j|w{syGY!X3sQj(S(a80IxGSHv`2&`
z3SpYVI#?1{(fev5bs7Lt`s=417iPQ8Bf_rKx<7+6h4*NDTBiYUtri$|T#QW>&hlum
z3#^4%RPPh`N`vFOGJ^xF2R#xj$DQJ0YkM3rP6VEfRc}M8P@`5RE>CN(@n~@4!rv@z
z)y&E!ZNViLThvvK?=6=BT`#@hfTIe@o0^rXG2<U|BvEho+;`&{Cim+syYeFNu2?D&
zq|hVw9g71V0gi30SSq|}xgNr8HV%MF>3*XPM<W%){hU{W+1Oeu;@Fc|FxdCo2ERhT
zS_(Y~{K9iQTh;h)Hey!_zj@pZ_&?B0_#u|0!y(M^k}7-ExT8sR^IW6R_Q|AH-2Zu}
zG^YZu_FT?h9U^c}s-a}PDzG51z_C<a*2Mnh4;qQ7d9o)RF0EH;#Xx+-HSpu{eWwmX
zKKaZZZ>+aiYQ@aEvW^a5BJgg8QgwPg;SqsBf!UtBIRTfzA4~?Wl<o4hEY*zE9(&s>
zFwb)}e`@iMWO9jcIBVc5^h(sJY$EmdrotliY|I^~5=O347^z~@NNlv9-=gtdAmiJ6
z`=rDB0(A<w&Qf@-BG*b4UTB3;oU#SC%GizXzZvzQY9E^`{`&hVMuvqJ=86l&?1u#8
z`xSoMdw*?4VM$7yClM3x&I#~02yFJMuLD$L813ElOY1>Jn98E?hPo$Do;-PK#Ax!=
z7GyF3L|2)iF$cp(P%Z+_#Bd7AEDSSHx-m&T4UQA_jd=&<|1dlYJdH^m*zEXL<DSNX
zNsG+yM|eNVEhxKC6hX`Gwfrgn?0+D97Ugs=(WU~WB7q2fD0dYhQ4fe}g<16XHiYxh
zRDly880tuHor~~u6hW*5YAnD?&)<)*zWu<ZIU2C$a9%>rK>1-+mS^)Pkzz*?E@-2b
z*bVaGoG{aXTu)0^XDMH$3t_zjb=N4kMo~^{6Ht8!B#d{RX0%Rf6>XUB#oL&_1fAbH
zaD~i9c_SsEq~)*@zMF4VSX_}0mS@h$Z7ue;7DXUW_QqudWNmifDwzadLMh}xN~K}-
zR{rfNnFIQKdDcuZ31eyN>>SxPPP*7nvYel9<Oon{X#HV+<1YZRq;#^YDigP~M*W1J
z8VmF?z`p_ET$fVZ5b{h8A*BdA^R4>AvnK{sF}vs77D&>8i4Qx8f)+sL*#&;dQ2);s
zd3?2m9CGXl$}-TQ$<KO-f*yrJUv^SUHq?HwNe+U}u`I>8JBOf3ptU)l_LKs0W*w)$
z5(ZwAjU?56(82m@tjItFd^?8v#+<4@K^a2rREn`rBL-w&os5g`g?@L2e37yDH&~hA
zbqIT#ld8fcxs_DWxbDbZ(6}V6{-=Qo0Ldw}@4AbIhk%~nU}=eXd~$c=b0aLsL3C;&
zd9^Rcp@ly!KgZEX$<c6;Lsj@p^JT`8I9J_)Sf0owtfaVob5%}_^<Nv`eXmR9>@JoV
zu{*x&EtM8K3L4ZaEx(*gIaLDJ%lT7*MfZ72^S~;qoJ$;x?+ts^Hp8dtRfU5&wX2f-
zz$H0VfnT;<e)K&UwAk}VzG=U)hpem>*gwj-wAz$IKqW5x+ZIctCWidin-5GL1oZSK
z?7oSv9ktBQ9F(ElN-J^F5#AQKzTmJiMXv>E^+QJ`@)h(`lS!+aT409Po|G)yl0VxD
zK>I*P9RlkojlZ-4;iV3ndI;#x(^Az`fT|zEkmExN>8Bq+d4TAU#LFlLF^r<j#BdtQ
zD&XT7R>ePc1jB5E9Clii%YYv{nz&@nmVw#T*pKQ<pew)_hiqLAW@j~NwKk(v;@6R=
z#Pk@4r5Y8Oj<N~i{W(^HkGkt5SA6d72FLcvRKpC1U0LK`%B5;)>t?evU`Y{Fzl+3M
zFtymCQpG;bU)*Yz+ZH;appSu`*n}#a7Nx(qQimd-`#`(Pk4z1KV`+7akQMo~kDA`h
zy}@nMFZrvnQlO!+8qj+kFM_3&^Rvz&s0LAHb?&h&*<@eE6f+(Ew)s%QxB*-j!1_VO
zqT?9{5-WM)sdO~yAva74_mnoYZEipV$RS56dx(^8)rB(OfkR_}yD;qQ+?qYIz+UoO
zTHk2_f|bz}+GI?UVPxXCld4^I(+@H~h+m@{m}`A<ltUQSRS9f#5`DzMGYxPLm?3xG
ziurGlXB~wf&IsbyI6Xp|^~w25I-fr7C?>Qay1NY61)p)_N$J7_SSu_`6piC@_jP`;
z4&&nR!)7qM-HLeucn!>cyGEQU1d9_@c%F4>Wf;J)JFiK@c4(OBpr^6BDB&LWV-EmR
z0DaM}p<)c^;zVLCb0E#{?|d!T+XJS@z8d7E3?=S=*;j|=v_yfQ<UrMKodWh%w;Q)a
z-^nhDEZZEs!i?^Ck(}UQ#0N8Fv9cEEwfMYV4F7=Py$P6NBGGS?F-F0RWama32Mw#V
zr`usDAjlY4cVa9y2rz(fA4~)+XRny$+;uwuYnVLrsC{plMVSK2IG7+aX;PtJU1zCj
ze6zVBa**P!#a!w)txiu=o;JH;V!}y4pZ)pa*d(7AbptN5AVXlScCgA1B;kf#R@Gr7
zv3@5*X?2B@#?D=nMd3^cdd$AN&L=Zkkp{Tf!OXpyNUY}^NUT1TvoosMb&G?A@p6ry
z-sNDW+>p_VoPqVe*lIxcB*1zF<HW!HJ*Q@9l=ycBhQ)EL-{!)2vc^wuv;S5K=<mDF
zYSbISSl-GrfbLBi7xy3>bC5GSjMD8iBqMy=QO4`%Ya2lLF-Ip~c9vF;Z3+QB#X)kS
zlqdTM0m^HR81(N&|H-zrQZ8(u6+tay4v{$9wKjCSN}Bs~ci@umG*}d*mP$E&>6QPu
z!y^<II|A1pN398lQ0mCBk{u2XDM);rY$?_zuUK91T89~=PgVZTD;-ucE+D+mlIlzD
zzi?PB{y=?vOjf^>jLc!sb4n_#84(YlpNJ|VJ3Fm&X|>-SI%Jk2T;4RGlxb+O4yrgB
z?@jgDE3(Gn0R;g$3i4Zxsl~Ep#@D+&0w%{myT*3g5FT)NQYR@rv=K>dy-1A<O)w}I
zAQXyn(A6j#L;gqx=L+utnZcx!SNVOJ2eP^RkcN}%x$0vI9jU{yb*+w}+&tl2l>gt^
zajzW7;K={a8dNp6IX+gEcwB=ZKLV*CT_;=!@(AdN`@^cLpx35@4wask#61IDMxT=3
zJ&f`=@GQzJ1PmaA1k3?e04sqHqbve69+lf|f8{FR-umKi3h0t3>r>U;G4@pWHlm%t
zD^ZYEkHph@QZyD;f>|8@i0d%{dKiMa6G?|JX5Ln5tSwgUyY6L`aJb3%&<l<w!bH_x
z(gwdcEC4cI?CR#qFlps_m_>9hx}T}mzf`$`fQOrKS?2(Urq;A20<_QvT_Z`xPf#Ty
ze+1=QOueSKL%>fP4;Kj#90v0^oqLFKoGl!#gPxHzoXofY6kf-$pyL6i#W(&90v>Dr
zfrYuy^)^$cW3|2wG9QA`G_ZnkHednPO%bVOfG1HNv$HeMeF$`Y^jy`BUXl@g6uL(%
zp=8F5`E>!pKLXb{_7YofAPCdxnkWUi5t~B>z?|0ExH1n#NA<@FXERB_b|!{{Ku^bl
zO1X-Fd+k>V)RUw15!2g&l3$~D3ztLpaJAPPe<}kY;3&$k#+Hb79H`(S0`8q;CK}bS
z2f(b465l#$?uxJSQRo?NY|WG!iC>%R^4yKZt+o@oOhYX0MctH9)H{Q#82!JvWHUA6
zMMwAB#{@Ln6HtP(JDb&=OuXK1p;JX(!1a~pK~*_F!d;n0!`<vu9;T3Gb-`j<#<$xa
zT=K^i>d?~sXzVFg+jz-4sG`4LZ%xU{qFVfZn}SO~KA*)R{6ZVbt*0rp(z`7t+Fjp9
z;7V+&HTEUdxQma~2t&D7jnT;d+WEZHH+ie${>pg;SOTaWAj@gV<fT)D^V5GvVnuxf
z<)SiECtt4n6R9kOoB*uYvHoFuMtUO#{U`?IvK%&bdJu`rU*@mxPU<e_fgaBRxRT#}
zcx<iqR!}JyeR}LQ7FrUPD0RMgyeOq|+sR_g<n@7k4fNfN0VXN6Hvn=?eq*@>W}`fe
z@J@y;d<A7Y%4O{t%`WTfax2K2*(C?cFG1FiRYiG}@TIud)hPR%W`hcMqs%KCLtA#h
zsAQ;I0J<r4_(3d4GD$US`Z4J8a&U)jHc!f#C|^X`HU?T!vuBswccE-VIKOB^<<gF_
zHhI%QejQ{Z=<`+5kgNP#s{Q}ANE+&e5Y}+gr^%htmPj?_9AFiOUjY`z5@#BQ0GN*Q
z9x#aEaNNW2MT8d!*fw$L#;HIWfSws0Vhxsp&Ie8aGZS<W7y)w}bO6kbxCX>d=n_16
rvTwV2^5n^rCr_R{dGh4RQx*DuhTcF|6)JJM00000NkvXXu0mjftt+lf

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/opencv-logo-30.png b/samples/winrt/ImageManipulations/C++/assets/opencv-logo-30.png
new file mode 100644
index 0000000000000000000000000000000000000000..efaf5468a19d1fd00f0aa95a51b47f849408fbba
GIT binary patch
literal 1099
zcmV-R1ho5!P)<h;3K|Lk000e1NJLTq0015U0015c1^@s6J20-I00001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L04^f{04^f|c%?sf00007bV*G`2i*n}
z3K=Tmv`v@*00YZOL_t(Y$F0^~h*eb-2k_s%cf!W3RQk}Uv@kObDhL8G@F9etFUrbZ
zg9>^nA$lt6p|@U&C@P2^f?oO}p#rHV3nJ)?K2%ByiWEyLourzXwR*Vc&fVwEokkhY
z;js7FYwz{nYwh)4dlkp=BudjZ-A+=<K%9tD&0X-5gSI5+Bo8N_1V@sI<g?)M<iex_
zak4<0{w>M=B<n8*{XdesqcJ#7hSkAc$?pw73<1uJCC7pXM{WFstqs;CUq%}slV6jA
zmF0cezF^aQz+-a>%Annb4P`JqjU9M5nJQd|+X|;PU>6te#D`@8XS_Igqwmhf>bJ82
zX*^Pr7l%CZesaP8>F&&fy|S>p_CoSp@^_^m@$`_Rmf_rm0FOHN&U||EIAUu);Qh(r
zp|J<BEE~QiOOl7GWTJ2g2NufZ$CAk*-rkp#26)pDwK92X!O0`IB>22iIuWdmexBs)
z<kL#NH@N1cWUyds@>`>LdsH-xp5@m?&l^XB`zzUrq0BLSbMj`eVuW{=22Td}ofv2g
z%}ib4BI$BrX$8>vcWm~ONnP38Sfj%^=jabKtrA|8{*<lv3u%kco!dQe3bDK`o37<6
zdvn_ByV4EPL<JVj*MD#LAD1m5pCI=VtJ>Ez#8u=$@=<bpu(5RQ3{)Ge5C4K}GT5xc
z%TvgQnrt~qjG$7yHeh0GCpv`1((W0U9?+!pi}bU!SJ*fQD02PK?f4zJxteo3d7yo<
z<(e_YW@+6_)l&R}ccka>X9M?bD-*Xf-@VP!el@fdtE)NZk&D_@RNhZ|e#o^S3TGS_
z8_IN-++A5SMLs(s9lcCUR$lpL3>Q=t+7!OhaimqXrPHwyXEwX;O7H1({=)ecz#)9x
zj`$Aj!cAD-C_R5nb;U_trLnfO%FC<qv|@FmaU82KLH<oy(o7!5S+nn-TuE6}4g5uV
zqzR~gVErgvUs3H0=@n_JI*?<+IN2q44&4zS5gV$AzJmC4;O0o;og!U|J(bmo9~2)*
zM{&7gleD-Bz?X23&NSKChF2^9OyO&MLUt(EV0~|s`T@9=)DfN=vbxXa=@!3x?Syby
z?+6pQjQFUrB-*rzsv7E7PPvObt?$ki!p<tPV<=_T|96P`00VI)v2S#_-Rgf&tRKz=
z=Sk1Zf*ibige{`3Ok+5ayfxa|OyYI&l71R3q6)yYNLqti6<0~)il3x+u}g7SX;ub0
zHDv;2ac=`|#M(x<m$HN0gJXTLGEmYoqEuftU^&C<dVZU){r{m_u0)*_;6GK1pAEOn
Ra5De^002ovPDHLkV1mpn5o7=W

literal 0
HcmV?d00001

diff --git a/samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png b/samples/winrt/ImageManipulations/C++/assets/placeholder-sdk.png
deleted file mode 100644
index 01b3138cf8c040c54f3a200b2052f94a10240ded..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 8991
zcmd6Nc|6qJ-#(KTZA4N@+E597$&zgpB@wcXeYqo*J;vCFN|9_KA%yH($Tov<m*pl)
zWXUqdlARHQF$?pY&*-kczt{8p|NFzMSL4h%@AF=->pDVowAA+PKDwKQg=L@m4OLwh
z7FK`ob8^=X@QEkv^Dy{_)lFCJDobJeu^I3mHoGgguCTBaN9>_nZwLQpce!Eg#=^3{
z9{OR871__n!gA_^y6P2uPm2Y-qk}<T(&7@MztPI!&Yh2XC!|>syl2;iuI5B$Y9`!J
zKd5~?lB?{2<!Y_H6zW}WELFP2g<$B{QxzRWO^d#nG#q7;^YNRt&XrW|Q%5d7l0Dq2
z0%O<SuiY47H8Qke`ksS!LExLmJd4E?R&dV`W4pywM!wsoPwAS8{ge|P6N_^le|qh<
z4WiJj`1>NoclbkFqD;r^+#H?|?Pz0D9~(xP8_p`JGHXA2^k_Z?gVAxavZ|xfXn5Qz
zbz!igproYh&;=u_Qo9ZhT%S*oMa_f9j~_c(4(K}(hpL>=JUl!^l#KJRd($y~e$n$;
z)V35j&ZTv(uV`@MbDTNF9e+^8(a|w==*yQ#c_&>Izgus<G4Zv5fkDv2^Xal($V5rI
z@X#w0(bU=357p!Ha&la0dh-J|rY)6)h3zZR4xc`KDs;+?9?p|{fE$Q2d$}-BW}lhz
zp~%cY=CW|DT;|xVzFQ0LHfB&Cgcq90Zd6=K#F$U)_ouoPU5XlkCaCesNK9)t1-H3c
zRPH{bEC29&upeb2PONG=?50AZv||acg=cD{!%E!nu!X&|GfG`eT~}UT!gsX?QIL_5
zp|ds~0WUYldQ_oB)OY{2G}f>-ndm&QJn<R7h+LkYo_=3gD29^wvQuZmu*kyExq9jP
zNn?=%!1Fy?Z)8VjvoK*{Vf~F^d<(G%i*slCI^c|<fq?<DWdvUTx^P6Cg?DqZ53%Yh
z-o2V%-lMV)X_lnp4)fYr?Q`tO-SSb)jp#F!m9N@^lWmFSW8InWaxu-?NWHXP_UV4R
zl(Iexp8}UhvOa71BB)I|<x%l4gHGy@pR%EW?<9pB`=0AJbEa!x;DLQ#p=iutjZejl
z+UiZ;I8oC{-=4~WZt1~t$5NGN`>Xr}YeCphNIk#%+5^#xS^e&4xIhE>y!!sdT3R8^
zN#xlXiY{-Qh+)3V<-##LIISN$SmBInE-o(aG#{Ni^Zs7vDRTNFs$|W%`04t$A{v6P
zgZA)Z;IW)v8S*+325FtN*dHmLW9&Z5&B6saIXTlU1|fPOQkM%`a>V2=zbne+dBXM9
z5{}w|^)V<=Eu@|c$$K-Kc}FDt%x#fFJ-37--Vv#K69!sMH>Az|^7hL;9n-<<i}#3c
z;9jxG<|M9V$?`Zq%n+3nbd^%pt*AGeh!$O1ofEPw(=M5L{oHg(u=XZh&S@EUDCx<;
z$1iIa^GY6|2BO!#)4Z|})^h(QPAIQ9W)Zt=uv`O2&c<LPd#_oF)lyq=j7=KxJb9sl
zAa?TyeH$wqr}BxtftDMy2(b>_YOkqBmR{06=BM{qSD#L!r3OwRQQ3nk3{h(p7V!Bl
z?U9c`dkR0x9l5}rGj1sZRpb$i52{aCV7pF?5cfR@2;K4K-sc7cJ!tezGpF(!PG#`5
zk39c0q$?5kezRk4a&`}^6Y<qGN$xY?OD@_cy3B`bYn5d5Vzy3JU~QY|$DwijaQ~t0
zyn>Q{$;-=s3VjvK+-j&qQXWP8@OUT3usZ$dU`|ep$ymU@-@~^UEQY`O$2G+AGyA<8
zb|rLW&y(B-z#%%rFq466>C(}HE~glpI>QR85y0Rl!Xw(<$aL=*`jMU^7I&B{PXyXD
zQ*5G|%!X!C;4UKpruW_O806WL0bo6w&|5*T_9Xc!%xW2z2zMpS-s<BOaJ>??*LAUi
z^>e#U1Sng<&TQ5ljd20S2I|6QXq8c~Y?QoLvXd^m?GOdtW(j23zVg~k@w#Eeo1Q~6
zyxz5QwSF|%-ndBS^;SGh3))@gzZJ`eSdPoDYM4_>nMXenj?^4EuMm6<_vLY=aVWgH
zQRo!dO&QigGRe3CCqB32-)#Oma`Ng{kdzhWPoF;Ru|Zu0``A6o%{|{c%U)CvvI~UJ
z1vcB$IgX4IGoRf|3hjVVqJ_0h932a!q@@04hLQ7ifZ;@USL<w7QBIEaq?6TxhAeco
zOcw4+iIB69C!Po@k8$KFhU@_Q9Tt9@hy~p=$eI?__+zoZw8`7sdt}QHowqm~0W^xC
zGh&WWa&*+<up=IiXML)118m3wOL#jtIB05=@T~B-5;t_j2yFAT2VT}+F-b7Kh0l}z
z<QX_DCPTS%_D%B(v9@8`pGm0fWl`$U)YwQ|S+ZAVycE=M06k;$nuaQKTSIemM?PtX
z_mh)%v!X(aR!F?!7Vdi9t3&3}%m}<^>uyWW+q5Z`POjoJq;c&784`J}E<0KC)NaTu
zYxYXpc<15j`zH0zex+7-&p1-t9P|B=TZ9FD<S~Z>V{_xziPBD!#2-K2^UJ!_eYhma
z2lfk4_Jm=^7U$;NgjrAxMMumPy#G`Elo_-W2M)`)A;j+mb8Ibq4cn|43XaEGOJBMT
z1)Izryi$#qvhV$-r>z*o#oR0aMw)CZUG!V@>Fw$oOZ(jLNtWbI#T<H|X9?fh<r}PZ
zXdl)uWIr<`b*<(~2O%rs*;NyYeI{CX$O_lDZvTUgt{`Au<6Smw{9-gn6LOid*PeAR
zrLJv8O0;=Ntjp+Cug{!{;9Sn^fRrhGtGQ@bM{u&T>6`bQ%5Uel(-jsCr}P;SLJy07
z=H|$hmrU+6+xSoR_fA29?}E)J2;?N%jW>psd#^r-VWu|h;17}lC>jTwtI(R`XX@C*
zlmxbHj9mYm|2I1?Fg>`?64x&4ue1~TMIFpP8Pzf5=<Hlk<3rwYOga@ha6)8cigH86
z*C;Q`7tW~~&H@_+<`1_G^?WkA+mX!gzoHrprA_LV@rr@wc5HuKedfxXH`VakwQHW8
zTu^Ta2%vZ=$y~Y=0|#Z=)6-+@<|et7M}h2nIXFz^Iwaj>-tQ1P2K7pf0CqFutJUC4
z&<#Kh<X>Um39SByE4Z6nie~uB`_nxQjV;umGJG8f%#YZyV~4|3dy>bGk-v`|-fwUn
z`prLFKS<SlO&yPoO1^pWLrbfmn~txGh=|~g{Qor87@MA+o|*Oj-!=eU9YNi<Z=W<s
z&>v}nP#0if?MshtCslbSP138}rW^pIDfe9ZYpY?xxOF15{_i`CaN(X(-*3fHB(j}E
z><pFnm<Mp6(B-s{1lauT3lMODhR+hFc6M1{xaYqx-UXSw3sKiW3Su`?2o@Z=E(}(l
zbq=(FAzn_IkM)rbuYP(8Ty%mnnHd9oRMdgcCekxr(F4qrUZ+f@Uv``P))Fh?IMbE!
z11h>*Y-hpU%&H~qEHpeGq?RWnB(SImoq;T<-VT6>?TkW4D}H%X0m{snR2G!`=l7lL
zM_AcfOzZGN{Kt;DYe@d#r0idf=TC3m#8p)EwZFN{{cB`-yLWjhC0FoNm95)#B=6(+
zS#AEwcF1-XzIbL=wtRaJsfDE4_Y%K-JFE*bh6TpD8x%}#VPW|`K4~L2H@ARME@q*E
z>$)w)pC~H5QWDIul||O<*@?nQQ}KVcnpXU;R-=l^$@>o-bmQG35^2yh0Sy|QJ}D-!
z7fLvnKvzi=QfPW^PO_%%w@<-t7JOTy?aW1|$-<|UdX78)5$*2yz2ry__s=CilmpGG
z51}`|q^k6O`C?_?n;*CboTGf=Vqj|ONsTElA(!pFbx$6HAlR^f>52YdM%jhHdjMu*
zu-Jv}96e)OFDL_)t#&|Oz<4YqI1*~{0CnHBlGO(hf$9V#M^qzf`NXRW(#&eOTL@fp
zy5LjM)IxiLl>OxOYi$Q0Xg~zT>{Yl<c@KFtaL)_uSl`k8Wo2d3DB@6^im(FM?5zUG
zz?9I%wMp$1B}Xu(%6%!z%laoDKnGa`c6QzdSGY^uG4$;Tbo&@CD;RIe9_Wj$Y&Yn(
zy(3RT!N;oGwryJ*eI_s<oZ|av$FDF)d@!3*6Y#T9R8;&mmOv?*D*{T8IjZEqjJEae
zcckjXDvdFY($tXM;DV9hGU)&|CK@_@^;X<kG|CS3P&vhf$}*SHkH1Q@;yCCaQ;m&{
z%K$35ig)+*sr;O>b%4W&G84mS8~1)-QKVp<PV$A5On<?+t&At@j=Bpyaa(rg@1<7Q
z2jx;3VmzNzTQt??Ip$<JL>fct(<N}S68zrt<E}i1D=xU9(YUgTioxL;AAvr(j%@E5
zvNQU_gej4Jfkxt$%q0@^ZBg_iq0TL@HcnkUzzXjmy<ZK<zLnOhjb2uv4Ti3+!7b@K
z<!OfFXNHeBb;c2>Cl8HEi$}Gw1iEsV_PxLZAORZvzcUfu;pRp@`N1_cW%ZwAAH1@u
z+<Z+aiX)j?g9*O5R^e^i<@cR@wes#vVWy2`2F*(&&X2QcgIwC=;pwbN=F@(c;x*Q$
zW435}zbP$AQ>k`m&lS9ZI&bn^BdtPv!6rvWGdro3zJbR@_>H-0`lgUW+)t&bd@j`P
zTBCk7c2q|zl@Q=d9WX&$d0l_09m%xZp_wttfexlI`ZHBV>WORgJS=Sw_94T+NRjb9
zMT;=FfxuG`3`#m3z3Ll-Uale1Lq3XRk>HG}H9F2eHaDatlaRRB!I<-5L@~UyG3DL_
z^g(_Zbj6$Sq(W^abe2O7nU~T2^)Mo09m)F)C*HGYu~$&hH>De=Q5HDZl%n)J!r<fG
ztHm+Tz35SNjF4f2{}Qd+=>cv<?6|S~t;_|DCOYYxG|5f&?~bs&_|4}^rE<hR`p~VW
zxRO@#DCq7T1LipYngXNZG5Zt+&pYLHSL{m|T4aj2nH^*KFWkmDylrzsc+SDVnm24s
zTRdSSV`?~?H}tc|LA-c&X^MYQ^QPzeaN9UPIvimXwkYCG_cPCxaIH$AKXxqNOxvBC
zzcKP`ZBA;&Qf8otQQY9IRNWDq|6I)BLz|`FZFeNPWa>kKUva~Hp1$As_-f-)twdY&
z-y9x^8)Hd^wENz;63P{as9bVic#*2)E03@}g%o*t+O|@GEawq;nn!}>AYn0@+Eg^V
zfUD^kEkf%!n|kn~8-=J<t~3(S^_Csh20eZ@>d+68uRa1{S5Q!}mbB=*GsjtHB;Hvj
z^Cc~5TY<^Jju;EVJ#n8V^Rn`DTJIW~z0G<K^$tn~S^8V^<8Q5nroBt4HnJ=7l~+71
zFGe#6-O#(;g)=n_QPdg`CeG>DwS{V#sy&z{gskrw&K++QPQBXK6eXUYrCO~w;Wyc^
zI-WnI)R$j@+P#{5)7O8W!1vs7=>ZOGsP+>MT$0e&HL`P{Zi+SuekXc;=mmk`UjA7h
zu0BEbhj%pjZK9lrhK7c(QX21YE=k_p<i>aTy=RcQ<quohVr_hu5>_wdR7{4<tJ#YC
z{)I-P{<)7KcvD_^3_d)mMQ^To#zpg?4BqP1tHea$S~Iy3>1B<=PZ$_lE&nr`BWYlT
zp&+DNob#&6bn#pxLO)cq&zmNoann<=)uSbUyxy!&tmR&jIwpLOaE1UcHqm>K1{+_d
z7noKoFX^QCR?FGNlONr(TsQU`2s+)cQ9n)%Uri$*j>VZCBHxL?szna*o$Vnf@6O6r
zI$~SOGv+_=y)uW2^*2X#T-l&C_z{eckJEaDyU596(U`1@4eLU72EO7d8=D+8Ovl_G
z@^K^w_{c@Oh*sg$tKl@s8zIfV2Ekx?7`qv_B2sDPq2)L6F&YcbXNvXCC~t57!1q~r
zo`3W?(}$Kz28H-4jJ9Qeo=>hC`Iwl$HQM-6E$w`siJp%lQro&^DdRz!pW=HFVI^YF
zI@*Mo{OR<AteF?&D`6LV#x++r^k@Mw8`uqnMIje{CEssaDN5#RvJs-nAx_8e`ie%`
z?=dDy#e|qQ9*m%ky9lcP-;Z0gRF%nlTfN8G2ulXDJBWBb+~Uk#=OG;9mcvdIGJ;P!
zcl-_A6g8XtQGZ;cPhq%^I_7iqnrj1DV)J#a8tKNseF;Z+tYLiaoIU{_iy>LSJ9w$<
z@pY?}{<7{t=5M;Cl&I(?8G}XqkdzOF;;Gt>rn<3=<$V!d(s{kwKt6CYE^HjPo>Qh}
z70-@BGOVi!X?&HKr9o%(<zs|-QRKMiQO}eR+E=vMB_T6)+$ZUUTyadXV$XV)fghz{
zF`=PwvznbB6@T4^=X#+61}Ze|j3b$|ay?}24C2J51saAR(kUbgnSdr37MR#N<2F31
zXquP(Z@s0$d5QBvxJ|564lFKv0XwYoxl-Ae`~7O(>NvWHtr{yP^+b=Iewv0x*=J3h
zkn8ogE<j7r;?hofHcTupMYf>PQ;YeRl{TFZm3e=Xk&4Q!(Lo>xf}+EbwKUi1nx)7u
z6*Z}`t_q)(R-SDiR&SqKFWoes%?=`;C9XHFrDB7KmQzK%mNVt&i;J+1re=LP6<^mo
znpMXu(SvdH`Hb_0uba?HM2lSq{r0bB&Qpg_XyWVs#gyf^Nd6bxl`f-?GDyB!+h}Oo
zAYq`Qc2$(t8R5@n8~{t`>|b(35BUcKLI5o0pe%~`CIbxXx}L7CzeEs)PcGaDlpn9g
z<q+deH1FCSSO?foN~plcL`YH0;Rr6KOIDO=Y?4jPue(+Rhb4B(yN$n_+;!rjSD@#5
zRt8BS!s1Q!=pEXA<P5!NJ=wlwqF{KKqE;lZSzMsVqrwvS3{YXTQP(ku26$?+ol^9x
zDJtqHw5XxJ)(?5WM7Ek)5cUy-O4P*8Zp!`mGe0H_RuF;+0)Pe=j(6RU6Swr&%)KGS
z<Vu-(06#&nj(X7zB^Te%3(&!j^<5CaxG1p7sL!iVR4RKX!~`c_g#dygx0-M0!hfR`
zUwu<kdq@{V&h-Wz5oPj9TQRV(aVd_n^U;q3%5UjxW{95*l(GvDu&jcRgWwJ>u+Hh}
zY<@-WZh(`wvHt=}fQKyrozRcAw*9c!Nv8e4oab@2<p4u|JrejE6sQ3icCt18lL>va
zOo|EkwYF|^Xu5CyCk2N{=wjh|UT&^Yo^W+JlNY~rX-EMqCMqh5-W)A_OA-qxfYp|c
zps7rD`RbJ%j}4T%I12gH7^XSW!Zn73AmBw-F0|FYn@o-3mGZm)(0$hCi<6U+^GldK
z?Zm}x5QEvbckeeM9$SFL`s{eB63YaiCBO=8g!Ze$MW-S3$zJJ7FTLAV^8ESpx~r!l
zzQ@7}K;3Xb4|l`_sub1FjLk=GXmS}F-`99`p_oFN`o(H0%f10F0g`-5+@gB=&;!%=
zR;>RL$roW^#{UlqyRG<(NRGU+?S0u=;e_9P;Sy6(VggKjIxl>EWZNJP4Zr%EbR0c?
zynNfv{gs09f0%R78Il(~w%m9Egc;?AD8+o+vX|!u1dpE%wyQ$$SQa7_tH&CD>I>VM
z6j(U`WMT&-DwyP{?J2vzCblIi7{Qu(&@caQ?y@B<@Etq0_fPT?0kZ!Akjs1f``LeQ
zAF;ynszZs^DrQ#6X;t}TOECn(fm;OzlW;)MR~lFwsQgP^cuM=pN`=97{=ZNcPHlka
zgZ*&tQ>uWswCFH%8Zg4wiS-S?S=VXB0ED(}PImS#aTBH%!g&$iG4=H6(`B`Y<7F6(
zoV}CNQ%Ht`*w^T&^%iyc#l9{Eif9D)f#d{@>IOYf>g>;KkD~goEfSoYA_O|le};rc
z7MLVtL1$fEz`{_~*Zs#8WVd}vZDIb#cuP$1;?y|A$INU=h^sptL)+SB@O}P+BA!;X
zN4dLquN?IFZ<3sv`ZrMNdH<Uv^A>%50|(u;ElIxbkhsO(t;kxzW;@lH^y`1UgV|W0
zj=<LDF5A1jh84YCo5J~fdwO`B>Y3>nQw&ilPvg6D^Yb6>G=<0hXHP0rjH3Wi)Lsk>
z-C6u(a2i@UAqo`Go6FT2bnoNo{y$S2lp^3|@)8n%EqQMKqFf}B?<KqTW2RL=MmNVC
zJPs8ykX@n1kC<$=Z`Km+Hq_JOw)%&egfSI$pfO*7h?wbc%FZ-3mOzPvBjHX*q~%VY
zhNQ7dro8EN|Lz}7S|yWBO-&R3JM`u=<h8YdcuBjD|Ekqyko3|-DnC_mh%w(^I?Ckt
zyP&}3w;!=O%?)V=BYO@OwC8A{+Xndg_*5WvseD2ia5FWaMU`8B+5r+~|3x#VX2uCR
zkC+nocck=<LrZ~MS#*IFNqR?8kVJiYV9C@EB(}e<N>o>6?sFmVh73~bDWfYx!}{9w
zOU&$mnsMvU#N$BF4A{gV@t~c}&(AND_qR`>-R$o$)Au=BBM{aurmS0E$PA+XZaE6+
z-XDK1Ies=Wv~R3KK+gRi@cQP^mLTQA91m<l7cX710kRESVcpT!Ohx<xE5^Iz2~+ag
zr5R8!VDy-4i}-Sey?9}SLRBQmA<ySsU?%OZR;CyF3e8Kw3!W(g(YJT+v-41H0F?ro
zgzH+z>t8lBLe)^$$^%^U4!OQsjW-4@d?-8nGBmmB{6N$@c;EtuAg=-~1wl9Ylv-Zi
zJK3JZ=Q+J4FEgieL1%h6x^4cip8_-RQ52QT$H(W`nRe}$%u7^q0$hF!nLt7mSs=x`
zdwQ<?Qp~Niro4d2o*(#A5VUH3`isg3I}vIffsW?^1kwMRETaAI9S5Zcu_*E19e!A}
z%VYhAwY(qI{SQ?M|EU)Y%c1P!zmu?|4gX`{HKg(d?%eI-7RRv*T$!`74&<vzdR9h8
zgCTgE`SX%YWh(W}?6%ze{0rJVX^<8PJM?At4O3bR;7j}h?WGGF8k%r}vLhy5`CWq#
zl}a6g{S-o&8i(#j0tT6f^zeB4ubx-AhvuFfF=iXT0FvB;vTW-KHUfJC#TS%kUaAt1
zrr(#bvxA%rh8q0w^1@94#e~q`m;rlRk(%*uRUf=DMac$1l6D-hnd>dsBWaQb!GIPs
z5EbwWLgHW>1%*jrzZjTDA9xcCuuSWAAoOgqp6~@SBs}m&$DrcYlS?K&P53Vm`nP)_
zypdcr*x6}KTU!u${Db`fFy<^A)ERbX@!oy=;@fxqA>*`6Jd_3<q<4(t*P{s#g(OjB
z%DB6WCCu!80?j2<gQbB%gNfq5Kqp9K(>=KZ<nnjzWQF?){XN~?Y}`;Hf_EXzv&42#
zc>8{52n_Lx^C$9%T;FD|^Ybz3RM;q?)GlImWyL0T0zx<}fkz;1bO>m>%QzZ-F~6#+
zKN-F0CG$Z~+g`nQDn-UQxu>r$VvkhqIR{8(;&4%Kv45hYqVm`Pf#7Z7*t^#VNJF#=
zi$2vyEiE?zFu7uVCMrC`?&|*i`!Rm^^)4$O(WK>NXS?9OM(XkF$(-++&~F0RhBw@6
zgNh`dRgcx~yX879<Wa(|($upQjR8genO_f87k$h2pc?gc0`2W#eWjeD@N;qQRS5}4
zE8q*3iM~9K7tH{}r>d8OL5GmJJYAEUzLw|LEZBePv^M;{rQ)qy$mmk(8bp(R^$aE_
z=>vQteC?eg#b1j-Cf)WeBF2fJ88iY`fw8fOCOqfDas3l#=|962`ZDunc<(HFG>CV1
zh!91?*|`YFUf6f(XL3|CZPsV=icB;#G*anJ0%!-U$HGH~;md>dV-2ATZ8C%p;5{Ep
znERe;dm0FqL(R$p%CV;4F{EaxkuS(5N#WvpeF%49cy3CvV3q6mb)Sh?#O~%*QU|=E
zyj(htZXgre**u;RXHhbh>{F;C!|x2n84<~k5I&fsY=PcDnwC8<NPW|CcE4cP8Fi(N
zm9OPqq`PslW#@8ctsB+CkGUfCN_zf$^8P{!Gk|E@cDou&VRK{Q!K@VjS<UY!5DOZ@
zQN6u}rdSW~cLxBu-h$^M#;^|k5>r^4W-f%5V<~7I^6t}-gWzNT4R3@@PaM;G2|k<a
z?*7oD_e}ytw@Q~lJF|qKFUR40E3nwXWbkyY_wh>)3Cskjxe@Iep7Rj3(HcU2GcCI8
zcSk=45w!*DR~Vcznn>jZ6?V%eFYwZh|I)b<o5z*KW&hA2*51LvUHI9GK^a#nc<NT;
zm#@k-JcZbZsW;F<el6zFc$v);F`F5!ri<FhSw5e2=S*T@t-(%y71wO1+_>2|g*>AW
z3#6W=I{pK^A;&XX#4$-HwjPO0=@xZ0q}XWqZeW@bjxi44&ms(cLy87&H{IIoOT(Po
zA?Qay*dle`Dc;wvO+k6{WRhr<v$cqpeJ%F>h271{RT{kE3<0M`#?6n~7&Q2!78dnu
LTB?Ottseaktfbe2

diff --git a/samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/smallTile-sdk.png
deleted file mode 100644
index 5546e8b24a69738114bc17b2b2d493a6872d67ad..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 1248
zcmeAS@N?(olHy`uVBq!ia0vp^av;pX1|+Qw)-3{3k|nMYCBgY=CFO}lsSJ)O`AMk?
zp1FzXsX?iUDV2pMQ*9U+m{T%CB1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+*
zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn
zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxKsVXI%s|1+P|wiV
z#N6CmN5ROz&_Lh7NZ-&%*U;R`*vQJjKmiJrfVLH-q*(>IxIyg#@@$ndN=gc>^!3Zj
z%k|2Q_413-^$jg8EkR}&8R-I5=oVMzl_XZ^<`pZ$OmImpPA<wUD9OyvQvjKmn3P{y
zVygsnDZ~r81-`y;gY$}^0R;>){ffi_eM3D1{oGuTzrd=COM+4n&cLd=IHa;5RX-@T
zIKQ+g85kdF$}r8qu)}W=NFmTQR{lkqz(`5Vami0E%}vcK@pQ3O0?O#6WTse|n3$Sa
zTDmy9nj4$D8X6i}IGH%PI2*Va8n{>*8k#!7%)qAC)y34v)Xdz{*vZAn(9qS;($vJl
z)xyQx%*e^f(b2>Zrq?sCxFj(zITdDaCeU7}UJJZ>t(=Qe6HD@oLh|!-U@0IVBfliS
zI3vG6!8zDeAv`lLCBM8F6gd#Tx}+9mmZhe+73JqDfJ4_R6N~M}u1=N)CT<3nuErMF
zeGSo@LQaV310ACeN*YK>1ttVce;_72;R8AFtdp7t%r8a2jPa$hZ3Y7aqmZYIV@SoV
zH(|GVn+<qcR&l4au9?s$;FiD|)*$$TBb7yh(M?17f~Xaf?~?A6i!+*jIfmYxBwBLB
z?st;hOPlj21<Snnj1<L^6#wNvx>U)puN1)>GjWDYb(7@t?Y2iuo7SC^e(wK3>@~xg
zMI8?7PRhyOSNeDN&u*(nlZ&MfRzH8rq}_NqyH&<=^8B|I4LQ+k9H%eLW)<BNb@!g}
zI)&SFJ&xa;>>+)vZ|V=`jsDXVcc>oTy0n3v?M%&Q3sa2+aW|74&4eCtU0$<efpN3;
zrGv9FMM7P<{0go`>WI7BOyoPGRM@CzI<vhm@N~nUO?ze<?YHaldByP4seRU*mlB=9
pDfJpPcf54uIl(@NeKehcnPFkgthf62xfX-U98Xt2mvv4FO#q_9qtO5W

diff --git a/samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/squareTile-sdk.png
deleted file mode 100644
index 126cf70d83e3973f6a4b040fb4af58f546692252..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 2482
zcmd5;Yg7|w8cxLvC|D2`1g$X?C`v99E-?Ybgb5G?fe;OBLNFwQ1WYE*BnA-0T1BWL
zMnSEBiomi}7ez!wj7SZoLW{S9>mp!LQZc9$K@p>LCn)az@bsMBUpvp4neYAPeV_OG
zoin*nt3zyNI?cr4a5kJ!kc+(!ns3YL*wg>BjSsQc0u?(}6$2-!G-3q8F{N-Kgy+b`
z>me>AmZopK4*BD77E&26Ruvl&&XB-zlGv<6N|P%wYm6o^O(~Y7LMnVBv|gqNAPhD%
z67Vu<0D<olL5WZXLCLbv3<QeFSk04Uq)O;gLf{I#e;NZLkV7glK25$sfiltp2ot;v
zY;E2q6Yvu%s?-3&`=DYYqVPd50^xl~6rzOUOTqgBB*4p?Mx%M+sT6=hrclWMl?c!n
zUQ`B!g8y(4FmH%7iNOVfKls9=079}#rDTxF8jXge@gl*<dNM$#)6E=IDiPBlqUj2i
zIE|=4T_zbo2$di*rAh`X@McDFBCJ*g5U@z!ryy5GM0_MxpdSi_m5iJwR+0e{g)Enw
z^P12`Rb1%bVSG{><)tejG8aN&H6p?Kk>oOIjMeVX9hnueXc&=*3~P#b0|-mha!8@#
zfB^*T3rQ-IGAK;84@jZ2*i<hX8vuaiEN>PVL;(Q`NCyBP<|N0bY-zzv7By%&(~AXq
z0RS6d0>M;_jYbLb@ecM{?mcPCQJ^ZZLIO?tm0^BA*wX*hmJx(NVik<=V0gpi1Vkmn
zDi}?MmH40-A3R^Ckir_&+?@Bhf)FCx1WAJtSdO2lE<^SS?<|TJ)0@p^(y=f<o%MTL
z>HktOG8PQkJR1KoDwA8-{F#>@2OkqY9vw)5ofiZ<81CJbt~lJZJ`Tv_rFA|n&f8e#
zZ@W@WORzY<a+c7ld@6T}N0Y}AQj-}4>%u6mJLVvFA)i~7r>AmGH>_)<mDMi{+#Z?_
zY4L#~k;wXL#n{)e+a_>+3VyyBxWv!Q_^*Yg+TjCkuY*?EXJ%C&ZLc_TFUhB@tlPKZ
ztuQIYLNMqid6%PJV$8LS%K7SL_)v<r_OA^GuVpPTc17lNd@J-lscwA}c4C*H&Sre4
zb6%`2C)$<JsU-cPf72t#=7FaJwMn+j41;g-PC?tV_VFy9-dNzDY-t3}!Mz*?c;a|t
z!m~wnMc;kX(KEy_6xTj*sTB$yFRtWwD&p?-W?MrjX$F*zk}6S;cEgykbDd7mlh)RH
zh~IjAJnw1Ni*LI%4)n^kcaLqqz4T?nqvr)%ei%-b#+5F-bD=3LZhY?f8%vkBqteFa
z0^z(Cr_Jtp#;rY52U4NN!?7Vxc2MuVDp!S_vh3Ymm8&j5J>88<3F-zz=d?{D?YBDk
z(@kr0US82Vnfi$6EjP7mr9NXVqdWecyFu9bQ+-vz8~*Jvx9S@}PI#nNetuSS!i8wk
z+2%t+i}JEQOZ7g#c_LBGC{o4ST9^^)NT7?J<gM~SR@~ReoPO1JDRSXv=RUCH1%=C5
zB)K^|uXwb-wxc7j)UYspaBlUb<IEXw5y3I(aAIiaqD{Yt%;`mbOyBdht?5_Jy?BZs
z&f&r}k#<BGAyLztXF4}TpV;=GKhNO_0^Te(Su=N31&qD<^`TYE;L|Ib7lW&(F0)G&
zN%&3joB1h)H0!eoN<p^6^&ZorlBiC{lGIbX&@tD*#fQGoA(5<x`=!ozoC^JABYgu@
zD^cVg`Of>5)0N#T*h;_Wx;TqK{z%zf-s~q+YwB9u^<lf$aNO0o@-FYlV;=kGTGe-k
zB1h+(S~Fb|KYo#Wf=i3>OgKBG`gUUdml{92j!Tihu~5eK)(TydZIShZuokRiT}2N0
zcDc2}bHhff=9HgJPtLf-jEF`G_WFA6JJQ)tb$hmVhTVW;aR_-}cG$zM?sa9##irpc
z<&R9Eq<<E@p3C)^@_B1I@nGZ7bQ$o-<J95UV@H-1*XSCBMfuC@uQ?PtL}xG1ez}%!
z)V%EnY-cI#^;0Im@?2@g>CAi4DOoQ%=KG!OUUvWW#nHkpQ#kO{GHv}x)0)lUe%p1v
zL%`CXz;=(464l$UN(Pd~u6Y!+_QyDFdT=0p(Y!NmdYhq;8m)2hzSOXmU)tVLhkyGc
zF~;%vBmOe}1}F9bBmR~m!XbgLKWR8P+QBib-tiabEv)6`w%^YW{6}_dhW_G+^FC7K
zkvB!3J8O+ct8^=>yBb0}b`Ge|l+VpAZvSFftI+ibddotU*X!`{FA_jPVWDxa^xdUq
zq+T0wnf!A6Rlfo5wU>UwtMlr*`CVPU#q2q2kjo0e5r6pT543r02EiydC0Asaw!_BW
zB<dsf-@b3#7I`^-q%%`&DcJ*7ZjQTBx(Z(9dC2AO?0q*t;;5GO^n!+L^>(j9N38zY
zVSnnVYg@*N=YGSlDqVZC^-JyRY6^JHUNANN_oKml)nKDbi%`78&Lwkq>3n8lOaK(M
z%XIY)`(*v_R>j{Wk6lNV(-IeGdy{*z&OsHogMSnZ|3Tg#&#R$#Tys~HmZY1|0$u&~
z8{Z!cZXd0F3%?F04BZXB^SFofI5YqCEde<bt;SX3Y-gE)E&dM$(HQY6?rfQ3Q}s6I
Qm*&4H4tq6N#ag%hU;S(27ytkO

diff --git a/samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png b/samples/winrt/ImageManipulations/C++/assets/storeLogo-sdk.png
deleted file mode 100644
index 2133f177d172d4c79ef1ffaa8088f786a2bdbe8f..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 1550
zcmeAS@N?(olHy`uVBq!ia0vp^Mj*_=1|;R|J2nC-$r9IylHmNblJdl&R0hYC{G?O`
z&)mfH)S%SFl*+=BsWuD@%qf{65hW46K32*3xq68pHF_1f1wh>l3^w)^1&PVosU-?Y
zsp*+{wo31J?^jaDOtDo8H}y5}EpSfF$n>ZxN)4{^3rViZPPR-@vbR&PsjvbXkegbP
zs8ErclUHn2VXFi-*9yo63F|8<fR&VF+bTgE72zA8;GAESs$i;Tpqp%9W}skZsAp(w
zVs37(qhMrUXrOOkq;F`XYiMp|Y-D9%pa2C*K--E^(yW49+@N*=dA3R!B_#z``ugSN
z<$C4Ddih1^`i7R4mLM~XjC6r2bc-wVN)jt{^NN*WCb*;)Cl_TFlw{`TDS%8&Ov*1U
zu~h=P6yk;40$*Ra!Fk2dfC2`Yennz|zM-Cher_(vUtrb6B|)hOXJA!b98y`3svneE
zoL^d$42+L7Wte7Q*x|Pbq!8#DEB~TQV5B7Gxa237=BDPAc)Hjs0cG@3GE=M!%v?=f
z3@n{ojf~A*4Gj$~oJ^ctoDEzI4O}b@4NV<kW?<9nVq$9HZ0P7}?Brr>Xy|HaX=q~T
zXkuhy<YsAPZfRi()9aa6T#}fVoC>oy6KF3~uM1wiR?bDKi6!|(A^G_^uoMuGkzbNu
zoRMFk;2dnK5T2Qrl3!j7iX4bvT~doO%TiO^it=+6z@clEiN$tTLlY-cQ*#SPb7Kqa
zzJ};cAt%K2fsWA!B@Lvc0uutJKM)h1@PQn7)=A9+=9eO1#>h2t<6vN5a`1F<45_&F
zCgNglvw^_UQ1K63?>IoPgvE$SQc<?Che3IQ;2{nJCo3k?OPjxx7<GOYjM|$1GUZ**
z+v;z3KTcX+Ij?*Fg?S<!Oo0mjnNNIfs}ALlt=%a&Ny|e!r`D<5@!X4UpPBC~zUNJ3
zlYZi~tC?AD*TTZ`=V|<`O3v9$6)#dJ=r5fAVb2YnoOXruj>9`RFR@5oEMEQcuh2HP
zp6FYXzh@K|KXK{P|2wZ_Iz!UOKY}UZOO97`J6F2O-)1bnXSiIfU8r#i)0E?L&d-t2
z)c7~uKsr%c^Nr5aQ$j_iEzTP2CUULicAD~e(?KcrHI`iRGF9`Xqr9aHn7pUHd@)Un
zYj5;f1(o7sYHzMT6tnTW>+t@;Wxnk<?*!Lb$E;+zlqz<(vuNppihlN|p5G(t7tMK*
zuv&A<^nbjst9Cv--KA{k&vuDdcNX)Lj+%*m?<d&HUMuPNThSn9Ubg5_(8J0DHzrJ0
zj_E2cQBJzoRkJ!Fd3R&%u|He4+B};vW&f$Iz)<^n+~i)P{8<6^nVwOBLD9eRj{Hmu
zR_P2f<Ju<eEr0o^kjNsDlB0r4HMUKe@^R9Sv>!*_3;D;aQ7@>=7RYwcvWU3HaL8rD
zamEmP#-v^oIY;GJrcGr_YyWP$|7PL>Nd~R3E+*rLwl`M(?ya};313mc{QT!#{=kD~
z*_z*~*><O-WqrJJIrok5mbwM;o$I69qFyy;ymaw@(j&f5{kf0Q8@9ijv;|lfIe_Dr
i%cW5R!Fdwhz{n80oh#+wlyFN>3GM0X=d#Wzp$P!Xu`&Pv

diff --git a/samples/winrt/ImageManipulations/C++/assets/tile-sdk.png b/samples/winrt/ImageManipulations/C++/assets/tile-sdk.png
deleted file mode 100644
index cdec0dbdccad7ae5dd0e92e3c3015449fffb7450..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 2665
zcma)8dpwj`AD^(gN@_z1&pSR_@0Ph|CX;bDv1_Dpuf%xfF$Ocwm>HL$5^q~u7S+3&
zTD-Ok5}6Q6nB-Pe79nQGbi)dHH^jK^u&Le8=e6%Xf1Kx>^ZS0kzu!6M_xYW3%GG6$
z)~d~`5D0{plcPNyfmlXV_0O-+RJHCMS4UL8O+p86p&J}1jAZa3gbfo8fB+{Bg9Xtc
z22&LF5VAlZ)B(1;x6qsBOa@^NnlX<-M{#&6HUeQ`6~$wKA&?LVfLLrU1vz|IiUin9
z3ewArhNbcBpdhwmG#_${c5w%zLqKyT(#jIBh$5>5IFOJ5L~%m70&)}uxu8o{_2;KC
zNMHdX451)@56YY73fRGX2rxrqQ6QFx1&BB_j<AzNBAEhsEDnpo;xRZp3P&On@MJ6&
z`0ycB-uTQwGTol~!Ix@8K?VthJTe9o85xO=B%onF3xhK^H=ozQ<54OEN+9A28Br*%
zz+_Ru9uk0jHc!Zgxxl<4BLEH;Qjn@he_sNJ_feKB_^?f?4Z}n+co-ZSJHMnwAdU9d
zP!8uKS|FrDpW^+W!UA^@55mwP0UXW;RR<SnGVh8<w&Oz#A<TD&;n2lhbPa-qupkKL
z0d{U?fESy~gd+tDXc~>|#1#k`To7`yryx~)G@H#N6A9)HW;k;^k$|<q;T&+gY^ioO
zW&|wJ&YoaTu(4g_+QVQt2jU7Bxy(;o!jjziMBwmLp6ww%I|5=-`7j4qSTLErbS&5<
z^*(T!OUHs+l8aFVgPA|pKOFPolqz@TyC0KQHTanJ5LcD!d{t8W)DlV&2u+2Py^VWR
z*PuKx>?KuS)BlTqYX-%Ae=h|P1LEg9mWlnv{$CwipSRw5W!7=Gl{L<lhA{D*wdHO7
zK2hM#N*k$Tw;0xYI4(OXl^`n5Dbm%fZ!TLwL{w=4&k!003(YZq^>v|$c&&wI(fkRs
zU|z&5m=`hsM?z)(;O1{jWK<1uq7yUx#%3OaYE=>Oc0k_VAnz%Ys)BE!w}l;RWk)8z
z(VENsO!gwpvfivAyHe0KY8rXrP=K=c_{hkX#>B^dA*a(?jrF?TX05mq{A2T$rv-;I
z$g)GLQthe-50+`?nAorF8~K&f1xcDT?^m3L8awoS^t+|B+_)o2M|S0bvx#3<n`y|1
zQ#}f!l{ab~Z)T3UoiRLmRM2U8FfQNZ*xLkAuE{_?wdBs>RHK)Q<PAwI!;bN-tGy?l
z`Zg17uWe$l3!k=C80KIbej0EOH9l9Cm`mUmC7dZw=7qQ%gg14(_q-NH+jv0lg=exx
zyXoedR%@vATc|7U?LN}G{f542=+&LLgbVcIJL#^UnbpR;b=lR;pZ#9cUy+HPWUWwo
zq@C<>97{jhg}3G8uH@@X&CJqU`E#W{P30#``^{%(OwJD-=-tyauopL0;VGqI3c5q4
zr*$ObhOaD=K;y>j@OB(*Y&F$>fHn1Sym(M#EK#3=slAk%n1|!amZGMfQyrkraP~!>
z)-W|mGF&kTS}6x41?jgc3I-VXbg1n0kWp%YDJoLz5y0_884jFCy2t_@V*^{WqK&Vj
z#j#K7hFadS*9^0nR!#e8^3SKrl7nC8{Bpi&c{jLW<V~C?HNZL8Yj8Niwzed3h~h53
zQwyegNbNi(?Y^rn{%Tcz*mpNhQ*RG#igfaQL~92c;GPyeZMV(Vz7?^%J2ryW9!+5u
zHMsM>mq)wKWPA5!c}o(GC~7L-m_Cc3yhuqVprfBOTg1$Tmq++%`0NgQG)Qb0okCcS
zk9B*@D2`=mr`HE}>8<&1fBcQj`m7M-x`@t+M|s|8?Qg!+3NgcXlQ8jD%v&B1)xof_
zvtup#a{1X2R~F;h=%WFHf!+0#aD@pljC}qB!EZ!qJ$7e9@Zl7H8MCd!Rj(*Pv;3cG
z%mXw7edE<t`76#l?7S86^1X|XL=qzpObM>MLDMZOdby>zc2ah&@JVyxK?m{O#8snd
zB#U9q_hK$7E?2vRqqBV^4jt&zytD1ruf;jKdWR&rv&!4_1MZjmDJ7le!AZhu7>vQR
ziRvEGNi$i|(y(#Xj$-A#llvm;X70rrh34!dIf$7uw@y^y^HeXtkYnZ^naWn(qCtz-
zRfkyezQXmBx(s)(K7(yCY7o(?6Gf}9*p%~{3*O1hsxMwH+d6PUivpeTLWS#Ui1`h)
zOGVoG;&%DQ#y)xL)3(9rUc+2ZFQ0p;CVlP^Kc4g1q`SM{{bQW6-Q`7Hn^&lZr_L>t
z#!LgqOV2XP*X;0WYFjJkQF7Q(Tf|d!5BC1jHIkC(IW;IO;F=`B;PJKz%Ko~rjCVcv
zvZ7<@FI+af-v2L@hhJkH+H-cbpZ4+lUtE7M<XHWKmPQ>hDOPlqpA&Q6Tso6^`10k(
zB-VRlVRfHXfnwSz-fc%$z3I=vkI#gxDJkFIxg}>XP<oT0*z>@`eQuV@r|{P(a>u6%
zbshAL;`_fWk*`fVne`@i^!iZ$<z7Z-WSUzglU>+wJrA7$N>k51Z_K`RLmbsqYJ5Ae
zpDHirz501}!eNS?kO8L1^C!)ktV)`Jj^<r=O@B1Hau&0^tbnBBkMT)4H+L%I653}n
zcUx-QE0O-LJ$Lg4JdOHt#!n1gAD7k?>`)VJh@*TSEK%<WcAFVF@k>sN(#lz}UAsoG
zRciR3+%kN&g+^=xSy?_x3snMB(~e+cy^QWP;%#Cq>n)f`f3<94`odnN$+D3+?MvMI
zW0MyJYI6zx>iRu%7OIN=he92%^@l>eWF=PB=s(r^zbEmR*TvEjf4XsIX4m^8zOJ*{
V^V80WL-UV6CkGe%d|Utc-vFTWTn+#L


From 91c519467decaf9bcd99d88c7889d9e85bb29a3d Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Thu, 20 Jun 2013 00:46:56 -0700
Subject: [PATCH 36/75] WinRT build fix for samples and static libs.

---
 platforms/winrt/arm.winrt.toolchain.cmake | 9 ++-------
 samples/cpp/latentsvm_multidetect.cpp     | 4 ++--
 2 files changed, 4 insertions(+), 9 deletions(-)

diff --git a/platforms/winrt/arm.winrt.toolchain.cmake b/platforms/winrt/arm.winrt.toolchain.cmake
index ac9af117d..81bb57fe6 100644
--- a/platforms/winrt/arm.winrt.toolchain.cmake
+++ b/platforms/winrt/arm.winrt.toolchain.cmake
@@ -8,10 +8,5 @@ add_definitions(-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
 set(CMAKE_CXX_FLAGS           ""                    CACHE STRING "c++ flags")
 set(CMAKE_C_FLAGS             ""                    CACHE STRING "c flags")
 
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ZW -EHsc -GS")
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -GS")
-
-
-set(CMAKE_SHARED_LINKER_FLAGS "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"                    CACHE STRING "shared linker flags")
-set(CMAKE_MODULE_LINKER_FLAGS "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"                    CACHE STRING "module linker flags")
-set(CMAKE_EXE_LINKER_FLAGS    "/r:System.Runtime.WindowsRuntime.dll /r:System.Threading.Tasks.dll"  CACHE STRING "executable linker flags")
\ No newline at end of file
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -EHsc -GS")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -GS")
\ No newline at end of file
diff --git a/samples/cpp/latentsvm_multidetect.cpp b/samples/cpp/latentsvm_multidetect.cpp
index d2105122a..619c54b84 100644
--- a/samples/cpp/latentsvm_multidetect.cpp
+++ b/samples/cpp/latentsvm_multidetect.cpp
@@ -3,7 +3,7 @@
 #include "opencv2/highgui/highgui.hpp"
 #include "opencv2/contrib/contrib.hpp"
 
-#ifdef WIN32
+#if defined(WIN32) || defined(_WIN32)
 #include <io.h>
 #else
 #include <dirent.h>
@@ -67,7 +67,7 @@ static void readDirectory( const string& directoryName, vector<string>& filename
 {
     filenames.clear();
 
-#ifdef WIN32
+#if defined(WIN32) | defined(_WIN32)
     struct _finddata_t s_file;
     string str = directoryName + "\\*.*";
 

From cc3fb3d18253776ebcba1797d36b62e494f2f249 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Wed, 26 Jun 2013 10:50:51 +0800
Subject: [PATCH 37/75] Let CLAHE_OCL reuse cv::CLAHE abstract class.

---
 modules/ocl/include/opencv2/ocl/ocl.hpp | 14 +-------------
 modules/ocl/src/imgproc.cpp             | 11 ++++++++---
 2 files changed, 9 insertions(+), 16 deletions(-)

diff --git a/modules/ocl/include/opencv2/ocl/ocl.hpp b/modules/ocl/include/opencv2/ocl/ocl.hpp
index 7395c7bcc..35350f01b 100644
--- a/modules/ocl/include/opencv2/ocl/ocl.hpp
+++ b/modules/ocl/include/opencv2/ocl/ocl.hpp
@@ -516,20 +516,8 @@ namespace cv
         CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
         
         //! only 8UC1 is supported now
-        class CV_EXPORTS CLAHE
+        class CV_EXPORTS CLAHE : public cv::CLAHE
         {
-        public:
-            virtual void apply(const oclMat &src, oclMat &dst) = 0;
-
-            virtual void setClipLimit(double clipLimit) = 0;
-            virtual double getClipLimit() const = 0;
-
-            virtual void setTilesGridSize(Size tileGridSize) = 0;
-            virtual Size getTilesGridSize() const = 0;
-
-            virtual void collectGarbage() = 0;
-
-            virtual ~CLAHE() {}
         };
         CV_EXPORTS Ptr<cv::ocl::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
         
diff --git a/modules/ocl/src/imgproc.cpp b/modules/ocl/src/imgproc.cpp
index 3dbd68df8..9d67cd8ae 100644
--- a/modules/ocl/src/imgproc.cpp
+++ b/modules/ocl/src/imgproc.cpp
@@ -1598,7 +1598,7 @@ namespace cv
 
                 cv::AlgorithmInfo* info() const;
 
-                void apply(const oclMat &src, oclMat &dst);
+                void apply(cv::InputArray src, cv::OutputArray dst);
 
                 void setClipLimit(double clipLimit);
                 double getClipLimit() const;
@@ -1616,14 +1616,19 @@ namespace cv
                 oclMat srcExt_;
                 oclMat lut_;
             };
-
             CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
             clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
             {
             }
 
-            void CLAHE_Impl::apply(const oclMat &src, oclMat &dst)
+            CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_OCL",
+                obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
+                obj.info()->addParam(obj, "tilesX", obj.tilesX_);
+                obj.info()->addParam(obj, "tilesY", obj.tilesY_))
+            void CLAHE_Impl::apply(cv::InputArray src_raw, cv::OutputArray dst_raw)
             {
+                oclMat& src = getOclMatRef(src_raw);
+                oclMat& dst = getOclMatRef(dst_raw);
                 CV_Assert( src.type() == CV_8UC1 );
 
                 dst.create( src.size(), src.type() );

From 132b885b2481e824629339cd9aac41b2a01aa754 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Wed, 26 Jun 2013 16:35:19 +0800
Subject: [PATCH 38/75] Add opencl implementation of Farnback optical flow.

---
 modules/ocl/include/opencv2/ocl/ocl.hpp       |  63 +++
 modules/ocl/perf/perf_opticalflow.cpp         | 131 ++++-
 .../ocl/src/opencl/optical_flow_farneback.cl  | 446 +++++++++++++++
 modules/ocl/src/optical_flow_farneback.cpp    | 507 ++++++++++++++++++
 modules/ocl/test/test_optflow.cpp             |  72 +++
 5 files changed, 1218 insertions(+), 1 deletion(-)
 create mode 100644 modules/ocl/src/opencl/optical_flow_farneback.cl
 create mode 100644 modules/ocl/src/optical_flow_farneback.cpp

diff --git a/modules/ocl/include/opencv2/ocl/ocl.hpp b/modules/ocl/include/opencv2/ocl/ocl.hpp
index 7395c7bcc..aecf2be74 100644
--- a/modules/ocl/include/opencv2/ocl/ocl.hpp
+++ b/modules/ocl/include/opencv2/ocl/ocl.hpp
@@ -1410,6 +1410,69 @@ namespace cv
             oclMat vPyr_[2];
             bool isDeviceArch11_;
         };
+
+        class CV_EXPORTS FarnebackOpticalFlow
+        {
+        public:
+            FarnebackOpticalFlow()
+            {
+                numLevels = 5;
+                pyrScale = 0.5;
+                fastPyramids = false;
+                winSize = 13;
+                numIters = 10;
+                polyN = 5;
+                polySigma = 1.1;
+                flags = 0;
+            }
+
+            int numLevels;
+            double pyrScale;
+            bool fastPyramids;
+            int winSize;
+            int numIters;
+            int polyN;
+            double polySigma;
+            int flags;
+
+            void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
+
+            void releaseMemory()
+            {
+                frames_[0].release();
+                frames_[1].release();
+                pyrLevel_[0].release();
+                pyrLevel_[1].release();
+                M_.release();
+                bufM_.release();
+                R_[0].release();
+                R_[1].release();
+                blurredFrame_[0].release();
+                blurredFrame_[1].release();
+                pyramid0_.clear();
+                pyramid1_.clear();
+            }
+
+        private:
+            void prepareGaussian(
+                int n, double sigma, float *g, float *xg, float *xxg,
+                double &ig11, double &ig03, double &ig33, double &ig55);
+
+            void setPolynomialExpansionConsts(int n, double sigma);
+
+            void updateFlow_boxFilter(
+                const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
+                oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
+
+            void updateFlow_gaussianBlur(
+                const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
+                oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
+
+            oclMat frames_[2];
+            oclMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
+            std::vector<oclMat> pyramid0_, pyramid1_;
+        };
+
         //////////////// build warping maps ////////////////////
         //! builds plane warping maps
         CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, const Mat &T, float scale, oclMat &map_x, oclMat &map_y);
diff --git a/modules/ocl/perf/perf_opticalflow.cpp b/modules/ocl/perf/perf_opticalflow.cpp
index 97283b206..4b987f481 100644
--- a/modules/ocl/perf/perf_opticalflow.cpp
+++ b/modules/ocl/perf/perf_opticalflow.cpp
@@ -225,4 +225,133 @@ PERFTEST(tvl1flow)
 
     TestSystem::instance().ExceptedMatSimilar(gold[0], flowx, 3e-3);
     TestSystem::instance().ExceptedMatSimilar(gold[1], flowy, 3e-3);
-}
\ No newline at end of file
+}
+
+///////////// FarnebackOpticalFlow ////////////////////////
+PERFTEST(FarnebackOpticalFlow)
+{
+    cv::Mat frame0 = imread("rubberwhale1.png", cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(frame0.empty());
+
+    cv::Mat frame1 = imread("rubberwhale2.png", cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(frame1.empty());
+
+    cv::ocl::oclMat d_frame0(frame0), d_frame1(frame1);
+
+    int polyNs[2] = { 5, 7 };
+    double polySigmas[2] = { 1.1, 1.5 };
+    int farneFlags[2] = { 0, cv::OPTFLOW_FARNEBACK_GAUSSIAN };
+    bool UseInitFlows[2] = { false, true };
+    double pyrScale = 0.5;
+
+    string farneFlagStrs[2] = { "BoxFilter", "GaussianBlur" };
+    string useInitFlowStrs[2] = { "", "UseInitFlow" };
+
+    for ( int i = 0; i < 2; ++i)
+    {
+        int polyN = polyNs[i];
+        double polySigma = polySigmas[i];
+
+        for ( int j = 0; j < 2; ++j)
+        {
+            int flags = farneFlags[j];
+
+            for ( int k = 0; k < 2; ++k)
+            {
+                bool useInitFlow = UseInitFlows[k];
+                SUBTEST << "polyN(" << polyN << "); " << farneFlagStrs[j] << "; " << useInitFlowStrs[k];
+
+                cv::ocl::FarnebackOpticalFlow farn;
+                farn.pyrScale = pyrScale;
+                farn.polyN = polyN;
+                farn.polySigma = polySigma;
+                farn.flags = flags;
+
+                cv::ocl::oclMat d_flowx, d_flowy;
+                cv::Mat flow, flowBuf, flowxBuf, flowyBuf;
+
+                WARMUP_ON;
+                farn(d_frame0, d_frame1, d_flowx, d_flowy);
+
+                if (useInitFlow)
+                {
+                    cv::Mat flowxy[] = {cv::Mat(d_flowx), cv::Mat(d_flowy)};
+                    cv::merge(flowxy, 2, flow);
+                    flow.copyTo(flowBuf);
+                    flowxy[0].copyTo(flowxBuf);
+                    flowxy[1].copyTo(flowyBuf);
+
+                    farn.flags |= cv::OPTFLOW_USE_INITIAL_FLOW;
+                    farn(d_frame0, d_frame1, d_flowx, d_flowy);
+                }
+                WARMUP_OFF;
+
+                cv::calcOpticalFlowFarneback(
+                    frame0, frame1, flow, farn.pyrScale, farn.numLevels, farn.winSize,
+                    farn.numIters, farn.polyN, farn.polySigma, farn.flags);
+
+                std::vector<cv::Mat> flowxy;
+                cv::split(flow, flowxy);
+
+                double diff0 = 0.0;
+                TestSystem::instance().setAccurate(ExceptedMatSimilar(flowxy[0], cv::Mat(d_flowx), 0.1, diff0));                     
+                TestSystem::instance().setDiff(diff0);
+                double diff1 = 0.0;
+                TestSystem::instance().setAccurate(ExceptedMatSimilar(flowxy[1], cv::Mat(d_flowy), 0.1, diff1));                     
+                TestSystem::instance().setDiff(diff1);
+
+                if (useInitFlow)
+                {
+                    cv::Mat flowx, flowy;
+                    farn.flags = (flags | cv::OPTFLOW_USE_INITIAL_FLOW);
+
+                    CPU_ON;
+                    cv::calcOpticalFlowFarneback(
+                        frame0, frame1, flowBuf, farn.pyrScale, farn.numLevels, farn.winSize,
+                        farn.numIters, farn.polyN, farn.polySigma, farn.flags);
+                    CPU_OFF;
+
+                    GPU_ON;
+                    farn(d_frame0, d_frame1, d_flowx, d_flowy);
+                    GPU_OFF;
+
+                    GPU_FULL_ON;
+                    d_frame0.upload(frame0);
+                    d_frame1.upload(frame1);
+                    d_flowx.upload(flowxBuf);
+                    d_flowy.upload(flowyBuf);
+                    farn(d_frame0, d_frame1, d_flowx, d_flowy);
+                    d_flowx.download(flowx);
+                    d_flowy.download(flowy);
+                    GPU_FULL_OFF;
+                }
+                else
+                {
+                    cv::Mat flow, flowx, flowy;
+                    cv::ocl::oclMat d_flowx, d_flowy;
+
+                    farn.flags = flags;
+
+                    CPU_ON;
+                    cv::calcOpticalFlowFarneback(
+                        frame0, frame1, flow, farn.pyrScale, farn.numLevels, farn.winSize,
+                        farn.numIters, farn.polyN, farn.polySigma, farn.flags);
+                    CPU_OFF;
+
+                    GPU_ON;
+                    farn(d_frame0, d_frame1, d_flowx, d_flowy);
+                    GPU_OFF;
+
+                    GPU_FULL_ON;
+                    d_frame0.upload(frame0);
+                    d_frame1.upload(frame1);
+                    farn(d_frame0, d_frame1, d_flowx, d_flowy);
+                    d_flowx.download(flowx);
+                    d_flowy.download(flowy);
+                    GPU_FULL_OFF;
+                }
+            }
+        }
+    }
+}
+
diff --git a/modules/ocl/src/opencl/optical_flow_farneback.cl b/modules/ocl/src/opencl/optical_flow_farneback.cl
new file mode 100644
index 000000000..2e5c6d960
--- /dev/null
+++ b/modules/ocl/src/opencl/optical_flow_farneback.cl
@@ -0,0 +1,446 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
+// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// @Authors
+//    Sen Liu, swjtuls1987@126.com
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other oclMaterials provided with the distribution.
+//
+//   * The name of the copyright holders may not 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 Intel Corporation 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.
+//
+//M*/
+
+
+#define tx  get_local_id(0)
+#define ty  get_local_id(1)
+#define bx  get_group_id(0)
+#define bdx get_local_size(0)
+
+#define BORDER_SIZE 5
+#define MAX_KSIZE_HALF 100
+
+#ifndef polyN
+#define polyN 5
+#endif
+
+__kernel void polynomialExpansion(__global float * dst,
+                                  __global __const float * src,
+                                  __global __const float * c_g,
+                                  __global __const float * c_xg,
+                                  __global __const float * c_xxg,
+                                  __local float * smem,
+                                  const float4 ig,
+                                  const int height, const int width,
+                                  int dstStep, int srcStep)
+{
+    const int y = get_global_id(1);
+    const int x = bx * (bdx - 2*polyN) + tx - polyN;
+
+    dstStep /= sizeof(*dst);
+    srcStep /= sizeof(*src);
+    
+    int xWarped;
+    __local float *row = smem + tx;
+
+    if (y < height && y >= 0)
+    {
+        xWarped = min(max(x, 0), width - 1);
+
+        row[0] = src[mad24(y, srcStep, xWarped)] * c_g[0];
+        row[bdx] = 0.f;
+        row[2*bdx] = 0.f;
+
+#pragma unroll
+        for (int k = 1; k <= polyN; ++k)
+        {
+            float t0 = src[mad24(max(y - k, 0), srcStep, xWarped)];
+            float t1 = src[mad24(min(y + k, height - 1), srcStep, xWarped)];
+
+            row[0] += c_g[k] * (t0 + t1);
+            row[bdx] += c_xg[k] * (t1 - t0);
+            row[2*bdx] += c_xxg[k] * (t0 + t1);
+        }
+    }
+
+    barrier(CLK_LOCAL_MEM_FENCE);
+
+    if (y < height && y >= 0 && tx >= polyN && tx + polyN < bdx && x < width)
+    {
+        float b1 = c_g[0] * row[0];
+        float b3 = c_g[0] * row[bdx];
+        float b5 = c_g[0] * row[2*bdx];
+        float b2 = 0, b4 = 0, b6 = 0;
+
+#pragma unroll
+        for (int k = 1; k <= polyN; ++k)
+        {
+            b1 += (row[k] + row[-k]) * c_g[k];
+            b4 += (row[k] + row[-k]) * c_xxg[k];
+            b2 += (row[k] - row[-k]) * c_xg[k];
+            b3 += (row[k + bdx] + row[-k + bdx]) * c_g[k];
+            b6 += (row[k + bdx] - row[-k + bdx]) * c_xg[k];
+            b5 += (row[k + 2*bdx] + row[-k + 2*bdx]) * c_g[k];
+        }
+
+        dst[mad24(y, dstStep, xWarped)] = b3*ig.s0;
+        dst[mad24(height + y, dstStep, xWarped)] = b2*ig.s0;
+        dst[mad24(2*height + y, dstStep, xWarped)] = b1*ig.s1 + b5*ig.s2;
+        dst[mad24(3*height + y, dstStep, xWarped)] = b1*ig.s1 + b4*ig.s2;
+        dst[mad24(4*height + y, dstStep, xWarped)] = b6*ig.s3;
+    }
+}
+
+inline int idx_row_low(const int y, const int last_row)
+{
+    return abs(y) % (last_row + 1);
+}
+
+inline int idx_row_high(const int y, const int last_row)
+{
+    return abs(last_row - abs(last_row - y)) % (last_row + 1);
+}
+
+inline int idx_row(const int y, const int last_row)
+{
+    return idx_row_low(idx_row_high(y, last_row), last_row);
+}
+
+inline int idx_col_low(const int x, const int last_col)
+{
+    return abs(x) % (last_col + 1);
+}
+
+inline int idx_col_high(const int x, const int last_col)
+{
+    return abs(last_col - abs(last_col - x)) % (last_col + 1);
+}
+
+inline int idx_col(const int x, const int last_col)
+{
+    return idx_col_low(idx_col_high(x, last_col), last_col);
+}
+
+__kernel void gaussianBlur(__global float * dst,
+                           __global const float * src,
+                           __global const float * c_gKer,
+                           __local float * smem,
+                           const int height,  const int width,
+                           int dstStep, int srcStep,
+                           const int ksizeHalf)
+{
+    const int y = get_global_id(1);
+    const int x = get_global_id(0);
+
+    dstStep /= sizeof(*dst);
+    srcStep /= sizeof(*src);
+
+    __local float *row = smem + ty * (bdx + 2*ksizeHalf);
+    
+    if (y < height)
+    {
+        // Vertical pass
+        for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)
+        {
+            int xExt = (int)(bx * bdx) + i - ksizeHalf;
+            xExt = idx_col(xExt, width - 1);
+            row[i] = src[mad24(y, srcStep, xExt)] * c_gKer[0];
+            for (int j = 1; j <= ksizeHalf; ++j)
+                row[i] += (src[mad24(idx_row_low(y - j, height - 1), srcStep, xExt)]
+                           + src[mad24(idx_row_high(y + j, height - 1), srcStep, xExt)]) * c_gKer[j];
+        }
+    }
+
+    barrier(CLK_LOCAL_MEM_FENCE);
+        
+    if (y < height && y >= 0 && x < width && x >= 0)
+    {
+        // Horizontal pass
+        row += tx + ksizeHalf;
+        float res = row[0] * c_gKer[0];
+        for (int i = 1; i <= ksizeHalf; ++i)
+            res += (row[-i] + row[i]) * c_gKer[i];
+
+        dst[mad24(y, dstStep, x)] = res;
+    }
+}
+
+__constant float c_border[BORDER_SIZE + 1] = { 0.14f, 0.14f, 0.4472f, 0.4472f, 0.4472f, 1.f };
+
+__kernel void updateMatrices(__global float * M,
+                             __global const float * flowx, __global const float * flowy,
+                             __global const float * R0, __global const float * R1,
+                             const int height, const int width,
+                             int mStep, int xStep,  int yStep, int R0Step, int R1Step)
+{
+    const int y = get_global_id(1);
+    const int x = get_global_id(0);
+    
+    mStep /= sizeof(*M);
+    xStep /= sizeof(*flowx);
+    yStep /= sizeof(*flowy);
+    R0Step /= sizeof(*R0);
+    R1Step /= sizeof(*R1);
+
+    if (y < height && y >= 0 && x < width && x >= 0)
+    {
+        float dx = flowx[mad24(y, xStep, x)];
+        float dy = flowy[mad24(y, yStep, x)];
+        float fx = x + dx;
+        float fy = y + dy;
+
+        int x1 = convert_int(floor(fx));
+        int y1 = convert_int(floor(fy));
+        fx -= x1; fy -= y1;
+
+        float r2, r3, r4, r5, r6;
+
+        if (x1 >= 0 && y1 >= 0 && x1 < width - 1 && y1 < height - 1)
+        {
+            float a00 = (1.f - fx) * (1.f - fy);
+            float a01 = fx * (1.f - fy);
+            float a10 = (1.f - fx) * fy;
+            float a11 = fx * fy;
+
+            r2 = a00 * R1[mad24(y1, R1Step, x1)] +
+                 a01 * R1[mad24(y1, R1Step, x1 + 1)] +
+                 a10 * R1[mad24(y1 + 1, R1Step, x1)] +
+                 a11 * R1[mad24(y1 + 1, R1Step, x1 + 1)];
+
+            r3 = a00 * R1[mad24(height + y1, R1Step, x1)] +
+                 a01 * R1[mad24(height + y1, R1Step, x1 + 1)] +
+                 a10 * R1[mad24(height + y1 + 1, R1Step, x1)] +
+                 a11 * R1[mad24(height + y1 + 1, R1Step, x1 + 1)];
+
+            r4 = a00 * R1[mad24(2*height + y1, R1Step, x1)] +
+                 a01 * R1[mad24(2*height + y1, R1Step, x1 + 1)] +
+                 a10 * R1[mad24(2*height + y1 + 1, R1Step, x1)] +
+                 a11 * R1[mad24(2*height + y1 + 1, R1Step, x1 + 1)];
+
+            r5 = a00 * R1[mad24(3*height + y1, R1Step, x1)] +
+                 a01 * R1[mad24(3*height + y1, R1Step, x1 + 1)] +
+                 a10 * R1[mad24(3*height + y1 + 1, R1Step, x1)] +
+                 a11 * R1[mad24(3*height + y1 + 1, R1Step, x1 + 1)];
+
+            r6 = a00 * R1[mad24(4*height + y1, R1Step, x1)] +
+                 a01 * R1[mad24(4*height + y1, R1Step, x1 + 1)] +
+                 a10 * R1[mad24(4*height + y1 + 1, R1Step, x1)] +
+                 a11 * R1[mad24(4*height + y1 + 1, R1Step, x1 + 1)];
+
+            r4 = (R0[mad24(2*height + y, R0Step, x)] + r4) * 0.5f;
+            r5 = (R0[mad24(3*height + y, R0Step, x)] + r5) * 0.5f;
+            r6 = (R0[mad24(4*height + y, R0Step, x)] + r6) * 0.25f;
+        }
+        else
+        {
+            r2 = r3 = 0.f;
+            r4 = R0[mad24(2*height + y, R0Step, x)];
+            r5 = R0[mad24(3*height + y, R0Step, x)];
+            r6 = R0[mad24(4*height + y, R0Step, x)] * 0.5f;
+        }
+
+        r2 = (R0[mad24(y, R0Step, x)] - r2) * 0.5f;
+        r3 = (R0[mad24(height + y, R0Step, x)] - r3) * 0.5f;
+
+        r2 += r4*dy + r6*dx;
+        r3 += r6*dy + r5*dx;
+
+        float scale =
+                c_border[min(x, BORDER_SIZE)] *
+                c_border[min(y, BORDER_SIZE)] *
+                c_border[min(width - x - 1, BORDER_SIZE)] *
+                c_border[min(height - y - 1, BORDER_SIZE)];
+
+        r2 *= scale; r3 *= scale; r4 *= scale;
+        r5 *= scale; r6 *= scale;
+
+        M[mad24(y, mStep, x)] = r4*r4 + r6*r6;
+        M[mad24(height + y, mStep, x)] = (r4 + r5)*r6;
+        M[mad24(2*height + y, mStep, x)] = r5*r5 + r6*r6;
+        M[mad24(3*height + y, mStep, x)] = r4*r2 + r6*r3;
+        M[mad24(4*height + y, mStep, x)] = r6*r2 + r5*r3;
+    }
+}
+
+__kernel void boxFilter5(__global float * dst,
+                         __global const float * src,
+                         __local float * smem,
+                         const int height,  const int width,
+                         int dstStep, int srcStep,
+                         const int ksizeHalf)
+{
+    const int y = get_global_id(1);
+    const int x = get_global_id(0);
+        
+    const float boxAreaInv = 1.f / ((1 + 2*ksizeHalf) * (1 + 2*ksizeHalf));
+    const int smw = bdx + 2*ksizeHalf; // shared memory "width"
+    __local float *row = smem + 5 * ty * smw;
+
+    dstStep /= sizeof(*dst);
+    srcStep /= sizeof(*src);
+
+    if (y < height)
+    {
+        // Vertical pass
+        for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)
+        {
+            int xExt = (int)(bx * bdx) + i - ksizeHalf;
+            xExt = min(max(xExt, 0), width - 1);
+
+            #pragma unroll
+            for (int k = 0; k < 5; ++k)
+                row[k*smw + i] = src[mad24(k*height + y, srcStep, xExt)];
+
+            for (int j = 1; j <= ksizeHalf; ++j)
+                #pragma unroll
+                for (int k = 0; k < 5; ++k)
+                    row[k*smw + i] +=
+                            src[mad24(k*height + max(y - j, 0), srcStep, xExt)] +
+                            src[mad24(k*height + min(y + j, height - 1), srcStep, xExt)];
+        }
+    }
+
+    barrier(CLK_LOCAL_MEM_FENCE);
+
+    if (y < height && y >= 0 && x < width && x >= 0)
+    {
+        // Horizontal pass
+
+        row += tx + ksizeHalf;
+        float res[5];
+
+        #pragma unroll
+        for (int k = 0; k < 5; ++k)
+            res[k] = row[k*smw];
+
+        for (int i = 1; i <= ksizeHalf; ++i)
+            #pragma unroll
+            for (int k = 0; k < 5; ++k)
+                res[k] += row[k*smw - i] + row[k*smw + i];
+
+        #pragma unroll
+        for (int k = 0; k < 5; ++k)
+            dst[mad24(k*height + y, dstStep, x)] = res[k] * boxAreaInv;
+    }
+}
+
+__kernel void updateFlow(__global float4 * flowx, __global float4 * flowy,
+                         __global const float4 * M,
+                         const int height, const int width,
+                         int xStep, int yStep, int mStep)
+{
+    const int y = get_global_id(1);
+    const int x = get_global_id(0);
+
+    xStep /= sizeof(*flowx);
+    yStep /= sizeof(*flowy);
+    mStep /= sizeof(*M);
+
+    if (y < height && y >= 0 && x < width && x >= 0)
+    {
+        float4 g11 = M[mad24(y, mStep, x)];
+        float4 g12 = M[mad24(height + y, mStep, x)];
+        float4 g22 = M[mad24(2*height + y, mStep, x)]; 
+        float4 h1 =  M[mad24(3*height + y, mStep, x)];
+        float4 h2 =  M[mad24(4*height + y, mStep, x)];
+
+        float4 detInv = (float4)(1.f) / (g11*g22 - g12*g12 + (float4)(1e-3f));
+
+        flowx[mad24(y, xStep, x)] = (g11*h2 - g12*h1) * detInv;
+        flowy[mad24(y, yStep, x)] = (g22*h1 - g12*h2) * detInv;
+    }
+}
+
+__kernel void gaussianBlur5(__global float * dst,
+                            __global const float * src,
+                            __global const float * c_gKer,
+                            __local float * smem,
+                            const int height,  const int width,
+                            int dstStep, int srcStep,
+                            const int ksizeHalf)
+{
+    const int y = get_global_id(1);
+    const int x = get_global_id(0);
+
+    const int smw = bdx + 2*ksizeHalf; // shared memory "width"
+    __local volatile float *row = smem + 5 * ty * smw;
+
+    dstStep /= sizeof(*dst);
+    srcStep /= sizeof(*src);
+
+    if (y < height)
+    {
+        // Vertical pass
+        for (int i = tx; i < bdx + 2*ksizeHalf; i += bdx)
+        {
+            int xExt = (int)(bx * bdx) + i - ksizeHalf;
+            xExt = idx_col(xExt, width - 1);
+
+            #pragma unroll
+            for (int k = 0; k < 5; ++k)
+                row[k*smw + i] = src[mad24(k*height + y, srcStep, xExt)] * c_gKer[0];
+
+            for (int j = 1; j <= ksizeHalf; ++j)
+                #pragma unroll
+                for (int k = 0; k < 5; ++k)
+                    row[k*smw + i] +=
+                            (src[mad24(k*height + idx_row_low(y - j, height - 1), srcStep, xExt)] +
+                                src[mad24(k*height + idx_row_high(y + j, height - 1), srcStep, xExt)]) * c_gKer[j];
+        }
+    }
+
+    barrier(CLK_LOCAL_MEM_FENCE);
+
+    if (y < height && y >= 0 && x < width && x >= 0)
+    {
+        // Horizontal pass
+
+        row += tx + ksizeHalf;
+        float res[5];
+
+        #pragma unroll
+        for (int k = 0; k < 5; ++k)
+            res[k] = row[k*smw] * c_gKer[0];
+
+        for (int i = 1; i <= ksizeHalf; ++i)
+            #pragma unroll
+            for (int k = 0; k < 5; ++k)
+                res[k] += (row[k*smw - i] + row[k*smw + i]) * c_gKer[i];
+
+        #pragma unroll
+        for (int k = 0; k < 5; ++k)
+            dst[mad24(k*height + y, dstStep, x)] = res[k];
+    }
+}
diff --git a/modules/ocl/src/optical_flow_farneback.cpp b/modules/ocl/src/optical_flow_farneback.cpp
new file mode 100644
index 000000000..6667eb725
--- /dev/null
+++ b/modules/ocl/src/optical_flow_farneback.cpp
@@ -0,0 +1,507 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
+// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// @Authors
+//      Sen Liu, swjtuls1987@126.com
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other oclMaterials provided with the distribution.
+//
+//   * The name of the copyright holders may not 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 Intel Corporation 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.
+//
+//M*/
+
+
+#include "precomp.hpp"
+#include "opencv2/video/tracking.hpp"
+
+using namespace std;
+using namespace cv;
+using namespace cv::ocl;
+
+#define MIN_SIZE 32
+
+namespace cv
+{
+    namespace ocl
+    {
+        ///////////////////////////OpenCL kernel strings///////////////////////////
+        extern const char *optical_flow_farneback;
+    }
+}
+
+namespace cv { namespace ocl { namespace optflow_farneback
+{
+    oclMat g;
+    oclMat xg;
+    oclMat xxg;
+    oclMat gKer;
+
+    float ig[4];
+
+    inline int divUp(int total, int grain)
+    {
+        return (total + grain - 1) / grain;
+    }
+
+    inline void setGaussianBlurKernel(const float *c_gKer, int ksizeHalf)
+    {
+        cv::Mat t_gKer(1, ksizeHalf + 1, CV_32FC1, const_cast<float *>(c_gKer));
+        gKer.upload(t_gKer);
+    }
+
+    void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    {
+        string kernelName("gaussianBlur");
+        size_t localThreads[3] = { 256, 1, 1 };
+        size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], src.rows, 1 };
+        int smem_size = (localThreads[0] + 2*ksizeHalf) * sizeof(float);
+
+        CV_Assert(dst.size() == src.size());
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
+        args.push_back(std::make_pair(smem_size, (void *)NULL));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1);
+    }
+
+    void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
+    {
+        string kernelName("polynomialExpansion");
+        size_t localThreads[3] = { 256, 1, 1 };
+        size_t globalThreads[3] = { divUp(src.cols, localThreads[0] - 2*polyN) * localThreads[0], src.rows, 1 };
+        int smem_size = 3 * localThreads[0] * sizeof(float);
+
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&g.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xg.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xxg.data));
+        args.push_back(std::make_pair(smem_size, (void *)NULL));
+        args.push_back(std::make_pair(sizeof(cl_float4), (void *)&ig));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+
+        char opt [128];
+        sprintf(opt, "-D polyN=%d", polyN);
+
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1, opt);
+    }
+
+    void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
+    {
+        string kernelName("updateMatrices");
+        size_t localThreads[3] = { 32, 8, 1 };
+        size_t globalThreads[3] = { divUp(flowx.cols, localThreads[0]) * localThreads[0],
+                                    divUp(flowx.rows, localThreads[1]) * localThreads[1],
+                                    1 };
+
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R0.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R1.data));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.cols));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&R0.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&R1.step));
+
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1);
+    }
+
+    void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    {
+        string kernelName("boxFilter5");
+        int height = src.rows / 5;
+        size_t localThreads[3] = { 256, 1, 1 };
+        size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], height, 1 };
+        int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
+
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+        args.push_back(std::make_pair(smem_size, (void *)NULL));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1);
+    }
+
+    void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
+    {
+        string kernelName("updateFlow");
+        int cols = divUp(flowx.cols, 4);
+        size_t localThreads[3] = { 32, 8, 1 };
+        size_t globalThreads[3] = { divUp(cols, localThreads[0]) * localThreads[0],
+                                    divUp(flowx.rows, localThreads[1]) * localThreads[0],
+                                    1 };
+
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
+        
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1);
+    }
+
+    void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    {
+        string kernelName("gaussianBlur5");
+        int height = src.rows / 5;
+        int width = src.cols;
+        size_t localThreads[3] = { 256, 1, 1 };
+        size_t globalThreads[3] = { divUp(width, localThreads[0]) * localThreads[0], height, 1 };
+        int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
+
+        std::vector< std::pair<size_t, const void *> > args;
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
+        args.push_back(std::make_pair(smem_size, (void *)NULL));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&width));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+
+        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+            globalThreads, localThreads, args, -1, -1);
+    }
+}}} // namespace cv { namespace ocl { namespace optflow_farneback
+
+static oclMat allocMatFromBuf(int rows, int cols, int type, oclMat &mat)
+{
+    if (!mat.empty() && mat.type() == type && mat.rows >= rows && mat.cols >= cols)
+        return mat(Rect(0, 0, cols, rows));
+    return mat = oclMat(rows, cols, type);
+}
+
+void cv::ocl::FarnebackOpticalFlow::prepareGaussian(
+        int n, double sigma, float *g, float *xg, float *xxg,
+        double &ig11, double &ig03, double &ig33, double &ig55)
+{
+    double s = 0.;
+    for (int x = -n; x <= n; x++)
+    {
+        g[x] = (float)std::exp(-x*x/(2*sigma*sigma));
+        s += g[x];
+    }
+
+    s = 1./s;
+    for (int x = -n; x <= n; x++)
+    {
+        g[x] = (float)(g[x]*s);
+        xg[x] = (float)(x*g[x]);
+        xxg[x] = (float)(x*x*g[x]);
+    }
+
+    Mat_<double> G(6, 6);
+    G.setTo(0);
+
+    for (int y = -n; y <= n; y++)
+    {
+        for (int x = -n; x <= n; x++)
+        {
+            G(0,0) += g[y]*g[x];
+            G(1,1) += g[y]*g[x]*x*x;
+            G(3,3) += g[y]*g[x]*x*x*x*x;
+            G(5,5) += g[y]*g[x]*x*x*y*y;
+        }
+    }
+
+    //G[0][0] = 1.;
+    G(2,2) = G(0,3) = G(0,4) = G(3,0) = G(4,0) = G(1,1);
+    G(4,4) = G(3,3);
+    G(3,4) = G(4,3) = G(5,5);
+
+    // invG:
+    // [ x        e  e    ]
+    // [    y             ]
+    // [       y          ]
+    // [ e        z       ]
+    // [ e           z    ]
+    // [                u ]
+    Mat_<double> invG = G.inv(DECOMP_CHOLESKY);
+
+    ig11 = invG(1,1);
+    ig03 = invG(0,3);
+    ig33 = invG(3,3);
+    ig55 = invG(5,5);
+}
+
+void cv::ocl::FarnebackOpticalFlow::setPolynomialExpansionConsts(int n, double sigma)
+{
+    vector<float> buf(n*6 + 3);
+    float* g = &buf[0] + n;
+    float* xg = g + n*2 + 1;
+    float* xxg = xg + n*2 + 1;
+
+    if (sigma < FLT_EPSILON)
+        sigma = n*0.3;
+
+    double ig11, ig03, ig33, ig55;
+    prepareGaussian(n, sigma, g, xg, xxg, ig11, ig03, ig33, ig55);
+
+    cv::Mat t_g(1, n + 1, CV_32FC1, g);
+    cv::Mat t_xg(1, n + 1, CV_32FC1, xg);
+    cv::Mat t_xxg(1, n + 1, CV_32FC1, xxg);
+
+    optflow_farneback::g.upload(t_g);
+    optflow_farneback::xg.upload(t_xg);
+    optflow_farneback::xxg.upload(t_xxg);
+
+    optflow_farneback::ig[0] = static_cast<float>(ig11);
+    optflow_farneback::ig[1] = static_cast<float>(ig03);
+    optflow_farneback::ig[2] = static_cast<float>(ig33);
+    optflow_farneback::ig[3] = static_cast<float>(ig55);
+}
+
+void cv::ocl::FarnebackOpticalFlow::updateFlow_boxFilter(
+        const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
+        oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
+{
+    optflow_farneback::boxFilter5Ocl(M, blockSize/2, bufM);
+
+    swap(M, bufM);
+
+    finish();
+
+    optflow_farneback::updateFlowOcl(M, flowx, flowy);
+
+    if (updateMatrices)
+        optflow_farneback::updateMatricesOcl(flowx, flowy, R0, R1, M);
+}
+
+
+void cv::ocl::FarnebackOpticalFlow::updateFlow_gaussianBlur(
+        const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
+        oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
+{
+    optflow_farneback::gaussianBlur5Ocl(M, blockSize/2, bufM);
+
+    swap(M, bufM);
+
+    optflow_farneback::updateFlowOcl(M, flowx, flowy);
+
+    if (updateMatrices)
+        optflow_farneback::updateMatricesOcl(flowx, flowy, R0, R1, M);
+}
+
+
+void cv::ocl::FarnebackOpticalFlow::operator ()(
+        const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy)
+{
+    CV_Assert(frame0.channels() == 1 && frame1.channels() == 1);
+    CV_Assert(frame0.size() == frame1.size());
+    CV_Assert(polyN == 5 || polyN == 7);
+    CV_Assert(!fastPyramids || std::abs(pyrScale - 0.5) < 1e-6);
+
+    Size size = frame0.size();
+    oclMat prevFlowX, prevFlowY, curFlowX, curFlowY;
+
+    flowx.create(size, CV_32F);
+    flowy.create(size, CV_32F);
+    oclMat flowx0 = flowx;
+    oclMat flowy0 = flowy;
+
+    // Crop unnecessary levels
+    double scale = 1;
+    int numLevelsCropped = 0;
+    for (; numLevelsCropped < numLevels; numLevelsCropped++)
+    {
+        scale *= pyrScale;
+        if (size.width*scale < MIN_SIZE || size.height*scale < MIN_SIZE)
+            break;
+    }
+
+    frame0.convertTo(frames_[0], CV_32F);
+    frame1.convertTo(frames_[1], CV_32F);
+
+    if (fastPyramids)
+    {
+        // Build Gaussian pyramids using pyrDown()
+        pyramid0_.resize(numLevelsCropped + 1);
+        pyramid1_.resize(numLevelsCropped + 1);
+        pyramid0_[0] = frames_[0];
+        pyramid1_[0] = frames_[1];
+        for (int i = 1; i <= numLevelsCropped; ++i)
+        {
+            pyrDown(pyramid0_[i - 1], pyramid0_[i]);
+            pyrDown(pyramid1_[i - 1], pyramid1_[i]);
+        }
+    }
+
+    setPolynomialExpansionConsts(polyN, polySigma);
+
+    for (int k = numLevelsCropped; k >= 0; k--)
+    {
+        scale = 1;
+        for (int i = 0; i < k; i++)
+            scale *= pyrScale;
+
+        double sigma = (1./scale - 1) * 0.5;
+        int smoothSize = cvRound(sigma*5) | 1;
+        smoothSize = std::max(smoothSize, 3);
+
+        int width = cvRound(size.width*scale);
+        int height = cvRound(size.height*scale);
+
+        if (fastPyramids)
+        {
+            width = pyramid0_[k].cols;
+            height = pyramid0_[k].rows;
+        }
+
+        if (k > 0)
+        {
+            curFlowX.create(height, width, CV_32F);
+            curFlowY.create(height, width, CV_32F);
+        }
+        else
+        {
+            curFlowX = flowx0;
+            curFlowY = flowy0;
+        }
+
+        if (!prevFlowX.data)
+        {
+            if (flags & cv::OPTFLOW_USE_INITIAL_FLOW)
+            {
+                resize(flowx0, curFlowX, Size(width, height), 0, 0, INTER_LINEAR);
+                resize(flowy0, curFlowY, Size(width, height), 0, 0, INTER_LINEAR);
+                multiply(scale, curFlowX, curFlowX);
+                multiply(scale, curFlowY, curFlowY);
+            }
+            else
+            {
+                curFlowX.setTo(0);
+                curFlowY.setTo(0);
+            }
+        }
+        else
+        {
+            resize(prevFlowX, curFlowX, Size(width, height), 0, 0, INTER_LINEAR);
+            resize(prevFlowY, curFlowY, Size(width, height), 0, 0, INTER_LINEAR);
+            multiply(1./pyrScale, curFlowX, curFlowX);
+            multiply(1./pyrScale, curFlowY, curFlowY);
+        }
+
+        oclMat M = allocMatFromBuf(5*height, width, CV_32F, M_);
+        oclMat bufM = allocMatFromBuf(5*height, width, CV_32F, bufM_);
+        oclMat R[2] =
+        {
+            allocMatFromBuf(5*height, width, CV_32F, R_[0]),
+            allocMatFromBuf(5*height, width, CV_32F, R_[1])
+        };
+
+        if (fastPyramids)
+        {
+            optflow_farneback::polynomialExpansionOcl(pyramid0_[k], polyN, R[0]);
+            optflow_farneback::polynomialExpansionOcl(pyramid1_[k], polyN, R[1]);
+        }
+        else
+        {
+            oclMat blurredFrame[2] =
+            {
+                allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[0]),
+                allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[1])
+            };
+            oclMat pyrLevel[2] =
+            {
+                allocMatFromBuf(height, width, CV_32F, pyrLevel_[0]),
+                allocMatFromBuf(height, width, CV_32F, pyrLevel_[1])
+            };
+
+            Mat g = getGaussianKernel(smoothSize, sigma, CV_32F);
+            optflow_farneback::setGaussianBlurKernel(g.ptr<float>(smoothSize/2), smoothSize/2);
+
+            for (int i = 0; i < 2; i++)
+            {
+                optflow_farneback::gaussianBlurOcl(frames_[i], smoothSize/2, blurredFrame[i]);
+                resize(blurredFrame[i], pyrLevel[i], Size(width, height), INTER_LINEAR);
+                optflow_farneback::polynomialExpansionOcl(pyrLevel[i], polyN, R[i]);
+            }
+        }
+
+        optflow_farneback::updateMatricesOcl(curFlowX, curFlowY, R[0], R[1], M);
+
+        if (flags & OPTFLOW_FARNEBACK_GAUSSIAN)
+        {
+            Mat g = getGaussianKernel(winSize, winSize/2*0.3f, CV_32F);
+            optflow_farneback::setGaussianBlurKernel(g.ptr<float>(winSize/2), winSize/2);
+        }
+        for (int i = 0; i < numIters; i++)
+        {
+            if (flags & OPTFLOW_FARNEBACK_GAUSSIAN)
+                updateFlow_gaussianBlur(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize, i < numIters-1);
+            else
+                updateFlow_boxFilter(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize, i < numIters-1);
+        }
+
+        prevFlowX = curFlowX;
+        prevFlowY = curFlowY;
+    }
+
+    flowx = curFlowX;
+    flowy = curFlowY;
+}
+
diff --git a/modules/ocl/test/test_optflow.cpp b/modules/ocl/test/test_optflow.cpp
index 0121be8f9..34adb352c 100644
--- a/modules/ocl/test/test_optflow.cpp
+++ b/modules/ocl/test/test_optflow.cpp
@@ -272,6 +272,78 @@ TEST_P(Sparse, Mat)
 INSTANTIATE_TEST_CASE_P(OCL_Video, Sparse, Combine(
     Values(false, true),
     Values(false, true)));
+//////////////////////////////////////////////////////
+// FarnebackOpticalFlow
+
+namespace
+{
+    IMPLEMENT_PARAM_CLASS(PyrScale, double)
+        IMPLEMENT_PARAM_CLASS(PolyN, int)
+        CV_FLAGS(FarnebackOptFlowFlags, 0, OPTFLOW_FARNEBACK_GAUSSIAN)
+        IMPLEMENT_PARAM_CLASS(UseInitFlow, bool)
+}
+
+PARAM_TEST_CASE(Farneback, PyrScale, PolyN, FarnebackOptFlowFlags, UseInitFlow)
+{
+    double pyrScale;
+    int polyN;
+    int flags;
+    bool useInitFlow;
+
+    virtual void SetUp()
+    {
+        pyrScale = GET_PARAM(0);
+        polyN = GET_PARAM(1);
+        flags = GET_PARAM(2);
+        useInitFlow = GET_PARAM(3);
+    }
+};
+
+TEST_P(Farneback, Accuracy)
+{
+    cv::Mat frame0 = imread(workdir + "/rubberwhale1.png", cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(frame0.empty());
+
+    cv::Mat frame1 = imread(workdir + "/rubberwhale2.png", cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(frame1.empty());
+
+    double polySigma = polyN <= 5 ? 1.1 : 1.5;
+
+    cv::ocl::FarnebackOpticalFlow farn;
+    farn.pyrScale = pyrScale;
+    farn.polyN = polyN;
+    farn.polySigma = polySigma;
+    farn.flags = flags;
+
+    cv::ocl::oclMat d_flowx, d_flowy;
+    farn(oclMat(frame0), oclMat(frame1), d_flowx, d_flowy);
+
+    cv::Mat flow;
+    if (useInitFlow)
+    {
+        cv::Mat flowxy[] = {cv::Mat(d_flowx), cv::Mat(d_flowy)};
+        cv::merge(flowxy, 2, flow);
+
+        farn.flags |= cv::OPTFLOW_USE_INITIAL_FLOW;
+        farn(oclMat(frame0), oclMat(frame1), d_flowx, d_flowy);
+    }
+
+    cv::calcOpticalFlowFarneback(
+        frame0, frame1, flow, farn.pyrScale, farn.numLevels, farn.winSize,
+        farn.numIters, farn.polyN, farn.polySigma, farn.flags);
+
+    std::vector<cv::Mat> flowxy;
+    cv::split(flow, flowxy);
+
+    EXPECT_MAT_SIMILAR(flowxy[0], d_flowx, 0.1);
+    EXPECT_MAT_SIMILAR(flowxy[1], d_flowy, 0.1);
+}
+
+INSTANTIATE_TEST_CASE_P(OCL_Video, Farneback, testing::Combine(
+    testing::Values(PyrScale(0.3), PyrScale(0.5), PyrScale(0.8)),
+    testing::Values(PolyN(5), PolyN(7)),
+    testing::Values(FarnebackOptFlowFlags(0), FarnebackOptFlowFlags(cv::OPTFLOW_FARNEBACK_GAUSSIAN)),
+    testing::Values(UseInitFlow(false), UseInitFlow(true))));
 
 #endif // HAVE_OPENCL
 

From 2ec1140b25098421915bc7781e2498c4858810c6 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Wed, 26 Jun 2013 16:58:20 +0800
Subject: [PATCH 39/75] fix pyrlk

---
 modules/ocl/src/mcwutil.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/ocl/src/mcwutil.cpp b/modules/ocl/src/mcwutil.cpp
index 75314fb49..4292a1f87 100644
--- a/modules/ocl/src/mcwutil.cpp
+++ b/modules/ocl/src/mcwutil.cpp
@@ -149,7 +149,7 @@ namespace cv
             cl_image_format format;
             int err;
             int depth    = mat.depth();
-            int channels = mat.channels();
+            int channels = mat.oclchannels();
 
             switch(depth)
             {

From 9270205947fffb5e01d1c157863071b3e7ecd2c4 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Wed, 26 Jun 2013 17:24:09 +0800
Subject: [PATCH 40/75] Fix build errors

---
 modules/ocl/perf/perf_opticalflow.cpp      | 10 ++++------
 modules/ocl/src/optical_flow_farneback.cpp | 12 ++++++------
 2 files changed, 10 insertions(+), 12 deletions(-)

diff --git a/modules/ocl/perf/perf_opticalflow.cpp b/modules/ocl/perf/perf_opticalflow.cpp
index 4b987f481..2b01e1955 100644
--- a/modules/ocl/perf/perf_opticalflow.cpp
+++ b/modules/ocl/perf/perf_opticalflow.cpp
@@ -293,12 +293,10 @@ PERFTEST(FarnebackOpticalFlow)
                 std::vector<cv::Mat> flowxy;
                 cv::split(flow, flowxy);
 
-                double diff0 = 0.0;
-                TestSystem::instance().setAccurate(ExceptedMatSimilar(flowxy[0], cv::Mat(d_flowx), 0.1, diff0));                     
-                TestSystem::instance().setDiff(diff0);
-                double diff1 = 0.0;
-                TestSystem::instance().setAccurate(ExceptedMatSimilar(flowxy[1], cv::Mat(d_flowy), 0.1, diff1));                     
-                TestSystem::instance().setDiff(diff1);
+                Mat md_flowx = cv::Mat(d_flowx);
+                Mat md_flowy = cv::Mat(d_flowy);
+                TestSystem::instance().ExceptedMatSimilar(flowxy[0], md_flowx, 0.1);
+                TestSystem::instance().ExceptedMatSimilar(flowxy[1], md_flowy, 0.1);
 
                 if (useInitFlow)
                 {
diff --git a/modules/ocl/src/optical_flow_farneback.cpp b/modules/ocl/src/optical_flow_farneback.cpp
index 6667eb725..17c021d7c 100644
--- a/modules/ocl/src/optical_flow_farneback.cpp
+++ b/modules/ocl/src/optical_flow_farneback.cpp
@@ -82,7 +82,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
         gKer.upload(t_gKer);
     }
 
-    void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    static void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
     {
         string kernelName("gaussianBlur");
         size_t localThreads[3] = { 256, 1, 1 };
@@ -105,7 +105,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
             globalThreads, localThreads, args, -1, -1);
     }
 
-    void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
+    static void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
     {
         string kernelName("polynomialExpansion");
         size_t localThreads[3] = { 256, 1, 1 };
@@ -132,7 +132,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
             globalThreads, localThreads, args, -1, -1, opt);
     }
 
-    void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
+    static void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
     {
         string kernelName("updateMatrices");
         size_t localThreads[3] = { 32, 8, 1 };
@@ -158,7 +158,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
             globalThreads, localThreads, args, -1, -1);
     }
 
-    void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    static void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
     {
         string kernelName("boxFilter5");
         int height = src.rows / 5;
@@ -180,7 +180,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
             globalThreads, localThreads, args, -1, -1);
     }
 
-    void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
+    static void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
     {
         string kernelName("updateFlow");
         int cols = divUp(flowx.cols, 4);
@@ -203,7 +203,7 @@ namespace cv { namespace ocl { namespace optflow_farneback
             globalThreads, localThreads, args, -1, -1);
     }
 
-    void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+    static void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
     {
         string kernelName("gaussianBlur5");
         int height = src.rows / 5;

From 5b2b76763e7e8cb9af972ef3b0075fd6b44e6d27 Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Wed, 26 Jun 2013 14:59:00 +0400
Subject: [PATCH 41/75] Fix miscellaneous warnings from compiling with MinGW.

Note that MinGW defines NOMINMAX by default.
---
 modules/ocl/perf/precomp.cpp | 4 +++-
 modules/ocl/src/haar.cpp     | 2 +-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/modules/ocl/perf/precomp.cpp b/modules/ocl/perf/precomp.cpp
index 9fc634290..dd3b5e4ea 100644
--- a/modules/ocl/perf/precomp.cpp
+++ b/modules/ocl/perf/precomp.cpp
@@ -42,7 +42,9 @@
 
 #include "precomp.hpp"
 #if GTEST_OS_WINDOWS
+#ifndef NOMINMAX
 #define NOMINMAX
+#endif
 # include <windows.h>
 #endif
 
@@ -278,7 +280,7 @@ enum GTestColor {
 };
 #if GTEST_OS_WINDOWS&&!GTEST_OS_WINDOWS_MOBILE
 // Returns the character attribute for the given color.
-WORD GetColorAttribute(GTestColor color) {
+static WORD GetColorAttribute(GTestColor color) {
     switch (color) {
     case COLOR_RED:    return FOREGROUND_RED;
     case COLOR_GREEN:  return FOREGROUND_GREEN;
diff --git a/modules/ocl/src/haar.cpp b/modules/ocl/src/haar.cpp
index 565270cdc..6283ac8d9 100644
--- a/modules/ocl/src/haar.cpp
+++ b/modules/ocl/src/haar.cpp
@@ -142,7 +142,7 @@ typedef struct
     int imgoff;
     float factor;
 } detect_piramid_info;
-#ifdef WIN32
+#ifdef _MSC_VER
 #define _ALIGNED_ON(_ALIGNMENT) __declspec(align(_ALIGNMENT))
 
 typedef _ALIGNED_ON(128) struct  GpuHidHaarTreeNode

From 29955620e013e524d45a44835bcaa0a2ef62543c Mon Sep 17 00:00:00 2001
From: Sergei Nosov <sergei.nosov@gmail.com>
Date: Wed, 26 Jun 2013 15:07:39 +0400
Subject: [PATCH 42/75] multiruns added to avoid the 'unreliable results' error

---
 modules/imgproc/perf/perf_cvt_color.cpp | 2 +-
 modules/imgproc/perf/perf_resize.cpp    | 3 ++-
 modules/imgproc/perf/perf_threshold.cpp | 3 ++-
 3 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/modules/imgproc/perf/perf_cvt_color.cpp b/modules/imgproc/perf/perf_cvt_color.cpp
index 89c7c6916..601beb899 100644
--- a/modules/imgproc/perf/perf_cvt_color.cpp
+++ b/modules/imgproc/perf/perf_cvt_color.cpp
@@ -258,7 +258,7 @@ PERF_TEST_P(Size_CvtMode, cvtColor8u,
     declare.time(100);
     declare.in(src, WARMUP_RNG).out(dst);
 
-    int runs = sz.width <= 320 ? 70 : 1;
+    int runs = sz.width <= 320 ? 70 : 5;
     TEST_CYCLE_MULTIRUN(runs) cvtColor(src, dst, mode, ch.dcn);
 
     SANITY_CHECK(dst, 1);
diff --git a/modules/imgproc/perf/perf_resize.cpp b/modules/imgproc/perf/perf_resize.cpp
index 7aef05ee5..ea959a627 100644
--- a/modules/imgproc/perf/perf_resize.cpp
+++ b/modules/imgproc/perf/perf_resize.cpp
@@ -85,7 +85,8 @@ PERF_TEST_P(MatInfo_Size_Scale, ResizeAreaFast,
 
     declare.in(src, WARMUP_RNG).out(dst);
 
-    TEST_CYCLE() resize(src, dst, dst.size(), 0, 0, INTER_AREA);
+    int runs = 15;
+    TEST_CYCLE_MULTIRUN(runs) resize(src, dst, dst.size(), 0, 0, INTER_AREA);
 
     //difference equal to 1 is allowed because of different possible rounding modes: round-to-nearest vs bankers' rounding
     SANITY_CHECK(dst, 1);
diff --git a/modules/imgproc/perf/perf_threshold.cpp b/modules/imgproc/perf/perf_threshold.cpp
index 01fff2e8c..9ccafd6b5 100644
--- a/modules/imgproc/perf/perf_threshold.cpp
+++ b/modules/imgproc/perf/perf_threshold.cpp
@@ -51,7 +51,8 @@ PERF_TEST_P(Size_Only, threshold_otsu, testing::Values(TYPICAL_MAT_SIZES))
 
     declare.in(src, WARMUP_RNG).out(dst);
 
-    TEST_CYCLE() threshold(src, dst, 0, maxval, THRESH_BINARY|THRESH_OTSU);
+    int runs = 15;
+    TEST_CYCLE_MULTIRUN(runs) threshold(src, dst, 0, maxval, THRESH_BINARY|THRESH_OTSU);
 
     SANITY_CHECK(dst);
 }

From 347c86d9b58d8c2e45ddce82acc4c54a5efb2e70 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Mon, 24 Jun 2013 01:10:18 -0700
Subject: [PATCH 43/75] Windows RT related code cleanup.

Windows RT sample cleanup.
Video I/O code cleanup.
---
 .../include/opencv2/highgui/highgui_c.h       |    2 +-
 modules/highgui/src/cap_msmf.cpp              |   44 +-
 platforms/scripts/cmake_winrt.cmd             |    6 +-
 .../{C++ => }/AdvancedCapture.xaml            |    0
 .../{C++ => }/AdvancedCapture.xaml.cpp        |    0
 .../{C++ => }/AdvancedCapture.xaml.h          |    0
 .../ImageManipulations/{C++ => }/App.xaml     |    0
 .../ImageManipulations/{C++ => }/App.xaml.cpp |    0
 .../ImageManipulations/{C++ => }/App.xaml.h   |    0
 .../OcvTransform/OcvImageManipulations.h      |   92 -
 .../{C++ => }/Constants.cpp                   |    0
 .../ImageManipulations/{C++ => }/Constants.h  |    0
 .../{C++ => }/MainPage.xaml                   |    0
 .../{C++ => }/MainPage.xaml.cpp               |    0
 .../{C++ => }/MainPage.xaml.h                 |    0
 .../{C++ => }/MediaCapture.sln                |    0
 .../{C++ => }/MediaCapture.vcxproj            |    0
 .../MediaExtensions/Common/AsyncCB.h          |    0
 .../MediaExtensions/Common/BufferLock.h       |    0
 .../MediaExtensions/Common/CritSec.h          |    0
 .../MediaExtensions/Common/LinkList.h         |    0
 .../MediaExtensions/Common/OpQueue.h          |    0
 .../OcvTransform/OcvImageManipulations.idl    |    0
 .../OcvTransform/OcvTransform.cpp             |    0
 .../OcvTransform/OcvTransform.def             |    0
 .../OcvTransform/OcvTransform.h               |    0
 .../OcvTransform/OcvTransform.vcxproj         |    0
 .../MediaExtensions/OcvTransform/dllmain.cpp  |    0
 .../{C++ => }/Package.appxmanifest            |    0
 .../{C++ => }/assets/opencv-logo-150.png      |  Bin
 .../{C++ => }/assets/opencv-logo-30.png       |  Bin
 .../{C++ => }/assets/splash-sdk.png           |  Bin
 .../{C++ => }/assets/windows-sdk.png          |  Bin
 .../{C++ => }/common/LayoutAwarePage.cpp      |    0
 .../{C++ => }/common/LayoutAwarePage.h        |    0
 .../{C++ => }/common/StandardStyles.xaml      |    0
 .../{C++ => }/common/suspensionmanager.cpp    |    0
 .../{C++ => }/common/suspensionmanager.h      |    0
 .../winrt/ImageManipulations/description.html |  238 --
 ...a0-3e7e-46df-b80b-1692acc1c812Combined.css |    0
 .../ImageManipulations/description/Brand.css  | 3629 -----------------
 .../description/Combined.css                  |    0
 .../description/Galleries.css                 |  418 --
 .../ImageManipulations/description/Layout.css |  147 -
 ...69f54-1c43-4037-b90b-5f775f1d945fBrand.css |  303 --
 .../description/iframedescription.css         |  179 -
 .../ImageManipulations/description/offline.js |   52 -
 samples/winrt/ImageManipulations/license.rtf  |   25 -
 .../ImageManipulations/{C++ => }/pch.cpp      |    0
 .../winrt/ImageManipulations/{C++ => }/pch.h  |    0
 .../sample-utils/SampleTemplateStyles.xaml    |    0
 51 files changed, 8 insertions(+), 5127 deletions(-)
 rename samples/winrt/ImageManipulations/{C++ => }/AdvancedCapture.xaml (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/AdvancedCapture.xaml.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/AdvancedCapture.xaml.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/App.xaml (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/App.xaml.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/App.xaml.h (100%)
 delete mode 100644 samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
 rename samples/winrt/ImageManipulations/{C++ => }/Constants.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/Constants.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MainPage.xaml (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MainPage.xaml.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MainPage.xaml.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaCapture.sln (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaCapture.vcxproj (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/Common/AsyncCB.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/Common/BufferLock.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/Common/CritSec.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/Common/LinkList.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/Common/OpQueue.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/OcvImageManipulations.idl (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/OcvTransform.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/OcvTransform.def (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/OcvTransform.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/OcvTransform.vcxproj (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/MediaExtensions/OcvTransform/dllmain.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/Package.appxmanifest (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/assets/opencv-logo-150.png (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/assets/opencv-logo-30.png (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/assets/splash-sdk.png (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/assets/windows-sdk.png (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/common/LayoutAwarePage.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/common/LayoutAwarePage.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/common/StandardStyles.xaml (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/common/suspensionmanager.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/common/suspensionmanager.h (100%)
 delete mode 100644 samples/winrt/ImageManipulations/description.html
 delete mode 100644 samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css
 delete mode 100644 samples/winrt/ImageManipulations/description/Brand.css
 delete mode 100644 samples/winrt/ImageManipulations/description/Combined.css
 delete mode 100644 samples/winrt/ImageManipulations/description/Galleries.css
 delete mode 100644 samples/winrt/ImageManipulations/description/Layout.css
 delete mode 100644 samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
 delete mode 100644 samples/winrt/ImageManipulations/description/iframedescription.css
 delete mode 100644 samples/winrt/ImageManipulations/description/offline.js
 delete mode 100644 samples/winrt/ImageManipulations/license.rtf
 rename samples/winrt/ImageManipulations/{C++ => }/pch.cpp (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/pch.h (100%)
 rename samples/winrt/ImageManipulations/{C++ => }/sample-utils/SampleTemplateStyles.xaml (100%)

diff --git a/modules/highgui/include/opencv2/highgui/highgui_c.h b/modules/highgui/include/opencv2/highgui/highgui_c.h
index fbcdba24f..9204ee81f 100644
--- a/modules/highgui/include/opencv2/highgui/highgui_c.h
+++ b/modules/highgui/include/opencv2/highgui/highgui_c.h
@@ -558,7 +558,7 @@ CVAPI(int)    cvGetCaptureDomain( CvCapture* capture);
 /* "black box" video file writer structure */
 typedef struct CvVideoWriter CvVideoWriter;
 
-#define CV_FOURCC_MACRO(c1, c2, c3, c4) ((c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24))
+#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24))
 
 CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4)
 {
diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index ae82b2c67..dfd206ea4 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -203,12 +203,8 @@ private:
     RawImage *ig_RIOut;
     ImageGrabber(unsigned int deviceID, bool synchronous);
     HRESULT CreateTopology(IMFMediaSource *pSource, IMFActivate *pSinkActivate, IMFTopology **ppTopo);
-    HRESULT AddSourceNode(
-    IMFTopology *pTopology,
-    IMFMediaSource *pSource,
-    IMFPresentationDescriptor *pPD,
-    IMFStreamDescriptor *pSD,
-    IMFTopologyNode **ppNode);
+    HRESULT AddSourceNode(IMFTopology *pTopology, IMFMediaSource *pSource,
+        IMFPresentationDescriptor *pPD, IMFStreamDescriptor *pSD, IMFTopologyNode **ppNode);
     HRESULT AddOutputNode(IMFTopology *pTopology, IMFActivate *pActivate, DWORD dwId, IMFTopologyNode **ppNode);
     // IUnknown methods
     STDMETHODIMP QueryInterface(REFIID iid, void** ppv);
@@ -886,7 +882,7 @@ FormatReader::~FormatReader(void)
 {
 }
 
-#define CHECK_HR(x) if (FAILED(x)) { printf("Checking failed !!!\n"); goto done; }
+#define CHECK_HR(x) if (FAILED(x)) { goto done; }
 
 ImageGrabber::ImageGrabber(unsigned int deviceID, bool synchronous):
     m_cRef(1),
@@ -904,10 +900,8 @@ ImageGrabber::ImageGrabber(unsigned int deviceID, bool synchronous):
 
 ImageGrabber::~ImageGrabber(void)
 {
-    printf("ImageGrabber::~ImageGrabber()\n");
     if (ig_pSession)
     {
-        printf("ig_pSession->Shutdown()\n");
         ig_pSession->Shutdown();
     }
 
@@ -947,31 +941,26 @@ HRESULT ImageGrabber::initImageGrabber(IMFMediaSource *pSource, GUID VideoFormat
     hr = pSource->CreatePresentationDescriptor(&pPD);
     if (FAILED(hr))
     {
-        printf("Error creating CreatePresentationDescriptor()\n");
         goto err;
     }
     BOOL fSelected;
     hr = pPD->GetStreamDescriptorByIndex(0, &fSelected, &pSD);
     if (FAILED(hr)) {
-        printf("Error GetStreamDescriptorByIndex()\n");
         goto err;
     }
     hr = pSD->GetMediaTypeHandler(&pHandler);
     if (FAILED(hr)) {
-        printf("Error GetMediaTypeHandler()\n");
         goto err;
     }
     DWORD cTypes = 0;
     hr = pHandler->GetMediaTypeCount(&cTypes);
     if (FAILED(hr)) {
-        printf("Error GetMediaTypeCount()\n");
         goto err;
     }
     if(cTypes > 0)
     {
         hr = pHandler->GetCurrentMediaType(&pCurrentType);
         if (FAILED(hr)) {
-            printf("Error GetCurrentMediaType()\n");
             goto err;
         }
         MT = FormatReader::Read(pCurrentType.Get());
@@ -986,10 +975,6 @@ err:
     {
         sizeRawImage = MT.MF_MT_FRAME_SIZE * 4;
     }
-    else
-    {
-        printf("Video format is not RBG 24/32!\n");
-    }
     CHECK_HR(hr = RawImage::CreateInstance(&ig_RIFirst, sizeRawImage));
     CHECK_HR(hr = RawImage::CreateInstance(&ig_RISecond, sizeRawImage));
     ig_RIOut = ig_RISecond;
@@ -1038,16 +1023,8 @@ HRESULT ImageGrabber::startGrabbing(void)
     PropVariantInit(&var);
     HRESULT hr = S_OK;
     hr = ig_pSession->SetTopology(0, ig_pTopology);
-    if (FAILED(hr))
-    {
-        printf("Error: cannot set topology (status %u)\n", hr);
-    }
     DPO->printOut(L"IMAGEGRABBER VIDEODEVICE %i: Start Grabbing of the images\n", ig_DeviceID);
     hr = ig_pSession->Start(&GUID_NULL, &var);
-    if (FAILED(hr))
-    {
-        printf("Error: cannot start session (status %u)\n", hr);
-    }
     for(;;)
     {
         HRESULT hrStatus = S_OK;
@@ -1289,7 +1266,6 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
     (void)llSampleDuration;
     (void)dwSampleSize;
 
-    //printf("ImageGrabber::OnProcessSample() -- begin\n");
     HANDLE tmp[] = {ig_hFinish, ig_hFrameGrabbed, NULL};
 
     DWORD status = WaitForMultipleObjects(2, tmp, FALSE, INFINITE);
@@ -1310,8 +1286,6 @@ STDMETHODIMP ImageGrabber::OnProcessSample(REFGUID guidMajorMediaType, DWORD dwS
         ig_RIOut = ig_RISecond;
     }
 
-    //printf("ImageGrabber::OnProcessSample() -- end\n");
-
     if (ig_Synchronous)
     {
         SetEvent(ig_hFrameReady);
@@ -3128,11 +3102,7 @@ void CvCaptureFile_MSMF::close()
 
     if (videoFileSource)
     {
-        HRESULT hr = videoFileSource->Shutdown();
-        if (FAILED(hr))
-        {
-            printf("VideoCapture Closing failed!\n");
-        }
+        videoFileSource->Shutdown();
     }
 }
 
@@ -3531,16 +3501,13 @@ bool CvVideoWriter_MSMF::open( const char* filename, int fourcc,
 
 void CvVideoWriter_MSMF::close()
 {
-    printf("VideoWriter::close()\n");
     if (!initiated)
     {
-        printf("VideoWriter was not Initialized\n");
         return;
     }
 
     initiated = false;
     HRESULT hr = sinkWriter->Finalize();
-    printf("sinkWriter Finalize status %u\n", hr);
     MFShutdown();
 }
 
@@ -3569,7 +3536,6 @@ bool CvVideoWriter_MSMF::writeFrame(const IplImage* img)
     HRESULT hr = WriteFrame(target, rtStart, rtDuration);
     if (FAILED(hr))
     {
-        printf("Private WriteFrame failed\n");
         delete[] target;
         return false;
     }
@@ -3600,7 +3566,6 @@ HRESULT CvVideoWriter_MSMF::InitializeSinkWriter(const char* filename)
     // Set the output media type.
     if (SUCCEEDED(hr))
     {
-        printf("MFCreateSinkWriterFromURL is successfull\n");
         hr = MFCreateMediaType(&mediaTypeOut);
     }
     if (SUCCEEDED(hr))
@@ -3755,7 +3720,6 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
 CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc,
                                         double fps, CvSize frameSize, int isColor )
 {
-    printf("Creating Media Foundation VideoWriter\n");
     CvVideoWriter_MSMF* writer = new CvVideoWriter_MSMF;
     if( writer->open( filename, fourcc, fps, frameSize, isColor != 0 ))
         return writer;
diff --git a/platforms/scripts/cmake_winrt.cmd b/platforms/scripts/cmake_winrt.cmd
index c6d8cb8e0..df70e856c 100644
--- a/platforms/scripts/cmake_winrt.cmd
+++ b/platforms/scripts/cmake_winrt.cmd
@@ -1,6 +1,6 @@
-mkdir build
-cd build
+mkdir build_winrt_arm
+cd build_winrt_arm
 
 rem call "C:\Program Files\Microsoft Visual Studio 11.0\VC\bin\x86_arm\vcvarsx86_arm.bat"
 
-cmake.exe -GNinja -DWITH_TBB=ON -DBUILD_TBB=ON -DCMAKE_BUILD_TYPE=Release -DWITH_FFMPEG=OFF -DBUILD_opencv_gpu=OFF -DBUILD_opencv_python=OFF -DCMAKE_TOOLCHAIN_FILE=..\..\winrt\arm.winrt.toolchain.cmake ..\..\..
+cmake.exe -GNinja -DWITH_TBB=ON -DBUILD_TBB=ON -DCMAKE_BUILD_TYPE=Release -DWITH_FFMPEG=OFF -DBUILD_opencv_gpu=OFF -DBUILD_opencv_python=OFF -DCMAKE_TOOLCHAIN_FILE=..\winrt\arm.winrt.toolchain.cmake ..\..
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml b/samples/winrt/ImageManipulations/AdvancedCapture.xaml
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml
rename to samples/winrt/ImageManipulations/AdvancedCapture.xaml
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp b/samples/winrt/ImageManipulations/AdvancedCapture.xaml.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.cpp
rename to samples/winrt/ImageManipulations/AdvancedCapture.xaml.cpp
diff --git a/samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h b/samples/winrt/ImageManipulations/AdvancedCapture.xaml.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/AdvancedCapture.xaml.h
rename to samples/winrt/ImageManipulations/AdvancedCapture.xaml.h
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml b/samples/winrt/ImageManipulations/App.xaml
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/App.xaml
rename to samples/winrt/ImageManipulations/App.xaml
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml.cpp b/samples/winrt/ImageManipulations/App.xaml.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/App.xaml.cpp
rename to samples/winrt/ImageManipulations/App.xaml.cpp
diff --git a/samples/winrt/ImageManipulations/C++/App.xaml.h b/samples/winrt/ImageManipulations/App.xaml.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/App.xaml.h
rename to samples/winrt/ImageManipulations/App.xaml.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h b/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
deleted file mode 100644
index 5fce7322c..000000000
--- a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.h
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 8.00.0595 */
-/* at Wed Jun 19 03:47:25 2013
- */
-/* Compiler settings for C:\Users\ASMORK~1\AppData\Local\Temp\OcvImageManipulations.idl-2e8e757e:
-    Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 8.00.0595 
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-/* @@MIDL_FILE_HEADING(  ) */
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 475
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-
-#ifndef __OcvImageManipulations_h__
-#define __OcvImageManipulations_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-#if defined(__cplusplus)
-#if defined(__MIDL_USE_C_ENUM)
-#define MIDL_ENUM enum
-#else
-#define MIDL_ENUM enum class
-#endif
-#endif
-
-
-/* Forward Declarations */ 
-
-/* header files for imported files */
-#include "Windows.Media.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
-/* [local] */ 
-
-#pragma warning(push)
-#pragma warning(disable:4001) 
-#pragma once
-#pragma warning(pop)
-#ifndef RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
-#define RUNTIMECLASS_OcvTransform_OcvImageManipulations_DEFINED
-extern const __declspec(selectany) WCHAR RuntimeClass_OcvTransform_OcvImageManipulations[] = L"OcvTransform.OcvImageManipulations";
-#endif
-
-
-/* interface __MIDL_itf_OcvImageManipulations_0000_0000 */
-/* [local] */ 
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_OcvImageManipulations_0000_0000_v0_0_s_ifspec;
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
diff --git a/samples/winrt/ImageManipulations/C++/Constants.cpp b/samples/winrt/ImageManipulations/Constants.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/Constants.cpp
rename to samples/winrt/ImageManipulations/Constants.cpp
diff --git a/samples/winrt/ImageManipulations/C++/Constants.h b/samples/winrt/ImageManipulations/Constants.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/Constants.h
rename to samples/winrt/ImageManipulations/Constants.h
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml b/samples/winrt/ImageManipulations/MainPage.xaml
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MainPage.xaml
rename to samples/winrt/ImageManipulations/MainPage.xaml
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp b/samples/winrt/ImageManipulations/MainPage.xaml.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MainPage.xaml.cpp
rename to samples/winrt/ImageManipulations/MainPage.xaml.cpp
diff --git a/samples/winrt/ImageManipulations/C++/MainPage.xaml.h b/samples/winrt/ImageManipulations/MainPage.xaml.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MainPage.xaml.h
rename to samples/winrt/ImageManipulations/MainPage.xaml.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.sln b/samples/winrt/ImageManipulations/MediaCapture.sln
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaCapture.sln
rename to samples/winrt/ImageManipulations/MediaCapture.sln
diff --git a/samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/MediaCapture.vcxproj
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaCapture.vcxproj
rename to samples/winrt/ImageManipulations/MediaCapture.vcxproj
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h b/samples/winrt/ImageManipulations/MediaExtensions/Common/AsyncCB.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Common/AsyncCB.h
rename to samples/winrt/ImageManipulations/MediaExtensions/Common/AsyncCB.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h b/samples/winrt/ImageManipulations/MediaExtensions/Common/BufferLock.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Common/BufferLock.h
rename to samples/winrt/ImageManipulations/MediaExtensions/Common/BufferLock.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h b/samples/winrt/ImageManipulations/MediaExtensions/Common/CritSec.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Common/CritSec.h
rename to samples/winrt/ImageManipulations/MediaExtensions/Common/CritSec.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h b/samples/winrt/ImageManipulations/MediaExtensions/Common/LinkList.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Common/LinkList.h
rename to samples/winrt/ImageManipulations/MediaExtensions/Common/LinkList.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h b/samples/winrt/ImageManipulations/MediaExtensions/Common/OpQueue.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/Common/OpQueue.h
rename to samples/winrt/ImageManipulations/MediaExtensions/Common/OpQueue.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.idl b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvImageManipulations.idl
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvImageManipulations.idl
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvImageManipulations.idl
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.cpp b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.cpp
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.cpp
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.def b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.def
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.def
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.def
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.h b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.h
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.h
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.vcxproj b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.vcxproj
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/OcvTransform.vcxproj
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/OcvTransform.vcxproj
diff --git a/samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/dllmain.cpp b/samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/dllmain.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/MediaExtensions/OcvTransform/dllmain.cpp
rename to samples/winrt/ImageManipulations/MediaExtensions/OcvTransform/dllmain.cpp
diff --git a/samples/winrt/ImageManipulations/C++/Package.appxmanifest b/samples/winrt/ImageManipulations/Package.appxmanifest
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/Package.appxmanifest
rename to samples/winrt/ImageManipulations/Package.appxmanifest
diff --git a/samples/winrt/ImageManipulations/C++/assets/opencv-logo-150.png b/samples/winrt/ImageManipulations/assets/opencv-logo-150.png
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/assets/opencv-logo-150.png
rename to samples/winrt/ImageManipulations/assets/opencv-logo-150.png
diff --git a/samples/winrt/ImageManipulations/C++/assets/opencv-logo-30.png b/samples/winrt/ImageManipulations/assets/opencv-logo-30.png
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/assets/opencv-logo-30.png
rename to samples/winrt/ImageManipulations/assets/opencv-logo-30.png
diff --git a/samples/winrt/ImageManipulations/C++/assets/splash-sdk.png b/samples/winrt/ImageManipulations/assets/splash-sdk.png
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/assets/splash-sdk.png
rename to samples/winrt/ImageManipulations/assets/splash-sdk.png
diff --git a/samples/winrt/ImageManipulations/C++/assets/windows-sdk.png b/samples/winrt/ImageManipulations/assets/windows-sdk.png
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/assets/windows-sdk.png
rename to samples/winrt/ImageManipulations/assets/windows-sdk.png
diff --git a/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp b/samples/winrt/ImageManipulations/common/LayoutAwarePage.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.cpp
rename to samples/winrt/ImageManipulations/common/LayoutAwarePage.cpp
diff --git a/samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h b/samples/winrt/ImageManipulations/common/LayoutAwarePage.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/common/LayoutAwarePage.h
rename to samples/winrt/ImageManipulations/common/LayoutAwarePage.h
diff --git a/samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml b/samples/winrt/ImageManipulations/common/StandardStyles.xaml
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/common/StandardStyles.xaml
rename to samples/winrt/ImageManipulations/common/StandardStyles.xaml
diff --git a/samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp b/samples/winrt/ImageManipulations/common/suspensionmanager.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/common/suspensionmanager.cpp
rename to samples/winrt/ImageManipulations/common/suspensionmanager.cpp
diff --git a/samples/winrt/ImageManipulations/C++/common/suspensionmanager.h b/samples/winrt/ImageManipulations/common/suspensionmanager.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/common/suspensionmanager.h
rename to samples/winrt/ImageManipulations/common/suspensionmanager.h
diff --git a/samples/winrt/ImageManipulations/description.html b/samples/winrt/ImageManipulations/description.html
deleted file mode 100644
index ad1df7d56..000000000
--- a/samples/winrt/ImageManipulations/description.html
+++ /dev/null
@@ -1,238 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
-    <head><link rel="stylesheet" type="text/css" href="description/Combined.css,0:SearchBox,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;amp;hashKey=E778FABBB649835AFE4E73BCAC4F643A" xmlns="http://www.w3.org/1999/xhtml" />
-<link rel="stylesheet" type="text/css" href="description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;amp;hashKey=B88AD897C8197B762EA1BF0238A60A9F" xmlns="http://www.w3.org/1999/xhtml" />
-
-        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-        <title>Media capture using capture device sample</title>
-        <link href="description/Galleries.css" type="text/css" rel="Stylesheet" /><link href="description/Layout.css" type="text/css" rel="Stylesheet" /><link href="description/Brand.css" type="text/css" rel="Stylesheet" /><link href="description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css" type="text/css" rel="Stylesheet" />
-        <link href="description/iframedescription.css" rel="Stylesheet" type="text/css" />
-        <script src="description/offline.js" type="text/javascript"></script>
-        <style type="text/css">
-            #projectInfo {
-                overflow: auto;
-            }
-            #longDesc {
-                clear:both;
-                margin: 25px 0 10px 0;
-            }
-
-            #SampleIndexList{
-                margin-left: 15px;
-            }
-        </style>
-    </head>
-<body>
-    <div id="offlineDescription">
-        <h1>Media capture using capture device sample</h1>
-        <br/>
-        <div id="projectInfo">
-            <div class="section">
-                    <div class="itemBarLong tagsContainer">
-                        <label for="Technologies">Technologies</label>
-                        <div id="Technologies">
-                            Windows Runtime
-                        </div>
-                    </div>
-                    <div class="itemBarLong tagsContainer">
-                        <label for="Topics">Topics</label>
-                        <div id="Topics">
-                            Devices and sensors
-                        </div>
-                    </div>
-                <div class="itemBarLong">
-                    <label for="Platforms">Platforms</label>
-                    <div id="Platforms">
-                        Windows RT
-                    </div>
-                </div>
-                <div class="itemBarLong">
-                    <label for="Requirements">Requirements</label>
-                    <div id="Requirements">
-                        
-                    </div>
-                </div>
-                <div class="itemBar">
-                    <label for="LastUpdated">Primary Language</label>
-                    <div id="LastUpdated">en-US</div>
-                </div>
-                <div class="itemBar">
-                    <label for="LastUpdated">Last Updated</label>
-                    <div id="LastUpdated">4/9/2013</div>
-                </div>
-                <div class="itemBarLong">
-                    <label for="License">License</label>
-                    <div id="License">
-                        <a href="license.rtf">MS-LPL</a></div>
-                </div>
-                <div class="itemBar">
-                    <div class="viewonlinecont">
-                        <a data-link="online" href="http://code.msdn.microsoft.com/windowsapps/Media-Capture-Sample-adf87622">View this sample online</a>
-                    </div>
-                </div>
-            </div>
-        </div>
-        
-                   
-<script type="text/javascript">
-    function initializePage() {
-        var otherTabClass = 'otherTab';
-        var hiddenPreClass = 'hidden';
-
-        var htmlDecode = function(encodedData) {
-            var decodedData = "";
-            if (encodedData) {
-                var div = document.createElement('div');
-                div.innerHTML = encodedData;
-                decodedData = div.firstChild.nodeValue.replace( /\\r\\n/ig , '\r\n');
-            }
-            return decodedData;
-        };
-                
-        Galleries.iterateElem(Galleries.findElem(null, 'div', 'scriptcode'), function (index, scriptBlock) {
-            var titleElem = Galleries.findElem(scriptBlock, 'div', 'title')[0];
-            var labelElems = Galleries.findElem(titleElem, 'span');
-            if (labelElems.length == 0) {
-                labelElems = titleElem;
-            }
-            var languageSpans = Galleries.findElem(scriptBlock, 'span', 'hidden');
-            var pres = Galleries.findElem(scriptBlock, 'pre');
-            if (languageSpans.length > 0 && pres.length > 1) {
-                Galleries.iterateElem(labelElems, function(index, elem) {
-                    var codePre = pres[index];
-                    var labelSpan = elem;
-                    var languageSpan = languageSpans[index];
-                            
-                    elem.code = codePre.innerHTML.replace( /(\r(\n)?)|((\r)?\n)/ig , '\\r\\n');
-                            
-                    codePre.className = codePre.className.replace(hiddenPreClass, '');
-                            
-                    languageSpan.parentNode.removeChild(languageSpan);
-                });
-
-                pres = Galleries.findElem(scriptBlock, 'pre');
-                Galleries.iterateElem(labelElems, function(index, elem) {
-                    var codePre = pres[index];
-                    var labelSpan = elem;
-                    if (index == 0) {
-                        scriptBlock.activeTab = 0;
-                    }
-                    else {
-                        labelSpan.className += otherTabClass;
-                        codePre.className += hiddenPreClass;
-                    }
-                    Galleries.attachEventHandler(labelSpan, 'click', function(e) {
-                        var activeTab = scriptBlock.activeTab;
-                        labelElems[activeTab].className += otherTabClass;
-                        pres[activeTab].className += hiddenPreClass;
-
-                        codePre.className = codePre.className.replace(hiddenPreClass, '');
-                        labelSpan.className = labelSpan.className.replace(otherTabClass, '');
-                        scriptBlock.activeTab = index;
-                    });
-                });
-
-                var preview = Galleries.findElem(scriptBlock, 'div', 'preview');
-                if (preview.length == 0) {
-                    preview.push(pres[pres.length - 1]);
-                }
-                Galleries.iterateElem(preview, function(index, elem) {
-                    elem.parentNode.removeChild(elem);
-                });
-
-                if (window.clipboardData && clipboardData.setData) {
-                    var copyLink = document.createElement('a');
-                    copyLink.href = 'javascript:void(0);';
-                    copyLink.className = 'copyCode';
-                    copyLink.innerHTML = 'Copy Code';
-                    Galleries.attachEventHandler(copyLink, 'click', function (e) {
-                        clipboardData.setData("Text", htmlDecode(labelElems[scriptBlock.activeTab].code));
-                        return false;
-                    });
-                    scriptBlock.insertBefore(copyLink, scriptBlock.childNodes[0]);
-                }
-            }
-        });
-    }
-
-    Galleries.onWindowLoad(function(){
-        initializePage();
-    });
-
-</script>
-<div id="longDesc">
-    
-<div id="mainSection">
-<p>This sample demonstrates how to use the <a href="http://msdn.microsoft.com/library/windows/apps/BR241124">
-<b>MediaCapture</b> </a>API to capture video, audio, and pictures from a capture device, such as a webcam.
-</p>
-<p>Specifically, this sample covers: </p>
-<ul>
-<li>Previewing video from a capture device, such as a webcam, connected to the computer.
-</li><li>Capturing video from a capture device, such as a webcam, connected to the computer.
-</li><li>Taking a picture from a capture device, such as a webcam, connected to the computer.
-</li><li>Enumerating cameras connected to the computer. </li><li>Adding a video effect to a video. </li><li>Recording audio from a capture device connected to the computer. </li></ul>
-<p></p>
-<p>For more information on capturing video in your app, see <a href="http://msdn.microsoft.com/library/windows/apps/Hh465152">
-Quickstart: capturing a photo or video using the camera dialog</a> and <a href="http://msdn.microsoft.com/library/windows/apps/Hh452791">
-Quickstart: capturing video using the MediaCapture API</a>.</p>
-<p class="note"><b>Important</b>&nbsp;&nbsp; </p>
-<p class="note">This sample uses the Media Extension feature of Windows&nbsp;8 to add functionality to the Microsoft Media Foundation pipeline. A Media Extension consists of a hybrid object that implements both Component Object Model (COM) and Windows Runtime
- interfaces. The COM interfaces interact with the Media Foundation pipeline. The Windows Runtime interfaces activate the component and interact with the Windows Store app.
-</p>
-<p class="note">In most situations, it is recommended that you use Visual C&#43;&#43; with Component Extensions (C&#43;&#43;/CX ) to interact with the Windows Runtime. But in the case of hybrid components that implement both COM and Windows Runtime interfaces, such as Media
- Extensions, this is not possible. C&#43;&#43;/CX can only create Windows Runtime objects. So, for hybrid objects it is recommended that you use
-<a href="http://go.microsoft.com/fwlink/p/?linkid=243149">Windows Runtime C&#43;&#43; Template Library</a> to interact with the Windows Runtime. Be aware that Windows Runtime C&#43;&#43; Template Library has limited support for implementing COM interfaces.</p>
-<p></p>
-<p>To obtain an evaluation copy of Windows&nbsp;8, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241655">
-Windows&nbsp;8</a>.</p>
-<p>To obtain an evaluation copy of Microsoft Visual Studio&nbsp;2012, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241656">
-Visual Studio&nbsp;2012</a>.</p>
-<h3><a id="related_topics"></a>Related topics</h3>
-<dl><dt><a href="http://go.microsoft.com/fwlink/p/?LinkID=227694">Windows 8 app samples</a>
-</dt><dt><b>Roadmaps</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465134">Adding multimedia</a>
-</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465156">Capturing or rendering audio, video, and images</a>
-</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh767284">Designing UX for apps</a>
-</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR229583">Roadmap for apps using C# and Visual Basic</a>
-</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700360">Roadmap for apps using C&#43;&#43;</a>
-</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465037">Roadmap for apps using JavaScript</a>
-</dt><dt><b>Tasks</b> </dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465152">Quickstart: capturing a photo or video using the camera dialog</a>
-</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh452791">Quickstart: capturing video using the MediaCapture API</a>
-</dt><dt><b>Reference</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR211961"><b>AddEffectAsync</b>
-</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226592"><b>ClearEffectsAsync</b>
-</a></dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR241124"><b>MediaCapture</b>
-</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226581"><b>MediaCaptureSettings</b>
-</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh701026"><b>MediaEncodingProfile</b>
-</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700863"><b>StartRecordToStorageFileAsync</b>
-</a></dt><dt><b>Windows.Media.Capture</b> </dt></dl>
-<h3>Operating system requirements</h3>
-<table>
-<tbody>
-<tr>
-<th>Client</th>
-<td><dt>Windows&nbsp;8 </dt></td>
-</tr>
-<tr>
-<th>Server</th>
-<td><dt>Windows Server&nbsp;2012 </dt></td>
-</tr>
-</tbody>
-</table>
-<h3>Build the sample</h3>
-<p></p>
-<ol>
-<li>Start Visual Studio Express&nbsp;2012 for Windows&nbsp;8 and select <b>File</b> &gt; <b>
-Open</b> &gt; <b>Project/Solution</b>. </li><li>Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio Express&nbsp;2012 for Windows&nbsp;8 Solution (.sln) file.
-</li><li>Press F7 or use <b>Build</b> &gt; <b>Build Solution</b> to build the sample. </li></ol>
-<p></p>
-<h3>Run the sample</h3>
-<p>To debug the app and then run it, press F5 or use <b>Debug</b> &gt; <b>Start Debugging</b>. To run the app without debugging, press Ctrl&#43;F5 or use
-<b>Debug</b> &gt; <b>Start Without Debugging</b>.</p>
-</div>
-
-</div>
-
-
-    </div>
-</body>
-</html>
diff --git a/samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css b/samples/winrt/ImageManipulations/description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css
deleted file mode 100644
index e69de29bb..000000000
diff --git a/samples/winrt/ImageManipulations/description/Brand.css b/samples/winrt/ImageManipulations/description/Brand.css
deleted file mode 100644
index 98415561e..000000000
--- a/samples/winrt/ImageManipulations/description/Brand.css
+++ /dev/null
@@ -1,3629 +0,0 @@
-#BodyBackground
-{
-    min-width:0px;
-}
-
-#JelloExpander, .IE7 #JelloExpander, .IE8 #JelloExpander, .IE9 #JelloExpander
-{
-    padding-left:0px;
-    padding-right:0px;
-}
-
-#JelloSizer
-{
-    margin: 0 auto;
-    max-width: 0px;
-    padding: 0;
-    width: 100%;
-}
-
-/* Global Styles */
-body 
-{
-    font-size:0.75em;
-}
-
-h1 
-{
-    font-size: 3em;
-    font-family: 'Segoe UI Light','Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
-    color: #707070;
-    font-weight: normal;
-    padding-top:4px;
-    margin-bottom: 17px;
-    line-height: 1.3;
-    font-weight:100;
-}
-
-h2, h3, h4, h5, h6 
-{
-    font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif;
-    color:#2a2a2a;
-    font-weight:normal;
-}
-
-a, a:link, a:visited {
-    color: #00749E;
-}
-a:hover {
-    color: #0095c4;
-    text-decoration:none;
-}
-
-/*---------- Masthead -----------*/
-
-.NetworkLogo a {
-    display: none;
-}
-
-/*-------- Start Advertisment --------*/
-
-.advertisment {
-    padding-top:5px;
-}
-
-/*-------- End Advertisment --------*/
-
-
-/*-------- Start LocalTabs Page --------*/
-#GalleriesNavigation {
-    float: right;
-}
-
-.LocalNavigation
-{
-    display:block;
-    overflow: auto;
-    width: auto;
-}
-    .LocalNavigation .HeaderTabs {
-        width: auto;
-    }
-        .LocalNavigation .TabOff a {
-            color:#333;
-        }
-
-        .LocalNavigation .TabOff a:hover {
-            background-color:#E0E7EC;
-            margin-top: 1px;
-            padding: 4px 6px;
-        }
-
-        .LocalNavigation #notificationLink span {
-            color:Red;
-            font-weight:bold;   
-        }
-    
-
-/*-------- End LocalTabs Page --------*/
-
-/*-------- Start SubMenu Page --------*/
-
-.subMenu
-{
-    margin: 0 0 10px 0;
-    color: #FFFFFF;
-    overflow: hidden;
-}
-
-.subMenu a, .subMenu span
-{
-    margin: 5px 5px 0 5px;
-}
-
-.subMenu > h2
-{
-    float: left;
-    margin: 7px 15px 0 0;
-    vertical-align: middle;
-    color: #666;
-    padding-bottom: 5px;
-}
-
-.subMenu .advancedSearchLink
-{
-    float: left;
-    margin: 9px 0 0 15px;
-}
-
-
-
-.subMenu .uploadLink
-{
-    float: right;
-    margin: 5px 5px 0 0;
-    padding: 0 0 0 30px;
-    height: 24px;
-    background: url('../Common/smalluploadicon.png') no-repeat 10px 0;
-    color: #0066E1;
-    cursor: pointer;
-}
-
-.subMenu #searchBoxContainer
-{
-    float: left;
-    width: 400px;
-    padding: 3px 50px;
-}
-
-/*-------- End SubMenu Page --------*/
-
-/*-------- Start SearchBox --------*/
-
-div.searchbox
-{
-    overflow:auto;
-    width:450px;
-    margin:26px 0 14px 0;
-}
-
-.srchbox
-{
-    width: 100%;
-    background: #FFFFFF;
-    padding: 0px 2px;
-    height: 25px;
-    border: 1px solid #ccc;
-    table-layout: auto;
-    margin-bottom:5px;
-}
-
-
-
-.srchbox #searchImageCell input
-{
-    background: transparent url('searchButton.png') no-repeat 0 0;
-    width: 20px;
-    height: 20px;
-    padding-left: 1px;
-    margin-top: 3px;
-}
-
-
-.srchbox #searchImageCell
-{
-    text-align: right;
-    padding: 0px;
-    vertical-align: middle;
-}
-
-.IE7 .srchbox #searchImageCell
-{
-    padding:2px 2px 0 0;
-}
-
-.srchbox #searchImageCell input
-{
-}
-
-
-table.srchbox
-{
-    table-layout: fixed;
-}
-
-.srchbox .stxtcell
-{
-    padding-right: 4px;
-    width:90%;
-}
-
-.srchbox .stxtcell > input
-{
-    margin-right: 4px;
-    height: 26px;
-    line-height:26px;
-    width: 100%;
-    padding: 0px;
-    padding-left: 4px;
-    padding-top: 2px;
-    border: none;
-    font-style: normal !important;
-    outline: none;
-}
-
-.IE7 .srchbox .stxtcell > input
-{
-    height: 20px;
-}
-
-.srchbox .stxtcell > input.stxtinptpassive
-{
-    color: #AAA;
-    font-style: normal !important;
-}
-
-/*-------- End SearchBox --------*/
-
-
-/*-------- Start Search Page --------*/
-
-
-#searchPage #mainContentContainer
-{
-    margin: 0 0 0 243px;
-}
-
-#searchPage .browseFilterBar, #dashboardPage .browseFilterBar
-{    
-    padding: 5px 0 6px 0;
-    
-}
-
-    #searchPage .browseFilterBar a, #dashboardPage .browseFilterBar a
-    {
-        font-weight:normal;
-    }
-
-    #searchPage .browseFilterBar .browseSort, #dashboardPage .browseFilterBar .browseSort
-    {
-        float:right;
-    }
-    
-    #searchPage .browseBreadcrumb
-    {
-        padding-top:3px;
-    }
-
-        #searchPage .browseFilterBar .browseSort select, #dashboardPage .browseFilterBar .browseSort select
-        {
-            height:20px;
-        }        
-        
-        #searchPage .browseFilterBar .browseSort img, #dashboardPage .browseFilterBar .browseSort img
-        {
-            vertical-align:text-top;
-        }
-
-#searchPage h2, #searchPage h3
-{
-    font-size: 1.25em;
-    padding: 2px 0 3px 3px;
-}
-
-#searchPage h2
-{
-    display:inline;
-    clear:none;
-}
-
- #dashboardsearchbox
- {
-     width:420px;
-     margin:0;
-     float:left;
- }
-
-/*-------- End Search Page --------*/
-
-/*-------- Begin Requests Page --------*/
-
-#requestsPage {
-    color:#666;
-}
-
-    #requestsPage h1 {
-        clear:none;
-    }
-    #requestsPage h2, #requestsPage h3
-    {
-        font-size: 1.25em;
-    }
-
-    #requestsPage h2
-    {
-        display:inline;
-        clear:none;
-    }
-
-    #requestsPage h3 
-    {
-        padding: 2px 0 3px 3px;
-    }
-
-    #requestsPage #mainContentContainer
-    {
-        margin: 0 0 0 243px;
-    }
-
-    #requestsPage #mainContentWrapper {
-        float:left;
-        width:100%;
-    }
-    #requestsPage #mainContent {
-        position:relative;
-    }
-
-    #requestsPage #mainContent .subtitle{
-        margin-bottom:5px;
-    }
-
-    #requestsPage #requestsFilterBar {
-        margin-top: 10px;
-        overflow: auto;
-    }
-
-        #requestsPage #requestsFilterBar .requestsCrumb {
-             float: left;
-            margin:10px 0 10px 10px;
-        }
-        #requestsPage #requestsFilterBar .requestsSort {
-            float: right;   
-            margin:10px 0 10px 0;
-        }
-    
-    #requestsPage #Pager {
-        text-align: center; 
-        padding-top: .75em; 
-        padding-bottom: .75em;
-    }
-
-    #requestsPage #requestsRss {
-        float: right;
-        margin: 2px 0 0 3px;
-        cursor: pointer;
-    }  
-    
-    .IE7 #requestsPage #requestsList {
-        padding-top: 10px;
-        margin-top:5px;
-    }
-
-    #requestsPage #requestsList .noResults {
-        padding: 10px 0;
-    }   
-   
-
-/*-------- End Requests Page --------*/
-
-/*--------  Begin Request List Item --------*/
-.requestlistitem td
-{
-    padding: .9em 0 .9em .5em;
-}
-    .requestlistitem .votebox
-    {
-        
-        text-align:center;
-    }
-    
-    .requestlistitem .voteboxcontainer
-    {
-        vertical-align:top;
-        width: 75px;
-    }
-
-    .requestlistitem #votelabel
-    {
-        border-width:1px;
-        border-bottom-style:solid;
-    }
-
-    #myRequestsTab #votenumber,
-    #requestsPage #votenumber
-    {
-        background-color: #777;
-        padding: 6px 10px;
-        color: #fff;
-        margin-bottom: 5px;
-        font-size: 1.6em;
-    }
-    
-    #myRequestsTab .votelink,
-    #requestsPage .votelink 
-    {
-        font-weight:bold;
-        background-color: #eee;
-        padding: 5px 0;
-        width: 75px;
-        float: left;
-    }
-
-    #myRequestsTab .needvote,
-    #requestsPage .needvote
-    {
-        font-weight:bold;
-    }
-
-    #myRequestsTab .alreadyvoted, #myRequestsTab .resolved
-    #requestsPage .alreadyvoted, #requestsPage .resolved
-    {
-        font-weight:bold;
-        color: #666;
-    }
-
-    .requestlistitem .linkform 
-    {
-        width:100%;
-        float:right;
-        margin-top:15px;
-    }
-
-    .requestlistitem .requesttitle 
-    {
-        font-weight:600;
-        margin-bottom:3px;
-    }
-
-    .requestlistitem .requester 
-    {
-        margin-bottom:3px;
-    }
-
-    .requestlistitem .hidden 
-    {
-        display:none;
-    }
-    
-    .requestlistitem .requestSummary div
-    {
-        margin-bottom:0.25em;
-    }
-    
-    .requestlistitem .requestSummary 
-    {
-        line-height: 1.45em;
-        width: 80%;
-    }
-    .requestlistitem .requestInfo
-    {
-        padding:1.2em 0 0 2.5em;
-        vertical-align:top;
-        width:15%;
-        line-height: 1.45em;
-    }
-    
-    .requestlinks > td
-    {
-        padding-bottom: 16px;
-    }
-    
-    .requestlinks div 
-    {
-        float:right;
-    }
-
-    .requestlistitem .textbox 
-    {
-        width:95%;
-    }
-    
-
-
-/*--------  End Request List Item --------*/
-
-
-/*--------  Begin New Request Form --------*/
-#newrequest {
-    margin-top:5px;
-    background:#F8F8F8;
-    border-width:1px;
-    border-style:solid;
-    border-color:#E8E8E8;
-    padding:5px;
-}
-
-#newrequest > div:first-child {
-    font-weight:bold;
-}
-
-#newrequest .itemheading {
-    margin-top:5px;
-}
-
-#newrequest textarea {
-    width:95%;
-}
-
-#newrequest .field-validation-error {
-    display:block;
-    color:Red;
-    font-weight:bold;
-}
-#newrequest #submit {
-    margin-top:5px;
-}
-
-/*--------  End New Request Form --------*/
-
-/*-------- Request Description Page ------*/
-
-.reqDescPage #mainContent {
-    overflow: auto;
-}
-.reqDescPage #header {
-    float: left;
-    width: 100%;
-}
-
-.reqDescPage {
-    color: #000 !important;
-}
-
-.reqDescPage #sideNav {
-    background-color: #fff;
-}
-
-.reqDescPage #header td {
-    vertical-align: bottom;
-}
-
-.reqDescPage #header #votenumber {
-    width: 50px;
-    padding: 6px 12px;
-    text-align: center;
-    float: left;
-}
-
-.reqDescPage #header .requestTitle {
-    margin: 0 0 5px 10px;
-    width: 85%;
-}
-
-.reqDescPage #header .requestTitle h1 {
-    margin-bottom: 0px;
-    font-size: 2em;
-}
-
-.reqDescPage #headerLinks {
-
-}
-
-.reqDescPage .votelink 
-{
-    text-align: center;
-    float: left;
-}
-
-#requestsPage #headerLinks .assignlink
-{
-    font-weight:bold;
-    background-color: #eee;
-    padding: 5px 10px;
-    float: left;
-    margin-left: 10px;
-}
-
-.reqDescPage #projectInfo {
-    clear: both;
-}
-
-.reqDescPage #solutions {
-    clear: both;
-    padding-top: 30px;
-}
-
-.reqDescPage .solutionItems {
-    clear: both;
-}
-
-.reqDescPage .solutionHeader {
-    border-bottom: 1px solid #ccc;
-}
-
-.reqDescPage .solutionAddContainer {
-    padding-top: 15px;
-    float: left;
-}
-
-.reqDescPage #SubmittedProjectLinkUrl {
-    width: 400px;
-}
-
-.reqDescPage .solutionItem {
-    margin-top: 25px;
-    padding: 0 5px 5px 0;
-    float: left;
-}
-.reqDescPage .solutionItemDetails {
-    float: left;
-    width: 535px;
-}
-
-.reqDescPage .solutionItemLinks {
-    margin-top: 10px;
-    clear: both;
-    float: left;
-    width: 100%;
-}
-
-.reqDescPage .solutionItemLinks a {
-    float: left;
-    margin-right: 10px;
-    font-weight:bold;
-    background-color: #eee;
-    padding: 5px 10px;
-}
-
-.reqDescPage .solutionItem .itemTitle {
-    font-size: 1.2em;
-    padding-bottom: 5px;
-}
-
-.reqDescPage .tagsContainer label {
-    display: none;
-}
-
-.reqDescPage .solutionItem  .summaryBox {
-    padding: .25em 0 .25em 0;
-    clear: both;
-    line-height: 1.45;
-}
-
-.reqDescPage .solutionsection {
-    float: left;
-    margin-left: 20px;
-}
-.reqDescPage .completedSolution {
-    font-size: 1.25em;
-    padding-top: 4px;
-}
-
-.reqDescPage .requestDescriptionCont, .reqDescPage .requestDicussions {
-    padding-top: 30px;
-    clear: both;
-    overflow: auto;
-}
-
-.reqDescPage .requestDescription {
-    padding-top: 10px;
-    line-height: 1.45;
-}
-
-.reqDescPage .requestDicussionsAsk {
-    padding: 10px 0;
-}
-
-.reqDescPage .watermark {
-        color:Gray;
-    }
-
-
-/*--------  Begin Extra Actions Section --------*/
-#extraActions
-{
-    float: right;
-    width: 300px;
-    vertical-align: top;
-}
-
-    #extraActions .section
-    {
-        padding: 0 0 10px 0;
-        overflow:auto;
-    }
- 
-        #extraActions .section a
-        {
-            font-weight:bold;
-        }
-/*--------  End Extra Actions Section --------*/
-
-/*--------  Begin Contribute --------*/
-
-
-#contributeSection a
-{
-    font-size:1.1em;
-}
-
-#contributeSection, #sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
-{
-    background-color:#fff;
-    margin: 0 0 9px 0;
-    padding-left: 0px;
-}
-
-#sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
-{
-    font-size:1.65em;
-    margin-top:42px;
-}
-
-#sideNav #contributeSection, #contributeSection
-{
-    padding:0 0 41px 0;
-}
-
-#projectPage .sidebar #contributeSection
-{
-    margin: 10px 0 10px 0;
-    padding:0 0 5px 0;
-    
-}
-
-#sideNav #contributeSection > div, .sidebar #contributeSection > div, #contributeSection > div
-{
-    padding: 0 0 2px 0;
-    overflow:auto;
-}
-
-#sideNav #contributeSection img, #contributeSection img
-{
-    float: left;
-    width: 25px;
-}
-
-#sideNav #contributeSection .contributeAction, .sidebar #contributeSection .contributeAction, #contributeSection .contributeAction
-{
-    padding:17px 0 0 0;
-}
-
-    #contributeSection .contributeAction img
-    {        
-        background-color:#00749e;
-        margin-right:9px;
-    }
-    
-    #contributeSection .contributeAction img:hover
-    {
-        background-color:#0095C4;
-    }
-    
-    #contributeSection .contributeAction a
-    {
-        display:block;
-        line-height: 1.8;
-    }
-
-#uploadLink, #exclamationLink, #myContributionsLink
-{
-    display:block;
-    line-height: 1.8;
-}
-
-#myContributionsLink span 
-{
-    color: red;    
-}
-
-#feedbackLink
-{
-    background: url("FeedbackIcon.png") no-repeat;
-    width: 40px;
-    height: 40px;
-}
-
-.itemRow .affiliationLink, #editorPicksSection .affiliationLink
-{
-    background: url("../common/MicrosoftLogo.png") no-repeat;
-    width: 82px;
-    height: 18px;
-}
-
-
-#contributeSection a+div
-{
-         
-}
-
-.IE7 #contributeSection a+div
-{
-    float:left;
-}
-/*--------  End Contribute --------*/
-
-
-/*--------  Begin Directory List Footer --------*/
-
-#directoryListFooter {
-    padding:5px;
-    margin-top:10px;
-    margin-bottom:10px;
-    border:1px solid #E6E6E6;
-    background-color:#F8F8F8;
-    width:438px;
-}
-
-#directoryListFooter h4 
-{
-    font-size:1em;
-}
-
-/*--------  End Directory List Footer --------*/
-
-/*--------  Begin Editors Picks --------*/
-#editorPicksSection ul
-{
-    padding-left:0px;
-    line-height:135%;
-}
-
-    #editorPicksSection ul li
-    {
-        clear: left;
-        padding-top: 10px;
-        list-style:none;
-    }
-    #editorPicksSection ul li:first-child {
-        padding-top: 0;
-    }
-        
-        #editorPicksSection a {
-            font-weight: normal !important;
-        }
-        
-        #editorPicksSection ul li .thumbnail
-        {
-            float: left;
-            padding: 3px;
-            max-width: 60px;
-        }
-        
-            #editorPicksSection ul li .thumbnail img {
-                max-width: 60px;
-            }
-/*--------  End Editors Picks --------*/
-
-/*--------  Begin Side Nav Section --------*/
-
-#sideNav
-{
-    width: 215px;
-    margin-left: 0;
-    vertical-align: top;
-    float: left;
-}
-
-    #sideNav #sideNavHeader
-    {
-        margin-bottom: 10px;
-        padding-left: 12px;
-    }
-
-    #sideNav #sideNavHeader a
-    {
-        margin-right:3px;
-    }
-
-    #sideNav .section
-    {
-        padding: 0 10px 18px 10px;
-    }
-        #sideNav .section h3
-        {
-            
-            padding: 2px 0 3px 3px;
-        }
-
-        #sideNav .section ul
-        {
-        }
-
-        #sideNav .section ul li
-        {
-            padding: 4px 0 2px;
-            margin-left: 3px;
-            margin-right: 3px;
-        }        
-
-
-        #sideNav .section form > div
-        {
-            padding: 4px 0 0 0;
-            border-bottom: none;
-            margin: 0 3px 0 3px;
-            color: #3A3E43;
-        }
-            .IE8 #sideNav .section ul li > div.itemText
-            {
-                word-wrap: break-word;
-                width: 225px;
-            }
-            #sideNav .section ul li > div.itemCount
-            {
-                color: #3A3E43;
-            }
-        #sideNav .section a
-        {
-            font-weight: normal;    
-        }
-
-        #sideNav .section a:hover
-        {
-            text-decoration: underline;
-        }
-
-/*--------  End Side Nav Section --------*/
-
-
-
-/*-------- Start Dashboard Page --------*/
-
-#dashboardPage {
-    padding-top:5px;
-    clear:both;
-}
-#dashboardPage .contributions .tabContents {
-    padding: 5px 5px 10px 0;
-    clear:both;
-}
-    #dashboardPage .contributions .noContributions {
-        clear:both;
-    }
-#dashboardPage #mainContentWrapper {
-    float:left;
-    width:100%;
-}
-
-#dashboardPage #detailsSection {
-    float:left;
-    margin-left:-100%;
-    width:240px;
-    padding: 0 0 18px 10px;
-}
-
-.IE7 #dashboardPage #detailsSection {
-    width:auto;
-    min-width: 300px;
-    max-width: 300px;
-}
-.IE7 #dashboardPage #detailsSection .itemBar {
-    width: 270px;
-}
-
-#dashboardPage #detailsSection h3 {
-    word-wrap:break-word;
-}
-
-#dashboardPage #mainContent {
-    margin:0 0 0 250px;
-    position:relative;
-}
-
-#dashboardPage .dashboardEvenRow
-{
-    background-color: #ececec;
-}
-#dashboardPage .dashboardPadding
-{
-    padding-bottom: 4px;
-}
-#dashboardPage .dashboardCell
-{
-    width: 100%;
-    vertical-align: top;
-    padding: 1em 0.5em 0.5em 0.5em;
-    word-wrap: break-word;
-}
-#dashboardPage .projectManagement
-{
-    width: 24em;
-    padding: 0em 1em 0em 1em;
-    vertical-align: top;
-    text-align: right;
-    float: right;
-}
-
-#dashboardPage #subscriptionsLink 
-{
-    position:absolute;
-    right:5px;
-}
-
-#dashboardPage .itemDelete
-{
-    vertical-align:top;
-    padding-top:.8em;
-    width:30px;
-}
-
-#dashboardPage .itemDeleteText
-{
-    border-style:solid;
-    border-width:thin;
-    border-collapse:collapse;
-    padding-bottom:2px;
-    padding-left:4px;
-    padding-right:4px;
-    color:Gray
-}
-
-#dashboardPage #myRequestsTab .requestTabHeaders
-{
-    font-weight:normal;
-    border-bottom: solid 1px #CCC;
-    padding-bottom: 10px;
-    padding-top: 10px;
-    float: left;
-    width: 100%;
-}
-
-#dashboardPage #myRequestsTab .requestTabHeaders div:first-child
-{
-    border: 0;
-}
-
-#dashboardPage #myRequestsTab .requestTabHeaders div
-{
-    padding: 2px 9px 3px 9px;
-    font-size: 0.9em;
-    line-height: 125%;
-    color:#00749E;
-    border-left: solid 1px #555;
-    cursor: pointer;
-    float: left;
-    text-align: center;
-}
-
-#dashboardPage #myRequestsTab .requestTabHeaders div.currentRequest
-{
-    background-color:#fff;
-    cursor: default;
-    border-bottom:none;
-    margin-bottom:-2px;
-    color:#000;    
-}
-
-#dashboardPage #myRequestsTab .requestTabHeaders div.currentRequest a {
-    color: #000;
-}
-
-
-#dashboardPage #myRequestsTab .requestTabHeaders div a
-{
-    text-decoration:none;
-}
-
-#dashboardPage #myRequestsTab .requestTabContents
-{
-    clear: both;
-}
-
-#dashboardPage #myRequestsTab .requestTabContents .noResults {
-    padding-top: 20px;
-}
-
-/*-------- End Dashboard Page --------*/
-
-/*-------- Start Upload Page --------*/
-
-#UploadPage
-{
-    margin-left:10px;
-    max-width:925px;
-}
-
-    #UploadPage .watermark {
-        color:Gray;
-    }
-
-    #UploadPage .projectTypeChoice   {
-    }
-
-        #UploadPage .projectTypeChoice > div {
-            padding: 20px 10px 20px 10px;
-            border: 1px solid darkgrey;
-            cursor: pointer;
-            height: 200px;
-            float: left;
-        }
-
-        #UploadPage .projectTypeChoice > div + div
-        {
-            margin: 0 0 0 5px;
-        }
-
-        #UploadPage .projectTypeChoice div.current
-        {
-            background-color: #E9E9E9;
-            cursor: default;
-        }
-
-            #UploadPage .projectTypeChoice div.choice {
-                font-size: large;
-                font-weight: bold;
-                padding: 0 0 10px 0;
-            }
-
-            #UploadPage .projectTypeChoice div.description {
-                padding: 0 0 0 17px;
-            }
-
-            #UploadPage .projectTypeChoice #genericSampleUploadDescription {
-                padding-top: 5px;
-            }
-
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription .logos {
-                    overflow: auto;    
-                }
-
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription .vslogo {
-                    background: url(../samples/vslogo.png) no-repeat;
-                    width: 125px;
-                    height: 18px;
-                }
-
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription .javalogo {
-                    background: url(../samples/javalogo.png) no-repeat;
-                    width: 33px;
-                    height: 60px;
-                    float: left;
-                }                
-                
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription .phplogo {
-                    background: url(../samples/phplogo.png) no-repeat;
-                    width: 65px;
-                    height: 35px;
-                    float: left;
-                    margin: 15px 0 0 10px;
-                }                
-                
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription .nodejslogo {
-                    background: url(../samples/nodejslogo.png) no-repeat;
-                    width: 90px;
-                    height: 25px;
-                    float: left;
-                    margin: 18px 0 0 10px;
-                }
-
-                #UploadPage .projectTypeChoice #genericSampleUploadDescription > div+div {
-                    margin-top: 10px;
-                }
-
-    #UploadPage .projectTypeContents {
-        clear: left;
-        padding: 10px 0 0 0;
-    }
-
-        #UploadPage .projectTypeContents .instruction > div+div {
-            padding-top: 5px;
-        }
-   #UploadPage #libraryContainer {
-       margin: 5px 0 0 0;
-       display: none;
-   }
-    #UploadPage fieldset
-    {
-        margin: 10px 0 30px 5px;
-    }
-
-        #UploadPage fieldset > *
-        {
-            margin-left:10px;
-        }
-
-        #UploadPage .fieldsetStyleContainer {
-            margin: 10px 0 0 5px;
-        }
-
-        #UploadPage fieldset h2,
-        #UploadPage .fieldsetStyleContainer h2
-        {   
-            font-family: 'Segoe UI Semibold','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;
-            font-size: 17px;
-            font-weight: bold;
-            color: #3A3E43;
-            border-bottom: 2px solid #EFEFEF;
-            width: 100%;
-            padding-bottom: 3px;
-            margin-left:0px;
-            margin-bottom:8px;
-        }
-
-        .IE7 #UploadPage fieldset h2,
-        .IE7 #UploadPage .fieldsetStyleContainer h2
-        {
-            margin-left:-10px;
-        }
-
-        #UploadPage fieldset .field-validation-error
-        {
-            clear:left;
-            display:block;
-            margin-top:4px;
-        }
-
-        #UploadPage fieldset .required
-        {
-            margin-left: 3px;
-        }
-
-        #UploadPage fieldset .instruction,
-        #UploadPage .fieldsetStyleContainer .description,
-        #UploadPage .fieldsetStyleContainer .instruction
-        {
-            color: #3A3E43;
-            margin:0 0 10px 0;
-        }
-
-        #UploadPage fieldset .faqLink
-        {
-            margin: 0 0 10px 0;
-        }
-
-        #UploadPage fieldset label 
-        {
-            display:block;
-        }
-
-        #UploadPage fieldset input[type=text]
-        {
-            width:60%;
-        }
-
-        #UploadPage fieldset input[type=checkbox]
-        {
-            float:left;
-            clear:left;
-            margin-right:5px;
-        }
-
-        #UploadPage fieldset input[type=radio]
-        {
-            float:left;
-            clear:left;
-            margin-right:5px;
-        }
-
-        #UploadPage fieldset#richDescription textarea 
-        {
-            width:70%;
-            height:600px;
-        }
-          
-        #UploadPage fieldset#summary textarea 
-        {
-            width:60%;
-            height:100px;
-            margin-top: 10px;
-            margin-left: -30px;
-        }
-
-        .IE #UploadPage fieldset#summary textarea, .IE9 #UploadPage fieldset#summary textarea
-        {
-            margin-left: -30px;
-            overflow: auto;
-        }
-
-        .FF #UploadPage fieldset#summary textarea
-        {
-            margin-left: -30px;
-        }
-
-        #UploadPage fieldset#summary #SummaryReadOnly 
-        {
-            width:60%;
-            margin-top: 10px;
-            padding-top: 5px;
-            color: #909082;
-        }
-
-        #UploadPage fieldset#summary #SummaryCharCount 
-        {
-            width:60%;
-            text-align: right;
-        }
-                
-        #UploadPage fieldset#options label 
-        {
-            margin-bottom:10px;
-        }
-        
-	    #UploadPage fieldset#license label
-	    {
-            margin-bottom:10px;
-        }        
-        
-        #UploadPage input[type="text"].tagInput, #UploadPage input[type="text"].listInput
-        {
-            width:40%;
-            float:left;
-        }
-
-        #UploadPage .addedTags, #UploadPage .addedProjects
-        {
-            margin-bottom:15px;
-            width: 500px;
-
-        }
-            #UploadPage .addedTags .tag, #UploadPage .addedProjects .projectTitle
-            {
-                position:relative;
-                overflow:hidden;
-            }
-
-                #UploadPage .addedTags .tag  label, #UploadPage .addedProjects .projectTitle  label 
-                {
-                    float:left;
-                    width: 450px;
-                }
-            
-                #UploadPage .addedTags .tag  a, #UploadPage .addedProjects .projectTitle  a 
-                {
-                    position:absolute;
-                    text-align:right;
-                    right:0px;
-                }
-         
-        .fileManager .fileUploadProgressIndicator
-        {
-            width: 500px;
-        }
-
-        .fileManager .uploadProcessingWarning {
-            margin-top: 5px;
-        }
-
-        .fileManager .fileUploadProgressIndicator .throbber
-        {
-            font-weight: bold;
-            background: url('./progressIndicatorWhite.gif') no-repeat 10px 0;
-            padding: 7px 10px 5px 60px;
-            height: 25px;
-            margin-left: -10px;
-        }
-
-        .fileManager #uploadFrame, .fileManager .uploadFrame
-        {
-            width:100%;
-        }
-
-            .fileManager .addLabel + a 
-            {
-                margin-left:25px;
-            }
-
-        .fileManager fieldset label {
-            display: block;
-        }
-
-        .fileManager .unlocalizedFiles {
-            color:#808080;
-        }
-
-        .fileManager .filesContainer 
-        {
-            margin-bottom:15px;
-            width: 500px;
-
-        }
-
-            .fileManager .filesContainer .file
-            {
-                position:relative;
-                overflow:hidden;
-            }
-
-                .fileManager .filesContainer .file .title {
-                    border-bottom: 1px solid #000000;
-                    padding-bottom: 3px;
-                    margin-top: 10px;
-                    margin-bottom: 10px;
-                }
-
-                    .fileManager .filesContainer .file .title .manageLinks
-                    {
-                        float: right;
-                    }
-                    
-                .fileManager .filesContainer .file .version {
-                        padding: 0 0 20px 10px;
-                }
-
-                    .fileManager .filesContainer .file .version label {
-                        float: left;
-                        font-weight: bold;
-                    }
-
-                    .fileManager .filesContainer .file .version span {
-                        float: left;
-                        margin-left: 5px;
-                    }
-
-                .fileManager .filesContainer .file .language {
-                    clear: left;
-                    padding: 0 0 5px 10px;
-                }
-
-                    .fileManager .filesContainer .file .language label {
-                        font-weight: bold;
-                    }
-
-                    .fileManager .filesContainer .file .language label + label {
-                        font-weight: normal;
-                        padding-left: 10px;
-                    }
-
-                    .fileManager .filesContainer .file .language div {
-                        padding-left: 20px;
-                    }
-                    
-                    .file .requirements {
-                        clear: left;
-                        padding: 0 0 0 10px;
-                    }
-
-                    .file .requirements label {
-                        font-weight: bold;
-                    }
-                    
-                    .file .requirements > div {
-                        padding-left: 20px;
-                    }
-                    
-                    .file .requirements .requirementsContent {
-                        padding-top: 5px;
-                        padding-bottom: 10px;
-                    }
-                    
-                    .file .requirements .requirementsContent label {
-                        font-style: italic;
-                        font-weight: normal;
-                    }
-                    
-                    .file .requirements .requirementsContent > div 
-                    {
-                       margin-bottom:4px;
-                       position:relative;
-                    }
-                    
-                    .requirementsContent .requirementsRemove {
-                        float:right;
-                        position:absolute;
-                        right:0px;
-                    }
-                    
-                    .requirements .requirementsAddError {
-                        color:#ff0000;
-                    }
-                    
-                    .requirements .reqBrowseButton {
-                        margin-left : 10px;
-                    }
-                    
-                    #UploadPage fieldset .requirements input[type="text"] {
-                        margin-right: 10px;
-                        width: 70%;
-                    }
-                    
-                    .reqBrowsefade
-                    {
-                        position: absolute;
-                        background-color: #aaaaaa;
-                    }
-                    .reqBrowse
-                    {
-                        background-color: #f4f4f4;
-                        border:1px solid #000000;
-                        -border-radius: 5px;
-                        -moz-border-radius: 5px;
-                        -webkit-border-radius: 5px;
-                        padding:15px;
-                        position: absolute;
-                        display: block;
-                    }
-
-                   .reqBrowsebuttons
-                    {
-                       text-align:right;
-                       position:absolute;
-                       right:10px;
-                       bottom:5px;
-                    }
-                    .reqBrowsebuttons > button
-                    {
-                        color: Blue;
-                        border: none;
-                        background: none;
-                        font-weight: bold;
-                        cursor:pointer;
-                    }
-
-                    .reqBrowseclose
-                    {
-                        display:none;
-                    }
-
-                    .reqBrowseDialog
-                    {
-                        width: 700px;
-                        clear:both;
-                        overflow:hidden;
-                        padding-bottom: 20px;
-                    }
-                    
-                    .reqBrowseDialog > h2 
-                    {
-                        border-bottom: 1px solid #000000;
-                        padding-bottom: 5px;
-                    }
-                    .reqBrowseDialog > p 
-                    {
-                        margin: 15px 0 15px 0;
-                    }
-                    
-                    .reqBrowseSearchCont
-                    {
-                        width: 100%;
-                        background: white;
-                        padding: 0px 2px;
-                        -moz-border-radius: 2px;
-                        border-radius: 2px;
-                        border: 1px solid #888;
-                        margin-bottom: 5px;
-                        height: 29px;
-                    }
-                    .reqBrowseSearchCont .rbboxcont
-                    {
-                        width:90%;
-                        float:left;
-                        margin-top: 2px;
-                    }
-                    
-                    .reqBrowseSearchCont input
-                    {
-                        border:none;
-                        outline:none;
-                        border-color: transparent;
-                    }
-                    .reqBrowseSearchBox
-                    {
-                        margin-right: 4px;
-                        height: 20px;
-                        line-height: 20px;
-                        width: 100%;
-                        padding-left: 4px;
-                        padding-top: 2px;
-                    }
-                    
-                    .reqBrowseSearchBoxDefault
-                    {
-                        color: #AAA;
-                    }
-                    .reqBrowseSearchCont .rbbtncont
-                    {
-                        float: right;
-                        margin-top: 4px;
-                    }
-                    .reqBrowseSearchBtn
-                    {
-                        background: transparent url('searchButton.png') no-repeat 0 0;
-                        width: 22px;
-                        height: 22px;
-                        float:left;
-                        cursor:pointer;
-                    }
-                    
-                    .reqBrowseTabs
-                    {
-                        border-bottom: 5px solid #E8E8E8;
-                        margin:3px 0;
-                        overflow:auto;
-                    }
-                    
-                    .reqBrowseTabs .reqBrowseTabsR
-                    {
-                        color:#fff !important;
-                    }
-                    
-                    .reqBrowseTabs .reqBrowseTabsHighlight
-                    {
-                        color:#000 !important;
-                        background-color:#E8E8E8;
-                    }
-                    
-                    .reqBrowseTabs a
-                    {
-                        padding:5px 12px;
-                        color:#fff;
-                        background-color:#888;
-                        font-weight:bold;
-                        float:left;
-                        margin: 0 4px 0px 0;
-                    }
-                    
-                    .reqBrowsePager td
-                    {
-                        text-align:center;
-                    }
-                    .reqBrowseDialog #Pager
-                    {
-                        margin: 5px 0 15px 0;
-                    }
-                    
-                    .reqBrowseContent
-                    {
-                        height:310px;
-                        overflow:auto;
-                        clear:both;
-                        position:relative;
-                    }
-                    
-                    .reqBrowsePager
-                    {
-                        width:700px;
-                        margin:0 auto;
-                    }
-                    
-                    .reqBrowseContentError
-                    {
-                        color:#ff0000;
-                        margin:5px;
-                    }
-                    .reqBrowseContent .requirementItem
-                    {
-                        border-bottom: 2px solid #E8E8E8;
-                        padding: 4px 0 6px 0;
-                        overflow:auto;
-                    }
-                    .reqBrowseContent .section1
-                    {
-                       float:left;
-                       width:75%;
-                       padding-left:25px;
-                       position:relative;
-                    }
-                    
-                    .reqBrowseContent .section1 input
-                    {
-                        position:absolute;
-                        left:0px;
-                    }
-                    
-                    .reqBrowseContent .title
-                    {
-                        font-weight:bold;
-                    }
-                    .reqBrowseContent .section2
-                    {
-                        float:right;
-                    }
-
-
-    .progressIndicatorfade
-    {
-        position: absolute;
-        background-color: #FFFFFF;
-    }
-    .progressIndicator
-    {
-        background-color: #f4f4f4;
-        border: 1px solid #000000;
-        -border-radius: 5px;
-        -moz-border-radius: 5px;
-        -webkit-border-radius: 5px;
-        padding: 15px;
-        position: absolute;
-        display: block;
-        max-width: 70%;
-        max-height: 70%;
-    }
-    #progressIndicator .progressIndicatorclose
-    {
-        display: none;
-    }
-
-    #progressIndicatorContent
-    {
-        font-weight: bold;
-        padding: 7px 10px 0 10px;
-        height: 25px;
-    }
-   
-
-/*-------- End Upload Page --------*/
-
-/* --- 
-   --- Homepage ---
-   --- */
-p
-{
-    margin: 0 0 1px 0;
-}
-#homePageHeader
-{
-    float: left;
-    margin-bottom: 1em;
-    width: 100%;
-}
-
-.tagline {
-    font-size: x-small;
-    position: relative;
-    top: -11px;
-}
-
-.logo
-{
-    float: left;
-    width: 455px;
-    height: 70px;
-    font-weight: bold;
-    font-size: 22px;
-    margin: 0 10px 0 0;
-    color: #3A3E43;
-}
-.logo > img
-{
-    float: right;
-}
-.logo > div
-{
-    color: #3A3E43;
-    font-weight: bold;
-    font-size: 22px;
-}
-
-.welcomeInfo
-{
-    float: left;
-    width: 700px;
-}
-.welcomeInfo h2
-{
-    font-size: 16px;
-}
-.welcomeInfo p
-{
-    margin: 5px 0 0 0;
-}
-
-#siteActions > div
-{
-    border: 1px solid #BBBBBB;
-    padding: 15px 5px 0 65px;
-    height: 55px;
-    background-repeat: no-repeat;
-    background-position: 10px 10px;
-}
-#siteActions a, #siteActions p
-{
-    margin-top: 5px;
-}
-
-#siteActions .label a
-{
-    font-size: 1.25em;
-    font-weight: bold;
-    margin-bottom: 3px;
-}
-
-#myGalleryBox
-{
-    background-image: url("MyGalleryIcon.png");
-}
-
-#findActions
-{
-    float: right;
-    padding: 10px;
-    width: 225px;
-    height: 50px;
-    border: 1px solid #BBBBBB;
-    margin: 0 10px 0 0;
-}
-
-#findBox div:first-child
-{
-    margin: 0 0 5px 0;
-    font-weight: bold;
-}
-
-#legalDisclaimer
-{
-    margin: 0 0 10px;
-    color: #798072;
-    font-size: 0.8em;
-}
-
-#siteActions
-{
-    float: right;
-    width: 200px;
-}
-#siteActions > div
-{
-    margin-bottom: 10px;
-}
-.homePageProjects
-{
-    width: 100%;
-    float: left;
-}
-.homePageProjects > div
-{
-    padding-left: 1.5em;
-}
-.homePageProjects > div:first-child
-{
-    padding-left: 0;
-}
-
-.homePageProjects .projectList ul
-{
-    padding: 0;
-    margin: 0;
-}
-.homePageProjects li
-{
-    margin-top: .5em;
-    padding-bottom: 0.5em;
-    list-style-type: none;
-}
-.homePageProjects .itemRow a, .homePageProjects .itemRow a:hover
-{
-    color: #0054A6;
-}
-
-.projectList > a:first-child
-{
-    margin-left: 1px;
-    float: right;
-}
-.projectList > a, .projectList > a:hover
-{
-    color: #5BAEDB;
-}
-.projectListTitle
-{
-    height: 27px;
-    font-size: 16px;
-    font-weight: bold;
-    line-height: 125%;
-    background: #E8E8E8;
-    padding: 5px 5px 5px 25px;
-}
-.homePageListPager
-{
-    text-align: right;
-    margin-bottom: -.5em;
-}
-
-.recentlyAddedProjects
-{
-    float: left;
-    width: 32%;
-}
-.mostPopularProjects
-{
-    float: right;
-    width: 32%;
-}
-.highestRankedProjects
-{
-    overflow: hidden;
-}
-* html .highestRankedProjects
-{
-    float: left;
-}
-* html .highestRankedProjects > div
-{
-    width: 100%;
-}
-
-#Pager
-{
-    text-align:left;
-}
-
-/* Impromptu warning style */
-.ipWarningfade
-{
-    position: absolute;
-    background-color: #aaaaaa;
-}
-div.ipWarning
-{
-    width: 400px;
-    position: absolute;
-    border-radius: 10px;
-    -moz-border-radius: 10px;
-    -webkit-border-radius: 10px;
-    padding: 20px 0 20px 20px;
-    background-color: #FCE5E6;
-    border: solid 2px #EE1F25;
-}
-.ipWarningcontainer
-{
-    font-weight: bold;
-}
-.ipWarningclose
-{
-    display: none;
-}
-.ipWarningmessage div
-{
-    position: relative;
-}
-.ipWarningmessage div div + div
-{
-    text-align: center;
-    padding-right: 20px;
-}
-.ipWarningmessage div div:first-child div
-{
-    margin-left: 50px;
-}
-.ipWarningmessage div div:first-child img
-{
-    position: absolute;
-    margin: -20px 0 0 0;
-    top: 35%;
-}
-.ipWarningbuttons
-{
-    text-align: center;
-    margin: 20px 0 0 0;
-}
-.ipWarning button
-{
-    padding: 4px 8px 4px 8px;
-    margin: 2px;
-    font-weight: bold;
-    border: solid 1px #A6A3A6;
-    color: #FFFFFF;
-    background: #B8BABC;
-    filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#B8BABC',EndColorStr='#949699');
-}
-
-#eyebrow
-{
-    width: 100%;
-}
-#siteMessage .unsupportedLocale {
-    margin: 10px 0 0 243px;
-    border: solid 1px #CCC;
-    background: #FCFEC5;
-    padding: 5px;
-}
-
-#Footer
-{
-    width: 100%;
-    height: auto;
-}
-
-.clear
-{
-    clear: both;
-}
-
-#buildVersion
-{
-    clear: both;
-    margin-left: auto;
-    margin-right: auto;
-    padding-right: 26px;
-    padding-top: 8px;
-    text-align: right;
-}
-
-#page
-{
-    clear: both;
-    padding-top: 10px;
-}
-
-#page h1
-{
-    padding: 10px 0px;
-}
-
-#ownerBar
-{
-    background: #EFEFEF;
-    border: 2px solid #7FCBF5;
-    text-align: left;
-    color: Black;
-    margin: 10px 0 20px 0;
-    padding: 5px;
-    word-spacing: 0px;
-    font-size: medium;
-}
-
-#ownerBar a
-{
-    color: Blue;
-    padding: 0 5px 0 5px;
-}
-
-
-
-
-/*-------- Start Tab Control --------*/
-
-.tabHeaders
-{
-    font-weight:normal;
-    text-transform: uppercase;
-    border-bottom: solid 1px #CCC;
-    float: left;
-    width: 100%;
-}
-
-.tabHeaders div
-{
-    padding: 7px 19px 8px 19px;
-    font-size: 0.9em;
-    line-height: 125%;
-    color:#00749E;
-    cursor: pointer;
-    float: left;
-    text-align: center;
-}
-
-.tabHeaders div.current
-{
-    background-color:#fff;
-    cursor: default;
-    border: 1px solid #CCC;
-    border-bottom:none;
-    margin-bottom:-2px;
-    color:#000;    
-}
-
-.tabHeaders div a
-{
-    text-decoration:none;
-}
-
-.tabContents
-{
-    clear: both;
-}
-
-#MainContent .tabHeaders div.current a
-{
-    color:#000;
-}
-
-.tabContents div.current
-{
-    display: block;
-}
-/*-------- End Tab Control --------*/
-
-.itemContainer
-{
-    width: 100%;
-}
-.itemRow .itemTitle
-{
-    padding-bottom: 5px;
-    font-size:1.1em;
-}
-
-.itemRow .itemBody, .itemRow .itemInfo
-{
-    padding:15px 17px 16px 0;
-}
-.itemRow .itemDescription
-{
-    overflow: hidden;
-    max-height: 80px;
-}
-.itemRow .itemBody
-{
-    vertical-align: top;
-    line-height: 1.4;
-}
-.itemRow .itemBody a.officialMicrosoftLabel
-{
-    color: #ACACAC;
-}
-.itemRow .itemInfo
-{
-    vertical-align: top;
-    padding-left: .5em;
-    line-height: 1.4;
-    width: 10em;
-    text-align:right;
-}
-
-.IE7 .itemRow .itemInfo
-{
-    width:11em;
-}
-
-.itemRow .itemInfo .ratingStars
-{
-    float: left;
-}
-.itemRow .itemInfo .ratingCount
-{
-    padding: 0 0 0 5px;
-    float: left;
-}
-.itemRow .ratingInfo
-{
-    text-align: center;
-}
-
-.itemRow .affiliationLink, #editorPicksSection .affiliationLink
-{
-    position: relative;
-    top: 3px;
-}
-
-#editorPicksSection a.officialMicrosoftLabel
-{
-    color: #ACACAC;
-}
-
-.itemRow .tagsContainer label {
-    display:none;
-}
-
-.editorPickedItem
-{
-    background-color:#F8F8F8;
-}
-
-.editorPickedText
-{
-    font-size:1.25em;
-    padding-bottom:2px;
-}
-.editorPickedItem > td 
-{
-    border-top:6px solid #fff;    
-}
-
-.dirSubHeading
-{
-    margin-bottom:15px;
-}
-
-#searchPage .dirSubHeading h2 
-{
-    line-height:1.4;
-    font-size:1.1em;
-}
-
-#searchPage .dirSubHeading h2 span
-{
-    padding-top:5px;
-    display:block;
-}
-
-#searchPage .dirSubHeading h1, #searchPage .dirSubHeading h2
-{
-    clear:none;
-    padding-left:0px;    
-}
-
-.dirSubHeading .dirSubLinks
-{
-    font-size:1.2em;
-    padding-top:5px;
-}
-
-
-.summaryBox
-{
-    padding: .25em 0 .25em 0;
-    clear: both;
-    line-height:1.45;
-}
-
-/*-------- Start Rating Stars --------*/
-
-.RatingStar
-{
-    width: 11px;
-    height: 11px;
-    padding: 0 8px 0 0;
-    background-position: center;
-    float: left;
-}
-
-.FilledRatingStar, .HalfRatingStar, .EmptyRatingStar, .FilledRatingStarHover
-{
-    width: 11px;
-    height: 11px;
-    padding: 0px 1px 0px 0px;
-    margin-top: 2px;
-}
-
-.FilledRatingStar
-{
-    background: url(../samples/fullStar.png) no-repeat;    
-}
-
-.ownerRating .FilledRatingStar
-{
-    background: url(../samples/fullStar.png) no-repeat;
-}
-
-.FilledRatingStarHover
-{
-    background: url(../samples/fullStarHover.png) no-repeat;
-    
-}
-
-.HalfRatingStar
-{
-    background: url(../samples/halfStar.png) no-repeat;
-   
-}
-
-.EmptyRatingStar
-{
-    background: url(../samples/emptyStar.png) no-repeat;
-    
-}
-
-.EditStarMode .RatingStar
-{
-    cursor: pointer;
-}
-
-
-
-/*-------- End Rating Stars --------*/
-
-.discussionFormTable
-{
-    width: 100%;
-    table-layout: fixed;
-}
-
-
-#ReviewsTabPane .seeAllLink, #DiscussionsTabPane .seeAllLink
-{
-    margin-top: 10px;
-    text-align: center;
-}
-
-/*-------- Start DiscussionsTab --------*/
-
-.threadActions
-{
-    text-align: right;
-    margin-top: 10px;
-    float: right;
-}
-
-#DiscussionsTabPane .reply, #DiscussionsTabPane .toggleDiscussion
-{
-    cursor: pointer;
-}
-
-
-#defaultDicussionText, #newDiscussion
-{
-    padding-top: 10px;
-}
-#DiscussionsTabPane .posts
-{
-    display: block;
-}
-#DiscussionsTabPane .threadHeader .left
-{
-    float: left;
-}
-#DiscussionsTabPane .threadHeader .right
-{
-    float: right;
-}
-#DiscussionsTabPane .normal
-{
-    font-weight: normal;
-}
-
-#DiscussionsTabPane .threadHeader
-{
-    position: relative;
-    background-color: #ECECEC;
-    padding: 4px 10px 4px 10px;
-}
-
-#DiscussionsTabPane .threadHeader .title
-{
-    color: #000000;
-    font-weight: bold;
-    margin-bottom: .7em;
-}
-#DiscussionsTabPane .threadHeader .label
-{
-    color: #000000;
-}
-#DiscussionsTabPane .postMeta
-{
-    color: #666666;
-}
-#DiscussionsTabPane .threadHeader .value
-{
-    font-weight: bold;
-    color: #000000;
-}
-
-#DiscussionsTabPane .reply
-{
-    font-weight: normal;
-    cursor: hand;
-}
-
-#DiscussionsTabPane ul li
-{
-    list-style-type: none;
-    list-style-image: none;
-    padding-bottom: 10px;
-}
-
-#DiscussionsTabPane ul
-{
-    padding-left: 0px;
-    margin-left: 0px;
-    padding-right: 2px;
-}
-
-.IE #reviewList .right
-{
-    margin-right: -1em;
-}
-
-#newDiscussion
-{
-    margin: 0 0 15px 0;
-}
-#newDiscussion #Title
-{
-    width: 50%;
-}
-#newDiscussion textarea
-{
-    width: 99%;
-    height: 10em;
-}
-
-#DiscussionsTabPane
-{
-    margin-left: 0px;
-    padding: 0 1em 1em 1em;
-}
-
-
-.postMeta
-{
-    float: right;
-}
-
-.postReply
-{
-    cursor: hand;
-    float: right;
-    font-weight: bold;
-}
-
-.postSaveReply
-{
-    display: none;
-}
-
-.postSaveReply textarea
-{
-    width: 99%;
-    margin-bottom: 4px;
-    height: 8em;
-}
-
-.toggleDiscussion
-{
-    cursor: hand;
-}
-
-.saveReplyErrorMessage
-{
-    display: none;
-    margin: 0 0 4px 0;
-    color: Red;
-    font-weight: bold;
-}
-
-#discussionListItem .avatar
-{
-    float: left;
-    padding: 5px;
-    vertical-align: middle;
-}
-
-#discussionListItem .discussion
-{
-    margin-left: 55px;
-    padding: 0 5px 5px 5px;
-    vertical-align: top;
-}
-
-.IE7 #discussionListItem .avatar
-{
-    margin-top: 15px;
-}
-
-
-/*-------- End DiscussionsTab --------*/
-
-
-.flotChart
-{
-    height: 300px;
-}
-
-#projectMenuBarTop
-{
-    padding: 10px 0 20px 0;
-    font-weight: bold;
-    font-size: 25px;
-}
-.dayHeader
-{
-    font-weight: bold;
-}
-
-/*-------- Start StatsPage --------*/
-#statsPage
-{
-    border: none;
-    background-color: Transparent;
-    margin-top: 1em;
-}
-
-#statsPage .rangeBox
-{
-    padding: 5px;
-    background-color: #ECECEC;
-    border: solid 1px #C2C2C2;
-    float: left;
-}
-#statsPage .statBox
-{
-    margin-top: 1em;
-    margin-bottom: 10px;
-    overflow: hidden;
-    display: none;
-}
-#statsPage .statBox h3
-{
-    font-size: 1.1em;
-    display: inline;
-}
-
-#statsPage #statMessage
-{
-    margin-top: 1em;
-    display: none;
-}
-
-#statsPage #statDownloadBox img {
-    float: left;
-}
-
-#statsPage .statDownloadLink {
-    padding-left: 5px;
-    vertical-align: middle;
-}
-
-#pointTooltip
-{
-    border: solid #000000 1px;
-    height: 35px;
-    background-color: #EEEEEE;
-    position: absolute;
-    display: none;
-    text-align: center;
-    padding: 9px;
-    border-radius: 4px;
-    -moz-border-radius: 4px;
-    -webkit-border-radius: 4px;
-    z-index: 1000;
-    white-space: nowrap;
-}
-
-.flotChart
-{
-    height: 300px;
-}
-
-/*-------- End StatsPage --------*/
-
-
-/***************************************************************/
-/* TagAutoComplete Styles */
-/***************************************************************/
-.AutoCompletePanel
-{
-    font-size: 95%;
-    border: solid .1em #999;
-    background-color: #f0f0f0;
-    padding: .15em;
-}
-
-.AutoCompletePanel div.Row
-{
-    color: #000;
-    cursor: pointer;
-    background-color: transparent;
-    padding: .15em .25em;
-    text-align: left;
-}
-
-.AutoCompletePanel div.Selected
-{
-    color: #fff;
-    background-color: #6D6D6D;
-}
-
-
-/*-------- Start Subscription Form --------*/
-
-#subscribeForm
-{
-    background-color: #D3D3D1;
-    border: 1px solid #000000;
-    -border-radius: 5px;
-    -moz-border-radius: 5px;
-    -webkit-border-radius: 5px;
-    padding: 15px;
-    position: absolute;
-    display: block;
-}
-
-#subscribeForm .subscribeFormbuttons
-{
-    text-align: right;
-    margin-top: 10px;
-}
-#subscribeForm .subscribeFormbuttons > button
-{
-    color: Blue;
-    border: none;
-    background: none;
-    font-weight: bold;
-    cursor: pointer;
-}
-
-#subscribeForm .subscribeFormclose
-{
-    display: none;
-}
-
-#subscribeForm table
-{
-    margin-bottom: 15px;
-}
-
-#subscribeForm table th
-{
-    text-align: left;
-    font-weight: bold;
-    border-bottom: 1px solid #000000;
-}
-
-#subscribeForm table td
-{
-    padding: 5px 10px 5px 20px;
-}
-
-#subscribeForm .rowHeading td
-{
-    font-weight: bold;
-    border-bottom: 1px solid #FFFFFF;
-}
-
-#subscribeForm table tr td:first-child
-{
-    padding: 5px 40px 5px 0;
-}
-
-
-/*-------- End Subscription Form --------*/
-
-/*-------- Start Tag Browser --------*/
-
-.tagBrowserfade
-{
-    position: absolute;
-    background-color: #aaaaaa;
-}
-#tagBrowser
-{
-    background-color: #f4f4f4;
-    border:1px solid #000000;
-    -border-radius: 5px;
-    -moz-border-radius: 5px;
-    -webkit-border-radius: 5px;
-    padding:15px;
-    position: absolute;
-    display: block;
-}
-
-#tagBrowser .tagBrowserbuttons
-{
-   text-align:right;
-   margin-top: 10px;
-}
-#tagBrowser .tagBrowserbuttons > button
-{
-    color: Blue;
-    border: none;
-    background: none;
-    font-weight: bold;
-    cursor:pointer;
-}
-
-#tagBrowser .tagBrowserclose
-{
-    display:none;
-}
-
-.tagBrowserContainer {
-    width: 450px;
-}
-
-.tagBrowserContainer h2 {
-    border-bottom: 1px solid #000000;
-    padding-bottom: 5px;
-}
-.tagBrowserContainer > p {
-    margin: 15px 0 15px 0;
-}
-
-.tagBrowserContainer .tags {
-    margin: 5px;
-    height: 225px;
-    overflow-y: scroll;
-}
-
-
-/*-------- End Tag Browser --------*/
-
-/*-------- Start List Filter Box --------*/
-
-div#filterInputBox
-{
-    overflow:auto;
-    min-width:225px;
-}
-
-.filterBox
-{
-    width: 100%;
-    background: #FFFFFF;
-    padding: 0px 2px;
-    height: 25px;
-    -moz-border-radius: 2px;
-    border-radius: 2px;
-    border: 1px solid #888888;
-    table-layout: auto;
-    margin-bottom:5px;
-}
-
-    .filterBox #filterImageCell
-    {
-        text-align: right;
-        padding: 0px;
-        vertical-align: middle;
-    }
-
-    .IE7 .filterBox #filterImageCell
-    {
-        padding:2px 2px 0 0;
-    }
-
-        .filterBox #filterImg
-        {
-            background: transparent url('searchButton.png') no-repeat 0 0;
-            width: 22px;
-            height: 22px;
-        }
-
-table.filterBox
-{
-    table-layout: fixed;
-}
-
-    .filterBox .stxtcell
-    {
-        padding-right: 4px;
-        width:90%;
-    }
-
-        .filterBox .stxtcell > input
-        {
-            margin-right: 4px;
-            height: 26px;
-            line-height:26px;
-            width: 100%;
-            padding: 0px;
-            padding-left: 4px;
-            padding-top: 2px;
-            border: none;
-        }
-
-        .IE7 .filterBox .stxtcell > input
-        {
-            height: 20px;
-        }
-
-            .filterBox .stxtcell > input.stxtinptpassive
-            {
-                color: #ACACAC;
-            }
-
-/*-------- End List Filter Box --------*/
-
-/*-------- Start Notifications --------*/
-
-#notificationsSummaryBox
-{
-    font-weight: bold;
-    padding: .5em;
-}
-
-
-.notificationsByDay, .notifications
-{
-    /*list-style: none;*/
-}
-
-.dayHeader
-{
-    border-bottom: 1px solid silver;
-    margin-top: 1em;
-    padding-bottom: .5em;
-}
-
-.notifications
-{
-    margin-top: .5em;
-}
-
-ul.notifications li
-{
-    line-height: 1.5em;
-}
-
-ul.notifications li.unread
-{
-    font-weight: bold;
-}
-
-ul.notifications li ol, ul.notifications li ul
-{
-    margin-left: 1.5em;
-}
-
-/*-------- End Notifications --------*/
-
-/*-------- Start ProjectDetailsPage --------*/
-
-#projectPage #projectInfo
-{
-    position: relative;
-    margin-top: 5px;
-    height: 100%;
-}
-#projectInfo .section
-{
-    float: left;
-    margin-bottom: 0px;
-    height: 100%;
-}
-
-    #projectInfo .section .itemBar, #projectInfo .section .itemBarLong
-    {
-        clear: both;
-        padding: 7px 0 7px 0;
-        overflow:auto;
-    }
-    
-     #projectInfo .section .itemBarLong:first-child
-     {
-         padding-top:3px;
-     }
-    
-    .IE7 #projectInfo .section .itemBar, .IE7 #projectInfo .section .itemBarLong
-    {
-        padding-top: 5px;
-    }
-
-    #projectInfo .section .itemBar > label, #projectInfo .section .itemBarLong > label
-    {
-        width: 130px;
-        float: left;
-        text-transform: capitalize;
-    }
-
-    #projectInfo .section .itemBar div#yourRating {
-        float:left;
-    }    
-    
-    #projectInfo .section .itemBar div.RatingStar {
-        margin:2px 1px 0 0;
-    }
-
-    #projectInfo .section .itemBar div#RatingCount {
-        padding: 0 0 0 3px;
-    }    
-    
-    #projectInfo .section .itemBar .ratingsWithCountContainer img {
-       vertical-align:top;
-       float:left;
-       padding-right: 4px;
-    }
-
-    #projectInfo .section .itemBar > span, #projectInfo .section .itemBarLong > span, #projectPage .section .itemBar > div
-    {
-        float: left;
-    }
-
-    #projectInfo .section .itemBar, #projectInfo .section .itemBarLong {
-        width: 100%;
-    }
-
-    #projectInfo .section .itemBar > span {
-        float: none;
-    }
-
-    #projectInfo .section .itemBar > span .shareThisItem {
-        white-space: nowrap;
-    }
-    
-    #projectInfo .section .itemBarLong div
-    {
-        margin-left: 130px;
-        padding: 0;
-    }
-    
-     #projectInfo .section .viewonlinecont
-     {
-         background-color:#d3d3d3;
-         padding:5px 10px;
-         margin-top:10px;
-         float:left;
-         font-weight:bold;
-     }
-
-#projectInfo #sectionLeft
-{
-    width: 50%;
-}
-#projectInfo #sectionRight
-{
-    width: 50%;
-}
-.IE7 #projectInfo #sectionRight
-{
-    width: auto;
-}
-
-#projectPage h2.projectSummary
-{    
-    font-weight:normal;
-    font-size: 1.1em;
-    margin-bottom: 11px;
-    line-height:1.4;
-    word-wrap: break-word;
-}
-
-.IE7 #projectPage h2.projectSummary
-{
-    font-family: 'Segoe UI' , 'Lucida Grande' ,Verdana,Arial,Helvetica,sans-serif;
-}
-
-.IE #projectPage .projectTitle, .IE9 #projectPage .projectTitle
-{
-    width: 100%; 
-}
-
-#projectPage #reportAbuse
-{
-    float: left;
-    font-size: x-small;
-}
-
-#projectPage .hiddenSidebar {
-    display: none;
-}
-
-#projectPage .fullProjectBody {
-    margin-left:-275px;
-}
-
-.IE8 #projectPage #userCard {
-    float: left;
-    height: auto;
-}
-
-#projectPage #userCard .avatar img {
-    max-width: 100px;
-    max-height: 100px;
-}
-
-#projectDetails
-{
-    overflow:hidden;
-}
-
-#projectBody
-{
-    width: 100%;
-    overflow:hidden;
-}
-
-    #projectDetails > div:first-child
-    {
-        margin: 5px 0 0 260px;
-    }
- 
-    #projectBody > div:first-child
-    {
-        margin: 20px 0 0 260px;
-    }
-
-    .IE7 #projectContent .tabHeaders
-    {
-        overflow:hidden;
-        margin-bottom:-20px;
-    }
-
-#projectPage .sidebar
-{
-    float: left;
-    width: 215px;
-    margin-right: -250px;
-}
-
-    #projectPage .sidebar .section
-    {
-        margin: 20px 0 10px 0;
-    }
-
-        #projectPage .sidebar .section .titleBar h3
-        {
-            padding: 0 0 2px 0;
-        }
-
-        #projectPage .sidebar .section .itemBarRight
-        {
-            min-height: 21px;
-            position: relative;
-            padding-top: 5px;
-        }
-
-        #projectPage .sidebar .section .titleBar
-        {
-            margin-bottom: 5px;
-        }
-
-        #projectPage .sidebar .section .authorItem
-        {
-            padding: 0 0 5px 10px;
-        }
-
-            #projectPage .sidebar .section .authorItem a
-            {
-                display:block;
-                float:left;
-                max-width:170px;
-            }
-
-            #projectPage .sidebar .section .authorItem > div
-            {
-                float:right;
-            }
-
-    #projectPage .sidebar #advertisement
-    {
-        margin-top: 20px;
-    }
-
-    #projectPage .sidebar #advertisement .label
-    {
-        text-align: center;    
-    }
-
-    #projectPage .sidebar #moreFromAuthor 
-    {
-        width:225px;
-        margin: 20px 0 10px 0;
-        float:left;
-    }
-    
-    #projectPage .sidebar  #moreFromAuthor .bottomBar {
-        padding: 5px 0px 5px 25px;
-        text-align: right;
-    }
-
-#projectPage #Collections {
-    min-height:22px;
-    min-width:169px;
-}
-
-#projectPage #Collections .bevelButton {
-    background-color: #8CC63F;
-}
-
-#projectPage .bevelButton
-{
-    font-weight: bold;
-    border-radius: 3px;
-    -moz-border-radius: 3px;
-    -webkit-border-radius: 3px;
-    color: white;
-    padding: 2px 10px 3px;
-    text-align: center;
-}
-
-#projectPage #DiscussionsTabPane .bevelButton
-{
-    font-weight: normal;
-    color: black;
-    padding: 1px 10px 1px;
-}
-
-#projectPage #Downloads {
-    padding: 0 0 8px 0;
-    float: left;
-}
-    #projectPage #Downloads > div:first-child {
-        float: left;
-        margin: 15px 0 0 0;
-        height:35px;
-        line-height:1.6;
-        width: 130px;
-    }
-    #projectPage #Downloads label 
-    {
-        font-size:1.25em;
-    }
-    #projectPage #Downloads input
-    {
-        min-width: 100px;
-        padding: 3px 10px 3px 10px;
-        margin: 3px 10px 0 10px;
-        font-weight: bold;
-        float: left;
-    }
-    
-    #projectPage #Downloads .button
-    {
-        background-color:#007494;
-        color:#fff;
-        padding:5px 15px;
-        margin: 15px 15px 0 0;
-        float:left;
-    }
-    
-    #projectPage #Downloads .button:hover 
-    {
-        background-color:#0095c4;
-        text-decoration:none;
-    }
-
-#projectPage #projectBody .attachments {
-    margin: 0 0 15px 0;
-}
-
-    #projectPage #projectBody .attachments label {
-        float: left;
-    }
-
-        #projectPage #projectBody .attachments .files a, #projectPage #projectBody .attachments .files span {
-            float: left;
-            padding: 0 5px 0 5px;
-        }
-
-#publishBar
-{
-    border: 1px solid #707070;
-    background-color: #F8F8F8;
-    margin-top: 10px;
-}
-
-#sourceItem {
-    height: 610px;
-}
-    #sourceItem > div:first-child {
-        padding: 20px 5px 0 15px;
-        font-weight: bold;
-    }
-    #sourceItem > div+div {
-        height: 560px;
-        padding: 10px;
-        overflow: auto;
-    }
-    #sourceItem .copyCode {
-        font-weight: normal;
-        margin: 0 15px 0 0;
-        float: right;
-    }
-
-.sourceList {
-    height: 600px;
-    padding: 5px;
-    border-top: 1px solid #CCC;
-    margin-top: -1px;
-}
-
-        .sourceList .sourceListTabHeader
-        {
-            margin:20px 10px;
-        }
-        .sourceList .sourceListTabs
-        {
-            margin-bottom:20px;
-            border-bottom: 1px solid #CCC;
-            float:left;
-            width:100%;
-        }
-        .sourceList .sourceListTabs .languageTab {
-            padding:5px 10px 5px 10px;
-            font-weight: bold;
-            float: left;
-            margin: 0 3px 0px 0;
-            color:#00749E;
-        }
-        .sourceList .sourceListTabs .languageTab:hover 
-        {
-            color: #0095C4;
-        }
-
-        .sourceList .sourceListTabs .selectedLanguage {
-            background-color: #fff;
-            color: #000;
-            border: 1px solid #ccc;
-            border-bottom:none;
-            margin-bottom:-2px;
-        }
-
-        .sourceList .sourceListTabs .unselectedLanguage {
-            cursor: pointer;
-        }
-
-        .sourceList .endTabs {
-            clear: both;
-        }
-
-    .sourceList .sourceListContent {
-        padding-top: 5px;
-    }
-
-
-.sbfc,
-.sbfe
-{
-    white-space: nowrap;
-	text-indent: 20px;
-	cursor: pointer;
-	padding: .2em 0em .2em 0em;
-	background-repeat: no-repeat;
-	background-position: left center;
-	font-weight: bold;
-	text-decoration: none !important;
-}
-
-.sbfc 
-{
-	background-image: url(../samples/node_closed.gif);
-}
-
-.sbfe
-{
-    white-space: nowrap;
-	background-image: url(../samples/node_opened.gif);
-}
-
-.ndbf
-{
-    white-space: nowrap;
-	text-indent:20px;
-}
-
-.sbf
-{
-    white-space: nowrap;
-	background: url(../samples/bullet.gif) no-repeat 4px -1px;
-	cursor: pointer;
-	text-indent: 20px;
-    white-space: nowrap;
-	padding: .1em 0em .1em 0em;
-}
-
-.sbsf,
-.sbf:hover
-{
-	color: #000;
-	text-decoration: none !important;
-	
-}
-
-.sbsf
-{
-	color: #000 !important;
-	background-color: rgb(232, 232, 232);
-}
-
-.sbf:hover
-{
-	color: #ce8b10;
-}
-
-/*-------- Translate --------*/
-.translatePage {
-    width: 900px;
-}
-.translatePage .fileManager {
-    margin-bottom:20px;
-}
-.translatePage .fileManager h4 {
-    margin-top:10px;
-}
-.translatePage #formContainer {
-    width: 100%;
-}
-.translatePage .formLabel {
-    width: 300px;
-    padding: 5px;
-}
- .translatePage .textInput {
-    width: 425px;
-}
-.translatePage TEXTAREA.richText {
-    height: 600px;
-    width: 620px;
-}
-.translatePage TEXTAREA.unadornedEditor {
-    height: 600px;
-}
-.translatePage .formWideLabel, .translatePage .richText {
-    padding: 5px;
-}
-.translatePage .formWideLabel, .translatePage .unadornedEditor {
-    width: 750px;
-    padding: 5px;
-}
-.translatePage #languageSelection {
-    margin: 15px;
-    display: inline-block;
-}
-
-.translateTab, .translateTabSelected {
-    font-weight: bold;
-    float: left;
-    text-align: center;
-    margin: 10px;
-    padding: 7px;
-    background: #E8E8E8;
-    white-space: nowrap;
-    cursor: pointer;
-}
-
-.translateTabSelected
-{
-    color: White;
-    background: Gray;
-}
-
-.translateTabSelected .translateLabel, .translateTab .translateLabel
-{
-    white-space: nowrap;  
-    float: left;  
-    padding: 0 5px 0 5px;
-}
-
-.translateTab #deleteLanguage, .translateTab #moreLanguages
-{
-    padding-left: 10px;
-}
-
-.translateLabel #deleteLanguage {
-    color: #FFFFFF;
-}
-/*-------- End Translate --------*/
-/*-------- Begin Eula --------*/
-
-
-#eulaPagefade
-{
-    position: absolute;
-    background-color: #FFFFFF;
-}
-
-#eulaPage
-{
-    background-color: #f4f4f4;
-    border: 1px solid #000000;
-    -border-radius: 5px;
-    -moz-border-radius: 5px;
-    -webkit-border-radius: 5px;
-    padding: 15px;
-    display: block;
-    max-width: 70%;
-}
-
-#eulaPage .eulaPageclose
-{
-    text-align: right;
-}
-
-#eulaPage .eulaPagemessage
-{
-    overflow: auto;
-    max-height: 350px;
-}
-
-    #eulaPage .eulaPagemessage h1
-    {
-        margin: 0 0 5px 0;
-    }
-
-#eulaPage .eulaPagebuttons
-{
-    text-align: right;
-    margin-top: 10px;
-}
-#eulaPage .eulaPagebuttons > button
-{
-    color: Blue;
-    border: none;
-    background: none;
-    font-weight: bold;
-    cursor: pointer;
-}
-
-
-        #eulaPage #eula #documentText
-        {
-            line-height: normal;
-        }
-
-/*-------- End DocumentView --------*/
-/*-------- Begin FAQ --------*/
-
-#FAQPage #TableOfContents h2
-{
-    padding: 5px;
-    border-bottom: 2px solid #EFEFEF;
-    margin: 0 0 10px 0;
-    max-width: 70%;
-}
-
-#FAQPage .FAQSection
-{
-    padding: 10px 0px;
-    width: 70%;
-}
-
-    #FAQPage .FAQSection h2
-    {
-        padding: 5px;
-        border-bottom: 2px solid #EFEFEF;
-    }
-
-    #FAQPage .FAQSection h3
-    {
-        padding: 5px;
-    }
-
-    #FAQPage .FAQSection ul, #FAQPage .FAQSection ol
-    {
-        margin: 0;
-    }
-
-    #FAQPage .FAQSection #description > div
-    {
-        overflow: auto;
-        padding-left: 10px;
-    }
-
-        #FAQPage .FAQSection #description img
-        {
-            float: left;
-        }
-
-        #FAQPage .FAQSection #description div > div
-        {
-            padding-top: 10px;
-            float: left;
-        }
-
-    #FAQPage .FAQSection > div > div
-    {
-        padding: 0 15px;
-    }
-
-    #FAQPage #Reputation th, #FAQPage #Reputation td
-    {
-        padding-left: 20px;
-    }
-    
-/*-------- End FAQ --------*/
-/*-------- Begin DocumentView --------*/
-
-#documentView #documentText
-{
-    line-height: normal;
-}
-
-/*-------- End DocumentView --------*/
-
-.Opera wbr:after
-{
-    content: "\00200B"; 
-}
-
-
-.IE9 wbr:after
-{
-    content: "\00200B"; 
-}
-
-.IE8 wbr {
-  width: 0px;
-  display: inline-block;
-  overflow: hidden;
-}
-
-/*-------- Begin FileManager --------*/
-
-.uploadControlNoError 
-        {
-            height:30px
-        }
-.uploadControlWithError 
-        {
-            height:80px;
-        }
-/*-------- End FileManager --------*/
-
-/*-------- Begin User Card --------*/
-#userCard .titleBar {
-    border-bottom: solid 5px #E8E8E8;
-    margin: 10px 0 5px 0;
-}
-    #userCard .titleBar h3
-    {
-        font-size: 1.0em;
-        font-weight: bold;
-        line-height: 125%;
-        padding: 0 0 2px 0;
-    }
-
-#userCard .userFeed {
-    float: right;
-}
-   
-#userCard .bio {
-    max-width:300px;
-    white-space: normal;
-}
-        
-#userCard .avatar
-{
-    padding: 5px 5px 10px 5px;
-    margin: 0 0 3px 0;
-    text-align: center;
-}
-
-#userCard .itemBar {
-    padding: 5px;
-}
-
-    #userCard .itemBar label
-    {
-        float: left;
-        text-transform: capitalize;
-    }
-
-    #userCard .itemBar label+span {
-        display: block;
-        margin-left: 100px;
-    }
-
-#userCard .collapsableSidebar {
-    clear:both;
-    width:100%;
-    margin-top: 5px;
-}
-
-/* Profile Overrides */
-#userCard
-{
-    padding: 0 0 10px 0
-}
-
-#userCard .profile-usercard
-{
-    width:225px;
-}
-
-#userCard .profile-usercard, #userCard .profile-inline, #userCard .profile-inline-header
-{
-    border:0px;
-    background-color:#fff;
-}
-
-#userCard .profile-userimage-large
-{
-    margin-bottom:10px;
-    border:none;
-    width:auto;
-    height:auto;
-}
-
-#userCard .profile-inline .profile-inline-header-details 
-{
-    width:100%;
-    display:block;
-    clear:both;
-    margin-left:0px;
-}
-
-
-    
-/*-------- End User Card --------*/
-/*-------- Begin Description Progress Meter --------*/
-
-#descriptionProgressMeter {
-    float: right; 
-    border-top: 1px solid #DADADA; 
-    border-left: 1px solid #DADADA; 
-    width: 210px;
-    padding-left: 7px;
-}
-
-    #descriptionProgressMeter h4 {
-        font-weight: bold;
-    }
-
-    #descriptionProgressMeter #progressGraphic {
-        border: 1px solid #888888;
-        width: 205px;        
-        margin: 10px 0;
-        background-color: #E9E9E9;
-        padding: 1px 0 0 1px;
-    }
-
-        #descriptionProgressMeter #progressGraphic div {
-            background-image: url("../common/progress_meter.png");
-            padding-left: 5px;
-        }
-
-    #descriptionProgressMeter #progressText {
-        font-weight: bold;
-        margin: 5px 0;
-        
-    }
-            
-    #descriptionProgressMeter #goodDescriptionText  p+p {    
-        padding: 5px 0;
-    }
-
-        #descriptionProgressMeter #goodDescriptionText > div {
-            margin-top: 5px;
-            width: 150px;
-            border-radius: 5px;
-            -moz-border-radius: 5px;
-            -webkit-border-radius: 5px;
-            overflow: auto;
-        }
-
-            #descriptionProgressMeter #goodDescriptionText div img {
-                float: left;
-            }
-
-            #descriptionProgressMeter #goodDescriptionText div div {    
-                margin: 7px 0 5px 10px;
-            }
-
-/*-------- End Description Progress Indicator --------*/
-
-/*-------- Start Sample Pack Tab View --------*/
-.SamplePackTab #headerBar
-{    
-    padding: 15px 5px 20px 5px;
-    font-weight: bold
-}
-    .SamplePackTab #headerBar .reportCount
-    {
-        padding-top: 2px;
-    }
-    .SamplePackTab #headerBar .samplePackSort
-    {
-        float: right;
-        color: #666;
-    }
-/*-------- End Sample Pack Tab View --------*/
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/description/Combined.css b/samples/winrt/ImageManipulations/description/Combined.css
deleted file mode 100644
index e69de29bb..000000000
diff --git a/samples/winrt/ImageManipulations/description/Galleries.css b/samples/winrt/ImageManipulations/description/Galleries.css
deleted file mode 100644
index ac2e94ee8..000000000
--- a/samples/winrt/ImageManipulations/description/Galleries.css
+++ /dev/null
@@ -1,418 +0,0 @@
-/* ***************************************************
-Galleries.css   - Common Structure
-
-This is where we define common layout for structures that are truly close to common across the different
-Galleries sites.  To make sure this works we need to follow certain conventions.
-
-1. Define each logical structure in its own section with its own comment block that gives the section
-a Name, Description and defines the root element if one exists (i.e #someElement). Also, mark the closing block.
-
-2. Indent styles in a section to represent if it is a child of a previous element.
-i.e.      #someDiv{
-            }
-                #someDiv ul {
-                }
- 
-3. Do not include brand specific information here like colors and fonts unless they are *really* common.
-
-4. If there is an element that you know will be overridden in each brand stylesheet still include it here with an empty definition. 
-This will aid in knowing what section to override and what selectors to use.
-
-i.e.    #someSction a {
-        }
-
-5.  When you add a new section also update the Table of Contents below so that we have a quick overview of the sections
-
- *****************************************************/
- 
-/****************************************************
-Table of Contents
-
-    Global - global classes
-
-    FileAttachmentDisplay - The list of attached files under the editor
-    Eyebrow - The breadcrumb control at the top of the master page
-    Pager - The common paging control, used for browsing pages of search results
-    Profile User Card - Elements in the profile usercard control
-    SideNav - The navigation side bar that contains the search filters
-
-
-*****************************************************/
-
-/********************************
-Name: Global
-Root: none
-Description: truly global classes
-********************************/
-body {
-    text-align: left;
-    direction: ltr;
-}
-
-img.rss {
-    background: url(../../../GlobalResources/Images/Rss.png) no-repeat;
-    background-position: 0px 0px;
-    height: 17px;
-    width: 17px;
-}
-/* End Global Section */
-
-/********************************
-Name: FileAttachmentDisplay
-Root: #fileAttachmentDisplay
-Description: The list of attached files under the editor
-********************************/
-#fileAttachmentDisplay {
-}
-    #fileAttachmentDisplay .attachment {
-        margin-right: 10px;
-        float: left;
-    }
-
-        #fileAttachmentDisplay .attachment .displayAttachment {
-            padding: 0px 0 13px 0;
-            float: left;
-        }
-
-        #fileAttachmentDisplay .attachment .removeAttachment {
-            background-image: url('/Content/Common/delete.png');
-            display: block;
-            width: 16px;
-            height: 16px;
-            float: left;
-        }
-/* End FileAttachmentDisplay Section */
-
-
-/********************************
-Name: Eyebrow
-Root: .EyebrowContainer
-Description: The breadcrumb control at the top of the master page
-********************************/
-.EyebrowContainer {
-}
-    .EyebrowContainer div.EyebrowElement{
-        display:inline;
-    }
-
-    .EyebrowContainer .EyebrowElement{
-        font-weight:normal
-    }
-    .EyebrowContainer .EyebrowLeafLink{
-        color:#000;
-    }
-/* End Eyebrow Section */
-
-/********************************
-Name: Pager
-Root: #Pager
-Description: The common paging control, used for browsing pages of search results
-********************************/
-#Pager {
-}
-    #Pager div{
-        display:inline;
-    }
-/* End Pager Section */
-
-/********************************
-
-Name: Profile User Card
-Root: #dashboardPage #userCard
-Description: Elements in the profile usercard control
-
-********************************/
-    #dashboardPage #userCard .profile-usercard-inline {
-        margin: 5px 0 10px 0;
-    }
-
-   /* #dashboardPage #userCard .profile-usercard {
-        width: 288px;
-    }
-/* End Profile User Card Section */
-
-/********************************
-
-Name: Discussion 
-Root: #DiscussionsTabPane
-Description: Defines the layout of the dicussion 
-
-
-********************************/
-#DiscussionsTabPane {
-}
-
-    #DiscussionsTabPane .itemHidden
-    {
-        background: lightgrey;
-    }
-
-    #discussionListItem {
-    }
-
-        .discussion .postActions
-        {
-            float: right;
-        }
-
-        #discussionListItem .postItem
-        {
-            white-space: pre-wrap;
-            word-wrap: break-word;
-            font-size:1em;
-        }
-
-/* End Discussion Section */
-
-
-/********************************
-
-Name: SearchDefaultLocale
-Root: .searchDefaultLocale
-Description: Defines the layout of the include english result checkbox on the Browse Page
-
-
-********************************/
-.searchDefaultLocale
-{
-    float: right;
-    margin: 20px 0 0 5px;
-}
-    .searchDefaultLocale input
-    {
-        vertical-align:top;
-    }
-    .searchDefaultLocale span
-    {
-        margin-left: -3px;
-    }
-/*-------- End SearchDefaultLocale --------*/
-
-
-/********************************
-
-Name: SideNav
-Root: #sideNav
-Description: Defines the layout of the naviation elements on the side of the Browse Page
-             These represent the different filters like Code Language, Category and Tag
-
-
-********************************/
-
-#sideNav {
-    width: 250px;
-    vertical-align:top;
-    background-color:#eee;
-}
-    #sideNav h3 {
-    }
-
-    #sideNav .section {
-        padding: 0 0 10px 0;
-        position: relative;
-    }
-
-        #sideNav .section a {
-        }
-
-        #sideNav .section a:hover {
-        }
-
-        #sideNav .section > div {
-            padding:5px 5px 5px 0;
-            line-height:150%;
-        }
-
-        #sideNav .section ul {
-            list-style-type:none;
-            padding:0px;
-            margin:0px;
-        }
-
-            #sideNav .section ul  li {
-                position: relative;
-                padding: 5px 5px 5px 0;
-            }
-    
-                #sideNav .section ul li .selectedFilter {
-                    float: left;
-                    padding-right: 5px;
-                }
-
-        #sideNav .section div.itemCount {
-            float: right;
-        }
-
-        #sideNav .section form input[ type = "checkbox"] {
-            margin: 0px 4px 0px 0px;
-            vertical-align: middle; 
-        }
-/* End SideNav Section */
-
-/*----------- Contribution Logos *******/
-.contributionLogo {
-    float: left;
-    position: relative;
-    margin-right: 6px;
-}
-
-.logo_visualstudio {
-    background: transparent url('../common/logos/visualstudio.png') no-repeat;
-    width: 23px;
-    height: 12px;
-    margin-top: 3px;
-}
-.logo_allinonecode {
-    background: transparent url('../common/logos/1code.png') no-repeat;
-    width: 14px;
-    height: 16px;
-}
-.logo_exchange {
-    background: transparent url('../common/logos/exchange.png') no-repeat;
-    width: 14px;
-    height: 16px;
-}
-.logo_ie {
-    background: transparent url('../common/logos/ie.png') no-repeat;
-    width: 16px;
-    height: 16px;
-}
-.logo_office {
-    background: transparent url('../common/logos/office.png') no-repeat;
-    width: 17px;
-    height: 16px;
-}
-.logo_windows {
-    background: transparent url('../common/logos/windows.png') no-repeat;
-    width: 17px;
-    height: 16px;
-    }
-.logo_azure {
-    background: transparent url('../common/logos/windowsazuredark.png') no-repeat;
-    width: 16px;
-    height: 16px;
-}
-
-.logo_windowsphone {
-    background: transparent url('../common/logos/windowsphone.png') no-repeat;
-    width: 16px;
-    height: 16px;
-    }
-
-    .contributionLogoTip {
-        position: absolute;
-        display: none;
-        border: solid 1px #CCC;
-        color: #333;
-        background-color: #F0F0F0;
-        font-size: 11px;
-        font-family: "Segoe UI",Sans-Serif;
-        box-shadow: 3px 3px 5px #888;
-        -moz-box-shadow: 3px 3px 5px #888;
-        z-index: 1003;
-        padding: 5px;
-        min-width: 250px;
-    }
-
-/*----------- End Contribution Logos *******/
-
-.clear
-{
-    clear: both;
-}
-
-.customcontributionLogoTip {
-        position: absolute;
-        display: none;
-        border: solid 1px #CCC;
-        background-color: white;
-        color: #333;
-        font-size: 11px;
-        font-family: "Segoe UI",Sans-Serif;
-        box-shadow: 3px 3px 5px #888;
-        -moz-box-shadow: 3px 3px 5px #888;
-        z-index: 1004;
-        padding: 5px;
-        min-width: 250px;
-}
-
-.customcontributionTittle {
-    font-size: 14px;
-    margin-left: 90px;
-}
-
-.customcontributionDiscription {
-    font-size: 13px;
-    margin: 10px 5px;
-    text-align: justify;
-}
-
-.customcontribution {
-    float: left;
-    position: relative;
-    margin-right: 6px;
-}
-
-.customcontributionLink {
-    margin-left: 5px;
-}
-
-.customcontributionlogo {
-    float: left;
-    padding: 0 10px;
-    margin: 0;
-    width: 70px;
-    height: 70px;
-    background-repeat: no-repeat; 
-}
-
-
-.logo_azure_large {
-    background-image:  url('../common/logos/windowsazure_large.png');
-}
-.logo_visualstudio_large {
-    background-image:  url('../common/logos/visualstudio_large.png');
-}
-.logo_exchange_large {
-    background-image:  url('../common/logos/exchange_large.png');
-}
-.logo_ie_large {
-    background-image:  url('../common/logos/ie_large.png');
-}
-.logo_office_large {
-    background-image:  url('../common/logos/office_large.png');
-}
-.logo_windows_large {
-    background-image:  url('../common/logos/windows_large.png');
-}
-.logo_windowsphone_large {
-    background-image:  url('../common/logos/windowsphone_large.png');
-}
-
-/* Custome Header */
-.dirSubHeading .windowssdk .container
-{
-    background: #FF3300 url('wpappsbackground.png') no-repeat;    
-    color: white;
-    padding: 8px 10px 18px 170px;   
-}
-
-.dirSubHeading .windowssdk .container h1, .dirSubHeading .windowssdk .container h2 {
-    color: white !important;
-}
-
-.dirSubHeading .windowssdk .container p {
-    margin: 20px 0 0 0 !important;
-}
-
-.dirSubHeading .windowssdk .container a {
-    background-color:#ffd800;
-    color: #2a2a2a !important; 
-    cursor:pointer; 
-    font-size:13px; 
-    font-family:'Segoe UI Semibold','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif; 
-    padding:4px 12px 6px;
-}
-
-
-
diff --git a/samples/winrt/ImageManipulations/description/Layout.css b/samples/winrt/ImageManipulations/description/Layout.css
deleted file mode 100644
index 625f77763..000000000
--- a/samples/winrt/ImageManipulations/description/Layout.css
+++ /dev/null
@@ -1,147 +0,0 @@
-#container {
-    min-height: 768px;
-}
-
-#leftSubHeaderContainer
-{
-    margin-top:20px;
-}
-
-#title h1
-{
-    font-size:25px;
-}
-
-#subtitle h2
-{
-    font-size:15px;
-}
-
-#subtitle
-{
-    margin-left:10px;
-}
-
-
-#formContainer
-{
-    margin-left:10px;
-    margin-top:30px;
-}
-
-.formLabel
-{
-    float:left;
-    width: 250px;
-}
-
-.formRow
-{
-    clear:both;
-    padding: 10px 0 10px 10px; 
-}
-
-
-.formRecaptchaRow
-{
-    clear:both;
-    float:left;
-    margin-top:20px;
-    margin-left:10px; 
-    margin-bottom:20px;   
-}
-
-.formSubmitRow
-{
-    clear:both;
-    margin-top:20px;
-    margin-left:300px; 
-    margin-bottom:20px;
-}
-
-.formControl {
-    width:300px;
-    float:left;
-}
-.formControl .textInput
-{
-    width:300px;
-}
-
-.formControl textarea
-{
-    width:425px;
-    height:100px;
-}
-
-.formControl .tag
-{
-    width:425px;
-}
-
-.formControl .richText
-{
-    margin-top:10px;
-    width:500px;
-    height:440px;
-}
-
-.formWideLabel
-{
-    width:500px;
-}
-
-.formBigLabel
-{
-    margin-top:20px;
-    font-size:20px;
-}
-
-.formControlBelow
-{
-    clear:both;
-    margin-top:10px;
-    width:500px;
-}
-
-.required
-{
-    color: Red;
-}
-.helpText
-{
-    color: #9D9D9D;
-    font-style: italic;
-}
-
-#agreementSummary
-{
-    clear:both;
-    margin-top:10px;
-    width:800px;
-}
-
-.field-validation-error, .validation-summary-errors
-{
-    color: #FF0000;
-    font-weight: bold;
-}
-
-.tinyMCETemplate {
-    position: relative;
-    left: 400px;
-    width: 300px;
-    max-height: 300px;
-    overflow: auto;
-}
-
-.IE6 .tinyMCETemplate {
-    left: 25px;
-}
-
-.ownerBar {
-    padding: 5px;
-}
-.ownerBar .ownerBarOptions {
-    float: right;
-}
diff --git a/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css b/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
deleted file mode 100644
index e3f039dfb..000000000
--- a/samples/winrt/ImageManipulations/description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css
+++ /dev/null
@@ -1,303 +0,0 @@
-/*Global*/
-h1 {
-    font-size: 36px;
-    font-family: 'Segoe UI Light';
-    color: #707070;
-    font-weight: normal;
-    margin-bottom: 17px !important;
-}
-
-h2, h3, h4, h5, h6, #searchPage h3 {
-    font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
-    font-weight:normal;
-    color: #2A2A2A !important;
-}
-
-a, a:link, a:visited {
-    color: #0095c4;
-}
-
-body {
-    color:#707070;
-}
-
-.profile-usercard {
-    color:#707070 !important;
-}
-
-/*temporary setting to override msdn_windows.css
-can remove once conflicting settings are removed from that file*/
-
-
-.LocalNavigation, .LocalNavigation .TabOn, .LocalNavigation .TabOn:hover, .LocalNavigation .TabOff, .LocalNavigation .TabOff a:hover {
-    display: block;
-    background-color:transparent !important;
-    color: #0095c4;
-}
-
-.LocalNavigation .TabOff a {
-color:#707070 ;
-}
-
-/*End Global*/
-
-.EyebrowContainer 
-{
-    margin-bottom: 0 !important;
-}
-
-#sideNav
-{
-    width: 215px !important;
-}
-
-#searchPage #mainContentContainer
-{
-    margin-right:0 !important;
-    margin-left:243px !important;
-}
-
-#searchPage .dirSubHeading h2 
-{
-    font-size: 14px !important;
-    font-weight: normal !important;
-    color: #454545 !important;
-    line-height: 1.45;
-}
-
-#searchPage #directoryListFooter, #searchPage #Pager {
-    font-size: 14px;
-}
-
-#searchPage h2, #searchPage h3
-{
-    font-size: 1.25em  !important;
-}
-
-#sideNav #contributeSection h3, .sidebar #contributeSection h3, #contributeSection h3
-{
-    font-size: 1.65em !important;
-}
-
-.subMenu > h2
-{
-    font-family: 'Segoe UI Light','Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
-    font-weight:normal;
-    font-size:30px;
-    margin: 15px 10px 5px 0;
-    padding-bottom:0px;
-}
-
-.itemRow {
-}
-    .itemRow .itemBody, .itemRow .itemInfo {
-        padding: 18px 17px 20px 0;
-         font-size: 14px;
-         line-height: 1.45em;
-    }
-
-    .itemRow .itemTitle {
-        font-weight: normal;
-    }
-
-    .itemRow .summaryBox{
-        color: #454545;
-    }
-
-    .Samples #MainContent .itemRow .itemTitle a {
-        font-weight: 600 !important;
-        line-height: 1.45;
-    }
-    #MainContent a.officialMicrosoftLabel
-    {
-        color: #ACACAC;
-    }
-
-
-.tabContents {
-    border-top-width:0px;
-}
-   
-#UploadPage {
-    margin: 0px 0px 0px 10px;
-}
-    #UploadPage h1 {
-        padding: 0;
-        font-size: 22px;
-    }
-    #UploadPage h2 {
-        color:#F39700 !important;
-    }
-
-    #UploadPage #uploadPageInstruction {
-        margin-top:10px;
-    }
-        
-    #UploadPage fieldset {
-        margin-left:0px;
-    }
-
-    #UploadPage fieldset h2 {
-        font-weight:normal;
-    }
-
-    #UploadPage fieldset#uploadsForm{
-        margin-top:25px;
-    }
-    
-    #UploadPage fieldset#summary textarea {
-        margin-left:0px;
-    }
-
-    #UploadPage .projectTypeChoice > div {
-        height: 250px;
-    }
-
-#sideNav {
-}
-
-    #sideNav .section h3 {
-        background-color: transparent;
-
-    }
-
-    #sideNav .section UL LI {
-        border-bottom-width: 0px;
-    }
-
-    #sideNav .section form > div {
-        border-bottom: none;
-        color: #707070;
-    }
-        #sideNav .section ul li > div.itemCount
-        {
-            color: #707070;
-        }
-
-
-#searchPage {
-}
-
-    #searchPage h2, #searchPage h3 {
-        text-transform:none;
-        background-color:transparent;
-        font-weight:normal;
-        font-size:1.2em;
-    }
-
-    #searchPage .browseFilterBar {
-        background-color:transparent;
-        border-width:0px;
-        font-weight:normal;
-    }
-
-#requestsPage {
-    padding-top:15px;
-}
-    #requestsPage .tabHeaders {
-        overflow: visible;
-    }
-
-    #requestsPage #requestsList {
-        border: none;
-    }
-
-
-    #requestsPage h2, #requestsPage h3 {
-        text-transform:none;
-        background-color:transparent;
-        font-weight:normal;
-        font-size:1.2em;
-    }
-
-    .reqBrowseContent .title {
-        font-weight: bold !important;
-        color:#000 !important;
-        font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
-    }
-
-    .reqDescPage #header #votenumber {
-        height: 30px;
-        padding: 9px 12px 3px 12px;
-    }
-
-#extraActions {
-}
-    #extraActions .section
-    {
-        margin-bottom: 10px;
-    }
-    #extraActions .section a
-    {
-        font-weight:normal;
-    }
-
-    #extraActions #contributeSection div img {
-        width:0px;
-    }
-
-
-
-#projectPage {
-}
-
-    #projectPage .projectTitle {
-        color: #707070;
-        margin: 5px 0px 15px 0px;
-    }
-
-    #projectPage h2.projectSummary, #projectPage #projectInfo, #projectPage .tabHeaders {
-        font-size: 14px !important;
-        line-height: 1.45em;
-        color: #454545 !important;
-        font-weight: normal !important;
-    }
-
-    #projectPage #projectInfo a {
-        color: #00749e;
-    }
-
-    #projectPage #Downloads a, #projectPage #Downloads label {
-        font-size: 14px;
-    }
-
-    #projectPage #reportAbuse {
-        font-size: 1em;
-    }
-
-    #projectPage #publishBar a, #projectPage #publishBar a:visited {
-        color: #0095c4;
-        font-weight: normal;
-    }
-
-    #projectPage #Collections .bevelButton{
-        background-color: #F8F8F8;
-        color: #0095C4;
-        border: 1px solid #707070;
-    }
-
-    #projectPage #DiscussionsTabPane .threadHeader .title {
-        font-weight:bold !important;
-        color:Black !important;#F8F8F8;
-        font-family: 'Segoe UI', 'Lucida Grande', Verdana, Arial, Helvetica, sans-serif !important;
-    }
-
-    #projectPage .sidebar .section .titleBar h3 {
-        font-weight:normal;
-        font-size:1.2em;
-    }
-
-#LocalNav {
-}
-
-    #LocalNav.HeaderTabs {
-        margin-left:11px;
-    }
-
-
-#searchPage .dirSubHeading h1
-{
-    margin-bottom:17px !important;
-}
-
-
diff --git a/samples/winrt/ImageManipulations/description/iframedescription.css b/samples/winrt/ImageManipulations/description/iframedescription.css
deleted file mode 100644
index 9abc9cdb3..000000000
--- a/samples/winrt/ImageManipulations/description/iframedescription.css
+++ /dev/null
@@ -1,179 +0,0 @@
-body {
-    color: #000000;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 0.813em;
-    font-style: normal;
-    word-wrap: break-word;
-}
-
-/*BEGIN HEADERS*/
-.h1, h1 {
-    color: #3A3E43;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 1.4em;
-    font-weight: bold;
-    margin: 0;
-}
-
-.h2, h2 {
-    color: #3A3E43;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 1.2em;
-    font-weight: bold;
-}
-.h3, h3 {
-    color: #3A3E43;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 1.077em;
-    font-weight: bold;
-}
-.h4, h4 {
-    color: #3A3E43;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 1em;
-    font-weight: bold;
-}
-h4.subHeading {
-    margin-bottom: 7px;
-    margin-top: 13px;
-}
-/*END HEADERS*/
-
-/*BEGIN LINKS*/
-a:link {
-    color: #00749E;
-    text-decoration: none;
-}
-a:hover {
-    text-decoration: underline;
-}
-a:visited {
-    color: #960BB4;
-    text-decoration: none;
-}
-a:focus {
-    outline: 1px dotted #000000;
-}
-
-a.libraryLink:link {
-    text-decoration:none;
-    border-bottom:1px dotted;
-}
-
-/*END LINKS*/
-
-/*BEGIN IMAGES*/
-img {
-    border: 0 none;
-}
-/*END IMAGES*/
-
-/*BEGIN TABLE*/
-.title table {
-    color: #000000;
-    font-family: 'Segoe UI',Verdana,Arial;
-    font-size: 1.077em;
-    font-style: normal;
-}
-table {
-    border-collapse: collapse;
-}
-
-table, table th, table td {
-    border:1px solid #BBBBBB;
-}
-/*END TABLE*/
-
-/*BEGIN LIST*/
-ul {
-    list-style-type: disc;
-    margin-left:40px;
-    padding-left: 0;
-}
-ul li {
-    padding-bottom: 10px;
-}
-ol {
-    margin-left:40px;
-    padding-left: 0;
-}
-ol li {
-    padding-bottom: 10px;
-}
-/*END LIST*/
-
-.scriptcode {
-    position: relative;
-    padding: 8px 8px 8px 8px;
-    background: #FFFFFF;
-    font-size: 12px;
-    line-height: 125%;
-    font-weight:normal;
-}
-.scriptcode pre 
-{ 
-    white-space: pre-wrap !important;       /* css-3 */
-    word-wrap: break-word !important;       /* Internet Explorer 5.5+ */
-    margin:0 0 10px 0 !important;
-    padding: 10px;
-    border-top: solid 2px #D0D2D2;
-    border-bottom: solid 2px #D0D2D2;
-    border-left: solid 1px #D0D2D2;
-    border-right: solid 1px #D0D2D2;
-}
-            
-.scriptcode .title { 
-    color:#E66A38;
-    font-size: 12px;
-    font-weight:bold;
-    margin: 0;
-    min-height: 23px;
-}
-.scriptcode .title > span:first-child {
-    border-left: solid 1px #D0D2D2;
-}
-.scriptcode .title > span {
-    padding: 4px 8px 4px 8px;
-    display: inline-block;
-    border-top: 1px solid #D0D2D2;
-    border-right: 1px solid #D0D2D2;
-    border-collapse: collapse;
-    text-align: center;
-    background: white;
-}
-.scriptcode .title > span.otherTab {
-    color: #1364C4;
-    background: #EFF5FF;
-    cursor: pointer;
-}
-
-.scriptcode .hidden {
-    display: none !important;
-    visibility: hidden !important;
-}
-
-.scriptcode  .copyCode {
-    padding: 8px 2px 0 2px !important;
-    margin-right: 15px;
-    position: absolute !important;
-    right: 0 !important;
-    top: 17px;
-    display:block !important;
-    background: #FFFFFF;
-}
-.scriptcode .pluginLinkHolder {
-    display: none;
-}
-.scriptcode .pluginEditHolderLink {
-    display: none;
-}
-
-.Opera wbr
-{
-    display: inline-block;
-}
-
-.IE9 wbr:after
-{
-content: "\00200B"; 
-}
diff --git a/samples/winrt/ImageManipulations/description/offline.js b/samples/winrt/ImageManipulations/description/offline.js
deleted file mode 100644
index f5d07c8af..000000000
--- a/samples/winrt/ImageManipulations/description/offline.js
+++ /dev/null
@@ -1,52 +0,0 @@
-var Galleries = Galleries || { };
-
-(function() {
-
-    function findElem(parent, tagName, className) {
-        var elemToSearch = (parent) ?  parent : document.body;
-        var tagMatch = elemToSearch.getElementsByTagName(tagName);
-        var evaluator = function(elem) {
-            return (className) ? (elem.className.indexOf(className) > -1) : true;
-        };
-
-        return findArrayElem(tagMatch, evaluator);
-    }
-
-    function findArrayElem(array, evaluator) {
-        var newArray = new Array();
-        for (var count = 0; count < array.length; count++) {
-            if (evaluator(array[count])) {
-                newArray.push(array[count]);
-            }
-        }
-        return newArray;
-    }
-
-    function iterateElem(elems, delegate) {
-        for(var count = 0; count < elems.length; count++) {
-            delegate(count, elems[count]);
-        }
-    }
-
-    function isHidden(elem) {
-        return (elem.offsetHeight === 0 && elem.offsetWidth === 0) || elem.style && elem.style.display === "none";
-    }
-    
-    function onWindowLoad(callback) {
-        attachEventHandler(null, 'load', callback);
-    }
- 
-    function attachEventHandler(elem, event, callback) {
-        var elemToAttach = (elem) ? elem : window;
-        if (document.addEventListener) {
-			elemToAttach.addEventListener(event, callback, false);
-		} else if ( document.attachEvent ) {
-			elemToAttach.attachEvent('on' + event, callback);
-		}
-    }
-
-    Galleries.findElem = findElem;
-    Galleries.iterateElem = iterateElem;
-    Galleries.attachEventHandler = attachEventHandler;
-    Galleries.onWindowLoad = onWindowLoad;
-})();
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/license.rtf b/samples/winrt/ImageManipulations/license.rtf
deleted file mode 100644
index 690a7ad07..000000000
--- a/samples/winrt/ImageManipulations/license.rtf
+++ /dev/null
@@ -1,25 +0,0 @@
-{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 MS Shell Dlg;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs16\f2\cf0 \cf0\ql{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
-{\fs40\f2 {\ltrch MICROSOFT LIMITED PUBLIC LICENSE version 1.1}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 \line {\ltrch ----------------------}\line \li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch This license governs use of code marked as \ldblquote sample\rdblquote  or \ldblquote example\rdblquote  available on this web site without a license agreement, as provided under the section above titled \ldblquote NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEB SITE.\rdblquote  If you use such code (the \ldblquote software\rdblquote ), you accept this license. If you do not accept the license, do not use the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch 1. Definitions}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch The terms \ldblquote reproduce,\rdblquote  \ldblquote reproduction,\rdblquote  \ldblquote derivative works,\rdblquote  and \ldblquote distribution\rdblquote  have the same meaning here as under U.S. copyright law. }\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch A \ldblquote contribution\rdblquote  is the original software, or any additions or changes to the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch A \ldblquote contributor\rdblquote  is any person that distributes its contribution under this license.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch \ldblquote Licensed patents\rdblquote  are a contributor\rquote s patent claims that read directly on its contribution.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch 2. Grant of Rights}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch 3. Conditions and Limitations}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (A) No Trademark License- This license does not grant you rights to use any contributors\rquote  name, logo, or trademarks.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (E) The software is licensed \ldblquote as-is.\rdblquote  You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 {\ltrch (F) Platform Limitation - The licenses granted in sections 2(A) and 2(B) extend only to the software or derivative works that you create that run directly on a Microsoft Windows operating system product, Microsoft run-time technology (such as the .NET Framework or Silverlight), or Microsoft application platform (such as Microsoft Office or Microsoft Dynamics).}\li0\ri0\sa0\sb0\fi0\ql\par}
-{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par}
-}
-}
\ No newline at end of file
diff --git a/samples/winrt/ImageManipulations/C++/pch.cpp b/samples/winrt/ImageManipulations/pch.cpp
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/pch.cpp
rename to samples/winrt/ImageManipulations/pch.cpp
diff --git a/samples/winrt/ImageManipulations/C++/pch.h b/samples/winrt/ImageManipulations/pch.h
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/pch.h
rename to samples/winrt/ImageManipulations/pch.h
diff --git a/samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml b/samples/winrt/ImageManipulations/sample-utils/SampleTemplateStyles.xaml
similarity index 100%
rename from samples/winrt/ImageManipulations/C++/sample-utils/SampleTemplateStyles.xaml
rename to samples/winrt/ImageManipulations/sample-utils/SampleTemplateStyles.xaml

From dcc4766129947853344a3cbb4819d2adcbb62b20 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Thu, 27 Jun 2013 09:57:42 +0800
Subject: [PATCH 44/75] Fix white-spacing

---
 modules/ocl/perf/perf_opticalflow.cpp         |  29 +-
 .../ocl/src/opencl/optical_flow_farneback.cl  |  58 ++--
 modules/ocl/src/optical_flow_farneback.cpp    | 317 +++++++++---------
 3 files changed, 207 insertions(+), 197 deletions(-)

diff --git a/modules/ocl/perf/perf_opticalflow.cpp b/modules/ocl/perf/perf_opticalflow.cpp
index 2b01e1955..936d7a77f 100644
--- a/modules/ocl/perf/perf_opticalflow.cpp
+++ b/modules/ocl/perf/perf_opticalflow.cpp
@@ -136,11 +136,13 @@ PERFTEST(PyrLKOpticalFlow)
             size_t mismatch = 0;
             for (int i = 0; i < (int)nextPts.size(); ++i)
             {
-                if(status[i] != ocl_status.at<unsigned char>(0, i)){
+                if(status[i] != ocl_status.at<unsigned char>(0, i))
+                {
                     mismatch++;
                     continue;
                 }
-                if(status[i]){
+                if(status[i])
+                {
                     Point2f gpu_rst = ocl_nextPts.at<Point2f>(0, i);
                     Point2f cpu_rst = nextPts[i];
                     if(fabs(gpu_rst.x - cpu_rst.x) >= 1. || fabs(gpu_rst.y - cpu_rst.y) >= 1.)
@@ -193,24 +195,24 @@ PERFTEST(tvl1flow)
     WARMUP_ON;
     d_alg(d0, d1, d_flowx, d_flowy);
     WARMUP_OFF;
-/*
-    double diff1 = 0.0, diff2 = 0.0;
-    if(ExceptedMatSimilar(gold[0], cv::Mat(d_flowx), 3e-3, diff1) == 1
-        &&ExceptedMatSimilar(gold[1], cv::Mat(d_flowy), 3e-3, diff2) == 1)
-        TestSystem::instance().setAccurate(1);
-    else
-        TestSystem::instance().setAccurate(0);
+    /*
+        double diff1 = 0.0, diff2 = 0.0;
+        if(ExceptedMatSimilar(gold[0], cv::Mat(d_flowx), 3e-3, diff1) == 1
+            &&ExceptedMatSimilar(gold[1], cv::Mat(d_flowy), 3e-3, diff2) == 1)
+            TestSystem::instance().setAccurate(1);
+        else
+            TestSystem::instance().setAccurate(0);
 
-    TestSystem::instance().setDiff(diff1);
-    TestSystem::instance().setDiff(diff2);
-*/
+        TestSystem::instance().setDiff(diff1);
+        TestSystem::instance().setDiff(diff2);
+    */
 
 
     GPU_ON;
     d_alg(d0, d1, d_flowx, d_flowy);
     d_alg.collectGarbage();
     GPU_OFF;
-    
+
 
     cv::Mat flowx, flowy;
 
@@ -352,4 +354,3 @@ PERFTEST(FarnebackOpticalFlow)
         }
     }
 }
-
diff --git a/modules/ocl/src/opencl/optical_flow_farneback.cl b/modules/ocl/src/opencl/optical_flow_farneback.cl
index 2e5c6d960..7cc564ede 100644
--- a/modules/ocl/src/opencl/optical_flow_farneback.cl
+++ b/modules/ocl/src/opencl/optical_flow_farneback.cl
@@ -71,7 +71,7 @@ __kernel void polynomialExpansion(__global float * dst,
 
     dstStep /= sizeof(*dst);
     srcStep /= sizeof(*src);
-    
+
     int xWarped;
     __local float *row = smem + tx;
 
@@ -168,7 +168,7 @@ __kernel void gaussianBlur(__global float * dst,
     srcStep /= sizeof(*src);
 
     __local float *row = smem + ty * (bdx + 2*ksizeHalf);
-    
+
     if (y < height)
     {
         // Vertical pass
@@ -184,7 +184,7 @@ __kernel void gaussianBlur(__global float * dst,
     }
 
     barrier(CLK_LOCAL_MEM_FENCE);
-        
+
     if (y < height && y >= 0 && x < width && x >= 0)
     {
         // Horizontal pass
@@ -207,7 +207,7 @@ __kernel void updateMatrices(__global float * M,
 {
     const int y = get_global_id(1);
     const int x = get_global_id(0);
-    
+
     mStep /= sizeof(*M);
     xStep /= sizeof(*flowx);
     yStep /= sizeof(*flowy);
@@ -223,7 +223,8 @@ __kernel void updateMatrices(__global float * M,
 
         int x1 = convert_int(floor(fx));
         int y1 = convert_int(floor(fy));
-        fx -= x1; fy -= y1;
+        fx -= x1;
+        fy -= y1;
 
         float r2, r3, r4, r5, r6;
 
@@ -278,13 +279,16 @@ __kernel void updateMatrices(__global float * M,
         r3 += r6*dy + r5*dx;
 
         float scale =
-                c_border[min(x, BORDER_SIZE)] *
-                c_border[min(y, BORDER_SIZE)] *
-                c_border[min(width - x - 1, BORDER_SIZE)] *
-                c_border[min(height - y - 1, BORDER_SIZE)];
+            c_border[min(x, BORDER_SIZE)] *
+            c_border[min(y, BORDER_SIZE)] *
+            c_border[min(width - x - 1, BORDER_SIZE)] *
+            c_border[min(height - y - 1, BORDER_SIZE)];
 
-        r2 *= scale; r3 *= scale; r4 *= scale;
-        r5 *= scale; r6 *= scale;
+        r2 *= scale;
+        r3 *= scale;
+        r4 *= scale;
+        r5 *= scale;
+        r6 *= scale;
 
         M[mad24(y, mStep, x)] = r4*r4 + r6*r6;
         M[mad24(height + y, mStep, x)] = (r4 + r5)*r6;
@@ -303,7 +307,7 @@ __kernel void boxFilter5(__global float * dst,
 {
     const int y = get_global_id(1);
     const int x = get_global_id(0);
-        
+
     const float boxAreaInv = 1.f / ((1 + 2*ksizeHalf) * (1 + 2*ksizeHalf));
     const int smw = bdx + 2*ksizeHalf; // shared memory "width"
     __local float *row = smem + 5 * ty * smw;
@@ -319,16 +323,16 @@ __kernel void boxFilter5(__global float * dst,
             int xExt = (int)(bx * bdx) + i - ksizeHalf;
             xExt = min(max(xExt, 0), width - 1);
 
-            #pragma unroll
+#pragma unroll
             for (int k = 0; k < 5; ++k)
                 row[k*smw + i] = src[mad24(k*height + y, srcStep, xExt)];
 
             for (int j = 1; j <= ksizeHalf; ++j)
-                #pragma unroll
+#pragma unroll
                 for (int k = 0; k < 5; ++k)
                     row[k*smw + i] +=
-                            src[mad24(k*height + max(y - j, 0), srcStep, xExt)] +
-                            src[mad24(k*height + min(y + j, height - 1), srcStep, xExt)];
+                        src[mad24(k*height + max(y - j, 0), srcStep, xExt)] +
+                        src[mad24(k*height + min(y + j, height - 1), srcStep, xExt)];
         }
     }
 
@@ -341,16 +345,16 @@ __kernel void boxFilter5(__global float * dst,
         row += tx + ksizeHalf;
         float res[5];
 
-        #pragma unroll
+#pragma unroll
         for (int k = 0; k < 5; ++k)
             res[k] = row[k*smw];
 
         for (int i = 1; i <= ksizeHalf; ++i)
-            #pragma unroll
+#pragma unroll
             for (int k = 0; k < 5; ++k)
                 res[k] += row[k*smw - i] + row[k*smw + i];
 
-        #pragma unroll
+#pragma unroll
         for (int k = 0; k < 5; ++k)
             dst[mad24(k*height + y, dstStep, x)] = res[k] * boxAreaInv;
     }
@@ -372,7 +376,7 @@ __kernel void updateFlow(__global float4 * flowx, __global float4 * flowy,
     {
         float4 g11 = M[mad24(y, mStep, x)];
         float4 g12 = M[mad24(height + y, mStep, x)];
-        float4 g22 = M[mad24(2*height + y, mStep, x)]; 
+        float4 g22 = M[mad24(2*height + y, mStep, x)];
         float4 h1 =  M[mad24(3*height + y, mStep, x)];
         float4 h2 =  M[mad24(4*height + y, mStep, x)];
 
@@ -408,16 +412,16 @@ __kernel void gaussianBlur5(__global float * dst,
             int xExt = (int)(bx * bdx) + i - ksizeHalf;
             xExt = idx_col(xExt, width - 1);
 
-            #pragma unroll
+#pragma unroll
             for (int k = 0; k < 5; ++k)
                 row[k*smw + i] = src[mad24(k*height + y, srcStep, xExt)] * c_gKer[0];
 
             for (int j = 1; j <= ksizeHalf; ++j)
-                #pragma unroll
+#pragma unroll
                 for (int k = 0; k < 5; ++k)
                     row[k*smw + i] +=
-                            (src[mad24(k*height + idx_row_low(y - j, height - 1), srcStep, xExt)] +
-                                src[mad24(k*height + idx_row_high(y + j, height - 1), srcStep, xExt)]) * c_gKer[j];
+                        (src[mad24(k*height + idx_row_low(y - j, height - 1), srcStep, xExt)] +
+                         src[mad24(k*height + idx_row_high(y + j, height - 1), srcStep, xExt)]) * c_gKer[j];
         }
     }
 
@@ -430,16 +434,16 @@ __kernel void gaussianBlur5(__global float * dst,
         row += tx + ksizeHalf;
         float res[5];
 
-        #pragma unroll
+#pragma unroll
         for (int k = 0; k < 5; ++k)
             res[k] = row[k*smw] * c_gKer[0];
 
         for (int i = 1; i <= ksizeHalf; ++i)
-            #pragma unroll
+#pragma unroll
             for (int k = 0; k < 5; ++k)
                 res[k] += (row[k*smw - i] + row[k*smw + i]) * c_gKer[i];
 
-        #pragma unroll
+#pragma unroll
         for (int k = 0; k < 5; ++k)
             dst[mad24(k*height + y, dstStep, x)] = res[k];
     }
diff --git a/modules/ocl/src/optical_flow_farneback.cpp b/modules/ocl/src/optical_flow_farneback.cpp
index 17c021d7c..e5a7abccf 100644
--- a/modules/ocl/src/optical_flow_farneback.cpp
+++ b/modules/ocl/src/optical_flow_farneback.cpp
@@ -55,178 +55,184 @@ using namespace cv::ocl;
 
 namespace cv
 {
-    namespace ocl
-    {
-        ///////////////////////////OpenCL kernel strings///////////////////////////
-        extern const char *optical_flow_farneback;
-    }
+namespace ocl
+{
+///////////////////////////OpenCL kernel strings///////////////////////////
+extern const char *optical_flow_farneback;
+}
 }
 
-namespace cv { namespace ocl { namespace optflow_farneback
+namespace cv {
+namespace ocl {
+namespace optflow_farneback
 {
-    oclMat g;
-    oclMat xg;
-    oclMat xxg;
-    oclMat gKer;
+oclMat g;
+oclMat xg;
+oclMat xxg;
+oclMat gKer;
 
-    float ig[4];
+float ig[4];
 
-    inline int divUp(int total, int grain)
-    {
-        return (total + grain - 1) / grain;
-    }
+inline int divUp(int total, int grain)
+{
+    return (total + grain - 1) / grain;
+}
 
-    inline void setGaussianBlurKernel(const float *c_gKer, int ksizeHalf)
-    {
-        cv::Mat t_gKer(1, ksizeHalf + 1, CV_32FC1, const_cast<float *>(c_gKer));
-        gKer.upload(t_gKer);
-    }
+inline void setGaussianBlurKernel(const float *c_gKer, int ksizeHalf)
+{
+    cv::Mat t_gKer(1, ksizeHalf + 1, CV_32FC1, const_cast<float *>(c_gKer));
+    gKer.upload(t_gKer);
+}
 
-    static void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
-    {
-        string kernelName("gaussianBlur");
-        size_t localThreads[3] = { 256, 1, 1 };
-        size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], src.rows, 1 };
-        int smem_size = (localThreads[0] + 2*ksizeHalf) * sizeof(float);
+static void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
+{
+    string kernelName("gaussianBlur");
+    size_t localThreads[3] = { 256, 1, 1 };
+    size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], src.rows, 1 };
+    int smem_size = (localThreads[0] + 2*ksizeHalf) * sizeof(float);
 
-        CV_Assert(dst.size() == src.size());
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
-        args.push_back(std::make_pair(smem_size, (void *)NULL));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+    CV_Assert(dst.size() == src.size());
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
+    args.push_back(std::make_pair(smem_size, (void *)NULL));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
 
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1);
-    }
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1);
+}
 
-    static void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
-    {
-        string kernelName("polynomialExpansion");
-        size_t localThreads[3] = { 256, 1, 1 };
-        size_t globalThreads[3] = { divUp(src.cols, localThreads[0] - 2*polyN) * localThreads[0], src.rows, 1 };
-        int smem_size = 3 * localThreads[0] * sizeof(float);
+static void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
+{
+    string kernelName("polynomialExpansion");
+    size_t localThreads[3] = { 256, 1, 1 };
+    size_t globalThreads[3] = { divUp(src.cols, localThreads[0] - 2*polyN) * localThreads[0], src.rows, 1 };
+    int smem_size = 3 * localThreads[0] * sizeof(float);
 
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&g.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xg.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xxg.data));
-        args.push_back(std::make_pair(smem_size, (void *)NULL));
-        args.push_back(std::make_pair(sizeof(cl_float4), (void *)&ig));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&g.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xg.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&xxg.data));
+    args.push_back(std::make_pair(smem_size, (void *)NULL));
+    args.push_back(std::make_pair(sizeof(cl_float4), (void *)&ig));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
 
-        char opt [128];
-        sprintf(opt, "-D polyN=%d", polyN);
+    char opt [128];
+    sprintf(opt, "-D polyN=%d", polyN);
 
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1, opt);
-    }
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1, opt);
+}
 
-    static void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
-    {
-        string kernelName("updateMatrices");
-        size_t localThreads[3] = { 32, 8, 1 };
-        size_t globalThreads[3] = { divUp(flowx.cols, localThreads[0]) * localThreads[0],
-                                    divUp(flowx.rows, localThreads[1]) * localThreads[1],
-                                    1 };
+static void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
+{
+    string kernelName("updateMatrices");
+    size_t localThreads[3] = { 32, 8, 1 };
+    size_t globalThreads[3] = { divUp(flowx.cols, localThreads[0]) * localThreads[0],
+                                divUp(flowx.rows, localThreads[1]) * localThreads[1],
+                                1
+                              };
 
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R0.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R1.data));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.cols));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&R0.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&R1.step));
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R0.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&R1.data));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.cols));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&R0.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&R1.step));
 
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1);
-    }
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1);
+}
 
-    static void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
-    {
-        string kernelName("boxFilter5");
-        int height = src.rows / 5;
-        size_t localThreads[3] = { 256, 1, 1 };
-        size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], height, 1 };
-        int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
+static void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+{
+    string kernelName("boxFilter5");
+    int height = src.rows / 5;
+    size_t localThreads[3] = { 256, 1, 1 };
+    size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], height, 1 };
+    int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
 
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
-        args.push_back(std::make_pair(smem_size, (void *)NULL));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+    args.push_back(std::make_pair(smem_size, (void *)NULL));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
 
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1);
-    }
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1);
+}
 
-    static void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
-    {
-        string kernelName("updateFlow");
-        int cols = divUp(flowx.cols, 4);
-        size_t localThreads[3] = { 32, 8, 1 };
-        size_t globalThreads[3] = { divUp(cols, localThreads[0]) * localThreads[0],
-                                    divUp(flowx.rows, localThreads[1]) * localThreads[0],
-                                    1 };
+static void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
+{
+    string kernelName("updateFlow");
+    int cols = divUp(flowx.cols, 4);
+    size_t localThreads[3] = { 32, 8, 1 };
+    size_t globalThreads[3] = { divUp(cols, localThreads[0]) * localThreads[0],
+                                divUp(flowx.rows, localThreads[1]) * localThreads[0],
+                                1
+                              };
 
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
-        
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1);
-    }
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowy.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.rows));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowx.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&flowy.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&M.step));
 
-    static void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
-    {
-        string kernelName("gaussianBlur5");
-        int height = src.rows / 5;
-        int width = src.cols;
-        size_t localThreads[3] = { 256, 1, 1 };
-        size_t globalThreads[3] = { divUp(width, localThreads[0]) * localThreads[0], height, 1 };
-        int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1);
+}
 
-        std::vector< std::pair<size_t, const void *> > args;
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
-        args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
-        args.push_back(std::make_pair(smem_size, (void *)NULL));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&width));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
-        args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+static void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
+{
+    string kernelName("gaussianBlur5");
+    int height = src.rows / 5;
+    int width = src.cols;
+    size_t localThreads[3] = { 256, 1, 1 };
+    size_t globalThreads[3] = { divUp(width, localThreads[0]) * localThreads[0], height, 1 };
+    int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
 
-        openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
-            globalThreads, localThreads, args, -1, -1);
-    }
-}}} // namespace cv { namespace ocl { namespace optflow_farneback
+    std::vector< std::pair<size_t, const void *> > args;
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
+    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&gKer.data));
+    args.push_back(std::make_pair(smem_size, (void *)NULL));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&height));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&width));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.step));
+    args.push_back(std::make_pair(sizeof(cl_int), (void *)&ksizeHalf));
+
+    openCLExecuteKernel(Context::getContext(), &optical_flow_farneback, kernelName,
+                        globalThreads, localThreads, args, -1, -1);
+}
+}
+}
+} // namespace cv { namespace ocl { namespace optflow_farneback
 
 static oclMat allocMatFromBuf(int rows, int cols, int type, oclMat &mat)
 {
@@ -236,8 +242,8 @@ static oclMat allocMatFromBuf(int rows, int cols, int type, oclMat &mat)
 }
 
 void cv::ocl::FarnebackOpticalFlow::prepareGaussian(
-        int n, double sigma, float *g, float *xg, float *xxg,
-        double &ig11, double &ig03, double &ig33, double &ig55)
+    int n, double sigma, float *g, float *xg, float *xxg,
+    double &ig11, double &ig03, double &ig33, double &ig55)
 {
     double s = 0.;
     for (int x = -n; x <= n; x++)
@@ -316,8 +322,8 @@ void cv::ocl::FarnebackOpticalFlow::setPolynomialExpansionConsts(int n, double s
 }
 
 void cv::ocl::FarnebackOpticalFlow::updateFlow_boxFilter(
-        const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
-        oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
+    const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
+    oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
 {
     optflow_farneback::boxFilter5Ocl(M, blockSize/2, bufM);
 
@@ -333,8 +339,8 @@ void cv::ocl::FarnebackOpticalFlow::updateFlow_boxFilter(
 
 
 void cv::ocl::FarnebackOpticalFlow::updateFlow_gaussianBlur(
-        const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
-        oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
+    const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
+    oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices)
 {
     optflow_farneback::gaussianBlur5Ocl(M, blockSize/2, bufM);
 
@@ -348,7 +354,7 @@ void cv::ocl::FarnebackOpticalFlow::updateFlow_gaussianBlur(
 
 
 void cv::ocl::FarnebackOpticalFlow::operator ()(
-        const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy)
+    const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy)
 {
     CV_Assert(frame0.channels() == 1 && frame1.channels() == 1);
     CV_Assert(frame0.size() == frame1.size());
@@ -504,4 +510,3 @@ void cv::ocl::FarnebackOpticalFlow::operator ()(
     flowx = curFlowX;
     flowy = curFlowY;
 }
-

From fc64faa22e3411f0fd32b5112154f999dbec7dbb Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Thu, 27 Jun 2013 10:06:37 +0800
Subject: [PATCH 45/75] Remove empty cv::ocl::CLAHE class.

---
 modules/ocl/include/opencv2/ocl/ocl.hpp | 5 +----
 modules/ocl/perf/perf_imgproc.cpp       | 4 ++--
 modules/ocl/src/imgproc.cpp             | 4 ++--
 modules/ocl/test/test_imgproc.cpp       | 2 +-
 4 files changed, 6 insertions(+), 9 deletions(-)

diff --git a/modules/ocl/include/opencv2/ocl/ocl.hpp b/modules/ocl/include/opencv2/ocl/ocl.hpp
index 35350f01b..8bd1c9f11 100644
--- a/modules/ocl/include/opencv2/ocl/ocl.hpp
+++ b/modules/ocl/include/opencv2/ocl/ocl.hpp
@@ -516,10 +516,7 @@ namespace cv
         CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
         
         //! only 8UC1 is supported now
-        class CV_EXPORTS CLAHE : public cv::CLAHE
-        {
-        };
-        CV_EXPORTS Ptr<cv::ocl::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
+        CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
         
         //! bilateralFilter
         // supports 8UC1 8UC4
diff --git a/modules/ocl/perf/perf_imgproc.cpp b/modules/ocl/perf/perf_imgproc.cpp
index b330c5ffa..ade501914 100644
--- a/modules/ocl/perf/perf_imgproc.cpp
+++ b/modules/ocl/perf/perf_imgproc.cpp
@@ -932,8 +932,8 @@ PERFTEST(CLAHE)
 
     double clipLimit = 40.0;
 
-    cv::Ptr<cv::CLAHE>      clahe   = cv::createCLAHE(clipLimit);
-    cv::Ptr<cv::ocl::CLAHE> d_clahe = cv::ocl::createCLAHE(clipLimit);
+    cv::Ptr<cv::CLAHE> clahe   = cv::createCLAHE(clipLimit);
+    cv::Ptr<cv::CLAHE> d_clahe = cv::ocl::createCLAHE(clipLimit);
 
     for (int size = Min_Size; size <= Max_Size; size *= Multiple)
     {
diff --git a/modules/ocl/src/imgproc.cpp b/modules/ocl/src/imgproc.cpp
index 9d67cd8ae..15c1539c0 100644
--- a/modules/ocl/src/imgproc.cpp
+++ b/modules/ocl/src/imgproc.cpp
@@ -1591,7 +1591,7 @@ namespace cv
 
         namespace
         {
-            class CLAHE_Impl : public cv::ocl::CLAHE
+            class CLAHE_Impl : public cv::CLAHE
             {
             public:
                 CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
@@ -1696,7 +1696,7 @@ namespace cv
             }
         }
 
-        cv::Ptr<cv::ocl::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
+        cv::Ptr<cv::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
         {
             return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
         }
diff --git a/modules/ocl/test/test_imgproc.cpp b/modules/ocl/test/test_imgproc.cpp
index 3a98671d5..3228b6c0c 100644
--- a/modules/ocl/test/test_imgproc.cpp
+++ b/modules/ocl/test/test_imgproc.cpp
@@ -1425,7 +1425,7 @@ PARAM_TEST_CASE(CLAHE, cv::Size, ClipLimit)
 
 TEST_P(CLAHE, Accuracy)
 {
-    cv::Ptr<cv::ocl::CLAHE> clahe = cv::ocl::createCLAHE(clipLimit);
+    cv::Ptr<cv::CLAHE> clahe = cv::ocl::createCLAHE(clipLimit);
     clahe->apply(g_src, g_dst);
     cv::Mat dst(g_dst);
 

From b2da1cdcc2e9b7fd95b3cda7ff8caa9f51c68085 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Thu, 27 Jun 2013 10:20:21 +0800
Subject: [PATCH 46/75] Temporarily disable command queue release as it causes
 program hang at exit

---
 modules/ocl/src/initialization.cpp | 26 ++------------------------
 1 file changed, 2 insertions(+), 24 deletions(-)

diff --git a/modules/ocl/src/initialization.cpp b/modules/ocl/src/initialization.cpp
index d4841fcfd..3dd0ec4ea 100644
--- a/modules/ocl/src/initialization.cpp
+++ b/modules/ocl/src/initialization.cpp
@@ -198,7 +198,8 @@ namespace cv
 
             if(clCmdQueue)
             {
-                openCLSafeCall(clReleaseCommandQueue(clCmdQueue));
+                //temporarily disable command queue release as it causes program hang at exit
+                //openCLSafeCall(clReleaseCommandQueue(clCmdQueue));
                 clCmdQueue = 0;
             }
 
@@ -1075,26 +1076,3 @@ namespace cv
     }//namespace ocl
 
 }//namespace cv
-
-#if defined BUILD_SHARED_LIBS && defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
-#include <windows.h>
-BOOL WINAPI DllMain( HINSTANCE, DWORD  fdwReason, LPVOID );
-
-BOOL WINAPI DllMain( HINSTANCE, DWORD  fdwReason, LPVOID )
-{
-    if( fdwReason == DLL_PROCESS_DETACH )
-    {
-        // application hangs if call clReleaseCommandQueue here, so release context only
-        // without context release application hangs as well
-        context_tear_down = 1;
-        Context* cv_ctx = Context::getContext();
-        if(cv_ctx)
-        {
-            cl_context ctx = cv_ctx->impl->oclcontext;
-            if(ctx)
-                openCLSafeCall(clReleaseContext(ctx));
-        }
-    }
-    return TRUE;
-}
-#endif

From 5de7627806dbd44f8f7ac9cc4c323f56cf193395 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Thu, 27 Jun 2013 11:26:51 +0400
Subject: [PATCH 47/75] Old android folder removed.

The changes must be applied after buildbot update only!
---
 android/android.toolchain.cmake | 1747 -------------------------------
 android/readme.txt              |    1 -
 platforms/readme.txt            |    4 +-
 3 files changed, 3 insertions(+), 1749 deletions(-)
 delete mode 100644 android/android.toolchain.cmake
 delete mode 100644 android/readme.txt

diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
deleted file mode 100644
index 9db174a13..000000000
--- a/android/android.toolchain.cmake
+++ /dev/null
@@ -1,1747 +0,0 @@
-message(STATUS "Android toolchain was moved to platfroms/android!")
-message(STATUS "This file is depricated and will be removed!")
-
-# Copyright (c) 2010-2011, Ethan Rublee
-# Copyright (c) 2011-2013, Andrey Kamaev
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# 1.  Redistributions of source code must retain the above copyright notice,
-#     this list of conditions and the following disclaimer.
-#
-# 2.  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.
-#
-# 3.  The name of the copyright holders 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.
-
-# ------------------------------------------------------------------------------
-#  Android CMake toolchain file, for use with the Android NDK r5-r8
-#  Requires cmake 2.6.3 or newer (2.8.5 or newer is recommended).
-#  See home page: https://github.com/taka-no-me/android-cmake
-#
-#  The file is mantained by the OpenCV project. The latest version can be get at
-#  http://code.opencv.org/projects/opencv/repository/revisions/master/changes/android/android.toolchain.cmake
-#
-#  Usage Linux:
-#   $ export ANDROID_NDK=/absolute/path/to/the/android-ndk
-#   $ mkdir build && cd build
-#   $ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake ..
-#   $ make -j8
-#
-#  Usage Linux (using standalone toolchain):
-#   $ export ANDROID_STANDALONE_TOOLCHAIN=/absolute/path/to/android-toolchain
-#   $ mkdir build && cd build
-#   $ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake ..
-#   $ make -j8
-#
-#  Usage Windows:
-#     You need native port of make to build your project.
-#     Android NDK r7 (or newer) already has make.exe on board.
-#     For older NDK you have to install it separately.
-#     For example, this one: http://gnuwin32.sourceforge.net/packages/make.htm
-#
-#   $ SET ANDROID_NDK=C:\absolute\path\to\the\android-ndk
-#   $ mkdir build && cd build
-#   $ cmake.exe -G"MinGW Makefiles"
-#       -DCMAKE_TOOLCHAIN_FILE=path\to\the\android.toolchain.cmake
-#       -DCMAKE_MAKE_PROGRAM="%ANDROID_NDK%\prebuilt\windows\bin\make.exe" ..
-#   $ cmake.exe --build .
-#
-#
-#  Options (can be set as cmake parameters: -D<option_name>=<value>):
-#    ANDROID_NDK=/opt/android-ndk - path to the NDK root.
-#      Can be set as environment variable. Can be set only at first cmake run.
-#
-#    ANDROID_STANDALONE_TOOLCHAIN=/opt/android-toolchain - path to the
-#      standalone toolchain. This option is not used if full NDK is found
-#      (ignored if ANDROID_NDK is set).
-#      Can be set as environment variable. Can be set only at first cmake run.
-#
-#    ANDROID_ABI=armeabi-v7a - specifies the target Application Binary
-#      Interface (ABI). This option nearly matches to the APP_ABI variable
-#      used by ndk-build tool from Android NDK.
-#
-#      Possible targets are:
-#        "armeabi" - matches to the NDK ABI with the same name.
-#           See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation.
-#        "armeabi-v7a" - matches to the NDK ABI with the same name.
-#           See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation.
-#        "armeabi-v7a with NEON" - same as armeabi-v7a, but
-#            sets NEON as floating-point unit
-#        "armeabi-v7a with VFPV3" - same as armeabi-v7a, but
-#            sets VFPV3 as floating-point unit (has 32 registers instead of 16).
-#        "armeabi-v6 with VFP" - tuned for ARMv6 processors having VFP.
-#        "x86" - matches to the NDK ABI with the same name.
-#            See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation.
-#        "mips" - matches to the NDK ABI with the same name
-#            (It is not tested on real devices by the authos of this toolchain)
-#            See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation.
-#
-#    ANDROID_NATIVE_API_LEVEL=android-8 - level of Android API compile for.
-#      Option is read-only when standalone toolchain is used.
-#
-#    ANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-4.6 - the name of compiler
-#      toolchain to be used. The list of possible values depends on the NDK
-#      version. For NDK r8c the possible values are:
-#
-#        * arm-linux-androideabi-4.4.3
-#        * arm-linux-androideabi-4.6
-#        * arm-linux-androideabi-clang3.1
-#        * mipsel-linux-android-4.4.3
-#        * mipsel-linux-android-4.6
-#        * mipsel-linux-android-clang3.1
-#        * x86-4.4.3
-#        * x86-4.6
-#        * x86-clang3.1
-#
-#    ANDROID_FORCE_ARM_BUILD=OFF - set ON to generate 32-bit ARM instructions
-#      instead of Thumb. Is not available for "x86" (inapplicable) and
-#      "armeabi-v6 with VFP" (is forced to be ON) ABIs.
-#
-#    ANDROID_NO_UNDEFINED=ON - set ON to show all undefined symbols as linker
-#      errors even if they are not used.
-#
-#    ANDROID_SO_UNDEFINED=OFF - set ON to allow undefined symbols in shared
-#      libraries. Automatically turned for NDK r5x and r6x due to GLESv2
-#      problems.
-#
-#    LIBRARY_OUTPUT_PATH_ROOT=${CMAKE_SOURCE_DIR} - where to output binary
-#      files. See additional details below.
-#
-#    ANDROID_SET_OBSOLETE_VARIABLES=ON - if set, then toolchain defines some
-#      obsolete variables which were used by previous versions of this file for
-#      backward compatibility.
-#
-#    ANDROID_STL=gnustl_static - specify the runtime to use.
-#
-#      Possible values are:
-#        none           -> Do not configure the runtime.
-#        system         -> Use the default minimal system C++ runtime library.
-#                          Implies -fno-rtti -fno-exceptions.
-#                          Is not available for standalone toolchain.
-#        system_re      -> Use the default minimal system C++ runtime library.
-#                          Implies -frtti -fexceptions.
-#                          Is not available for standalone toolchain.
-#        gabi++_static  -> Use the GAbi++ runtime as a static library.
-#                          Implies -frtti -fno-exceptions.
-#                          Available for NDK r7 and newer.
-#                          Is not available for standalone toolchain.
-#        gabi++_shared  -> Use the GAbi++ runtime as a shared library.
-#                          Implies -frtti -fno-exceptions.
-#                          Available for NDK r7 and newer.
-#                          Is not available for standalone toolchain.
-#        stlport_static -> Use the STLport runtime as a static library.
-#                          Implies -fno-rtti -fno-exceptions for NDK before r7.
-#                          Implies -frtti -fno-exceptions for NDK r7 and newer.
-#                          Is not available for standalone toolchain.
-#        stlport_shared -> Use the STLport runtime as a shared library.
-#                          Implies -fno-rtti -fno-exceptions for NDK before r7.
-#                          Implies -frtti -fno-exceptions for NDK r7 and newer.
-#                          Is not available for standalone toolchain.
-#        gnustl_static  -> Use the GNU STL as a static library.
-#                          Implies -frtti -fexceptions.
-#        gnustl_shared  -> Use the GNU STL as a shared library.
-#                          Implies -frtti -fno-exceptions.
-#                          Available for NDK r7b and newer.
-#                          Silently degrades to gnustl_static if not available.
-#
-#    ANDROID_STL_FORCE_FEATURES=ON - turn rtti and exceptions support based on
-#      chosen runtime. If disabled, then the user is responsible for settings
-#      these options.
-#
-#  What?:
-#    android-cmake toolchain searches for NDK/toolchain in the following order:
-#      ANDROID_NDK - cmake parameter
-#      ANDROID_NDK - environment variable
-#      ANDROID_STANDALONE_TOOLCHAIN - cmake parameter
-#      ANDROID_STANDALONE_TOOLCHAIN - environment variable
-#      ANDROID_NDK - default locations
-#      ANDROID_STANDALONE_TOOLCHAIN - default locations
-#
-#    Make sure to do the following in your scripts:
-#      SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${my_cxx_flags}" )
-#      SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${my_cxx_flags}" )
-#    The flags will be prepopulated with critical flags, so don't loose them.
-#    Also be aware that toolchain also sets configuration-specific compiler
-#    flags and linker flags.
-#
-#    ANDROID and BUILD_ANDROID will be set to true, you may test any of these
-#    variables to make necessary Android-specific configuration changes.
-#
-#    Also ARMEABI or ARMEABI_V7A or X86 or MIPS will be set true, mutually
-#    exclusive. NEON option will be set true if VFP is set to NEON.
-#
-#    LIBRARY_OUTPUT_PATH_ROOT should be set in cache to determine where Android
-#    libraries will be installed.
-#    Default is ${CMAKE_SOURCE_DIR}, and the android libs will always be
-#    under the ${LIBRARY_OUTPUT_PATH_ROOT}/libs/${ANDROID_NDK_ABI_NAME}
-#    (depending on the target ABI). This is convenient for Android packaging.
-#
-#  Change Log:
-#   - initial version December 2010
-#   - April 2011
-#     [+] added possibility to build with NDK (without standalone toolchain)
-#     [+] support cross-compilation on Windows (native, no cygwin support)
-#     [+] added compiler option to force "char" type to be signed
-#     [+] added toolchain option to compile to 32-bit ARM instructions
-#     [+] added toolchain option to disable SWIG search
-#     [+] added platform "armeabi-v7a with VFPV3"
-#     [~] ARM_TARGETS renamed to ARM_TARGET
-#     [+] EXECUTABLE_OUTPUT_PATH is set by toolchain (required on Windows)
-#     [~] Fixed bug with ANDROID_API_LEVEL variable
-#     [~] turn off SWIG search if it is not found first time
-#   - May 2011
-#     [~] ANDROID_LEVEL is renamed to ANDROID_API_LEVEL
-#     [+] ANDROID_API_LEVEL is detected by toolchain if not specified
-#     [~] added guard to prevent changing of output directories on the first
-#         cmake pass
-#     [~] toolchain exits with error if ARM_TARGET is not recognized
-#   - June 2011
-#     [~] default NDK path is updated for version r5c
-#     [+] variable CMAKE_SYSTEM_PROCESSOR is set based on ARM_TARGET
-#     [~] toolchain install directory is added to linker paths
-#     [-] removed SWIG-related stuff from toolchain
-#     [+] added macro find_host_package, find_host_program to search
-#         packages/programs on the host system
-#     [~] fixed path to STL library
-#   - July 2011
-#     [~] fixed options caching
-#     [~] search for all supported NDK versions
-#     [~] allowed spaces in NDK path
-#   - September 2011
-#     [~] updated for NDK r6b
-#   - November 2011
-#     [*] rewritten for NDK r7
-#     [+] x86 toolchain support (experimental)
-#     [+] added "armeabi-v6 with VFP" ABI for ARMv6 processors.
-#     [~] improved compiler and linker flags management
-#     [+] support different build flags for Release and Debug configurations
-#     [~] by default compiler flags the same as used by ndk-build (but only
-#         where reasonable)
-#     [~] ANDROID_NDK_TOOLCHAIN_ROOT is splitted to ANDROID_STANDALONE_TOOLCHAIN
-#         and ANDROID_TOOLCHAIN_ROOT
-#     [~] ARM_TARGET is renamed to ANDROID_ABI
-#     [~] ARMEABI_NDK_NAME is renamed to ANDROID_NDK_ABI_NAME
-#     [~] ANDROID_API_LEVEL is renamed to ANDROID_NATIVE_API_LEVEL
-#   - January 2012
-#     [+] added stlport_static support (experimental)
-#     [+] added special check for cygwin
-#     [+] filtered out hidden files (starting with .) while globbing inside NDK
-#     [+] automatically applied GLESv2 linkage fix for NDK revisions 5-6
-#     [+] added ANDROID_GET_ABI_RAWNAME to get NDK ABI names by CMake flags
-#   - February 2012
-#     [+] updated for NDK r7b
-#     [~] fixed cmake try_compile() command
-#     [~] Fix for missing install_name_tool on OS X
-#   - March 2012
-#     [~] fixed incorrect C compiler flags
-#     [~] fixed CMAKE_SYSTEM_PROCESSOR change on ANDROID_ABI change
-#     [+] improved toolchain loading speed
-#     [+] added assembler language support (.S)
-#     [+] allowed preset search paths and extra search suffixes
-#   - April 2012
-#     [+] updated for NDK r7c
-#     [~] fixed most of problems with compiler/linker flags and caching
-#     [+] added option ANDROID_FUNCTION_LEVEL_LINKING
-#   - May 2012
-#     [+] updated for NDK r8
-#     [+] added mips architecture support
-#   - August 2012
-#     [+] updated for NDK r8b
-#     [~] all intermediate files generated by toolchain are moved to CMakeFiles
-#     [~] libstdc++ and libsupc are removed from explicit link libraries
-#     [+] added CCache support (via NDK_CCACHE environment or cmake variable)
-#     [+] added gold linker support for NDK r8b
-#     [~] fixed mips linker flags for NDK r8b
-#   - September 2012
-#     [+] added NDK release name detection (see ANDROID_NDK_RELEASE)
-#     [+] added support for all C++ runtimes from NDK
-#         (system, gabi++, stlport, gnustl)
-#     [+] improved warnings on known issues of NDKs
-#     [~] use gold linker as default if available (NDK r8b)
-#     [~] globally turned off rpath
-#     [~] compiler options are aligned with NDK r8b
-#   - October 2012
-#     [~] fixed C++ linking: explicitly link with math library (OpenCV #2426)
-#   - November 2012
-#     [+] updated for NDK r8c
-#     [+] added support for clang compiler
-#   - December 2012
-#     [+] suppress warning about unused CMAKE_TOOLCHAIN_FILE variable
-#     [+] adjust API level to closest compatible as NDK does
-#     [~] fixed ccache full path search
-#     [+] updated for NDK r8d
-#     [~] compiler options are aligned with NDK r8d
-#   - March 2013
-#     [+] updated for NDK r8e (x86 version)
-#     [+] support x86_64 version of NDK
-#   - April 2013
-#     [+] support non-release NDK layouts (from Linaro git and Android git)
-#     [~] automatically detect if explicit link to crtbegin_*.o is needed
-# ------------------------------------------------------------------------------
-
-cmake_minimum_required( VERSION 2.6.3 )
-
-if( DEFINED CMAKE_CROSSCOMPILING )
- # subsequent toolchain loading is not really needed
- return()
-endif()
-
-if( CMAKE_TOOLCHAIN_FILE )
- # touch toolchain variable only to suppress "unused variable" warning
-endif()
-
-get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE )
-if( _CMAKE_IN_TRY_COMPILE )
- include( "${CMAKE_CURRENT_SOURCE_DIR}/../android.toolchain.config.cmake" OPTIONAL )
-endif()
-
-# this one is important
-set( CMAKE_SYSTEM_NAME Linux )
-# this one not so much
-set( CMAKE_SYSTEM_VERSION 1 )
-
-# rpath makes low sence for Android
-set( CMAKE_SKIP_RPATH TRUE CACHE BOOL "If set, runtime paths are not added when using shared libraries." )
-
-set( ANDROID_SUPPORTED_NDK_VERSIONS ${ANDROID_EXTRA_NDK_VERSIONS} -r8e -r8d -r8c -r8b -r8 -r7c -r7b -r7 -r6b -r6 -r5c -r5b -r5 "" )
-if(NOT DEFINED ANDROID_NDK_SEARCH_PATHS)
- if( CMAKE_HOST_WIN32 )
-  file( TO_CMAKE_PATH "$ENV{PROGRAMFILES}" ANDROID_NDK_SEARCH_PATHS )
-  set( ANDROID_NDK_SEARCH_PATHS "${ANDROID_NDK_SEARCH_PATHS}/android-ndk" "$ENV{SystemDrive}/NVPACK/android-ndk" )
- else()
-  file( TO_CMAKE_PATH "$ENV{HOME}" ANDROID_NDK_SEARCH_PATHS )
-  set( ANDROID_NDK_SEARCH_PATHS /opt/android-ndk "${ANDROID_NDK_SEARCH_PATHS}/NVPACK/android-ndk" )
- endif()
-endif()
-if(NOT DEFINED ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH)
- set( ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH /opt/android-toolchain )
-endif()
-
-set( ANDROID_SUPPORTED_ABIS_arm "armeabi-v7a;armeabi;armeabi-v7a with NEON;armeabi-v7a with VFPV3;armeabi-v6 with VFP" )
-set( ANDROID_SUPPORTED_ABIS_x86 "x86" )
-set( ANDROID_SUPPORTED_ABIS_mipsel "mips" )
-
-set( ANDROID_DEFAULT_NDK_API_LEVEL 8 )
-set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 9 )
-set( ANDROID_DEFAULT_NDK_API_LEVEL_mips 9 )
-
-
-macro( __LIST_FILTER listvar regex )
- if( ${listvar} )
-  foreach( __val ${${listvar}} )
-   if( __val MATCHES "${regex}" )
-    list( REMOVE_ITEM ${listvar} "${__val}" )
-   endif()
-  endforeach()
- endif()
-endmacro()
-
-macro( __INIT_VARIABLE var_name )
- set( __test_path 0 )
- foreach( __var ${ARGN} )
-  if( __var STREQUAL "PATH" )
-   set( __test_path 1 )
-   break()
-  endif()
- endforeach()
- if( __test_path AND NOT EXISTS "${${var_name}}" )
-  unset( ${var_name} CACHE )
- endif()
- if( "${${var_name}}" STREQUAL "" )
-  set( __values 0 )
-  foreach( __var ${ARGN} )
-   if( __var STREQUAL "VALUES" )
-    set( __values 1 )
-   elseif( NOT __var STREQUAL "PATH" )
-    set( __obsolete 0 )
-    if( __var MATCHES "^OBSOLETE_.*$" )
-     string( REPLACE "OBSOLETE_" "" __var "${__var}" )
-     set( __obsolete 1 )
-    endif()
-    if( __var MATCHES "^ENV_.*$" )
-     string( REPLACE "ENV_" "" __var "${__var}" )
-     set( __value "$ENV{${__var}}" )
-    elseif( DEFINED ${__var} )
-     set( __value "${${__var}}" )
-    else()
-     if( __values )
-      set( __value "${__var}" )
-     else()
-      set( __value "" )
-     endif()
-    endif()
-    if( NOT "${__value}" STREQUAL "" )
-     if( __test_path )
-      if( EXISTS "${__value}" )
-       file( TO_CMAKE_PATH "${__value}" ${var_name} )
-       if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE )
-        message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." )
-       endif()
-       break()
-      endif()
-     else()
-      set( ${var_name} "${__value}" )
-       if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE )
-        message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." )
-       endif()
-      break()
-     endif()
-    endif()
-   endif()
-  endforeach()
-  unset( __value )
-  unset( __values )
-  unset( __obsolete )
- elseif( __test_path )
-  file( TO_CMAKE_PATH "${${var_name}}" ${var_name} )
- endif()
- unset( __test_path )
-endmacro()
-
-macro( __DETECT_NATIVE_API_LEVEL _var _path )
- SET( __ndkApiLevelRegex "^[\t ]*#define[\t ]+__ANDROID_API__[\t ]+([0-9]+)[\t ]*$" )
- FILE( STRINGS ${_path} __apiFileContent REGEX "${__ndkApiLevelRegex}" )
- if( NOT __apiFileContent )
-  message( SEND_ERROR "Could not get Android native API level. Probably you have specified invalid level value, or your copy of NDK/toolchain is broken." )
- endif()
- string( REGEX REPLACE "${__ndkApiLevelRegex}" "\\1" ${_var} "${__apiFileContent}" )
- unset( __apiFileContent )
- unset( __ndkApiLevelRegex )
-endmacro()
-
-macro( __DETECT_TOOLCHAIN_MACHINE_NAME _var _root )
- if( EXISTS "${_root}" )
-  file( GLOB __gccExePath RELATIVE "${_root}/bin/" "${_root}/bin/*-gcc${TOOL_OS_SUFFIX}" )
-  __LIST_FILTER( __gccExePath "^[.].*" )
-  list( LENGTH __gccExePath __gccExePathsCount )
-  if( NOT __gccExePathsCount EQUAL 1  AND NOT _CMAKE_IN_TRY_COMPILE )
-   message( WARNING "Could not determine machine name for compiler from ${_root}" )
-   set( ${_var} "" )
-  else()
-   get_filename_component( __gccExeName "${__gccExePath}" NAME_WE )
-   string( REPLACE "-gcc" "" ${_var} "${__gccExeName}" )
-  endif()
-  unset( __gccExePath )
-  unset( __gccExePathsCount )
-  unset( __gccExeName )
- else()
-  set( ${_var} "" )
- endif()
-endmacro()
-
-
-# fight against cygwin
-set( ANDROID_FORBID_SYGWIN TRUE CACHE BOOL "Prevent cmake from working under cygwin and using cygwin tools")
-mark_as_advanced( ANDROID_FORBID_SYGWIN )
-if( ANDROID_FORBID_SYGWIN )
- if( CYGWIN )
-  message( FATAL_ERROR "Android NDK and android-cmake toolchain are not welcome Cygwin. It is unlikely that this cmake toolchain will work under cygwin. But if you want to try then you can set cmake variable ANDROID_FORBID_SYGWIN to FALSE and rerun cmake." )
- endif()
-
- if( CMAKE_HOST_WIN32 )
-  # remove cygwin from PATH
-  set( __new_path "$ENV{PATH}")
-  __LIST_FILTER( __new_path "cygwin" )
-  set(ENV{PATH} "${__new_path}")
-  unset(__new_path)
- endif()
-endif()
-
-
-# detect current host platform
-if( NOT DEFINED ANDROID_NDK_HOST_X64 AND CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "amd64|x86_64|AMD64")
- set( ANDROID_NDK_HOST_X64 1 CACHE BOOL "Try to use 64-bit compiler toolchain" )
- mark_as_advanced( ANDROID_NDK_HOST_X64 )
-endif()
-
-set( TOOL_OS_SUFFIX "" )
-if( CMAKE_HOST_APPLE )
- set( ANDROID_NDK_HOST_SYSTEM_NAME "darwin-x86_64" )
- set( ANDROID_NDK_HOST_SYSTEM_NAME2 "darwin-x86" )
-elseif( CMAKE_HOST_WIN32 )
- set( ANDROID_NDK_HOST_SYSTEM_NAME "windows-x86_64" )
- set( ANDROID_NDK_HOST_SYSTEM_NAME2 "windows" )
- set( TOOL_OS_SUFFIX ".exe" )
-elseif( CMAKE_HOST_UNIX )
- set( ANDROID_NDK_HOST_SYSTEM_NAME "linux-x86_64" )
- set( ANDROID_NDK_HOST_SYSTEM_NAME2 "linux-x86" )
-else()
- message( FATAL_ERROR "Cross-compilation on your platform is not supported by this cmake toolchain" )
-endif()
-
-if( NOT ANDROID_NDK_HOST_X64 )
- set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} )
-endif()
-
-# see if we have path to Android NDK
-__INIT_VARIABLE( ANDROID_NDK PATH ENV_ANDROID_NDK )
-if( NOT ANDROID_NDK )
- # see if we have path to Android standalone toolchain
- __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ENV_ANDROID_STANDALONE_TOOLCHAIN OBSOLETE_ANDROID_NDK_TOOLCHAIN_ROOT OBSOLETE_ENV_ANDROID_NDK_TOOLCHAIN_ROOT )
-
- if( NOT ANDROID_STANDALONE_TOOLCHAIN )
-  #try to find Android NDK in one of the the default locations
-  set( __ndkSearchPaths )
-  foreach( __ndkSearchPath ${ANDROID_NDK_SEARCH_PATHS} )
-   foreach( suffix ${ANDROID_SUPPORTED_NDK_VERSIONS} )
-    list( APPEND __ndkSearchPaths "${__ndkSearchPath}${suffix}" )
-   endforeach()
-  endforeach()
-  __INIT_VARIABLE( ANDROID_NDK PATH VALUES ${__ndkSearchPaths} )
-  unset( __ndkSearchPaths )
-
-  if( ANDROID_NDK )
-   message( STATUS "Using default path for Android NDK: ${ANDROID_NDK}" )
-   message( STATUS "  If you prefer to use a different location, please define a cmake or environment variable: ANDROID_NDK" )
-  else()
-   #try to find Android standalone toolchain in one of the the default locations
-   __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH )
-
-   if( ANDROID_STANDALONE_TOOLCHAIN )
-    message( STATUS "Using default path for standalone toolchain ${ANDROID_STANDALONE_TOOLCHAIN}" )
-    message( STATUS "  If you prefer to use a different location, please define the variable: ANDROID_STANDALONE_TOOLCHAIN" )
-   endif( ANDROID_STANDALONE_TOOLCHAIN )
-  endif( ANDROID_NDK )
- endif( NOT ANDROID_STANDALONE_TOOLCHAIN )
-endif( NOT ANDROID_NDK )
-
-# remember found paths
-if( ANDROID_NDK )
- get_filename_component( ANDROID_NDK "${ANDROID_NDK}" ABSOLUTE )
- set( ANDROID_NDK "${ANDROID_NDK}" CACHE INTERNAL "Path of the Android NDK" FORCE )
- set( BUILD_WITH_ANDROID_NDK True )
- if( EXISTS "${ANDROID_NDK}/RELEASE.TXT" )
-  file( STRINGS "${ANDROID_NDK}/RELEASE.TXT" ANDROID_NDK_RELEASE_FULL LIMIT_COUNT 1 REGEX r[0-9]+[a-z]? )
-  string( REGEX MATCH r[0-9]+[a-z]? ANDROID_NDK_RELEASE "${ANDROID_NDK_RELEASE_FULL}" )
- else()
-  set( ANDROID_NDK_RELEASE "r1x" )
-  set( ANDROID_NDK_RELEASE_FULL "unreleased" )
- endif()
-elseif( ANDROID_STANDALONE_TOOLCHAIN )
- get_filename_component( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" ABSOLUTE )
- # try to detect change
- if( CMAKE_AR )
-  string( LENGTH "${ANDROID_STANDALONE_TOOLCHAIN}" __length )
-  string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidStandaloneToolchainPreviousPath )
-  if( NOT __androidStandaloneToolchainPreviousPath STREQUAL ANDROID_STANDALONE_TOOLCHAIN )
-   message( FATAL_ERROR "It is not possible to change path to the Android standalone toolchain on subsequent run." )
-  endif()
-  unset( __androidStandaloneToolchainPreviousPath )
-  unset( __length )
- endif()
- set( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" CACHE INTERNAL "Path of the Android standalone toolchain" FORCE )
- set( BUILD_WITH_STANDALONE_TOOLCHAIN True )
-else()
- list(GET ANDROID_NDK_SEARCH_PATHS 0 ANDROID_NDK_SEARCH_PATH)
- message( FATAL_ERROR "Could not find neither Android NDK nor Android standalone toolchain.
-    You should either set an environment variable:
-      export ANDROID_NDK=~/my-android-ndk
-    or
-      export ANDROID_STANDALONE_TOOLCHAIN=~/my-android-toolchain
-    or put the toolchain or NDK in the default path:
-      sudo ln -s ~/my-android-ndk ${ANDROID_NDK_SEARCH_PATH}
-      sudo ln -s ~/my-android-toolchain ${ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH}" )
-endif()
-
-# android NDK layout
-if( BUILD_WITH_ANDROID_NDK )
- if( NOT DEFINED ANDROID_NDK_LAYOUT )
-  # try to automatically detect the layout
-  if( EXISTS "${ANDROID_NDK}/RELEASE.TXT")
-   set( ANDROID_NDK_LAYOUT "RELEASE" )
-  elseif( EXISTS "${ANDROID_NDK}/../../linux-x86/toolchain/" )
-   set( ANDROID_NDK_LAYOUT "LINARO" )
-  elseif( EXISTS "${ANDROID_NDK}/../../gcc/" )
-   set( ANDROID_NDK_LAYOUT "ANDROID" )
-  endif()
- endif()
- set( ANDROID_NDK_LAYOUT "${ANDROID_NDK_LAYOUT}" CACHE STRING "The inner layout of NDK" )
- mark_as_advanced( ANDROID_NDK_LAYOUT )
- if( ANDROID_NDK_LAYOUT STREQUAL "LINARO" )
-  set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment
-  set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../${ANDROID_NDK_HOST_SYSTEM_NAME}/toolchain" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH  "" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" )
- elseif( ANDROID_NDK_LAYOUT STREQUAL "ANDROID" )
-  set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment
-  set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../gcc/${ANDROID_NDK_HOST_SYSTEM_NAME}/arm" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH  "" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" )
- else() # ANDROID_NDK_LAYOUT STREQUAL "RELEASE"
-  set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/toolchains" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH  "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME}" )
-  set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME2}" )
- endif()
- get_filename_component( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK_TOOLCHAINS_PATH}" ABSOLUTE )
-
- # try to detect change of NDK
- if( CMAKE_AR )
-  string( LENGTH "${ANDROID_NDK_TOOLCHAINS_PATH}" __length )
-  string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidNdkPreviousPath )
-  if( NOT __androidNdkPreviousPath STREQUAL ANDROID_NDK_TOOLCHAINS_PATH )
-   message( FATAL_ERROR "It is not possible to change the path to the NDK on subsequent CMake run. You must remove all generated files from your build folder first.
-   " )
-  endif()
-  unset( __androidNdkPreviousPath )
-  unset( __length )
- endif()
-endif()
-
-
-# get all the details about standalone toolchain
-if( BUILD_WITH_STANDALONE_TOOLCHAIN )
- __DETECT_NATIVE_API_LEVEL( ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h" )
- set( ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} )
- set( __availableToolchains "standalone" )
- __DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" )
- if( NOT __availableToolchainMachines )
-  message( FATAL_ERROR "Could not determine machine name of your toolchain. Probably your Android standalone toolchain is broken." )
- endif()
- if( __availableToolchainMachines MATCHES i686 )
-  set( __availableToolchainArchs "x86" )
- elseif( __availableToolchainMachines MATCHES arm )
-  set( __availableToolchainArchs "arm" )
- elseif( __availableToolchainMachines MATCHES mipsel )
-  set( __availableToolchainArchs "mipsel" )
- endif()
- execute_process( COMMAND "${ANDROID_STANDALONE_TOOLCHAIN}/bin/${__availableToolchainMachines}-gcc${TOOL_OS_SUFFIX}" -dumpversion
-                  OUTPUT_VARIABLE __availableToolchainCompilerVersions OUTPUT_STRIP_TRAILING_WHITESPACE )
- string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9]+)?" __availableToolchainCompilerVersions "${__availableToolchainCompilerVersions}" )
- if( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/bin/clang${TOOL_OS_SUFFIX}" )
-  list( APPEND __availableToolchains "standalone-clang" )
-  list( APPEND __availableToolchainMachines ${__availableToolchainMachines} )
-  list( APPEND __availableToolchainArchs ${__availableToolchainArchs} )
-  list( APPEND __availableToolchainCompilerVersions ${__availableToolchainCompilerVersions} )
- endif()
-endif()
-
-macro( __GLOB_NDK_TOOLCHAINS __availableToolchainsVar __availableToolchainsLst __toolchain_subpath )
- foreach( __toolchain ${${__availableToolchainsLst}} )
-  if( "${__toolchain}" MATCHES "-clang3[.][0-9]$" AND NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${__toolchain}${__toolchain_subpath}" )
-   string( REGEX REPLACE "-clang3[.][0-9]$" "-4.6" __gcc_toolchain "${__toolchain}" )
-  else()
-   set( __gcc_toolchain "${__toolchain}" )
-  endif()
-  __DETECT_TOOLCHAIN_MACHINE_NAME( __machine "${ANDROID_NDK_TOOLCHAINS_PATH}/${__gcc_toolchain}${__toolchain_subpath}" )
-  if( __machine )
-   string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9x]+)?$" __version "${__gcc_toolchain}" )
-   if( __machine MATCHES i686 )
-    set( __arch "x86" )
-   elseif( __machine MATCHES arm )
-    set( __arch "arm" )
-   elseif( __machine MATCHES mipsel )
-    set( __arch "mipsel" )
-   endif()
-   list( APPEND __availableToolchainMachines "${__machine}" )
-   list( APPEND __availableToolchainArchs "${__arch}" )
-   list( APPEND __availableToolchainCompilerVersions "${__version}" )
-   list( APPEND ${__availableToolchainsVar} "${__toolchain}" )
-  endif()
-  unset( __gcc_toolchain )
- endforeach()
-endmacro()
-
-# get all the details about NDK
-if( BUILD_WITH_ANDROID_NDK )
- file( GLOB ANDROID_SUPPORTED_NATIVE_API_LEVELS RELATIVE "${ANDROID_NDK}/platforms" "${ANDROID_NDK}/platforms/android-*" )
- string( REPLACE "android-" "" ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_SUPPORTED_NATIVE_API_LEVELS}" )
- set( __availableToolchains "" )
- set( __availableToolchainMachines "" )
- set( __availableToolchainArchs "" )
- set( __availableToolchainCompilerVersions "" )
- if( ANDROID_TOOLCHAIN_NAME AND EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_TOOLCHAIN_NAME}/" )
-  # do not go through all toolchains if we know the name
-  set( __availableToolchainsLst "${ANDROID_TOOLCHAIN_NAME}" )
-  __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" )
-  if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 )
-   __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" )
-   if( __availableToolchains )
-    set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} )
-   endif()
-  endif()
- endif()
- if( NOT __availableToolchains )
-  file( GLOB __availableToolchainsLst RELATIVE "${ANDROID_NDK_TOOLCHAINS_PATH}" "${ANDROID_NDK_TOOLCHAINS_PATH}/*" )
-  if( __availableToolchains )
-   list(SORT __availableToolchainsLst) # we need clang to go after gcc
-  endif()
-  __LIST_FILTER( __availableToolchainsLst "^[.]" )
-  __LIST_FILTER( __availableToolchainsLst "llvm" )
-  __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" )
-  if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 )
-   __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" )
-   if( __availableToolchains )
-    set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} )
-   endif()
-  endif()
- endif()
- if( NOT __availableToolchains )
-  message( FATAL_ERROR "Could not find any working toolchain in the NDK. Probably your Android NDK is broken." )
- endif()
-endif()
-
-# build list of available ABIs
-set( ANDROID_SUPPORTED_ABIS "" )
-set( __uniqToolchainArchNames ${__availableToolchainArchs} )
-list( REMOVE_DUPLICATES __uniqToolchainArchNames )
-list( SORT __uniqToolchainArchNames )
-foreach( __arch ${__uniqToolchainArchNames} )
- list( APPEND ANDROID_SUPPORTED_ABIS ${ANDROID_SUPPORTED_ABIS_${__arch}} )
-endforeach()
-unset( __uniqToolchainArchNames )
-if( NOT ANDROID_SUPPORTED_ABIS )
- message( FATAL_ERROR "No one of known Android ABIs is supported by this cmake toolchain." )
-endif()
-
-# choose target ABI
-__INIT_VARIABLE( ANDROID_ABI OBSOLETE_ARM_TARGET OBSOLETE_ARM_TARGETS VALUES ${ANDROID_SUPPORTED_ABIS} )
-# verify that target ABI is supported
-list( FIND ANDROID_SUPPORTED_ABIS "${ANDROID_ABI}" __androidAbiIdx )
-if( __androidAbiIdx EQUAL -1 )
- string( REPLACE ";" "\", \"", PRINTABLE_ANDROID_SUPPORTED_ABIS  "${ANDROID_SUPPORTED_ABIS}" )
- message( FATAL_ERROR "Specified ANDROID_ABI = \"${ANDROID_ABI}\" is not supported by this cmake toolchain or your NDK/toolchain.
-   Supported values are: \"${PRINTABLE_ANDROID_SUPPORTED_ABIS}\"
-   " )
-endif()
-unset( __androidAbiIdx )
-
-# set target ABI options
-if( ANDROID_ABI STREQUAL "x86" )
- set( X86 true )
- set( ANDROID_NDK_ABI_NAME "x86" )
- set( ANDROID_ARCH_NAME "x86" )
- set( ANDROID_ARCH_FULLNAME "x86" )
- set( ANDROID_LLVM_TRIPLE "i686-none-linux-android" )
- set( CMAKE_SYSTEM_PROCESSOR "i686" )
-elseif( ANDROID_ABI STREQUAL "mips" )
- set( MIPS true )
- set( ANDROID_NDK_ABI_NAME "mips" )
- set( ANDROID_ARCH_NAME "mips" )
- set( ANDROID_ARCH_FULLNAME "mipsel" )
- set( ANDROID_LLVM_TRIPLE "mipsel-none-linux-android" )
- set( CMAKE_SYSTEM_PROCESSOR "mips" )
-elseif( ANDROID_ABI STREQUAL "armeabi" )
- set( ARMEABI true )
- set( ANDROID_NDK_ABI_NAME "armeabi" )
- set( ANDROID_ARCH_NAME "arm" )
- set( ANDROID_ARCH_FULLNAME "arm" )
- set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" )
- set( CMAKE_SYSTEM_PROCESSOR "armv5te" )
-elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" )
- set( ARMEABI_V6 true )
- set( ANDROID_NDK_ABI_NAME "armeabi" )
- set( ANDROID_ARCH_NAME "arm" )
- set( ANDROID_ARCH_FULLNAME "arm" )
- set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" )
- set( CMAKE_SYSTEM_PROCESSOR "armv6" )
- # need always fallback to older platform
- set( ARMEABI true )
-elseif( ANDROID_ABI STREQUAL "armeabi-v7a")
- set( ARMEABI_V7A true )
- set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
- set( ANDROID_ARCH_NAME "arm" )
- set( ANDROID_ARCH_FULLNAME "arm" )
- set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" )
- set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
-elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" )
- set( ARMEABI_V7A true )
- set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
- set( ANDROID_ARCH_NAME "arm" )
- set( ANDROID_ARCH_FULLNAME "arm" )
- set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" )
- set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
- set( VFPV3 true )
-elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" )
- set( ARMEABI_V7A true )
- set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
- set( ANDROID_ARCH_NAME "arm" )
- set( ANDROID_ARCH_FULLNAME "arm" )
- set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" )
- set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
- set( VFPV3 true )
- set( NEON true )
-else()
- message( SEND_ERROR "Unknown ANDROID_ABI=\"${ANDROID_ABI}\" is specified." )
-endif()
-
-if( CMAKE_BINARY_DIR AND EXISTS "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" )
- # really dirty hack
- # it is not possible to change CMAKE_SYSTEM_PROCESSOR after the first run...
- file( APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" "SET(CMAKE_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")\n" )
-endif()
-
-if( ANDROID_ARCH_NAME STREQUAL "arm" AND NOT ARMEABI_V6 )
- __INIT_VARIABLE( ANDROID_FORCE_ARM_BUILD OBSOLETE_FORCE_ARM VALUES OFF )
- set( ANDROID_FORCE_ARM_BUILD ${ANDROID_FORCE_ARM_BUILD} CACHE BOOL "Use 32-bit ARM instructions instead of Thumb-1" FORCE )
- mark_as_advanced( ANDROID_FORCE_ARM_BUILD )
-else()
- unset( ANDROID_FORCE_ARM_BUILD CACHE )
-endif()
-
-# choose toolchain
-if( ANDROID_TOOLCHAIN_NAME )
- list( FIND __availableToolchains "${ANDROID_TOOLCHAIN_NAME}" __toolchainIdx )
- if( __toolchainIdx EQUAL -1 )
-  list( SORT __availableToolchains )
-  string( REPLACE ";" "\n  * " toolchains_list "${__availableToolchains}" )
-  set( toolchains_list "  * ${toolchains_list}")
-  message( FATAL_ERROR "Specified toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is missing in your NDK or broken. Please verify that your NDK is working or select another compiler toolchain.
-To configure the toolchain set CMake variable ANDROID_TOOLCHAIN_NAME to one of the following values:\n${toolchains_list}\n" )
- endif()
- list( GET __availableToolchainArchs ${__toolchainIdx} __toolchainArch )
- if( NOT __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME )
-  message( SEND_ERROR "Selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is not able to compile binaries for the \"${ANDROID_ARCH_NAME}\" platform." )
- endif()
-else()
- set( __toolchainIdx -1 )
- set( __applicableToolchains "" )
- set( __toolchainMaxVersion "0.0.0" )
- list( LENGTH __availableToolchains __availableToolchainsCount )
- math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" )
- foreach( __idx RANGE ${__availableToolchainsCount} )
-  list( GET __availableToolchainArchs ${__idx} __toolchainArch )
-  if( __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME )
-   list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion )
-   string( REPLACE "x" "99" __toolchainVersion "${__toolchainVersion}")
-   if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion )
-    set( __toolchainMaxVersion "${__toolchainVersion}" )
-    set( __toolchainIdx ${__idx} )
-   endif()
-  endif()
- endforeach()
- unset( __availableToolchainsCount )
- unset( __toolchainMaxVersion )
- unset( __toolchainVersion )
-endif()
-unset( __toolchainArch )
-if( __toolchainIdx EQUAL -1 )
- message( FATAL_ERROR "No one of available compiler toolchains is able to compile for ${ANDROID_ARCH_NAME} platform." )
-endif()
-list( GET __availableToolchains ${__toolchainIdx} ANDROID_TOOLCHAIN_NAME )
-list( GET __availableToolchainMachines ${__toolchainIdx} ANDROID_TOOLCHAIN_MACHINE_NAME )
-list( GET __availableToolchainCompilerVersions ${__toolchainIdx} ANDROID_COMPILER_VERSION )
-
-unset( __toolchainIdx )
-unset( __availableToolchains )
-unset( __availableToolchainMachines )
-unset( __availableToolchainArchs )
-unset( __availableToolchainCompilerVersions )
-
-# choose native API level
-__INIT_VARIABLE( ANDROID_NATIVE_API_LEVEL ENV_ANDROID_NATIVE_API_LEVEL ANDROID_API_LEVEL ENV_ANDROID_API_LEVEL ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME} ANDROID_DEFAULT_NDK_API_LEVEL )
-string( REGEX MATCH "[0-9]+" ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" )
-# adjust API level
-set( __real_api_level ${ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME}} )
-foreach( __level ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} )
- if( NOT __level GREATER ANDROID_NATIVE_API_LEVEL AND NOT __level LESS __real_api_level )
-  set( __real_api_level ${__level} )
- endif()
-endforeach()
-if( __real_api_level AND NOT ANDROID_NATIVE_API_LEVEL EQUAL __real_api_level )
- message( STATUS "Adjusting Android API level 'android-${ANDROID_NATIVE_API_LEVEL}' to 'android-${__real_api_level}'")
- set( ANDROID_NATIVE_API_LEVEL ${__real_api_level} )
-endif()
-unset(__real_api_level)
-# validate
-list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx )
-if( __levelIdx EQUAL -1 )
- message( SEND_ERROR "Specified Android native API level 'android-${ANDROID_NATIVE_API_LEVEL}' is not supported by your NDK/toolchain." )
-else()
- if( BUILD_WITH_ANDROID_NDK )
-  __DETECT_NATIVE_API_LEVEL( __realApiLevel "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}/usr/include/android/api-level.h" )
-  if( NOT __realApiLevel EQUAL ANDROID_NATIVE_API_LEVEL )
-   message( SEND_ERROR "Specified Android API level (${ANDROID_NATIVE_API_LEVEL}) does not match to the level found (${__realApiLevel}). Probably your copy of NDK is broken." )
-  endif()
-  unset( __realApiLevel )
- endif()
- set( ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" CACHE STRING "Android API level for native code" FORCE )
- if( CMAKE_VERSION VERSION_GREATER "2.8" )
-  list( SORT ANDROID_SUPPORTED_NATIVE_API_LEVELS )
-  set_property( CACHE ANDROID_NATIVE_API_LEVEL PROPERTY STRINGS ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} )
- endif()
-endif()
-unset( __levelIdx )
-
-
-# remember target ABI
-set( ANDROID_ABI "${ANDROID_ABI}" CACHE STRING "The target ABI for Android. If arm, then armeabi-v7a is recommended for hardware floating point." FORCE )
-if( CMAKE_VERSION VERSION_GREATER "2.8" )
- list( SORT ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME} )
- set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} )
-endif()
-
-
-# runtime choice (STL, rtti, exceptions)
-if( NOT ANDROID_STL )
- # honor legacy ANDROID_USE_STLPORT
- if( DEFINED ANDROID_USE_STLPORT )
-  if( ANDROID_USE_STLPORT )
-   set( ANDROID_STL stlport_static )
-  endif()
-  message( WARNING "You are using an obsolete variable ANDROID_USE_STLPORT to select the STL variant. Use -DANDROID_STL=stlport_static instead." )
- endif()
- if( NOT ANDROID_STL )
-  set( ANDROID_STL gnustl_static )
- endif()
-endif()
-set( ANDROID_STL "${ANDROID_STL}" CACHE STRING "C++ runtime" )
-set( ANDROID_STL_FORCE_FEATURES ON CACHE BOOL "automatically configure rtti and exceptions support based on C++ runtime" )
-mark_as_advanced( ANDROID_STL ANDROID_STL_FORCE_FEATURES )
-
-if( BUILD_WITH_ANDROID_NDK )
- if( NOT "${ANDROID_STL}" MATCHES "^(none|system|system_re|gabi\\+\\+_static|gabi\\+\\+_shared|stlport_static|stlport_shared|gnustl_static|gnustl_shared)$")
-  message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\".
-The possible values are:
-  none           -> Do not configure the runtime.
-  system         -> Use the default minimal system C++ runtime library.
-  system_re      -> Same as system but with rtti and exceptions.
-  gabi++_static  -> Use the GAbi++ runtime as a static library.
-  gabi++_shared  -> Use the GAbi++ runtime as a shared library.
-  stlport_static -> Use the STLport runtime as a static library.
-  stlport_shared -> Use the STLport runtime as a shared library.
-  gnustl_static  -> (default) Use the GNU STL as a static library.
-  gnustl_shared  -> Use the GNU STL as a shared library.
-" )
- endif()
-elseif( BUILD_WITH_STANDALONE_TOOLCHAIN )
- if( NOT "${ANDROID_STL}" MATCHES "^(none|gnustl_static|gnustl_shared)$")
-  message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\".
-The possible values are:
-  none           -> Do not configure the runtime.
-  gnustl_static  -> (default) Use the GNU STL as a static library.
-  gnustl_shared  -> Use the GNU STL as a shared library.
-" )
- endif()
-endif()
-
-unset( ANDROID_RTTI )
-unset( ANDROID_EXCEPTIONS )
-unset( ANDROID_STL_INCLUDE_DIRS )
-unset( __libstl )
-unset( __libsupcxx )
-
-if( NOT _CMAKE_IN_TRY_COMPILE AND ANDROID_NDK_RELEASE STREQUAL "r7b" AND ARMEABI_V7A AND NOT VFPV3 AND ANDROID_STL MATCHES "gnustl" )
- message( WARNING  "The GNU STL armeabi-v7a binaries from NDK r7b can crash non-NEON devices. The files provided with NDK r7b were not configured properly, resulting in crashes on Tegra2-based devices and others when trying to use certain floating-point functions (e.g., cosf, sinf, expf).
-You are strongly recommended to switch to another NDK release.
-" )
-endif()
-
-if( NOT _CMAKE_IN_TRY_COMPILE AND X86 AND ANDROID_STL MATCHES "gnustl" AND ANDROID_NDK_RELEASE STREQUAL "r6" )
-  message( WARNING  "The x86 system header file from NDK r6 has incorrect definition for ptrdiff_t. You are recommended to upgrade to a newer NDK release or manually patch the header:
-See https://android.googlesource.com/platform/development.git f907f4f9d4e56ccc8093df6fee54454b8bcab6c2
-  diff --git a/ndk/platforms/android-9/arch-x86/include/machine/_types.h b/ndk/platforms/android-9/arch-x86/include/machine/_types.h
-  index 5e28c64..65892a1 100644
-  --- a/ndk/platforms/android-9/arch-x86/include/machine/_types.h
-  +++ b/ndk/platforms/android-9/arch-x86/include/machine/_types.h
-  @@ -51,7 +51,11 @@ typedef long int       ssize_t;
-   #endif
-   #ifndef _PTRDIFF_T
-   #define _PTRDIFF_T
-  -typedef long           ptrdiff_t;
-  +#  ifdef __ANDROID__
-  +     typedef int            ptrdiff_t;
-  +#  else
-  +     typedef long           ptrdiff_t;
-  +#  endif
-   #endif
-" )
-endif()
-
-
-# setup paths and STL for standalone toolchain
-if( BUILD_WITH_STANDALONE_TOOLCHAIN )
- set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" )
- set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" )
- set( ANDROID_SYSROOT "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot" )
-
- if( NOT ANDROID_STL STREQUAL "none" )
-  set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/include/c++/${ANDROID_COMPILER_VERSION}" )
-  if( ARMEABI_V7A AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}/bits" )
-   list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}" )
-  elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb/bits" )
-   list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb" )
-  else()
-   list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" )
-  endif()
-  # always search static GNU STL to get the location of libsupc++.a
-  if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libstdc++.a" )
-   set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb" )
-  elseif( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libstdc++.a" )
-   set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}" )
-  elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libstdc++.a" )
-   set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb" )
-  elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libstdc++.a" )
-   set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib" )
-  endif()
-  if( __libstl )
-   set( __libsupcxx "${__libstl}/libsupc++.a" )
-   set( __libstl    "${__libstl}/libstdc++.a" )
-  endif()
-  if( NOT EXISTS "${__libsupcxx}" )
-   message( FATAL_ERROR "The required libstdsupc++.a is missing in your standalone toolchain.
- Usually it happens because of bug in make-standalone-toolchain.sh script from NDK r7, r7b and r7c.
- You need to either upgrade to newer NDK or manually copy
-     $ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a
- to
-     ${__libsupcxx}
-   " )
-  endif()
-  if( ANDROID_STL STREQUAL "gnustl_shared" )
-   if( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" )
-    set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" )
-   elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" )
-    set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" )
-   elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" )
-    set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" )
-   endif()
-  endif()
- endif()
-endif()
-
-# clang
-if( "${ANDROID_TOOLCHAIN_NAME}" STREQUAL "standalone-clang" )
- set( ANDROID_COMPILER_IS_CLANG 1 )
- execute_process( COMMAND "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/clang${TOOL_OS_SUFFIX}" --version OUTPUT_VARIABLE ANDROID_CLANG_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE )
- string( REGEX MATCH "[0-9]+[.][0-9]+" ANDROID_CLANG_VERSION "${ANDROID_CLANG_VERSION}")
-elseif( "${ANDROID_TOOLCHAIN_NAME}" MATCHES "-clang3[.][0-9]?$" )
- string( REGEX MATCH "3[.][0-9]$" ANDROID_CLANG_VERSION "${ANDROID_TOOLCHAIN_NAME}")
- string( REGEX REPLACE "-clang${ANDROID_CLANG_VERSION}$" "-4.6" ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" )
- if( NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}/bin/clang${TOOL_OS_SUFFIX}" )
-  message( FATAL_ERROR "Could not find the Clang compiler driver" )
- endif()
- set( ANDROID_COMPILER_IS_CLANG 1 )
- set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" )
-else()
- set( ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" )
- unset( ANDROID_COMPILER_IS_CLANG CACHE )
-endif()
-
-string( REPLACE "." "" _clang_name "clang${ANDROID_CLANG_VERSION}" )
-if( NOT EXISTS "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" )
- set( _clang_name "clang" )
-endif()
-
-
-# setup paths and STL for NDK
-if( BUILD_WITH_ANDROID_NDK )
- set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" )
- set( ANDROID_SYSROOT "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}" )
-
- if( ANDROID_STL STREQUAL "none" )
-  # do nothing
- elseif( ANDROID_STL STREQUAL "system" )
-  set( ANDROID_RTTI             OFF )
-  set( ANDROID_EXCEPTIONS       OFF )
-  set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" )
- elseif( ANDROID_STL STREQUAL "system_re" )
-  set( ANDROID_RTTI             ON )
-  set( ANDROID_EXCEPTIONS       ON )
-  set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" )
- elseif( ANDROID_STL MATCHES "gabi" )
-  if( ANDROID_NDK_RELEASE STRLESS "r7" )
-   message( FATAL_ERROR "gabi++ is not awailable in your NDK. You have to upgrade to NDK r7 or newer to use gabi++.")
-  endif()
-  set( ANDROID_RTTI             ON )
-  set( ANDROID_EXCEPTIONS       OFF )
-  set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/gabi++/include" )
-  set( __libstl                 "${ANDROID_NDK}/sources/cxx-stl/gabi++/libs/${ANDROID_NDK_ABI_NAME}/libgabi++_static.a" )
- elseif( ANDROID_STL MATCHES "stlport" )
-  if( NOT ANDROID_NDK_RELEASE STRLESS "r8d" )
-   set( ANDROID_EXCEPTIONS       ON )
-  else()
-   set( ANDROID_EXCEPTIONS       OFF )
-  endif()
-  if( ANDROID_NDK_RELEASE STRLESS "r7" )
-   set( ANDROID_RTTI            OFF )
-  else()
-   set( ANDROID_RTTI            ON )
-  endif()
-  set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/stlport/stlport" )
-  set( __libstl                 "${ANDROID_NDK}/sources/cxx-stl/stlport/libs/${ANDROID_NDK_ABI_NAME}/libstlport_static.a" )
- elseif( ANDROID_STL MATCHES "gnustl" )
-  set( ANDROID_EXCEPTIONS       ON )
-  set( ANDROID_RTTI             ON )
-  if( EXISTS "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" )
-   if( ARMEABI_V7A AND ANDROID_COMPILER_VERSION VERSION_EQUAL "4.7" AND ANDROID_NDK_RELEASE STREQUAL "r8d" )
-    # gnustl binary for 4.7 compiler is buggy :(
-    # TODO: look for right fix
-    set( __libstl                "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/4.6" )
-   else()
-    set( __libstl                "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" )
-   endif()
-  else()
-   set( __libstl                "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++" )
-  endif()
-  set( ANDROID_STL_INCLUDE_DIRS "${__libstl}/include" "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/include" )
-  if( EXISTS "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" )
-   set( __libstl                "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" )
-  else()
-   set( __libstl                "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libstdc++.a" )
-  endif()
- else()
-  message( FATAL_ERROR "Unknown runtime: ${ANDROID_STL}" )
- endif()
- # find libsupc++.a - rtti & exceptions
- if( ANDROID_STL STREQUAL "system_re" OR ANDROID_STL MATCHES "gnustl" )
-  set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r8b or newer
-  if( NOT EXISTS "${__libsupcxx}" )
-   set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r7-r8
-  endif()
-  if( NOT EXISTS "${__libsupcxx}" ) # before r7
-   if( ARMEABI_V7A )
-    if( ANDROID_FORCE_ARM_BUILD )
-     set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libsupc++.a" )
-    else()
-     set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libsupc++.a" )
-    endif()
-   elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD )
-    set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libsupc++.a" )
-   else()
-    set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libsupc++.a" )
-   endif()
-  endif()
-  if( NOT EXISTS "${__libsupcxx}")
-   message( ERROR "Could not find libsupc++.a for a chosen platform. Either your NDK is not supported or is broken.")
-  endif()
- endif()
-endif()
-
-
-# case of shared STL linkage
-if( ANDROID_STL MATCHES "shared" AND DEFINED __libstl )
- string( REPLACE "_static.a" "_shared.so" __libstl "${__libstl}" )
- if( NOT _CMAKE_IN_TRY_COMPILE AND __libstl MATCHES "[.]so$" )
-  get_filename_component( __libstlname "${__libstl}" NAME )
-  execute_process( COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${__libstl}" "${LIBRARY_OUTPUT_PATH}/${__libstlname}" RESULT_VARIABLE __fileCopyProcess )
-  if( NOT __fileCopyProcess EQUAL 0 OR NOT EXISTS "${LIBRARY_OUTPUT_PATH}/${__libstlname}")
-   message( SEND_ERROR "Failed copying of ${__libstl} to the ${LIBRARY_OUTPUT_PATH}/${__libstlname}" )
-  endif()
-  unset( __fileCopyProcess )
-  unset( __libstlname )
- endif()
-endif()
-
-
-# ccache support
-__INIT_VARIABLE( _ndk_ccache NDK_CCACHE ENV_NDK_CCACHE )
-if( _ndk_ccache )
- if( DEFINED NDK_CCACHE AND NOT EXISTS NDK_CCACHE )
-  unset( NDK_CCACHE CACHE )
- endif()
- find_program( NDK_CCACHE "${_ndk_ccache}" DOC "The path to ccache binary")
-else()
- unset( NDK_CCACHE CACHE )
-endif()
-unset( _ndk_ccache )
-
-
-# setup the cross-compiler
-if( NOT CMAKE_C_COMPILER )
- if( NDK_CCACHE AND NOT ANDROID_SYSROOT MATCHES "[ ;\"]" )
-  set( CMAKE_C_COMPILER   "${NDK_CCACHE}" CACHE PATH "ccache as C compiler" )
-  set( CMAKE_CXX_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C++ compiler" )
-  if( ANDROID_COMPILER_IS_CLANG )
-   set( CMAKE_C_COMPILER_ARG1   "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}"   CACHE PATH "C compiler")
-   set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler")
-  else()
-   set( CMAKE_C_COMPILER_ARG1   "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "C compiler")
-   set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler")
-  endif()
- else()
-  if( ANDROID_COMPILER_IS_CLANG )
-   set( CMAKE_C_COMPILER   "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}"   CACHE PATH "C compiler")
-   set( CMAKE_CXX_COMPILER "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler")
-  else()
-   set( CMAKE_C_COMPILER   "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"    CACHE PATH "C compiler" )
-   set( CMAKE_CXX_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}"    CACHE PATH "C++ compiler" )
-  endif()
- endif()
- set( CMAKE_ASM_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"     CACHE PATH "assembler" )
- set( CMAKE_STRIP        "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-strip${TOOL_OS_SUFFIX}"   CACHE PATH "strip" )
- set( CMAKE_AR           "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ar${TOOL_OS_SUFFIX}"      CACHE PATH "archive" )
- set( CMAKE_LINKER       "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ld${TOOL_OS_SUFFIX}"      CACHE PATH "linker" )
- set( CMAKE_NM           "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-nm${TOOL_OS_SUFFIX}"      CACHE PATH "nm" )
- set( CMAKE_OBJCOPY      "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objcopy${TOOL_OS_SUFFIX}" CACHE PATH "objcopy" )
- set( CMAKE_OBJDUMP      "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objdump${TOOL_OS_SUFFIX}" CACHE PATH "objdump" )
- set( CMAKE_RANLIB       "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ranlib${TOOL_OS_SUFFIX}"  CACHE PATH "ranlib" )
-endif()
-
-set( _CMAKE_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_MACHINE_NAME}-" )
-if( CMAKE_VERSION VERSION_LESS 2.8.5 )
- set( CMAKE_ASM_COMPILER_ARG1 "-c" )
-endif()
-if( APPLE )
- find_program( CMAKE_INSTALL_NAME_TOOL NAMES install_name_tool )
- if( NOT CMAKE_INSTALL_NAME_TOOL )
-  message( FATAL_ERROR "Could not find install_name_tool, please check your installation." )
- endif()
- mark_as_advanced( CMAKE_INSTALL_NAME_TOOL )
-endif()
-
-# Force set compilers because standard identification works badly for us
-include( CMakeForceCompiler )
-CMAKE_FORCE_C_COMPILER( "${CMAKE_C_COMPILER}" GNU )
-if( ANDROID_COMPILER_IS_CLANG )
- set( CMAKE_C_COMPILER_ID Clang)
-endif()
-set( CMAKE_C_PLATFORM_ID Linux )
-set( CMAKE_C_SIZEOF_DATA_PTR 4 )
-set( CMAKE_C_HAS_ISYSROOT 1 )
-set( CMAKE_C_COMPILER_ABI ELF )
-CMAKE_FORCE_CXX_COMPILER( "${CMAKE_CXX_COMPILER}" GNU )
-if( ANDROID_COMPILER_IS_CLANG )
- set( CMAKE_CXX_COMPILER_ID Clang)
-endif()
-set( CMAKE_CXX_PLATFORM_ID Linux )
-set( CMAKE_CXX_SIZEOF_DATA_PTR 4 )
-set( CMAKE_CXX_HAS_ISYSROOT 1 )
-set( CMAKE_CXX_COMPILER_ABI ELF )
-set( CMAKE_CXX_SOURCE_FILE_EXTENSIONS cc cp cxx cpp CPP c++ C )
-# force ASM compiler (required for CMake < 2.8.5)
-set( CMAKE_ASM_COMPILER_ID_RUN TRUE )
-set( CMAKE_ASM_COMPILER_ID GNU )
-set( CMAKE_ASM_COMPILER_WORKS TRUE )
-set( CMAKE_ASM_COMPILER_FORCED TRUE )
-set( CMAKE_COMPILER_IS_GNUASM 1)
-set( CMAKE_ASM_SOURCE_FILE_EXTENSIONS s S asm )
-
-# flags and definitions
-remove_definitions( -DANDROID )
-add_definitions( -DANDROID )
-
-if( ANDROID_SYSROOT MATCHES "[ ;\"]" )
- if( CMAKE_HOST_WIN32 )
-  # try to convert path to 8.3 form
-  file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "@echo %~s1" )
-  execute_process( COMMAND "$ENV{ComSpec}" /c "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "${ANDROID_SYSROOT}"
-                   OUTPUT_VARIABLE __path OUTPUT_STRIP_TRAILING_WHITESPACE
-                   RESULT_VARIABLE __result ERROR_QUIET )
-  if( __result EQUAL 0 )
-   file( TO_CMAKE_PATH "${__path}" ANDROID_SYSROOT )
-   set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" )
-  else()
-   set( ANDROID_CXX_FLAGS "--sysroot=\"${ANDROID_SYSROOT}\"" )
-  endif()
- else()
-  set( ANDROID_CXX_FLAGS "'--sysroot=${ANDROID_SYSROOT}'" )
- endif()
- if( NOT _CMAKE_IN_TRY_COMPILE )
-  # quotes can break try_compile and compiler identification
-  message(WARNING "Path to your Android NDK (or toolchain) has non-alphanumeric symbols.\nThe build might be broken.\n")
- endif()
-else()
- set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" )
-endif()
-
-# NDK flags
-if( ARMEABI OR ARMEABI_V7A )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fpic -funwind-tables" )
- if( NOT ANDROID_FORCE_ARM_BUILD AND NOT ARMEABI_V6 )
-  set( ANDROID_CXX_FLAGS_RELEASE "-mthumb -fomit-frame-pointer -fno-strict-aliasing" )
-  set( ANDROID_CXX_FLAGS_DEBUG   "-marm -fno-omit-frame-pointer -fno-strict-aliasing" )
-  if( NOT ANDROID_COMPILER_IS_CLANG )
-   set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -finline-limit=64" )
-  endif()
- else()
-  # always compile ARMEABI_V6 in arm mode; otherwise there is no difference from ARMEABI
-  set( ANDROID_CXX_FLAGS_RELEASE "-marm -fomit-frame-pointer -fstrict-aliasing" )
-  set( ANDROID_CXX_FLAGS_DEBUG   "-marm -fno-omit-frame-pointer -fno-strict-aliasing" )
-  if( NOT ANDROID_COMPILER_IS_CLANG )
-   set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" )
-  endif()
- endif()
-elseif( X86 )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funwind-tables" )
- if( NOT ANDROID_COMPILER_IS_CLANG )
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" )
- else()
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fPIC" )
- endif()
- set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer -fstrict-aliasing" )
- set( ANDROID_CXX_FLAGS_DEBUG   "-fno-omit-frame-pointer -fno-strict-aliasing" )
-elseif( MIPS )
- set( ANDROID_CXX_FLAGS         "${ANDROID_CXX_FLAGS} -fpic -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0" )
- set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer" )
- set( ANDROID_CXX_FLAGS_DEBUG   "-fno-omit-frame-pointer" )
- if( NOT ANDROID_COMPILER_IS_CLANG )
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
-  set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} -funswitch-loops -finline-limit=300" )
- endif()
-elseif()
- set( ANDROID_CXX_FLAGS_RELEASE "" )
- set( ANDROID_CXX_FLAGS_DEBUG   "" )
-endif()
-
-set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" ) # good/necessary when porting desktop libraries
-
-if( NOT X86 AND NOT ANDROID_COMPILER_IS_CLANG )
- set( ANDROID_CXX_FLAGS "-Wno-psabi ${ANDROID_CXX_FLAGS}" )
-endif()
-
-if( NOT ANDROID_COMPILER_VERSION VERSION_LESS "4.6" )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -no-canonical-prefixes" ) # see https://android-review.googlesource.com/#/c/47564/
-endif()
-
-# ABI-specific flags
-if( ARMEABI_V7A )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv7-a -mfloat-abi=softfp" )
- if( NEON )
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=neon" )
- elseif( VFPV3 )
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3" )
- else()
-  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3-d16" )
- endif()
-elseif( ARMEABI_V6 )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv6 -mfloat-abi=softfp -mfpu=vfp" ) # vfp == vfpv2
-elseif( ARMEABI )
- set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv5te -mtune=xscale -msoft-float" )
-endif()
-
-if( ANDROID_STL MATCHES "gnustl" AND (EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}") )
- set( CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
- set( CMAKE_CXX_CREATE_SHARED_MODULE  "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
- set( CMAKE_CXX_LINK_EXECUTABLE       "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" )
-else()
- set( CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
- set( CMAKE_CXX_CREATE_SHARED_MODULE  "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
- set( CMAKE_CXX_LINK_EXECUTABLE       "<CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" )
-endif()
-
-# STL
-if( EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}" )
- if( EXISTS "${__libstl}" )
-  set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libstl}\"" )
-  set( CMAKE_CXX_CREATE_SHARED_MODULE  "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libstl}\"" )
-  set( CMAKE_CXX_LINK_EXECUTABLE       "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libstl}\"" )
- endif()
- if( EXISTS "${__libsupcxx}" )
-  set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" )
-  set( CMAKE_CXX_CREATE_SHARED_MODULE  "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" )
-  set( CMAKE_CXX_LINK_EXECUTABLE       "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libsupcxx}\"" )
-  # C objects:
-  set( CMAKE_C_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_C_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
-  set( CMAKE_C_CREATE_SHARED_MODULE  "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_C_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" )
-  set( CMAKE_C_LINK_EXECUTABLE       "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" )
-  set( CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" )
-  set( CMAKE_C_CREATE_SHARED_MODULE  "${CMAKE_C_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" )
-  set( CMAKE_C_LINK_EXECUTABLE       "${CMAKE_C_LINK_EXECUTABLE} \"${__libsupcxx}\"" )
- endif()
- if( ANDROID_STL MATCHES "gnustl" )
-  if( NOT EXISTS "${ANDROID_LIBM_PATH}" )
-   set( ANDROID_LIBM_PATH -lm )
-  endif()
-  set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} ${ANDROID_LIBM_PATH}" )
-  set( CMAKE_CXX_CREATE_SHARED_MODULE  "${CMAKE_CXX_CREATE_SHARED_MODULE} ${ANDROID_LIBM_PATH}" )
-  set( CMAKE_CXX_LINK_EXECUTABLE       "${CMAKE_CXX_LINK_EXECUTABLE} ${ANDROID_LIBM_PATH}" )
- endif()
-endif()
-
-# variables controlling optional build flags
-if (ANDROID_NDK_RELEASE STRLESS "r7")
- # libGLESv2.so in NDK's prior to r7 refers to missing external symbols.
- # So this flag option is required for all projects using OpenGL from native.
- __INIT_VARIABLE( ANDROID_SO_UNDEFINED                      VALUES ON )
-else()
- __INIT_VARIABLE( ANDROID_SO_UNDEFINED                      VALUES OFF )
-endif()
-__INIT_VARIABLE( ANDROID_NO_UNDEFINED OBSOLETE_NO_UNDEFINED VALUES ON )
-__INIT_VARIABLE( ANDROID_FUNCTION_LEVEL_LINKING             VALUES ON )
-__INIT_VARIABLE( ANDROID_GOLD_LINKER                        VALUES ON )
-__INIT_VARIABLE( ANDROID_NOEXECSTACK                        VALUES ON )
-__INIT_VARIABLE( ANDROID_RELRO                              VALUES ON )
-
-set( ANDROID_NO_UNDEFINED           ${ANDROID_NO_UNDEFINED}           CACHE BOOL "Show all undefined symbols as linker errors" )
-set( ANDROID_SO_UNDEFINED           ${ANDROID_SO_UNDEFINED}           CACHE BOOL "Allows or disallows undefined symbols in shared libraries" )
-set( ANDROID_FUNCTION_LEVEL_LINKING ${ANDROID_FUNCTION_LEVEL_LINKING} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" )
-set( ANDROID_GOLD_LINKER            ${ANDROID_GOLD_LINKER}            CACHE BOOL "Enables gold linker (only avaialble for NDK r8b for ARM and x86 architectures on linux-86 and darwin-x86 hosts)" )
-set( ANDROID_NOEXECSTACK            ${ANDROID_NOEXECSTACK}            CACHE BOOL "Allows or disallows undefined symbols in shared libraries" )
-set( ANDROID_RELRO                  ${ANDROID_RELRO}                  CACHE BOOL "Enables RELRO - a memory corruption mitigation technique" )
-mark_as_advanced( ANDROID_NO_UNDEFINED ANDROID_SO_UNDEFINED ANDROID_FUNCTION_LEVEL_LINKING ANDROID_GOLD_LINKER ANDROID_NOEXECSTACK ANDROID_RELRO )
-
-# linker flags
-set( ANDROID_LINKER_FLAGS "" )
-
-if( ARMEABI_V7A )
- # this is *required* to use the following linker flags that routes around
- # a CPU bug in some Cortex-A8 implementations:
- set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--fix-cortex-a8" )
-endif()
-
-if( ANDROID_NO_UNDEFINED )
- if( MIPS )
-  # there is some sysroot-related problem in mips linker...
-  if( NOT ANDROID_SYSROOT MATCHES "[ ;\"]" )
-   set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined -Wl,-rpath-link,${ANDROID_SYSROOT}/usr/lib" )
-  endif()
- else()
-  set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined" )
- endif()
-endif()
-
-if( ANDROID_SO_UNDEFINED )
- set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-allow-shlib-undefined" )
-endif()
-
-if( ANDROID_FUNCTION_LEVEL_LINKING )
- set( ANDROID_CXX_FLAGS    "${ANDROID_CXX_FLAGS} -fdata-sections -ffunction-sections" )
- set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--gc-sections" )
-endif()
-
-if( ANDROID_COMPILER_VERSION VERSION_EQUAL "4.6" )
- if( ANDROID_GOLD_LINKER AND (CMAKE_HOST_UNIX OR ANDROID_NDK_RELEASE STRGREATER "r8b") AND (ARMEABI OR ARMEABI_V7A OR X86) )
-  set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=gold" )
- elseif( ANDROID_NDK_RELEASE STRGREATER "r8b")
-  set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=bfd" )
- elseif( ANDROID_NDK_RELEASE STREQUAL "r8b" AND ARMEABI AND NOT _CMAKE_IN_TRY_COMPILE )
-  message( WARNING "The default bfd linker from arm GCC 4.6 toolchain can fail with 'unresolvable R_ARM_THM_CALL relocation' error message. See https://code.google.com/p/android/issues/detail?id=35342
-  On Linux and OS X host platform you can workaround this problem using gold linker (default).
-  Rerun cmake with -DANDROID_GOLD_LINKER=ON option in case of problems.
-" )
- endif()
-endif() # version 4.6
-
-if( ANDROID_NOEXECSTACK )
- if( ANDROID_COMPILER_IS_CLANG )
-  set( ANDROID_CXX_FLAGS    "${ANDROID_CXX_FLAGS} -Xclang -mnoexecstack" )
- else()
-  set( ANDROID_CXX_FLAGS    "${ANDROID_CXX_FLAGS} -Wa,--noexecstack" )
- endif()
- set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,noexecstack" )
-endif()
-
-if( ANDROID_RELRO )
- set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,relro -Wl,-z,now" )
-endif()
-
-if( ANDROID_COMPILER_IS_CLANG )
- set( ANDROID_CXX_FLAGS "-Qunused-arguments ${ANDROID_CXX_FLAGS}" )
- if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD )
-  set( ANDROID_CXX_FLAGS_RELEASE "-target thumbv7-none-linux-androideabi ${ANDROID_CXX_FLAGS_RELEASE}" )
-  set( ANDROID_CXX_FLAGS_DEBUG   "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS_DEBUG}" )
- else()
-  set( ANDROID_CXX_FLAGS "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS}" )
- endif()
- if( BUILD_WITH_ANDROID_NDK )
-  set( ANDROID_CXX_FLAGS "-gcc-toolchain ${ANDROID_TOOLCHAIN_ROOT} ${ANDROID_CXX_FLAGS}" )
- endif()
-endif()
-
-# cache flags
-set( CMAKE_CXX_FLAGS           ""                        CACHE STRING "c++ flags" )
-set( CMAKE_C_FLAGS             ""                        CACHE STRING "c flags" )
-set( CMAKE_CXX_FLAGS_RELEASE   "-O3 -DNDEBUG"            CACHE STRING "c++ Release flags" )
-set( CMAKE_C_FLAGS_RELEASE     "-O3 -DNDEBUG"            CACHE STRING "c Release flags" )
-set( CMAKE_CXX_FLAGS_DEBUG     "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c++ Debug flags" )
-set( CMAKE_C_FLAGS_DEBUG       "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c Debug flags" )
-set( CMAKE_SHARED_LINKER_FLAGS ""                        CACHE STRING "shared linker flags" )
-set( CMAKE_MODULE_LINKER_FLAGS ""                        CACHE STRING "module linker flags" )
-set( CMAKE_EXE_LINKER_FLAGS    "-Wl,-z,nocopyreloc"      CACHE STRING "executable linker flags" )
-
-# put flags to cache (for debug purpose only)
-set( ANDROID_CXX_FLAGS         "${ANDROID_CXX_FLAGS}"         CACHE INTERNAL "Android specific c/c++ flags" )
-set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE}" CACHE INTERNAL "Android specific c/c++ Release flags" )
-set( ANDROID_CXX_FLAGS_DEBUG   "${ANDROID_CXX_FLAGS_DEBUG}"   CACHE INTERNAL "Android specific c/c++ Debug flags" )
-set( ANDROID_LINKER_FLAGS      "${ANDROID_LINKER_FLAGS}"      CACHE INTERNAL "Android specific c/c++ linker flags" )
-
-# finish flags
-set( CMAKE_CXX_FLAGS           "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" )
-set( CMAKE_C_FLAGS             "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" )
-set( CMAKE_CXX_FLAGS_RELEASE   "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}" )
-set( CMAKE_C_FLAGS_RELEASE     "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}" )
-set( CMAKE_CXX_FLAGS_DEBUG     "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_DEBUG}" )
-set( CMAKE_C_FLAGS_DEBUG       "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_C_FLAGS_DEBUG}" )
-set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
-set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
-set( CMAKE_EXE_LINKER_FLAGS    "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" )
-
-if( MIPS AND BUILD_WITH_ANDROID_NDK AND ANDROID_NDK_RELEASE STREQUAL "r8" )
- set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_SHARED_LINKER_FLAGS}" )
- set( CMAKE_MODULE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_MODULE_LINKER_FLAGS}" )
- set( CMAKE_EXE_LINKER_FLAGS    "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.x ${CMAKE_EXE_LINKER_FLAGS}" )
-endif()
-
-# configure rtti
-if( DEFINED ANDROID_RTTI AND ANDROID_STL_FORCE_FEATURES )
- if( ANDROID_RTTI )
-  set( CMAKE_CXX_FLAGS "-frtti ${CMAKE_CXX_FLAGS}" )
- else()
-  set( CMAKE_CXX_FLAGS "-fno-rtti ${CMAKE_CXX_FLAGS}" )
- endif()
-endif()
-
-# configure exceptios
-if( DEFINED ANDROID_EXCEPTIONS AND ANDROID_STL_FORCE_FEATURES )
- if( ANDROID_EXCEPTIONS )
-  set( CMAKE_CXX_FLAGS "-fexceptions ${CMAKE_CXX_FLAGS}" )
-  set( CMAKE_C_FLAGS "-fexceptions ${CMAKE_C_FLAGS}" )
- else()
-  set( CMAKE_CXX_FLAGS "-fno-exceptions ${CMAKE_CXX_FLAGS}" )
-  set( CMAKE_C_FLAGS "-fno-exceptions ${CMAKE_C_FLAGS}" )
- endif()
-endif()
-
-# global includes and link directories
-include_directories( SYSTEM "${ANDROID_SYSROOT}/usr/include" ${ANDROID_STL_INCLUDE_DIRS} )
-link_directories( "${CMAKE_INSTALL_PREFIX}/libs/${ANDROID_NDK_ABI_NAME}" )
-
-# detect if need link crtbegin_so.o explicitly
-if( NOT DEFINED ANDROID_EXPLICIT_CRT_LINK )
- set( __cmd "${CMAKE_CXX_CREATE_SHARED_LIBRARY}" )
- string( REPLACE "<CMAKE_CXX_COMPILER>" "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}" __cmd "${__cmd}" )
- string( REPLACE "<CMAKE_C_COMPILER>"   "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}"   __cmd "${__cmd}" )
- string( REPLACE "<CMAKE_SHARED_LIBRARY_CXX_FLAGS>" "${CMAKE_CXX_FLAGS}" __cmd "${__cmd}" )
- string( REPLACE "<LANGUAGE_COMPILE_FLAGS>" "" __cmd "${__cmd}" )
- string( REPLACE "<LINK_FLAGS>" "${CMAKE_SHARED_LINKER_FLAGS}" __cmd "${__cmd}" )
- string( REPLACE "<CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS>" "-shared" __cmd "${__cmd}" )
- string( REPLACE "<CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG>" "" __cmd "${__cmd}" )
- string( REPLACE "<TARGET_SONAME>" "" __cmd "${__cmd}" )
- string( REPLACE "<TARGET>" "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/toolchain_crtlink_test.so" __cmd "${__cmd}" )
- string( REPLACE "<OBJECTS>" "\"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" __cmd "${__cmd}" )
- string( REPLACE "<LINK_LIBRARIES>" "" __cmd "${__cmd}" )
- separate_arguments( __cmd )
- foreach( __var ANDROID_NDK ANDROID_NDK_TOOLCHAINS_PATH ANDROID_STANDALONE_TOOLCHAIN )
-  if( ${__var} )
-   set( __tmp "${${__var}}" )
-   separate_arguments( __tmp )
-   string( REPLACE "${__tmp}" "${${__var}}" __cmd "${__cmd}")
-  endif()
- endforeach()
- string( REPLACE "'" "" __cmd "${__cmd}" )
- string( REPLACE "\"" "" __cmd "${__cmd}" )
- execute_process( COMMAND ${__cmd} RESULT_VARIABLE __cmd_result OUTPUT_QUIET ERROR_QUIET )
- if( __cmd_result EQUAL 0 )
-  set( ANDROID_EXPLICIT_CRT_LINK ON )
- else()
-  set( ANDROID_EXPLICIT_CRT_LINK OFF )
- endif()
-endif()
-
-if( ANDROID_EXPLICIT_CRT_LINK )
- set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" )
- set( CMAKE_CXX_CREATE_SHARED_MODULE  "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" )
-endif()
-
-# setup output directories
-set( LIBRARY_OUTPUT_PATH_ROOT ${CMAKE_SOURCE_DIR} CACHE PATH "root for library output, set this to change where android libs are installed to" )
-set( CMAKE_INSTALL_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/user" CACHE STRING "path for installing" )
-
-if(NOT _CMAKE_IN_TRY_COMPILE)
- if( EXISTS "${CMAKE_SOURCE_DIR}/jni/CMakeLists.txt" )
-  set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin/${ANDROID_NDK_ABI_NAME}" CACHE PATH "Output directory for applications" )
- else()
-  set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin" CACHE PATH "Output directory for applications" )
- endif()
- set( LIBRARY_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/libs/${ANDROID_NDK_ABI_NAME}" CACHE PATH "path for android libs" )
-endif()
-
-# set these global flags for cmake client scripts to change behavior
-set( ANDROID True )
-set( BUILD_ANDROID True )
-
-# where is the target environment
-set( CMAKE_FIND_ROOT_PATH "${ANDROID_TOOLCHAIN_ROOT}/bin" "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" "${ANDROID_SYSROOT}" "${CMAKE_INSTALL_PREFIX}" "${CMAKE_INSTALL_PREFIX}/share" )
-
-# only search for libraries and includes in the ndk toolchain
-set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY )
-set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY )
-set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY )
-
-
-# macro to find packages on the host OS
-macro( find_host_package )
- set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER )
- set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER )
- set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER )
- if( CMAKE_HOST_WIN32 )
-  SET( WIN32 1 )
-  SET( UNIX )
- elseif( CMAKE_HOST_APPLE )
-  SET( APPLE 1 )
-  SET( UNIX )
- endif()
- find_package( ${ARGN} )
- SET( WIN32 )
- SET( APPLE )
- SET( UNIX 1 )
- set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY )
- set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY )
- set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY )
-endmacro()
-
-
-# macro to find programs on the host OS
-macro( find_host_program )
- set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER )
- set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER )
- set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER )
- if( CMAKE_HOST_WIN32 )
-  SET( WIN32 1 )
-  SET( UNIX )
- elseif( CMAKE_HOST_APPLE )
-  SET( APPLE 1 )
-  SET( UNIX )
- endif()
- find_program( ${ARGN} )
- SET( WIN32 )
- SET( APPLE )
- SET( UNIX 1 )
- set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY )
- set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY )
- set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY )
-endmacro()
-
-
-macro( ANDROID_GET_ABI_RAWNAME TOOLCHAIN_FLAG VAR )
- if( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI" )
-  set( ${VAR} "armeabi" )
- elseif( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI_V7A" )
-  set( ${VAR} "armeabi-v7a" )
- elseif( "${TOOLCHAIN_FLAG}" STREQUAL "X86" )
-  set( ${VAR} "x86" )
- elseif( "${TOOLCHAIN_FLAG}" STREQUAL "MIPS" )
-  set( ${VAR} "mips" )
- else()
-  set( ${VAR} "unknown" )
- endif()
-endmacro()
-
-
-# export toolchain settings for the try_compile() command
-if( NOT PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" )
- set( __toolchain_config "")
- foreach( __var NDK_CCACHE  LIBRARY_OUTPUT_PATH_ROOT  ANDROID_FORBID_SYGWIN  ANDROID_SET_OBSOLETE_VARIABLES
-                ANDROID_NDK_HOST_X64
-                ANDROID_NDK
-                ANDROID_NDK_LAYOUT
-                ANDROID_STANDALONE_TOOLCHAIN
-                ANDROID_TOOLCHAIN_NAME
-                ANDROID_ABI
-                ANDROID_NATIVE_API_LEVEL
-                ANDROID_STL
-                ANDROID_STL_FORCE_FEATURES
-                ANDROID_FORCE_ARM_BUILD
-                ANDROID_NO_UNDEFINED
-                ANDROID_SO_UNDEFINED
-                ANDROID_FUNCTION_LEVEL_LINKING
-                ANDROID_GOLD_LINKER
-                ANDROID_NOEXECSTACK
-                ANDROID_RELRO
-                ANDROID_LIBM_PATH
-                ANDROID_EXPLICIT_CRT_LINK
-                )
-  if( DEFINED ${__var} )
-   if( "${__var}" MATCHES " ")
-    set( __toolchain_config "${__toolchain_config}set( ${__var} \"${${__var}}\" CACHE INTERNAL \"\" )\n" )
-   else()
-    set( __toolchain_config "${__toolchain_config}set( ${__var} ${${__var}} CACHE INTERNAL \"\" )\n" )
-   endif()
-  endif()
- endforeach()
- file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/android.toolchain.config.cmake" "${__toolchain_config}" )
- unset( __toolchain_config )
-endif()
-
-
-# set some obsolete variables for backward compatibility
-set( ANDROID_SET_OBSOLETE_VARIABLES ON CACHE BOOL "Define obsolete Andrid-specific cmake variables" )
-mark_as_advanced( ANDROID_SET_OBSOLETE_VARIABLES )
-if( ANDROID_SET_OBSOLETE_VARIABLES )
- set( ANDROID_API_LEVEL ${ANDROID_NATIVE_API_LEVEL} )
- set( ARM_TARGET "${ANDROID_ABI}" )
- set( ARMEABI_NDK_NAME "${ANDROID_NDK_ABI_NAME}" )
-endif()
-
-
-# Variables controlling behavior or set by cmake toolchain:
-#   ANDROID_ABI : "armeabi-v7a" (default), "armeabi", "armeabi-v7a with NEON", "armeabi-v7a with VFPV3", "armeabi-v6 with VFP", "x86", "mips"
-#   ANDROID_NATIVE_API_LEVEL : 3,4,5,8,9,14 (depends on NDK version)
-#   ANDROID_STL : gnustl_static/gnustl_shared/stlport_static/stlport_shared/gabi++_static/gabi++_shared/system_re/system/none
-#   ANDROID_FORBID_SYGWIN : ON/OFF
-#   ANDROID_NO_UNDEFINED : ON/OFF
-#   ANDROID_SO_UNDEFINED : OFF/ON  (default depends on NDK version)
-#   ANDROID_FUNCTION_LEVEL_LINKING : ON/OFF
-#   ANDROID_GOLD_LINKER : ON/OFF
-#   ANDROID_NOEXECSTACK : ON/OFF
-#   ANDROID_RELRO : ON/OFF
-#   ANDROID_FORCE_ARM_BUILD : ON/OFF
-#   ANDROID_STL_FORCE_FEATURES : ON/OFF
-#   ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF
-# Can be set only at the first run:
-#   ANDROID_NDK
-#   ANDROID_STANDALONE_TOOLCHAIN
-#   ANDROID_TOOLCHAIN_NAME : the NDK name of compiler toolchain
-#   ANDROID_NDK_HOST_X64 : try to use x86_64 toolchain (default for x64 host systems)
-#   ANDROID_NDK_LAYOUT : the inner NDK structure (RELEASE, LINARO, ANDROID)
-#   LIBRARY_OUTPUT_PATH_ROOT : <any valid path>
-#   NDK_CCACHE : <path to your ccache executable>
-# Obsolete:
-#   ANDROID_API_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL
-#   ARM_TARGET : superseded by ANDROID_ABI
-#   ARM_TARGETS : superseded by ANDROID_ABI (can be set only)
-#   ANDROID_NDK_TOOLCHAIN_ROOT : superseded by ANDROID_STANDALONE_TOOLCHAIN (can be set only)
-#   ANDROID_USE_STLPORT : superseded by ANDROID_STL=stlport_static
-#   ANDROID_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL (completely removed)
-#
-# Primary read-only variables:
-#   ANDROID : always TRUE
-#   ARMEABI : TRUE for arm v6 and older devices
-#   ARMEABI_V6 : TRUE for arm v6
-#   ARMEABI_V7A : TRUE for arm v7a
-#   NEON : TRUE if NEON unit is enabled
-#   VFPV3 : TRUE if VFP version 3 is enabled
-#   X86 : TRUE if configured for x86
-#   MIPS : TRUE if configured for mips
-#   BUILD_ANDROID : always TRUE
-#   BUILD_WITH_ANDROID_NDK : TRUE if NDK is used
-#   BUILD_WITH_STANDALONE_TOOLCHAIN : TRUE if standalone toolchain is used
-#   ANDROID_NDK_HOST_SYSTEM_NAME : "windows", "linux-x86" or "darwin-x86" depending on host platform
-#   ANDROID_NDK_ABI_NAME : "armeabi", "armeabi-v7a", "x86" or "mips" depending on ANDROID_ABI
-#   ANDROID_NDK_RELEASE : one of r5, r5b, r5c, r6, r6b, r7, r7b, r7c, r8, r8b, r8c, r8d, r8e; set only for NDK
-#   ANDROID_ARCH_NAME : "arm" or "x86" or "mips" depending on ANDROID_ABI
-#   ANDROID_SYSROOT : path to the compiler sysroot
-#   TOOL_OS_SUFFIX : "" or ".exe" depending on host platform
-#   ANDROID_COMPILER_IS_CLANG : TRUE if clang compiler is used
-# Obsolete:
-#   ARMEABI_NDK_NAME : superseded by ANDROID_NDK_ABI_NAME
-#
-# Secondary (less stable) read-only variables:
-#   ANDROID_COMPILER_VERSION : GCC version used
-#   ANDROID_CXX_FLAGS : C/C++ compiler flags required by Android platform
-#   ANDROID_SUPPORTED_ABIS : list of currently allowed values for ANDROID_ABI
-#   ANDROID_TOOLCHAIN_MACHINE_NAME : "arm-linux-androideabi", "arm-eabi" or "i686-android-linux"
-#   ANDROID_TOOLCHAIN_ROOT : path to the top level of toolchain (standalone or placed inside NDK)
-#   ANDROID_CLANG_TOOLCHAIN_ROOT : path to clang tools
-#   ANDROID_SUPPORTED_NATIVE_API_LEVELS : list of native API levels found inside NDK
-#   ANDROID_STL_INCLUDE_DIRS : stl include paths
-#   ANDROID_RTTI : if rtti is enabled by the runtime
-#   ANDROID_EXCEPTIONS : if exceptions are enabled by the runtime
-#   ANDROID_GCC_TOOLCHAIN_NAME : read-only, differs from ANDROID_TOOLCHAIN_NAME only if clang is used
-#   ANDROID_CLANG_VERSION : version of clang compiler if clang is used
-#   ANDROID_LIBM_PATH : path to libm.so (set to something like $(TOP)/out/target/product/<product_name>/obj/lib/libm.so) to workaround unresolved `sincos`
-#
-# Defaults:
-#   ANDROID_DEFAULT_NDK_API_LEVEL
-#   ANDROID_DEFAULT_NDK_API_LEVEL_${ARCH}
-#   ANDROID_NDK_SEARCH_PATHS
-#   ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH
-#   ANDROID_SUPPORTED_ABIS_${ARCH}
-#   ANDROID_SUPPORTED_NDK_VERSIONS
diff --git a/android/readme.txt b/android/readme.txt
deleted file mode 100644
index 2d5f3962f..000000000
--- a/android/readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-All Android specific sources are moved to platforms/android.
\ No newline at end of file
diff --git a/platforms/readme.txt b/platforms/readme.txt
index 7e1c4555c..dfe046142 100644
--- a/platforms/readme.txt
+++ b/platforms/readme.txt
@@ -1 +1,3 @@
-This folder contains toolchains and additional files that are needed for cross compitation.
\ No newline at end of file
+This folder contains toolchains and additional files that are needed for cross compilation.
+For more information see introduction tutorials for target platform in documentation:
+http://docs.opencv.org/doc/tutorials/introduction/table_of_content_introduction/table_of_content_introduction.html#table-of-content-introduction
\ No newline at end of file

From e241c14b9409b1c5ada11fe50f0d96058446ff1c Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 26 Jun 2013 17:12:51 +0400
Subject: [PATCH 48/75] OpenCV Library and Manager version incremented.

OpenCV Version 2.4.6;
OpenCV Manager Version 2.8;
Doc fixes.
---
 .../android_binary_package/O4A_SDK.rst         | 14 +++++++-------
 .../dev_with_OCV_on_Android.rst                | 18 +++++++++---------
 modules/core/include/opencv2/core/version.hpp  |  2 +-
 .../src/java/android+OpenCVLoader.java         |  5 +++++
 .../android/service/doc/BaseLoaderCallback.rst |  2 +-
 platforms/android/service/doc/JavaHelper.rst   |  4 ++++
 .../android/service/engine/AndroidManifest.xml |  4 ++--
 .../jni/BinderComponent/OpenCVEngine.cpp       |  2 +-
 8 files changed, 30 insertions(+), 21 deletions(-)

diff --git a/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst b/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
index b6c859dc3..20f0bf655 100644
--- a/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
+++ b/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
@@ -48,10 +48,10 @@ The structure of package contents looks as follows:
 
 ::
 
-    OpenCV-2.4.5-android-sdk
+    OpenCV-2.4.6-android-sdk
     |_ apk
-    |   |_ OpenCV_2.4.5_binary_pack_armv7a.apk
-    |   |_ OpenCV_2.4.5_Manager_2.7_XXX.apk
+    |   |_ OpenCV_2.4.6_binary_pack_armv7a.apk
+    |   |_ OpenCV_2.4.6_Manager_2.8_XXX.apk
     |
     |_ doc
     |_ samples
@@ -157,10 +157,10 @@ Get the OpenCV4Android SDK
 
    .. code-block:: bash
 
-      unzip ~/Downloads/OpenCV-2.4.5-android-sdk.zip
+      unzip ~/Downloads/OpenCV-2.4.6-android-sdk.zip
 
-.. |opencv_android_bin_pack| replace:: :file:`OpenCV-2.4.5-android-sdk.zip`
-.. _opencv_android_bin_pack_url: http://sourceforge.net/projects/opencvlibrary/files/opencv-android/2.4.5/OpenCV-2.4.5-android-sdk.zip/download
+.. |opencv_android_bin_pack| replace:: :file:`OpenCV-2.4.6-android-sdk.zip`
+.. _opencv_android_bin_pack_url: http://sourceforge.net/projects/opencvlibrary/files/opencv-android/2.4.6/OpenCV-2.4.6-android-sdk.zip/download
 .. |opencv_android_bin_pack_url| replace:: |opencv_android_bin_pack|
 .. |seven_zip| replace:: 7-Zip
 .. _seven_zip: http://www.7-zip.org/
@@ -295,7 +295,7 @@ Well, running samples from Eclipse is very simple:
   .. code-block:: sh
     :linenos:
 
-    <Android SDK path>/platform-tools/adb install <OpenCV4Android SDK path>/apk/OpenCV_2.4.5_Manager_2.7_armv7a-neon.apk
+    <Android SDK path>/platform-tools/adb install <OpenCV4Android SDK path>/apk/OpenCV_2.4.6_Manager_2.8_armv7a-neon.apk
 
   .. note:: ``armeabi``, ``armv7a-neon``, ``arm7a-neon-android8``, ``mips`` and ``x86`` stand for
             platform targets:
diff --git a/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.rst b/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.rst
index 5709b64b3..368c3b2b7 100644
--- a/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.rst
+++ b/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.rst
@@ -55,14 +55,14 @@ Manager to access OpenCV libraries externally installed in the target system.
    :guilabel:`File -> Import -> Existing project in your workspace`.
 
    Press :guilabel:`Browse`  button and locate OpenCV4Android SDK 
-   (:file:`OpenCV-2.4.5-android-sdk/sdk`).
+   (:file:`OpenCV-2.4.6-android-sdk/sdk`).
 
    .. image:: images/eclipse_opencv_dependency0.png
         :alt: Add dependency from OpenCV library
         :align: center
 
 #. In application project add a reference to the OpenCV Java SDK in 
-   :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.5``.
+   :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.6``.
 
    .. image:: images/eclipse_opencv_dependency1.png
         :alt: Add dependency from OpenCV library
@@ -101,7 +101,7 @@ See the "15-puzzle" OpenCV sample for details.
         public void onResume()
         {
             super.onResume();
-            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, mLoaderCallback);
+            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
         }
 
         ...
@@ -128,27 +128,27 @@ described above.
 #. Add the OpenCV library project to your workspace the same way as for the async initialization 
    above. Use menu :guilabel:`File -> Import -> Existing project in your workspace`, 
    press :guilabel:`Browse` button and select OpenCV SDK path 
-   (:file:`OpenCV-2.4.5-android-sdk/sdk`).
+   (:file:`OpenCV-2.4.6-android-sdk/sdk`).
 
    .. image:: images/eclipse_opencv_dependency0.png
         :alt: Add dependency from OpenCV library
         :align: center
 
 #. In the application project add a reference to the OpenCV4Android SDK in 
-   :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.5``;
+   :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.6``;
 
    .. image:: images/eclipse_opencv_dependency1.png
        :alt: Add dependency from OpenCV library
        :align: center
 
 #. If your application project **doesn't have a JNI part**, just copy the corresponding OpenCV 
-   native libs from :file:`<OpenCV-2.4.5-android-sdk>/sdk/native/libs/<target_arch>` to your
+   native libs from :file:`<OpenCV-2.4.6-android-sdk>/sdk/native/libs/<target_arch>` to your
    project directory to folder :file:`libs/<target_arch>`.
 
    In case of the application project **with a JNI part**, instead of manual libraries copying you 
    need to modify your ``Android.mk`` file:
    add the following two code lines after the ``"include $(CLEAR_VARS)"`` and before 
-   ``"include path_to_OpenCV-2.4.5-android-sdk/sdk/native/jni/OpenCV.mk"``
+   ``"include path_to_OpenCV-2.4.6-android-sdk/sdk/native/jni/OpenCV.mk"``
 
    .. code-block:: make
       :linenos:
@@ -221,7 +221,7 @@ taken:
 
    .. code-block:: make
 
-      include C:\Work\OpenCV4Android\OpenCV-2.4.5-android-sdk\sdk\native\jni\OpenCV.mk
+      include C:\Work\OpenCV4Android\OpenCV-2.4.6-android-sdk\sdk\native\jni\OpenCV.mk
 
    Should be inserted into the :file:`jni/Android.mk` file **after** this line:
 
@@ -379,7 +379,7 @@ result.
        public void onResume()
        {
            super.onResume();
-           OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
+           OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
        }
 
 #. Defines that your activity implements ``CvViewFrameListener2`` interface and fix activity related
diff --git a/modules/core/include/opencv2/core/version.hpp b/modules/core/include/opencv2/core/version.hpp
index 5676a1795..0a7760873 100644
--- a/modules/core/include/opencv2/core/version.hpp
+++ b/modules/core/include/opencv2/core/version.hpp
@@ -49,7 +49,7 @@
 
 #define CV_VERSION_EPOCH    2
 #define CV_VERSION_MAJOR    4
-#define CV_VERSION_MINOR    5
+#define CV_VERSION_MINOR    6
 #define CV_VERSION_REVISION 0
 
 #define CVAUX_STR_EXP(__A)  #__A
diff --git a/modules/java/generator/src/java/android+OpenCVLoader.java b/modules/java/generator/src/java/android+OpenCVLoader.java
index fb05b826c..a76471eac 100644
--- a/modules/java/generator/src/java/android+OpenCVLoader.java
+++ b/modules/java/generator/src/java/android+OpenCVLoader.java
@@ -27,6 +27,11 @@ public class OpenCVLoader
      */
     public static final String OPENCV_VERSION_2_4_5 = "2.4.5";
 
+    /**
+     * OpenCV Library version 2.4.6.
+     */
+    public static final String OPENCV_VERSION_2_4_6 = "2.4.6";
+
 
     /**
      * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java").
diff --git a/platforms/android/service/doc/BaseLoaderCallback.rst b/platforms/android/service/doc/BaseLoaderCallback.rst
index 71915c449..f8c30a800 100644
--- a/platforms/android/service/doc/BaseLoaderCallback.rst
+++ b/platforms/android/service/doc/BaseLoaderCallback.rst
@@ -48,7 +48,7 @@ See the "15-puzzle" OpenCV sample for details.
         super.onResume();
 
         Log.i(TAG, "Trying to load OpenCV library");
-        if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this, mOpenCVCallBack))
+        if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mOpenCVCallBack))
         {
             Log.e(TAG, "Cannot connect to OpenCV Manager");
         }
diff --git a/platforms/android/service/doc/JavaHelper.rst b/platforms/android/service/doc/JavaHelper.rst
index e90b016e5..9262a7cf7 100644
--- a/platforms/android/service/doc/JavaHelper.rst
+++ b/platforms/android/service/doc/JavaHelper.rst
@@ -55,3 +55,7 @@ OpenCV version constants
 .. data:: OPENCV_VERSION_2_4_5
 
     OpenCV Library version 2.4.5
+
+.. data:: OPENCV_VERSION_2_4_6
+
+    OpenCV Library version 2.4.6
diff --git a/platforms/android/service/engine/AndroidManifest.xml b/platforms/android/service/engine/AndroidManifest.xml
index 954955678..b2141e0ce 100644
--- a/platforms/android/service/engine/AndroidManifest.xml
+++ b/platforms/android/service/engine/AndroidManifest.xml
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="org.opencv.engine"
-    android:versionCode="27@ANDROID_PLATFORM_VERSION_CODE@"
-    android:versionName="2.7" >
+    android:versionCode="28@ANDROID_PLATFORM_VERSION_CODE@"
+    android:versionName="2.8" >
 
     <uses-sdk android:minSdkVersion="@ANDROID_NATIVE_API_LEVEL@" />
     <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
diff --git a/platforms/android/service/engine/jni/BinderComponent/OpenCVEngine.cpp b/platforms/android/service/engine/jni/BinderComponent/OpenCVEngine.cpp
index 274e36a4b..b0b2b5137 100644
--- a/platforms/android/service/engine/jni/BinderComponent/OpenCVEngine.cpp
+++ b/platforms/android/service/engine/jni/BinderComponent/OpenCVEngine.cpp
@@ -15,7 +15,7 @@ using namespace android;
 
 const int OpenCVEngine::Platform = DetectKnownPlatforms();
 const int OpenCVEngine::CpuID = GetCpuID();
-const int OpenCVEngine::KnownVersions[] = {2040000, 2040100, 2040200, 2040300, 2040301, 2040302, 2040400, 2040500};
+const int OpenCVEngine::KnownVersions[] = {2040000, 2040100, 2040200, 2040300, 2040301, 2040302, 2040400, 2040500, 2040600};
 
 bool OpenCVEngine::ValidateVersion(int version)
 {

From 664b720e4dc2dc91701b52bc7b97c1974cb07fcc Mon Sep 17 00:00:00 2001
From: Roman Donchenko <roman.donchenko@itseez.com>
Date: Wed, 26 Jun 2013 18:34:36 +0400
Subject: [PATCH 49/75] Extended Google Test to allow filtering by parameter
 value.

---
 modules/ts/include/opencv2/ts/ts_gtest.h |  3 +++
 modules/ts/src/ts_gtest.cpp              | 33 +++++++++++++++++++++++-
 2 files changed, 35 insertions(+), 1 deletion(-)

diff --git a/modules/ts/include/opencv2/ts/ts_gtest.h b/modules/ts/include/opencv2/ts/ts_gtest.h
index 2d1227ecd..80b410bb3 100644
--- a/modules/ts/include/opencv2/ts/ts_gtest.h
+++ b/modules/ts/include/opencv2/ts/ts_gtest.h
@@ -17566,6 +17566,9 @@ GTEST_DECLARE_string_(color);
 // the tests to run. If the filter is not given all tests are executed.
 GTEST_DECLARE_string_(filter);
 
+// OpenCV extension: same as filter, but for the parameters string.
+GTEST_DECLARE_string_(param_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);
diff --git a/modules/ts/src/ts_gtest.cpp b/modules/ts/src/ts_gtest.cpp
index 7c388cbd4..48870913c 100644
--- a/modules/ts/src/ts_gtest.cpp
+++ b/modules/ts/src/ts_gtest.cpp
@@ -497,6 +497,7 @@ const char kBreakOnFailureFlag[] = "break_on_failure";
 const char kCatchExceptionsFlag[] = "catch_exceptions";
 const char kColorFlag[] = "color";
 const char kFilterFlag[] = "filter";
+const char kParamFilterFlag[] = "param_filter";
 const char kListTestsFlag[] = "list_tests";
 const char kOutputFlag[] = "output";
 const char kPrintTimeFlag[] = "print_time";
@@ -575,6 +576,7 @@ class GTestFlagSaver {
     death_test_style_ = GTEST_FLAG(death_test_style);
     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
     filter_ = GTEST_FLAG(filter);
+    param_filter_ = GTEST_FLAG(param_filter);
     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
     list_tests_ = GTEST_FLAG(list_tests);
     output_ = GTEST_FLAG(output);
@@ -596,6 +598,7 @@ class GTestFlagSaver {
     GTEST_FLAG(death_test_style) = death_test_style_;
     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
     GTEST_FLAG(filter) = filter_;
+    GTEST_FLAG(param_filter) = param_filter_;
     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
     GTEST_FLAG(list_tests) = list_tests_;
     GTEST_FLAG(output) = output_;
@@ -617,6 +620,7 @@ class GTestFlagSaver {
   std::string death_test_style_;
   bool death_test_use_fork_;
   std::string filter_;
+  std::string param_filter_;
   std::string internal_run_death_test_;
   bool list_tests_;
   std::string output_;
@@ -1699,6 +1703,12 @@ GTEST_DEFINE_string_(
     "exclude).  A test is run if it matches one of the positive "
     "patterns and does not match any of the negative patterns.");
 
+GTEST_DEFINE_string_(
+    param_filter,
+    internal::StringFromGTestEnv("param_filter", kUniversalFilter),
+    "Same syntax and semantics as for param, but these patterns "
+    "have to match the test's parameters.");
+
 GTEST_DEFINE_bool_(list_tests, false,
                    "List all tests without running them.");
 
@@ -4188,6 +4198,14 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
   }
 
+  const char* const param_filter = GTEST_FLAG(param_filter).c_str();
+
+  // Ditto.
+  if (!String::CStringEquals(param_filter, kUniversalFilter)) {
+    ColoredPrintf(COLOR_YELLOW,
+                  "Note: %s parameter filter = %s\n", GTEST_NAME_, param_filter);
+  }
+
   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
     ColoredPrintf(COLOR_YELLOW,
@@ -5873,9 +5891,15 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
                                                    kDisableTestFilter);
       test_info->is_disabled_ = is_disabled;
 
+      const std::string value_param(test_info->value_param() == NULL ?
+                                    "" : test_info->value_param());
+
       const bool matches_filter =
           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
-                                                       test_name);
+                                                       test_name) &&
+          internal::UnitTestOptions::MatchesFilter(value_param,
+                                                   GTEST_FLAG(param_filter).c_str());
+
       test_info->matches_filter_ = matches_filter;
 
       const bool is_runnable =
@@ -6223,6 +6247,12 @@ static const char kColorEncodedHelpMessage[] =
 "      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_ "param_filter=@YPOSITIVE_PATTERNS"
+    "[@G-@YNEGATIVE_PATTERNS]@D\n"
+"      Like @G--" GTEST_FLAG_PREFIX_
+                      "filter@D, but applies to the test's parameter. If a\n"
+"      test is not parameterized, its parameter is considered to be the\n"
+"      empty string.\n"
 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
 "      Run all disabled tests too.\n"
 "\n"
@@ -6300,6 +6330,7 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
         ParseBoolFlag(arg, kDeathTestUseFork,
                       &GTEST_FLAG(death_test_use_fork)) ||
         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
+        ParseStringFlag(arg, kParamFilterFlag, &GTEST_FLAG(param_filter)) ||
         ParseStringFlag(arg, kInternalRunDeathTestFlag,
                         &GTEST_FLAG(internal_run_death_test)) ||
         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||

From 070a77ae0def65a92d596d0deefb0c2526753c06 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 26 Jun 2013 02:31:47 -0700
Subject: [PATCH 50/75] TBB updated to version 4.1 update 4.

---
 3rdparty/tbb/CMakeLists.txt | 48 ++++++++++++++++++++++---------------
 1 file changed, 29 insertions(+), 19 deletions(-)

diff --git a/3rdparty/tbb/CMakeLists.txt b/3rdparty/tbb/CMakeLists.txt
index 942404133..03183d1c2 100644
--- a/3rdparty/tbb/CMakeLists.txt
+++ b/3rdparty/tbb/CMakeLists.txt
@@ -1,10 +1,14 @@
 #Cross compile TBB from source
 project(tbb)
 
-# Development release
-set(tbb_ver "tbb41_20130516oss")
-set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130516oss_src.tgz")
-set(tbb_md5 "08c14d1c196bc9595d8c52bedc239937")
+if (WIN32 AND NOT ARM)
+  message(FATAL_ERROR "BUILD_TBB option supports Windows on ARM only!\nUse regular official TBB build instead of the BUILD_TBB option!")
+endif()
+
+# 4.1 update 4 - works fine
+set(tbb_ver "tbb41_20130613oss")
+set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130613oss_src.tgz")
+set(tbb_md5 "108c8c1e481b0aaea61878289eb28b6a")
 set(tbb_version_file "version_string.ver")
 ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow -Wunused-parameter)
 
@@ -121,7 +125,7 @@ if(NOT EXISTS "${tbb_src_dir}")
               RESULT_VARIABLE tbb_untar_RESULT)
 
   if(NOT tbb_untar_RESULT EQUAL 0 OR NOT EXISTS "${tbb_src_dir}")
-    message(FATAL_ERROR "Failed to unpack TBB sources (${tbb_untar_RESULT} ${tbb_src_dir})")
+    message(FATAL_ERROR "Failed to unpack TBB sources from ${tbb_tarball} to ${tbb_src_dir} with error ${tbb_untar_RESULT}")
   endif()
 endif()
 
@@ -137,18 +141,22 @@ file(GLOB lib_hdrs "${tbb_src_dir}/src/tbb/*.h")
 list(APPEND lib_srcs "${tbb_src_dir}/src/rml/client/rml_tbb.cpp")
 
 if (WIN32)
-  add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0
-                /D__TBB_BUILD=1
-                /DTBB_NO_LEGACY=1
-                /D_UNICODE
-                /DUNICODE
-                /DWINAPI_FAMILY=WINAPI_FAMILY_APP
-                /DDO_ITT_NOTIFY=0
-                /DUSE_WINTHREAD
-                /D_WIN32_WINNT=0x0602
-                /D__TBB_WIN32_USE_CL_BUILTINS
+  add_definitions(/D__TBB_DYNAMIC_LOAD_ENABLED=0
+                  /D__TBB_BUILD=1
+                  /DTBB_NO_LEGACY=1
+                  /D_UNICODE
+                  /DUNICODE
+                  /DWINAPI_FAMILY=WINAPI_FAMILY_APP
+                  /DDO_ITT_NOTIFY=0
+                  /DUSE_WINTHREAD
                ) # defines were copied from windows.cl.inc
 
+  if (ARM)
+    add_definitions(/D_WIN32_WINNT=0x0602
+                    /D__TBB_WIN32_USE_CL_BUILTINS
+                   )
+  endif()
+
 set(CMAKE_LINKER_FLAGS "${CMAKE_LINKER_FLAGS} /APPCONTAINER")
 else()
   add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0         #required
@@ -193,16 +201,18 @@ set(TBB_SOURCE_FILES ${TBB_SOURCE_FILES} "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_vers
 
 add_library(tbb ${TBB_SOURCE_FILES})
 
-if (ARM AND WIN32)
+if (WIN32)
+  if (ARM)
+    set(platform_macro /D_M_ARM=1)
+  endif()
+
   add_custom_command(TARGET tbb
                      PRE_BUILD
-                     COMMAND ${CMAKE_C_COMPILER} /nologo /TC /EP ${tbb_src_dir}\\src\\tbb\\win32-tbb-export.def /DTBB_NO_LEGACY=1 /D_CRT_SECURE_NO_DEPRECATE /D__TBB_BUILD=1 /D_M_ARM=1 /I${tbb_src_dir}\\src /I${tbb_src_dir}\\include > "${tbb_src_dir}\\src\\tbb\\tbb.def"
+                     COMMAND ${CMAKE_C_COMPILER} /nologo /TC /EP ${tbb_src_dir}\\src\\tbb\\win32-tbb-export.def /DTBB_NO_LEGACY=1 /D_CRT_SECURE_NO_DEPRECATE /D__TBB_BUILD=1 ${platform_macro} /I${tbb_src_dir}\\src /I${tbb_src_dir}\\include > "${tbb_src_dir}\\src\\tbb\\tbb.def"
                      WORKING_DIRECTORY ${tbb_src_dir}\\src\\tbb
                      COMMENT "Generating tbb.def file" VERBATIM
                     )
-endif()
 
-if (WIN32)
   set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEF:${tbb_src_dir}/src/tbb/tbb.def /DLL /MAP /fixed:no /INCREMENTAL:NO")
 else()
   target_link_libraries(tbb c m dl)

From 7c5bd7880474cb9712c79328a30c198511f070f4 Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Wed, 26 Jun 2013 23:56:50 -0700
Subject: [PATCH 51/75] Test fixes

Calib3d badarg tests fixed. Default exception handling enabled;
Highgui Video I/O tests fixed on ARM;
Code cleanup.
---
 modules/highgui/src/cap_msmf.cpp          | 245 +++-------------------
 modules/highgui/test/test_video_io.cpp    |   4 +-
 platforms/winrt/arm.winrt.toolchain.cmake |   8 +-
 3 files changed, 29 insertions(+), 228 deletions(-)

diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp
index dfd206ea4..09f65b7e8 100644
--- a/modules/highgui/src/cap_msmf.cpp
+++ b/modules/highgui/src/cap_msmf.cpp
@@ -2759,8 +2759,7 @@ public:
     virtual int getCaptureDomain() { return CV_CAP_MSMF; } // Return the type of the capture object: CV_CAP_VFW, etc...
 protected:
     void init();
-    int index, width, height,fourcc;
-    int widthSet, heightSet;
+    int index, width, height, fourcc;
     IplImage* frame;
     videoInput VI;
 };
@@ -2777,18 +2776,18 @@ CvCaptureCAM_MSMF::CvCaptureCAM_MSMF():
     width(-1),
     height(-1),
     fourcc(-1),
-    widthSet(-1),
-    heightSet(-1),
     frame(NULL),
     VI(videoInput::getInstance())
 {
     CoInitialize(0);
 }
+
 CvCaptureCAM_MSMF::~CvCaptureCAM_MSMF()
 {
     close();
     CoUninitialize();
 }
+
 void CvCaptureCAM_MSMF::close()
 {
     if( index >= 0 )
@@ -2797,7 +2796,7 @@ void CvCaptureCAM_MSMF::close()
         index = -1;
         cvReleaseImage(&frame);
     }
-    widthSet = heightSet = width = height = -1;
+    width = height = -1;
 }
 
 // Initialize camera input
@@ -2846,50 +2845,7 @@ double CvCaptureCAM_MSMF::getProperty( int property_id )
         return VI.getWidth(index);
     case CV_CAP_PROP_FRAME_HEIGHT:
         return VI.getHeight(index);
-    case CV_CAP_PROP_FOURCC:
-        // FIXME: implement method in VideoInput back end
-        //return VI.getFourcc(index);
-        ;
-    case CV_CAP_PROP_FPS:
-        // FIXME: implement method in VideoInput back end
-        //return VI.getFPS(index);
-        ;
     }
-    // video filter properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_BRIGHTNESS:
-    case CV_CAP_PROP_CONTRAST:
-    case CV_CAP_PROP_HUE:
-    case CV_CAP_PROP_SATURATION:
-    case CV_CAP_PROP_SHARPNESS:
-    case CV_CAP_PROP_GAMMA:
-    case CV_CAP_PROP_MONOCROME:
-    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
-    case CV_CAP_PROP_BACKLIGHT:
-    case CV_CAP_PROP_GAIN:
-        // FIXME: implement method in VideoInput back end
-        // if ( VI.getVideoSettingFilter(index, VI.getVideoPropertyFromCV(property_id), min_value,
-        //                               max_value, stepping_delta, current_value, flags,defaultValue) )
-        //     return (double)current_value;
-        return 0.;
-    }
-    // camera properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_PAN:
-    case CV_CAP_PROP_TILT:
-    case CV_CAP_PROP_ROLL:
-    case CV_CAP_PROP_ZOOM:
-    case CV_CAP_PROP_EXPOSURE:
-    case CV_CAP_PROP_IRIS:
-    case CV_CAP_PROP_FOCUS:
-    // FIXME: implement method in VideoInput back end
-    //     if (VI.getVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),min_value,
-    //          max_value,stepping_delta,current_value,flags,defaultValue) ) return (double)current_value;
-        return 0.;
-    }
-    // unknown parameter or value not available
     return -1;
 }
 bool CvCaptureCAM_MSMF::setProperty( int property_id, double value )
@@ -2906,89 +2862,21 @@ bool CvCaptureCAM_MSMF::setProperty( int property_id, double value )
         height = cvRound(value);
         handled = true;
         break;
-    case CV_CAP_PROP_FOURCC:
-        fourcc = (int)(unsigned long)(value);
-        if ( fourcc == -1 ) {
-            // following cvCreateVideo usage will pop up caprturepindialog here if fourcc=-1
-            // TODO - how to create a capture pin dialog
-        }
-        handled = true;
-        break;
-    case CV_CAP_PROP_FPS:
-        // FIXME: implement method in VideoInput back end
-        // int fps = cvRound(value);
-        // if (fps != VI.getFPS(index))
-        // {
-        //     VI.stopDevice(index);
-        //     VI.setIdealFramerate(index,fps);
-        //     if (widthSet > 0 && heightSet > 0)
-        //         VI.setupDevice(index, widthSet, heightSet);
-        //     else
-        //         VI.setupDevice(index);
-        // }
-        // return VI.isDeviceSetup(index);
-        ;
     }
+
     if ( handled ) {
-        // a stream setting
         if( width > 0 && height > 0 )
         {
-            if( width != (int)VI.getWidth(index) || height != (int)VI.getHeight(index) )//|| fourcc != VI.getFourcc(index) )
+            if( width != (int)VI.getWidth(index) || height != (int)VI.getHeight(index)  && VI.isDeviceSetup(index))//|| fourcc != VI.getFourcc(index) )
             {
-                // FIXME: implement method in VideoInput back end
-                // int fps = static_cast<int>(VI.getFPS(index));
-                // VI.stopDevice(index);
-                // VI.setIdealFramerate(index, fps);
-                // VI.setupDeviceFourcc(index, width, height, fourcc);
+                VI.closeDevice(index);
+                VI.setupDevice(index, width, height);
             }
-            bool success = VI.isDeviceSetup(index);
-            if (success)
-            {
-                widthSet = width;
-                heightSet = height;
-                width = height = fourcc = -1;
-            }
-            return success;
+            return VI.isDeviceSetup(index);
         }
         return true;
     }
-    // show video/camera filter dialog
-    // FIXME: implement method in VideoInput back end
-    // if ( property_id == CV_CAP_PROP_SETTINGS ) {
-    //     VI.showSettingsWindow(index);
-    //     return true;
-    // }
-    //video Filter properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_BRIGHTNESS:
-    case CV_CAP_PROP_CONTRAST:
-    case CV_CAP_PROP_HUE:
-    case CV_CAP_PROP_SATURATION:
-    case CV_CAP_PROP_SHARPNESS:
-    case CV_CAP_PROP_GAMMA:
-    case CV_CAP_PROP_MONOCROME:
-    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
-    case CV_CAP_PROP_BACKLIGHT:
-    case CV_CAP_PROP_GAIN:
-        // FIXME: implement method in VideoInput back end
-        //return VI.setVideoSettingFilter(index,VI.getVideoPropertyFromCV(property_id),(long)value);
-        ;
-    }
-    //camera properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_PAN:
-    case CV_CAP_PROP_TILT:
-    case CV_CAP_PROP_ROLL:
-    case CV_CAP_PROP_ZOOM:
-    case CV_CAP_PROP_EXPOSURE:
-    case CV_CAP_PROP_IRIS:
-    case CV_CAP_PROP_FOCUS:
-        // FIXME: implement method in VideoInput back end
-        //return VI.setVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),(long)value);
-        ;
-    }
+
     return false;
 }
 
@@ -3109,103 +2997,9 @@ void CvCaptureFile_MSMF::close()
 bool CvCaptureFile_MSMF::setProperty(int property_id, double value)
 {
     // image capture properties
-    bool handled = false;
-    unsigned int width, height;
-    int fourcc;
-    switch( property_id )
-    {
-    case CV_CAP_PROP_FRAME_WIDTH:
-        // width = cvRound(value);
-        // handled = true;
-        break;
-    case CV_CAP_PROP_FRAME_HEIGHT:
-        // height = cvRound(value);
-        // handled = true;
-        break;
-    case CV_CAP_PROP_FOURCC:
-        fourcc = (int)(unsigned long)(value);
-        if ( fourcc == -1 ) {
-            // following cvCreateVideo usage will pop up caprturepindialog here if fourcc=-1
-            // TODO - how to create a capture pin dialog
-        }
-        handled = true;
-        break;
-    case CV_CAP_PROP_FPS:
-        // FIXME: implement method in VideoInput back end
-        // int fps = cvRound(value);
-        // if (fps != VI.getFPS(index))
-        // {
-        //     VI.stopDevice(index);
-        //     VI.setIdealFramerate(index,fps);
-        //     if (widthSet > 0 && heightSet > 0)
-        //         VI.setupDevice(index, widthSet, heightSet);
-        //     else
-        //         VI.setupDevice(index);
-        // }
-        // return VI.isDeviceSetup(index);
-        ;
-    }
-    if ( handled ) {
-        // a stream setting
-        if( width > 0 && height > 0 )
-        {
-            if( width != captureFormats[captureFormatIndex].width ||
-                height != captureFormats[captureFormatIndex].height )//|| fourcc != VI.getFourcc(index) )
-            {
-                // FIXME: implement method in VideoInput back end
-                // int fps = static_cast<int>(VI.getFPS(index));
-                // VI.stopDevice(index);
-                // VI.setIdealFramerate(index, fps);
-                // VI.setupDeviceFourcc(index, width, height, fourcc);
-            }
-            if (isOpened)
-            {
-                // widthSet = width;
-                // heightSet = height;
-                // width = height = fourcc = -1;
-            }
-            return isOpened;
-        }
-        return true;
-    }
-    // show video/camera filter dialog
     // FIXME: implement method in VideoInput back end
-    // if ( property_id == CV_CAP_PROP_SETTINGS ) {
-    //     VI.showSettingsWindow(index);
-    //     return true;
-    // }
-    //video Filter properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_BRIGHTNESS:
-    case CV_CAP_PROP_CONTRAST:
-    case CV_CAP_PROP_HUE:
-    case CV_CAP_PROP_SATURATION:
-    case CV_CAP_PROP_SHARPNESS:
-    case CV_CAP_PROP_GAMMA:
-    case CV_CAP_PROP_MONOCROME:
-    case CV_CAP_PROP_WHITE_BALANCE_BLUE_U:
-    case CV_CAP_PROP_BACKLIGHT:
-    case CV_CAP_PROP_GAIN:
-        // FIXME: implement method in VideoInput back end
-        //return VI.setVideoSettingFilter(index,VI.getVideoPropertyFromCV(property_id),(long)value);
-        ;
-    }
-    //camera properties
-    switch( property_id )
-    {
-    case CV_CAP_PROP_PAN:
-    case CV_CAP_PROP_TILT:
-    case CV_CAP_PROP_ROLL:
-    case CV_CAP_PROP_ZOOM:
-    case CV_CAP_PROP_EXPOSURE:
-    case CV_CAP_PROP_IRIS:
-    case CV_CAP_PROP_FOCUS:
-        // FIXME: implement method in VideoInput back end
-        //return VI.setVideoSettingCamera(index,VI.getCameraPropertyFromCV(property_id),(long)value);
-        ;
-    }
-
+    (void) property_id;
+    (void) value;
     return false;
 }
 
@@ -3238,7 +3032,7 @@ double CvCaptureFile_MSMF::getProperty(int property_id)
 
 bool CvCaptureFile_MSMF::grabFrame()
 {
-    DWORD waitResult = -1;
+    DWORD waitResult = (DWORD)-1;
     if (isOpened)
     {
         SetEvent(grabberThread->getImageGrabber()->ig_hFrameGrabbed);
@@ -3507,7 +3301,7 @@ void CvVideoWriter_MSMF::close()
     }
 
     initiated = false;
-    HRESULT hr = sinkWriter->Finalize();
+    sinkWriter->Finalize();
     MFShutdown();
 }
 
@@ -3667,6 +3461,16 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
 
     if (SUCCEEDED(hr))
     {
+#if defined(_M_ARM)
+        hr = MFCopyImage(
+            pData,                      // Destination buffer.
+            -cbWidth,                   // Destination stride.
+            (BYTE*)videoFrameBuffer,    // First row in source image.
+            cbWidth,                    // Source stride.
+            cbWidth,                    // Image width in bytes.
+            videoHeight                 // Image height in pixels.
+            );
+#else
         hr = MFCopyImage(
             pData,                      // Destination buffer.
             cbWidth,                    // Destination stride.
@@ -3675,6 +3479,7 @@ HRESULT CvVideoWriter_MSMF::WriteFrame(DWORD *videoFrameBuffer, const LONGLONG&
             cbWidth,                    // Image width in bytes.
             videoHeight                 // Image height in pixels.
             );
+#endif
     }
 
     if (buffer)
diff --git a/modules/highgui/test/test_video_io.cpp b/modules/highgui/test/test_video_io.cpp
index f46235b3e..5d4de7ecb 100644
--- a/modules/highgui/test/test_video_io.cpp
+++ b/modules/highgui/test/test_video_io.cpp
@@ -73,10 +73,12 @@ const VideoFormat g_specific_fmt_list[] =
         VideoFormat("wmv", CV_FOURCC_MACRO('M', 'P', 'G', '1')),
         VideoFormat("wmv", CV_FOURCC_MACRO('M', 'S', 'S', '1')),
         VideoFormat("wmv", CV_FOURCC_MACRO('M', 'S', 'S', '2')),*/
-        //VideoFormat("avi", CV_FOURCC_MACRO('H', '2', '6', '4')),
+#if !defined(_M_ARM)
         VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '1')),
         VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '2')),
+#endif
         VideoFormat("wmv", CV_FOURCC_MACRO('W', 'M', 'V', '3')),
+        VideoFormat("avi", CV_FOURCC_MACRO('H', '2', '6', '4')),
         //VideoFormat("wmv", CV_FOURCC_MACRO('W', 'V', 'C', '1')),
         VideoFormat()
 };
diff --git a/platforms/winrt/arm.winrt.toolchain.cmake b/platforms/winrt/arm.winrt.toolchain.cmake
index 81bb57fe6..b34056cd5 100644
--- a/platforms/winrt/arm.winrt.toolchain.cmake
+++ b/platforms/winrt/arm.winrt.toolchain.cmake
@@ -3,10 +3,4 @@ set(CMAKE_SYSTEM_PROCESSOR "arm-v7a")
 
 set(CMAKE_FIND_ROOT_PATH "${CMAKE_SOURCE_DIR}/platforms/winrt")
 set(CMAKE_REQUIRED_DEFINITIONS -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
-add_definitions(-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
-
-set(CMAKE_CXX_FLAGS           ""                    CACHE STRING "c++ flags")
-set(CMAKE_C_FLAGS             ""                    CACHE STRING "c flags")
-
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -EHsc -GS")
-set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -GS")
\ No newline at end of file
+add_definitions(-D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE)
\ No newline at end of file

From e32700cf8f92b04fa2b0112281c1f369428b6584 Mon Sep 17 00:00:00 2001
From: Dominik Rose <mya@server.fake>
Date: Thu, 27 Jun 2013 15:05:32 +0200
Subject: [PATCH 52/75] dc1394-2: support for operation mode 1394b added

---
 modules/highgui/src/cap_dc1394_v2.cpp | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/modules/highgui/src/cap_dc1394_v2.cpp b/modules/highgui/src/cap_dc1394_v2.cpp
index 2aa494fac..f197337cd 100644
--- a/modules/highgui/src/cap_dc1394_v2.cpp
+++ b/modules/highgui/src/cap_dc1394_v2.cpp
@@ -295,6 +295,11 @@ bool CvCaptureCAM_DC1394_v2_CPP::startCapture()
         return false;
     if (isoSpeed > 0)
     {
+        // if capable set operation mode to 1394b for iso speeds above 400
+        if (isoSpeed > 400 && dcCam->bmode_capable == DC1394_TRUE)
+        {
+            dc1394_video_set_operation_mode(dcCam, DC1394_OPERATION_MODE_1394B);
+        }
         code = dc1394_video_set_iso_speed(dcCam,
                                           isoSpeed <= 100 ? DC1394_ISO_SPEED_100 :
                                           isoSpeed <= 200 ? DC1394_ISO_SPEED_200 :

From 14dd345cdf5f8197f7080a857c69363537b3f39b Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Fri, 28 Jun 2013 10:12:18 +0800
Subject: [PATCH 53/75] Fix ocl::setBinaryDiskCache Previously the function
 requires Info::Impl implicitly. A call will create new Context this function
 which is not intended. The properties are now moved to global scope to fix
 this issue.

---
 modules/ocl/src/initialization.cpp | 47 +++++++++++++-----------------
 1 file changed, 21 insertions(+), 26 deletions(-)

diff --git a/modules/ocl/src/initialization.cpp b/modules/ocl/src/initialization.cpp
index d4841fcfd..bd6a8e9c7 100644
--- a/modules/ocl/src/initialization.cpp
+++ b/modules/ocl/src/initialization.cpp
@@ -123,9 +123,6 @@ namespace cv
             codeCache.clear();
             cacheSize = 0;
         }
-
-        // not to be exported to dynamic lib
-        void setBinaryDiskCacheImpl(int mode, String path, Info::Impl * impl);
         struct Info::Impl
         {
             cl_platform_id oclplatform;
@@ -143,9 +140,6 @@ namespace cv
             char extra_options[512];
             int  double_support;
             int unified_memory; //1 means integrated GPU, otherwise this value is 0
-            bool enable_disk_cache; 
-            bool update_disk_cache;
-            string binpath;
             int refcounter;
 
             Impl();
@@ -173,6 +167,16 @@ namespace cv
             void releaseResources();
         };
 
+        // global variables to hold binary cache properties
+        static bool enable_disk_cache = 
+#ifdef _DEBUG
+            false;
+#else
+            true;
+#endif
+        static bool update_disk_cache = false;
+        static String binpath = "";
+
         Info::Impl::Impl()
             :oclplatform(0),
             oclcontext(0),
@@ -183,13 +187,9 @@ namespace cv
             maxComputeUnits(0),
             double_support(0),
             unified_memory(0),
-            enable_disk_cache(false),
-            update_disk_cache(false),
-            binpath("./"),
             refcounter(1)
         {
             memset(extra_options, 0, 512);
-            setBinaryDiskCacheImpl(CACHE_RELEASE, String("./"), this);
         }
 
         void Info::Impl::releaseResources()
@@ -504,29 +504,24 @@ namespace cv
             return openCLGetKernelFromSource(clCxt, source, kernelName, NULL);
         }
 
-        void setBinaryDiskCacheImpl(int mode, String path, Info::Impl * impl)
+        void setBinaryDiskCache(int mode, String path)
         {
-            impl->update_disk_cache = (mode & CACHE_UPDATE) == CACHE_UPDATE;
-            impl->enable_disk_cache = 
+            update_disk_cache = (mode & CACHE_UPDATE) == CACHE_UPDATE;
+            enable_disk_cache = 
 #ifdef _DEBUG 
                 (mode & CACHE_DEBUG)   == CACHE_DEBUG;
 #else
                 (mode & CACHE_RELEASE) == CACHE_RELEASE;
 #endif
-            if(impl->enable_disk_cache && !path.empty())
+            if(enable_disk_cache && !path.empty())
             {
-                impl->binpath = path;
+                binpath = path;
             }
         }
-        void setBinaryDiskCache(int mode, cv::String path)
-        {
-            setBinaryDiskCacheImpl(mode, path, Context::getContext()->impl);
-        }
 
         void setBinpath(const char *path)
         {
-            Context *clcxt = Context::getContext();
-            clcxt->impl->binpath = path;
+            binpath = path;
         }
 
         int savetofile(const Context*,  cl_program &program, const char *fileName)
@@ -594,15 +589,15 @@ namespace cv
                     strcat(all_build_options, build_options);
                 if(all_build_options != NULL)
                 {
-                    filename = clCxt->impl->binpath  + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + all_build_options + ".clb";
+                    filename = binpath + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + all_build_options + ".clb";
                 }
                 else
                 {
-                    filename = clCxt->impl->binpath  + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + ".clb";
+                    filename = binpath + kernelName + "_" + clCxt->impl->devName[clCxt->impl->devnum] + ".clb";
                 }
 
-                FILE *fp = clCxt->impl->enable_disk_cache ? fopen(filename.c_str(), "rb") : NULL;
-                if(fp == NULL || clCxt->impl->update_disk_cache)
+                FILE *fp = enable_disk_cache ? fopen(filename.c_str(), "rb") : NULL;
+                if(fp == NULL || update_disk_cache)
                 {
                     if(fp != NULL)
                         fclose(fp);
@@ -611,7 +606,7 @@ namespace cv
                                   clCxt->impl->oclcontext, 1, source, NULL, &status);
                     openCLVerifyCall(status);
                     status = clBuildProgram(program, 1, &(clCxt->impl->devices[clCxt->impl->devnum]), all_build_options, NULL, NULL);
-                    if(status == CL_SUCCESS && clCxt->impl->enable_disk_cache)
+                    if(status == CL_SUCCESS && enable_disk_cache)
                         savetofile(clCxt, program, filename.c_str());
                 }
                 else

From e858a6c347cdf6e4c4122a8717b72137591e5d79 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Fri, 28 Jun 2013 10:39:09 +0800
Subject: [PATCH 54/75] Renew function logic.

---
 modules/ocl/src/initialization.cpp | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/modules/ocl/src/initialization.cpp b/modules/ocl/src/initialization.cpp
index bd6a8e9c7..780c24583 100644
--- a/modules/ocl/src/initialization.cpp
+++ b/modules/ocl/src/initialization.cpp
@@ -168,13 +168,13 @@ namespace cv
         };
 
         // global variables to hold binary cache properties
-        static bool enable_disk_cache = 
+        static int enable_disk_cache = 
 #ifdef _DEBUG
             false;
 #else
             true;
 #endif
-        static bool update_disk_cache = false;
+        static int update_disk_cache = false;
         static String binpath = "";
 
         Info::Impl::Impl()
@@ -506,8 +506,14 @@ namespace cv
 
         void setBinaryDiskCache(int mode, String path)
         {
-            update_disk_cache = (mode & CACHE_UPDATE) == CACHE_UPDATE;
-            enable_disk_cache = 
+            if(mode == CACHE_NONE)
+            {
+                update_disk_cache = 0;
+                enable_disk_cache = 0;
+                return;
+            }
+            update_disk_cache |= (mode & CACHE_UPDATE) == CACHE_UPDATE;
+            enable_disk_cache |= 
 #ifdef _DEBUG 
                 (mode & CACHE_DEBUG)   == CACHE_DEBUG;
 #else

From a5383b8627e1c52bfc114283b0ddf7b990adb439 Mon Sep 17 00:00:00 2001
From: peng xiao <hisenxpress@gmail.com>
Date: Fri, 28 Jun 2013 10:52:39 +0800
Subject: [PATCH 55/75] Move function definition from header to cpp.

---
 modules/ocl/include/opencv2/ocl/ocl.hpp    | 28 ++--------------------
 modules/ocl/src/optical_flow_farneback.cpp | 28 ++++++++++++++++++++++
 2 files changed, 30 insertions(+), 26 deletions(-)

diff --git a/modules/ocl/include/opencv2/ocl/ocl.hpp b/modules/ocl/include/opencv2/ocl/ocl.hpp
index aecf2be74..a41555c04 100644
--- a/modules/ocl/include/opencv2/ocl/ocl.hpp
+++ b/modules/ocl/include/opencv2/ocl/ocl.hpp
@@ -1414,17 +1414,7 @@ namespace cv
         class CV_EXPORTS FarnebackOpticalFlow
         {
         public:
-            FarnebackOpticalFlow()
-            {
-                numLevels = 5;
-                pyrScale = 0.5;
-                fastPyramids = false;
-                winSize = 13;
-                numIters = 10;
-                polyN = 5;
-                polySigma = 1.1;
-                flags = 0;
-            }
+            FarnebackOpticalFlow();
 
             int numLevels;
             double pyrScale;
@@ -1437,21 +1427,7 @@ namespace cv
 
             void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
 
-            void releaseMemory()
-            {
-                frames_[0].release();
-                frames_[1].release();
-                pyrLevel_[0].release();
-                pyrLevel_[1].release();
-                M_.release();
-                bufM_.release();
-                R_[0].release();
-                R_[1].release();
-                blurredFrame_[0].release();
-                blurredFrame_[1].release();
-                pyramid0_.clear();
-                pyramid1_.clear();
-            }
+            void releaseMemory();
 
         private:
             void prepareGaussian(
diff --git a/modules/ocl/src/optical_flow_farneback.cpp b/modules/ocl/src/optical_flow_farneback.cpp
index e5a7abccf..e622446bb 100644
--- a/modules/ocl/src/optical_flow_farneback.cpp
+++ b/modules/ocl/src/optical_flow_farneback.cpp
@@ -241,6 +241,34 @@ static oclMat allocMatFromBuf(int rows, int cols, int type, oclMat &mat)
     return mat = oclMat(rows, cols, type);
 }
 
+cv::ocl::FarnebackOpticalFlow::FarnebackOpticalFlow()
+{
+    numLevels = 5;
+    pyrScale = 0.5;
+    fastPyramids = false;
+    winSize = 13;
+    numIters = 10;
+    polyN = 5;
+    polySigma = 1.1;
+    flags = 0;
+}
+
+void cv::ocl::FarnebackOpticalFlow::releaseMemory()
+{
+    frames_[0].release();
+    frames_[1].release();
+    pyrLevel_[0].release();
+    pyrLevel_[1].release();
+    M_.release();
+    bufM_.release();
+    R_[0].release();
+    R_[1].release();
+    blurredFrame_[0].release();
+    blurredFrame_[1].release();
+    pyramid0_.clear();
+    pyramid1_.clear();
+}
+
 void cv::ocl::FarnebackOpticalFlow::prepareGaussian(
     int n, double sigma, float *g, float *xg, float *xxg,
     double &ig11, double &ig03, double &ig33, double &ig55)

From 587fb4940dbf9ae1c2e6e8aaac06f9d26b5bcdbd Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 11:43:43 +0800
Subject: [PATCH 56/75] some accuracy fix of HOG

---
 modules/ocl/src/hog.cpp                 | 16 ++++++++++++++--
 modules/ocl/src/opencl/objdetect_hog.cl | 15 +++++++++++++++
 modules/ocl/test/test_objdetect.cpp     |  6 +++---
 3 files changed, 32 insertions(+), 5 deletions(-)

diff --git a/modules/ocl/src/hog.cpp b/modules/ocl/src/hog.cpp
index 3533cce69..412afee8b 100644
--- a/modules/ocl/src/hog.cpp
+++ b/modules/ocl/src/hog.cpp
@@ -1816,8 +1816,14 @@ void cv::ocl::device::hog::normalize_hists(int nbins,
         openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
                              localThreads, args, -1, -1, "-D CPU");
     else
+    {
+        cl_kernel kernel = openCLGetKernelFromSource(clCxt, &objdetect_hog, kernelName);
+        int wave_size = queryDeviceInfo<WAVEFRONT_SIZE, int>(kernel);
+        char opt[32] = {0};
+        sprintf(opt, "-D WAVE_SIZE=%d", wave_size);
         openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
-                             localThreads, args, -1, -1);
+                             localThreads, args, -1, -1, opt);
+    }
 }
 
 void cv::ocl::device::hog::classify_hists(int win_height, int win_width, 
@@ -1879,8 +1885,14 @@ void cv::ocl::device::hog::classify_hists(int win_height, int win_width,
         openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
                              localThreads, args, -1, -1, "-D CPU");
     else
+    {
+        cl_kernel kernel = openCLGetKernelFromSource(clCxt, &objdetect_hog, kernelName);
+        int wave_size = queryDeviceInfo<WAVEFRONT_SIZE, int>(kernel);
+        char opt[32] = {0};
+        sprintf(opt, "-D WAVE_SIZE=%d", wave_size);
         openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
-                             localThreads, args, -1, -1);
+                             localThreads, args, -1, -1, opt);
+    }
 }
 
 void cv::ocl::device::hog::extract_descrs_by_rows(int win_height, int win_width, 
diff --git a/modules/ocl/src/opencl/objdetect_hog.cl b/modules/ocl/src/opencl/objdetect_hog.cl
index 05d538330..b9103380d 100644
--- a/modules/ocl/src/opencl/objdetect_hog.cl
+++ b/modules/ocl/src/opencl/objdetect_hog.cl
@@ -318,6 +318,10 @@ float reduce_smem(volatile __local float* smem, int size)
     if (tid < 32)
     {
         if (size >= 64) smem[tid] = sum = sum + smem[tid + 32];
+#if WAVE_SIZE < 32
+    } barrier(CLK_LOCAL_MEM_FENCE);
+    if (tid < 16) {
+#endif
         if (size >= 32) smem[tid] = sum = sum + smem[tid + 16];
         if (size >= 16) smem[tid] = sum = sum + smem[tid + 8];
         if (size >= 8) smem[tid] = sum = sum + smem[tid + 4];
@@ -418,6 +422,9 @@ __kernel void classify_hists_180_kernel(
     {
         smem[tid] = product = product + smem[tid + 32];
     }
+#if WAVE_SIZE < 32
+    barrier(CLK_LOCAL_MEM_FENCE);
+#endif
     if (tid < 16)
     {
         smem[tid] = product = product + smem[tid + 16];
@@ -487,6 +494,10 @@ __kernel void classify_hists_252_kernel(
     if (tid < 32)
     {      
         smem[tid] = product = product + smem[tid + 32];
+#if WAVE_SIZE < 32
+    } barrier(CLK_LOCAL_MEM_FENCE);
+    if (tid < 16) {
+#endif
         smem[tid] = product = product + smem[tid + 16];
         smem[tid] = product = product + smem[tid + 8];
         smem[tid] = product = product + smem[tid + 4];
@@ -553,6 +564,10 @@ __kernel void classify_hists_kernel(
     if (tid < 32)
     {       
         smem[tid] = product = product + smem[tid + 32];
+#if WAVE_SIZE < 32
+    } barrier(CLK_LOCAL_MEM_FENCE);
+    if (tid < 16) {
+#endif
         smem[tid] = product = product + smem[tid + 16];
         smem[tid] = product = product + smem[tid + 8];
         smem[tid] = product = product + smem[tid + 4];
diff --git a/modules/ocl/test/test_objdetect.cpp b/modules/ocl/test/test_objdetect.cpp
index 86590f798..bc719b097 100644
--- a/modules/ocl/test/test_objdetect.cpp
+++ b/modules/ocl/test/test_objdetect.cpp
@@ -146,17 +146,17 @@ TEST_P(HOG, Detect)
     if (winSize.width == 48 && winSize.height == 96)
     {
         // daimler's base
-        ocl_hog.setSVMDetector(ocl_hog.getPeopleDetector48x96());
+        ocl_hog.setSVMDetector(hog.getDaimlerPeopleDetector());
         hog.setSVMDetector(hog.getDaimlerPeopleDetector());
     }
     else if (winSize.width == 64 && winSize.height == 128)
     {
-        ocl_hog.setSVMDetector(ocl_hog.getPeopleDetector64x128());
+        ocl_hog.setSVMDetector(hog.getDefaultPeopleDetector());
         hog.setSVMDetector(hog.getDefaultPeopleDetector());
     }
     else
     {
-        ocl_hog.setSVMDetector(ocl_hog.getDefaultPeopleDetector());
+        ocl_hog.setSVMDetector(hog.getDefaultPeopleDetector());
         hog.setSVMDetector(hog.getDefaultPeopleDetector());
     }
 

From f1d9680ba8fbd16d2b7c2ee21bf826bad73ac22b Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 11:44:43 +0800
Subject: [PATCH 57/75] format the ocl's samples name

---
 modules/ocl/test/main.cpp  | 2 ++
 samples/ocl/CMakeLists.txt | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/modules/ocl/test/main.cpp b/modules/ocl/test/main.cpp
index dd46ff6e0..4ba02cf9b 100644
--- a/modules/ocl/test/main.cpp
+++ b/modules/ocl/test/main.cpp
@@ -118,6 +118,8 @@ int main(int argc, char **argv)
 
     setDevice(oclinfo[pid], device);
 
+    setBinaryDiskCache(CACHE_UPDATE);
+
     cout << "Device type:" << type << endl << "Device name:" << oclinfo[pid].DeviceName[device] << endl;
     return RUN_ALL_TESTS();
 }
diff --git a/samples/ocl/CMakeLists.txt b/samples/ocl/CMakeLists.txt
index cdcf2f3e5..a201d8338 100644
--- a/samples/ocl/CMakeLists.txt
+++ b/samples/ocl/CMakeLists.txt
@@ -27,7 +27,7 @@ if(BUILD_EXAMPLES AND OCV_DEPENDENCIES_FOUND)
     target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} ${OPENCV_OCL_SAMPLES_REQUIRED_DEPS})
 
     set_target_properties(${the_target} PROPERTIES
-      OUTPUT_NAME "${name}_${project}"
+      OUTPUT_NAME "${project}-example-${name}"
       PROJECT_LABEL "(EXAMPLE_${project_upper}) ${name}")
 
     if(ENABLE_SOLUTION_FOLDERS)

From c1a59b8d8066e475e2e9f9da03f29e5e45d9096c Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 13:38:58 +0800
Subject: [PATCH 58/75] more fix to HOG

---
 modules/ocl/src/opencl/objdetect_hog.cl | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/modules/ocl/src/opencl/objdetect_hog.cl b/modules/ocl/src/opencl/objdetect_hog.cl
index b9103380d..8ca12704e 100644
--- a/modules/ocl/src/opencl/objdetect_hog.cl
+++ b/modules/ocl/src/opencl/objdetect_hog.cl
@@ -133,7 +133,9 @@ __kernel void compute_hists_lut_kernel(
             final_hist[(cell_x * 2 + cell_y) * cnbins + bin_id] = 
                 hist_[0] + hist_[1] + hist_[2];
     }
+#ifdef CPU
     barrier(CLK_LOCAL_MEM_FENCE);
+#endif
 
     int tid = (cell_y * CELLS_PER_BLOCK_Y + cell_x) * 12 + cell_thread_x;
     if ((tid < cblock_hist_size) && (gid < blocks_total))
@@ -225,8 +227,9 @@ __kernel void compute_hists_kernel(
             final_hist[(cell_x * 2 + cell_y) * cnbins + bin_id] = 
                 hist_[0] + hist_[1] + hist_[2];
     }
+#ifdef CPU
     barrier(CLK_LOCAL_MEM_FENCE);
-
+#endif
     int tid = (cell_y * CELLS_PER_BLOCK_Y + cell_x) * 12 + cell_thread_x;
     if ((tid < cblock_hist_size) && (gid < blocks_total))
     {

From 6982ea5a669de8e412ce407adceca5efb16c5906 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 15:08:39 +0800
Subject: [PATCH 59/75] some tweaks to samples

---
 samples/ocl/clahe.cpp        | 108 +++++++++++++++++++++++++++++++++++
 samples/ocl/facedetect.cpp   |   7 ++-
 samples/ocl/hog.cpp          |  10 +++-
 samples/ocl/stereo_match.cpp |  16 ++++--
 4 files changed, 134 insertions(+), 7 deletions(-)
 create mode 100644 samples/ocl/clahe.cpp

diff --git a/samples/ocl/clahe.cpp b/samples/ocl/clahe.cpp
new file mode 100644
index 000000000..72fc2fb61
--- /dev/null
+++ b/samples/ocl/clahe.cpp
@@ -0,0 +1,108 @@
+#include <iostream>
+#include "opencv2/core/core.hpp"
+#include "opencv2/imgproc/imgproc.hpp"
+#include "opencv2/highgui/highgui.hpp"
+#include "opencv2/ocl/ocl.hpp"
+using namespace cv;
+using namespace std;
+
+Ptr<CLAHE> pFilter;
+int tilesize;
+int cliplimit;
+string outfile;
+
+static void TSize_Callback(int pos)
+{
+    if(pos==0)
+    {
+        pFilter->setTilesGridSize(Size(1,1));
+    }
+    pFilter->setTilesGridSize(Size(tilesize,tilesize));
+}
+
+static void Clip_Callback(int)
+{
+    pFilter->setClipLimit(cliplimit);
+}
+
+int main(int argc, char** argv)
+{
+    const char* keys =
+        "{ i | input   |                    | specify input image }"
+        "{ c | camera  |    0               | specify camera id   }"
+        "{ s | use_cpu |    false           | use cpu algorithm   }"
+        "{ o | output  | clahe_output.jpg   | specify output save path}";
+
+    CommandLineParser cmd(argc, argv, keys);
+    string infile = cmd.get<string>("i");
+    outfile = cmd.get<string>("o");
+    int camid = cmd.get<int>("c");
+    bool use_cpu = cmd.get<bool>("s");
+    CvCapture* capture = 0;
+    bool running = true;
+
+    namedWindow("CLAHE");
+    createTrackbar("Tile Size", "CLAHE", &tilesize, 32, (TrackbarCallback)TSize_Callback);
+    createTrackbar("Clip Limit", "CLAHE", &cliplimit, 20, (TrackbarCallback)Clip_Callback);
+    Mat frame, outframe;
+    ocl::oclMat d_outframe;
+    
+    int cur_clip;
+    Size cur_tilesize;
+    if(use_cpu)
+    {
+        pFilter = createCLAHE();
+    }
+    else
+    {
+        pFilter = ocl::createCLAHE();
+    }
+    cur_clip = (int)pFilter->getClipLimit();
+    cur_tilesize = pFilter->getTilesGridSize();
+    setTrackbarPos("Tile Size", "CLAHE", cur_tilesize.width);
+    setTrackbarPos("Clip Limit", "CLAHE", cur_clip);
+    if(infile != "")
+    {
+        frame = imread(infile);
+        if(frame.empty())
+        {
+            cout << "error read image: " << infile << endl;
+            return -1;
+        }
+    }
+    else
+    {
+        capture = cvCaptureFromCAM(camid);
+    }
+    cout << "\nControls:\n"
+         << "\to - save output image\n"
+         << "\tESC - exit\n";
+    while(running)
+    {
+        if(capture)
+            frame = cvQueryFrame(capture);
+        else
+            frame = imread(infile);
+        if(frame.empty())
+        {
+            continue;
+        }
+        if(use_cpu)
+        {
+            cvtColor(frame, frame, COLOR_BGR2GRAY);
+            pFilter->apply(frame, outframe);
+        }
+        else
+        {
+            ocl::oclMat d_frame(frame);
+            ocl::cvtColor(d_frame, d_outframe, COLOR_BGR2GRAY);
+            pFilter->apply(d_outframe, d_outframe);
+            d_outframe.download(outframe);
+        }
+        imshow("CLAHE", outframe);
+        char key = (char)cvWaitKey(3);
+        if(key == 'o') imwrite(outfile, outframe);
+        else if(key == 27) running = false;
+    }
+    return 0;
+}
diff --git a/samples/ocl/facedetect.cpp b/samples/ocl/facedetect.cpp
index a49610aeb..ead99b07e 100644
--- a/samples/ocl/facedetect.cpp
+++ b/samples/ocl/facedetect.cpp
@@ -252,8 +252,13 @@ void Draw(Mat& img, vector<Rect>& faces, double scale)
         radius = cvRound((r->width + r->height)*0.25*scale);
         circle( img, center, radius, color, 3, 8, 0 );
     }
-    imshow( "result", img );
     imwrite( outputName, img );
+    if(abs(scale-1.0)>.001)
+    {
+        resize(img, img, Size(img.cols/scale, img.rows/scale));
+    }
+    imshow( "result", img );
+    
 }
 
 
diff --git a/samples/ocl/hog.cpp b/samples/ocl/hog.cpp
index ff53e010c..a8f6b06ea 100644
--- a/samples/ocl/hog.cpp
+++ b/samples/ocl/hog.cpp
@@ -57,6 +57,7 @@ private:
     string vdo_source;
     string output;
     int camera_id;
+    bool write_once;
 };
 
 int main(int argc, char** argv)
@@ -97,6 +98,7 @@ App::App(CommandLineParser& cmd)
          << "\tESC - exit\n"
          << "\tm - change mode GPU <-> CPU\n"
          << "\tg - convert image to gray or not\n"
+         << "\to - save output image once, or switch on/off video save\n"
          << "\t1/q - increase/decrease HOG scale\n"
          << "\t2/w - increase/decrease levels count\n"
          << "\t3/e - increase/decrease HOG group threshold\n"
@@ -120,6 +122,7 @@ App::App(CommandLineParser& cmd)
     hit_threshold = win_width == 48 ? 1.4 : 0.;
     scale = 1.05;
     gamma_corr = true;
+    write_once = false;
 
     cout << "Group threshold: " << gr_threshold << endl;
     cout << "Levels number: " << nlevels << endl;
@@ -254,10 +257,11 @@ void App::run()
 
             workEnd();
 
-            if (output!="")
+            if (output!="" && write_once)
             {
                 if (img_source!="")     // wirte image
                 {
+                    write_once = false;
                     imwrite(output, img_to_show);
                 }
                 else                    //write video
@@ -340,6 +344,10 @@ void App::handleKey(char key)
         gamma_corr = !gamma_corr;
         cout << "Gamma correction: " << gamma_corr << endl;
         break;
+    case 'o':
+    case 'O':
+        write_once = !write_once;
+        break;
     }
 }
 
diff --git a/samples/ocl/stereo_match.cpp b/samples/ocl/stereo_match.cpp
index abe75c70e..8a5031ed7 100644
--- a/samples/ocl/stereo_match.cpp
+++ b/samples/ocl/stereo_match.cpp
@@ -49,7 +49,7 @@ struct App
         return ss.str();
     }
 private:
-    bool running;
+    bool running, write_once;
 
     Mat left_src, right_src;
     Mat left, right;
@@ -115,6 +115,7 @@ App::App(CommandLineParser& cmd)
     cout << "stereo_match_ocl sample\n";
     cout << "\nControls:\n"
          << "\tesc - exit\n"
+         << "\to - save output image once\n"
          << "\tp - print current parameters\n"
          << "\tg - convert source images into gray\n"
          << "\tm - change stereo match method\n"
@@ -132,6 +133,7 @@ App::App(CommandLineParser& cmd)
     else cout << "unknown method!\n";
     ndisp = cmd.get<int>("n");
     out_img = cmd.get<string>("o");
+    write_once = false;
 }
 
 
@@ -161,10 +163,8 @@ void App::run()
     printParams();
 
     running = true;
-    bool written = false;
     while (running)
     {
-
         // Prepare disparity map of specified type
         Mat disp;
         oclMat d_disp;
@@ -192,19 +192,21 @@ void App::run()
             csbp(d_left, d_right, d_disp);
             break;
         }
+
         // Show results
         d_disp.download(disp);
         workEnd();
+
         if (method != BM)
         {
             disp.convertTo(disp, 0);
         }
         putText(disp, text(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar::all(255));
         imshow("disparity", disp);
-        if(!written)
+        if(write_once)
         {
             imwrite(out_img, disp);
-            written = true;
+            write_once = false;
         }
         handleKey((char)waitKey(3));
     }
@@ -378,6 +380,10 @@ void App::handleKey(char key)
             cout << "level_count: " << csbp.levels << endl;
         }
         break;
+    case 'o':
+    case 'O':
+        write_once = true;
+        break;
     }
 }
 

From a8db327574ede94dff6d978f16cc097907dbb442 Mon Sep 17 00:00:00 2001
From: Alexander Shishkov <alexander.shishkov@itseez.com>
Date: Fri, 5 Apr 2013 01:31:30 +0400
Subject: [PATCH 60/75] changed contacts in tutorual

---
 doc/conf.py                                            |  1 +
 .../how_to_write_a_tutorial.rst                        | 10 +++++-----
 2 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/doc/conf.py b/doc/conf.py
index f3f7aec58..00321735d 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -312,6 +312,7 @@ extlinks = {
             'imgproc_geometric' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/geometric_transformations.html#%s', None ),
 
             'opencv_group' : ('http://tech.groups.yahoo.com/group/OpenCV/%s', None),
+            'opencv_qa' : ('http://answers.opencv.org/%s', None),
 
             'cvt_color': ('http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor%s', None),
             'imread':    ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread%s', None),
diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index e1815ed49..4cfb07a2d 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -3,7 +3,7 @@
 How to write a tutorial for OpenCV?
 ***********************************
 
-Okay, so assume you have just finished a project of yours implementing something based on OpenCV and you want to present/share it with the community. Luckily, OpenCV is an *open source project*. This means that in theory anyone has access to the full source code and may extend it. While making a robust and practical library (like OpenCV) is great, the success of a library also depends on how user friendly it is. To improve on this aspect, the OpenCV team has already been listening to user feedback from its :opencv_group:`Yahoo user group <>` and by making samples you can find in the source directories sample folder. The addition of the tutorials (in both online and PDF format) is an extension of these efforts.
+Okay, so assume you have just finished a project of yours implementing something based on OpenCV and you want to present/share it with the community. Luckily, OpenCV is an *open source project*. This means that in theory anyone has access to the full source code and may extend it. While making a robust and practical library (like OpenCV) is great, the success of a library also depends on how user friendly it is. To improve on this aspect, the OpenCV team has already been listening to user feedback from its :opencv_qa:`OpenCV Q&A forum <>` and by making samples you can find in the source directories sample folder. The addition of the tutorials (in both online and PDF format) is an extension of these efforts.
 
 Goal
 ====
@@ -38,7 +38,7 @@ Usually, an OpenCV tutorial has the following parts:
 As you can see you will need at least some basic knowledge of the *reST* system in order to complete the task at hand with success. However, don't worry *reST* (and *Sphinx*) was made with simplicity in mind. It is easy to grasp its basics. I found that the `OpenAlea documentations introduction on this subject <http://openalea.gforge.inria.fr/doc/openalea/doc/_build/html/source/tutorial/rest_syntax.html>`_ (or the `Thomas Cokelaer one <http://thomas-cokelaer.info/tutorials/sphinx/rest_syntax.html>`_ ) should enough for this. If for some directive or feature you need a more in-depth description look it up in the official |reST|_ help files or at the |Sphinx|_ documentation.
 In our world achieving some tasks is possible in multiple ways. However, some of the roads to take may have obvious or hidden advantages over others. Then again, in some other cases it may come down to just simple user preference. Here, I'll present how I decided to write the tutorials, based on my personal experience. If for some of them you know a better solution and you can back it up feel free to use that. I've nothing against it, as long as it gets the job done in an elegant fashion.
 Now the best would be if you could make the integration yourself. For this you need first to have the source code. I recommend following the guides for your operating system on acquiring OpenCV sources. For Linux users look :ref:`here <Linux-Installation>` and for :ref:`Windows here <Windows_Installation>`. You must also install python and sphinx with its dependencies in order to be able to build the documentation.
-Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the trunk source files from  :file:`git://code.opencv.org/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact dr. Gary Bradski at -delete-bradski@-delete-willowgarage.com. Otherwise, you can just send the resulting files to us via the :opencv_group:`Yahoo user group <>` or to me at -delete-bernat@-delete-primeranks.net and I'll add it. If you have questions, suggestions or constructive critics I will gladly listen to them. If you send it to the OpenCV group please tag its subject with a **[Tutorial]** entry.
+Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the trunk source files from  :file:`git://github.com/Itseez/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact OpenCV administrator -delete-admin@-delete-opencv.org. Otherwise, you can just send the resulting files to us at -delete-admin@-delete-opencv.org and we'll add it. 
 
 Format the Source Code
 ======================
@@ -339,6 +339,6 @@ Now here's our recommendation for the structure of the tutorial (although, remem
 Take home the pride and joy of a job well done!
 ===============================================
 
-Once you are done contact me or dr. Gary Bradski with the tutorial. We may submit the tutorial ourselves to the trunk branch of our repository or ask you to do so.
-Now, to see your work **live** you may need to wait some time. The PDFs are updated usually at the launch of a new OpenCV version. The web pages are a little more diverse. They are automatically rebuilt in each evening. However, the **opencv.itseez.com** website contains only the most recent **stable branch** of OpenCV. Currently this is 2.3. When we add something new (like a tutorial) that first goes to the **trunk branch** of our repository. A build of this you may find on the **opencv.itseez.com/trunk** website. Although, we try to make a build every night occasionally we might freeze any of the branches to fix upcoming issues. During this it may take a little longer to see your work *live*, however if you submited it, be sure that eventually it will show up.
-If you have any questions or advices relating to this tutorial you can contact me at -delete-bernat@-delete-primeranks.net. Of course, delete the -delete- parts of that e-mail address.
\ No newline at end of file
+Once you are done contact us with the tutorial. We may submit the tutorial ourselves to the trunk branch of our repository or ask you to do a pullrequest to our repository.
+Now, to see your work **live** you may need to wait some time. The PDFs are updated usually at the launch of a new OpenCV version. The web pages are a little more diverse. They are automatically rebuilt in each evening. However, the **docs.opencv.org** website contains only the most recent **stable branch** of OpenCV. Currently this is 2.4. When we add something new (like a tutorial) that first goes to the **trunk branch** of our repository. A build of this you may find on the **docs.opencv.org/trunk** website. Although, we try to make a build every night occasionally we might freeze any of the branches to fix upcoming issues. During this it may take a little longer to see your work *live*, however if you submited it, be sure that eventually it will show up.
+If you have any questions or advices relating to this tutorial you can contact us at -delete-admin@-delete-opencv.org. Of course, delete the -delete- parts of that e-mail address.
\ No newline at end of file

From e447d87496522cf64543828c3bc768973ff6962e Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Thu, 13 Jun 2013 16:48:17 +0400
Subject: [PATCH 61/75] Added link to contribution process, updated formatting

---
 .../how_to_write_a_tutorial.rst               | 61 ++++++++++++++++---
 1 file changed, 52 insertions(+), 9 deletions(-)

diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index 4cfb07a2d..4b79aed7a 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -1,9 +1,22 @@
 .. _howToWriteTutorial:
 
-How to write a tutorial for OpenCV?
-***********************************
+How to write a tutorial for OpenCV
+**********************************
 
-Okay, so assume you have just finished a project of yours implementing something based on OpenCV and you want to present/share it with the community. Luckily, OpenCV is an *open source project*. This means that in theory anyone has access to the full source code and may extend it. While making a robust and practical library (like OpenCV) is great, the success of a library also depends on how user friendly it is. To improve on this aspect, the OpenCV team has already been listening to user feedback from its :opencv_qa:`OpenCV Q&A forum <>` and by making samples you can find in the source directories sample folder. The addition of the tutorials (in both online and PDF format) is an extension of these efforts.
+Okay, so assume you have just finished a project of yours implementing something
+based on OpenCV and you want to present/share it with the community. Luckily, OpenCV
+is an *open source project*. This means that anyone has access to the full source
+code and may propose extensions. And a good tutorial is a valuable addition to the
+library! Please read instructions on contribution process here:
+http://opencv.org/contribute.html. You may also find this page helpful:
+http://code.opencv.org/projects/opencv/wiki/How_to_contribute.
+
+While making a robust and practical library (like OpenCV) is great, the success of a
+library also depends on how user friendly it is. To improve on this aspect, the
+OpenCV team has already been listening to user feedback at :opencv_qa:`OpenCV Q&A
+forum <>` and by making samples you can find in the source directories
+:file:`samples` folder. The addition of the tutorials (in both online and PDF format)
+is an extension of these efforts.
 
 Goal
 ====
@@ -15,7 +28,17 @@ Goal
 
 .. _Sphinx: http://sphinx.pocoo.org/
 
-The tutorials are just as an important part of the library as  the implementation of those crafty data structures and algorithms you can find in OpenCV. Therefore, the source codes for the tutorials are part of the library. And yes, I meant source codes. The reason for this formulation is that the tutorials are written by using the |Sphinx|_ documentation generation system. This is based on the popular python documentation system called |reST|_ (reST). ReStructuredText is a really neat language that by using a few simple conventions (indentation, directives) and emulating old school e-mail writing techniques (text only) tries to offer a simple way to create and edit documents. Sphinx extends this with some new features and creates the resulting document in both HTML (for web) and PDF (for offline usage) format.
+The tutorials are just as an important part of the library as the implementation of
+those crafty data structures and algorithms you can find in OpenCV. Therefore, the
+source codes for the tutorials are part of the library. And yes, I meant source
+codes. The reason for this formulation is that the tutorials are written by using the
+|Sphinx|_ documentation generation system. This is based on the popular Python
+documentation system called |reST|_ (reST). ReStructuredText is a really neat
+language that by using a few simple conventions (indentation, directives) and
+emulating old school email writing techniques (text only) tries to offer a simple
+way to create and edit documents. Sphinx extends this with some new features and
+creates the resulting document in both HTML (for web) and PDF (for offline usage)
+format.
 
 Usually, an OpenCV tutorial has the following parts:
 
@@ -36,14 +59,17 @@ Usually, an OpenCV tutorial has the following parts:
     #. For more complex demonstrations you may create a video.
 
 As you can see you will need at least some basic knowledge of the *reST* system in order to complete the task at hand with success. However, don't worry *reST* (and *Sphinx*) was made with simplicity in mind. It is easy to grasp its basics. I found that the `OpenAlea documentations introduction on this subject <http://openalea.gforge.inria.fr/doc/openalea/doc/_build/html/source/tutorial/rest_syntax.html>`_ (or the `Thomas Cokelaer one <http://thomas-cokelaer.info/tutorials/sphinx/rest_syntax.html>`_ ) should enough for this. If for some directive or feature you need a more in-depth description look it up in the official |reST|_ help files or at the |Sphinx|_ documentation.
+
 In our world achieving some tasks is possible in multiple ways. However, some of the roads to take may have obvious or hidden advantages over others. Then again, in some other cases it may come down to just simple user preference. Here, I'll present how I decided to write the tutorials, based on my personal experience. If for some of them you know a better solution and you can back it up feel free to use that. I've nothing against it, as long as it gets the job done in an elegant fashion.
+
 Now the best would be if you could make the integration yourself. For this you need first to have the source code. I recommend following the guides for your operating system on acquiring OpenCV sources. For Linux users look :ref:`here <Linux-Installation>` and for :ref:`Windows here <Windows_Installation>`. You must also install python and sphinx with its dependencies in order to be able to build the documentation.
-Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the trunk source files from  :file:`git://github.com/Itseez/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact OpenCV administrator -delete-admin@-delete-opencv.org. Otherwise, you can just send the resulting files to us at -delete-admin@-delete-opencv.org and we'll add it. 
+
+Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the trunk source files from :file:`git://github.com/Itseez/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact OpenCV administrator -delete-admin@-delete-opencv.org. Otherwise, you can just send the resulting files to us at -delete-admin@-delete-opencv.org and we'll add it.
 
 Format the Source Code
 ======================
 
-Before I start this let it be clear: the main goal is to have a working sample code. However, for your tutorial to be of a top notch quality you should follow a few guide lines I am going to present here. In case you have an application by using the older interface (with *IplImage*, *CVMat*, *cvLoadImage* and such) consider migrating it to the new C++ interface. The tutorials are intended to be an up to date help for our users. And as of OpenCV 2 the OpenCV emphasis on using the less error prone and clearer C++ interface. Therefore, if possible please convert your code to the C++ interface. For this it may help to read the :ref:`InteroperabilityWithOpenCV1` tutorial. However, once you have an OpenCV 2 working code, then you should make your source code snippet as easy to read as possible. Here're a couple of advices for this:
+Before I start this let it be clear: the main goal is to have a working sample code. However, for your tutorial to be of a top notch quality you should follow a few guide lines I am going to present here. In case you have an application by using the older interface (with *IplImage*, *cvMat*, *cvLoadImage* and such) consider migrating it to the new C++ interface. The tutorials are intended to be an up to date help for our users. And as of OpenCV 2 the OpenCV emphasis on using the less error prone and clearer C++ interface. Therefore, if possible please convert your code to the C++ interface. For this it may help to read the :ref:`InteroperabilityWithOpenCV1` tutorial. However, once you have an OpenCV 2 working code, then you should make your source code snippet as easy to read as possible. Here're a couple of advices for this:
 
 .. container:: enumeratevisibleitemswithsquare
 
@@ -102,6 +128,7 @@ Navigate to the :file:`opencv/doc/tutorials/section/table_of_content_section` fo
       \pagebreak
 
 The first line is a reference to the section title in the reST system. The section title will be a link and you may refer to it via the ``:ref:`` directive. The *include* directive imports the template text from the definitions directories *noContent.rst* file. *Sphinx* does not creates the PDF from scratch. It does this by first creating a latex file. Then creates the PDF from the latex file. With the *raw* directive you can directly add to this output commands. Its unique argument is for what kind of output to add the content of the directive. For the PDFs it may happen that multiple sections will overlap on a single page. To avoid this at the end of the TOC we add a *pagebreak* latex command, that hints to the LATEX system that the next line should be on a new page.
+
 If you have one of this, try to transform it to the following form:
 
 .. include:: ../../definitions/tocDefinitions.rst
@@ -157,6 +184,7 @@ Until the *raw* directive what you can see is a TOC tree entry. Here's how a TOC
                    :width:  90pt
 
 As you can see we have an image to the left and a description box to the right. To create two boxes we use a table with two columns and a single row. In the left column is the image and in the right one the description. However, the image directive is way too long to fit in a column. Therefore, we need to use the substitution definition system. We add this definition after the TOC tree. All images for the TOC tree are to be put in the images folder near its |reST|_ file. We use the point measurement system because we are also creating PDFs. PDFs are printable documents, where there is no such thing that pixels (px), just points (pt). And while generally space is no problem for web pages (we have monitors with **huge** resolutions) the size of the paper (A4 or letter) is constant and will be for a long time in the future. Therefore, size constrains come in play more like for the PDF, than the generated HTML code.
+
 Now your images should be as small as possible, while still offering the intended information for the user. Remember that the tutorial will become part of the OpenCV source code. If you add large images (that manifest in form of large image size) it will just increase the size of the repository pointlessly. If someone wants to download it later, its download time will be that much longer. Not to mention the larger PDF size for the tutorials and the longer load time for the web pages. In terms of pixels a TOC image should not be larger than 120 X 120 pixels. Resize your images if they are larger!
 
 .. note:: If you add a larger image and specify a smaller image size, *Sphinx* will not resize that. At build time will add the full size image and the resize will be done by your browser after the image is loaded. A 120 X 120 image is somewhere below 10KB. If you add a 110KB image, you have just pointlessly added a 100KB extra data to transfer over the internet for every user!
@@ -189,7 +217,9 @@ Now before each TOC entry you need to add the three lines of:
      .. cssclass:: toctableopencv
 
 The plus sign (+) is to enumerate tutorials by using bullet points. So for every TOC entry we have a corresponding bullet point represented by the +. Sphinx is highly indenting sensitive. Indentation is used to express from which point until to which point does a construction last. Un-indentation means end of that construction. So to keep all the bullet points to the same group the following TOC entries (until the next +) should be indented by two spaces.
+
 Here, I should also mention that **always** prefer using spaces instead of tabs. Working with only spaces makes possible that if we both use monotype fonts we will see the same thing. Tab size is text editor dependent and as should be avoided. *Sphinx* translates all tabs into 8 spaces before interpreting it.
+
 It turns out that the automatic formatting of both the HTML and PDF(LATEX) system messes up our tables. Therefore, we need to help them out a little. For the PDF generation we add the ``.. tabularcolumns:: m{100pt} m{300pt}`` directive. This means that the first column should be 100 points wide and middle aligned. For the HTML look we simply name the following table of a *toctableopencv* class type. Then, we can modify the look of the table by modifying the CSS of our web page. The CSS definitions go into the :file:`opencv/doc/_themes/blue/static/default.css_t` file.
 
 .. code-block:: css
@@ -221,12 +251,14 @@ However, you should not need to modify this. Just add these three lines (plus ke
       ../mat - the basic image container/mat - the basic image container
 
 The page break entry comes for separating sections and should be only one in a TOC tree |reST|_ file. Finally, at the end of the TOC tree we need to add our tutorial to the *Sphinx* TOC tree system. *Sphinx* will generate from this the previous-next-up information for the HTML file and add items to the PDF according to the order here. By default this TOC tree directive generates a simple table of contents. However, we already created a fancy looking one so we no longer need this basic one. Therefore, we add the *hidden* option to do not show it.
+
 The path is of a relative type. We step back in the file system and then go into the :file:`mat - the basic image container` directory for the :file:`mat - the basic image container.rst` file. Putting out the *rst* extension for the file is optional.
 
 Write the tutorial
 ==================
 
 Create a folder with the name of your tutorial. Preferably, use small letters only. Then create a text file in this folder with *rst* extension and the same name. If you have images for the tutorial create an :file:`images` folder and add your images there. When creating your images follow the guidelines described in the previous part!
+
 Now here's our recommendation for the structure of the tutorial (although, remember that this is not carved in the stone; if you have a better idea, use it!):
 
 .. container:: enumeratevisibleitemswithsquare
@@ -339,6 +371,17 @@ Now here's our recommendation for the structure of the tutorial (although, remem
 Take home the pride and joy of a job well done!
 ===============================================
 
-Once you are done contact us with the tutorial. We may submit the tutorial ourselves to the trunk branch of our repository or ask you to do a pullrequest to our repository.
-Now, to see your work **live** you may need to wait some time. The PDFs are updated usually at the launch of a new OpenCV version. The web pages are a little more diverse. They are automatically rebuilt in each evening. However, the **docs.opencv.org** website contains only the most recent **stable branch** of OpenCV. Currently this is 2.4. When we add something new (like a tutorial) that first goes to the **trunk branch** of our repository. A build of this you may find on the **docs.opencv.org/trunk** website. Although, we try to make a build every night occasionally we might freeze any of the branches to fix upcoming issues. During this it may take a little longer to see your work *live*, however if you submited it, be sure that eventually it will show up.
-If you have any questions or advices relating to this tutorial you can contact us at -delete-admin@-delete-opencv.org. Of course, delete the -delete- parts of that e-mail address.
\ No newline at end of file
+Once you are done please make a pull request with the tutorial. Now, to see your work
+**live** you may need to wait some time. The PDFs are updated usually at the launch
+of a new OpenCV version. The web pages are a little more diverse. They are
+automatically rebuilt nightly. However, the **docs.opencv.org** website contains only
+the most recent **stable branch** of OpenCV. Currently this is 2.4. If, for example,
+you have submitted your tutorial to the Git's ``master`` branch, then it should appear at
+the **docs.opencv.org/master** website soon. Although, we try to make a build every
+night, occasionally we might freeze any of the branches to fix upcoming issues.
+During this it may take a little longer to see your work online, however if you
+submited it, be sure that eventually it will show up.
+
+If you have any questions or advices relating to this tutorial you can contact us at
+-delete-admin@-delete-opencv.org. Of course, delete the -delete- parts of that email
+address.
\ No newline at end of file

From 2980a885701b582029f7ff922973775b79ddc924 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 11:51:40 +0400
Subject: [PATCH 62/75] Mentioned 2.4 and master branches

---
 .../how_to_write_a_tutorial.rst               | 24 +++++++++----------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index 4b79aed7a..bd8b56ca2 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -371,17 +371,17 @@ Now here's our recommendation for the structure of the tutorial (although, remem
 Take home the pride and joy of a job well done!
 ===============================================
 
-Once you are done please make a pull request with the tutorial. Now, to see your work
-**live** you may need to wait some time. The PDFs are updated usually at the launch
-of a new OpenCV version. The web pages are a little more diverse. They are
-automatically rebuilt nightly. However, the **docs.opencv.org** website contains only
-the most recent **stable branch** of OpenCV. Currently this is 2.4. If, for example,
-you have submitted your tutorial to the Git's ``master`` branch, then it should appear at
-the **docs.opencv.org/master** website soon. Although, we try to make a build every
-night, occasionally we might freeze any of the branches to fix upcoming issues.
-During this it may take a little longer to see your work online, however if you
-submited it, be sure that eventually it will show up.
+Once you are done please make a GitHub pull request with the tutorial. Now, to see
+your work **live** you may need to wait some time. The PDFs are updated usually at
+the launch of a new OpenCV version. The web pages are a little more diverse. They are
+automatically rebuilt nightly. Currently we use ``2.4`` and ``master`` branches for
+daily builds. So, if your pull request was merged to any of these branches, your
+material will be published at **docs.opencv.org/2.4** or **docs.opencv.org/master**
+correspondingly. Everything that was added to ``2.4`` is merged to ``master`` branch
+every week. Although, we try to make a build every night, occasionally we might
+freeze any of the branches to fix upcoming issues. During this it may take a little
+longer to see your work online, however if you submitted it, be sure that eventually
+it will show up.
 
 If you have any questions or advices relating to this tutorial you can contact us at
--delete-admin@-delete-opencv.org. Of course, delete the -delete- parts of that email
-address.
\ No newline at end of file
+-delete-admin@-delete-opencv.org (delete the -delete- parts of that email address).
\ No newline at end of file

From 2cacad9470c26a356baa621fab69c655504cc663 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 11:53:39 +0400
Subject: [PATCH 63/75] updated email address

---
 doc/conf.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/conf.py b/doc/conf.py
index 00321735d..4b250b80b 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -284,7 +284,7 @@ latex_domain_indices = True
 # (source start file, name, description, authors, manual section).
 man_pages = [
     ('index', 'opencv', u'The OpenCV Reference Manual',
-     [u'opencv-dev@itseez.com'], 1)
+     [u'admin@opencv.org'], 1)
 ]
 
 # ---- External links for tutorials -----------------

From a78ebc11755a60864aaf9b7fa1b61531d420eafd Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 12:12:53 +0400
Subject: [PATCH 64/75] Updated a couple of more links

---
 doc/conf.py                                        |  3 ++-
 doc/tutorials/definitions/noContent.rst            |  2 +-
 .../how_to_write_a_tutorial.rst                    | 14 +++++++-------
 3 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/doc/conf.py b/doc/conf.py
index 4b250b80b..5b3dce6ad 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -311,8 +311,9 @@ extlinks = {
             'feature2d' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/feature_detection.html#%s', None ),
             'imgproc_geometric' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/geometric_transformations.html#%s', None ),
 
-            'opencv_group' : ('http://tech.groups.yahoo.com/group/OpenCV/%s', None),
+            'opencv_group' : ('http://answers.opencv.org/%s', None),
             'opencv_qa' : ('http://answers.opencv.org/%s', None),
+            'how_to_contribute' : ('http://code.opencv.org/projects/opencv/wiki/How_to_contribute/%s', None),
 
             'cvt_color': ('http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor%s', None),
             'imread':    ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread%s', None),
diff --git a/doc/tutorials/definitions/noContent.rst b/doc/tutorials/definitions/noContent.rst
index 35f9b2ae4..a273a9ad1 100644
--- a/doc/tutorials/definitions/noContent.rst
+++ b/doc/tutorials/definitions/noContent.rst
@@ -1,3 +1,3 @@
 
 .. note::
-   Unfortunetly we have no tutorials into this section. Nevertheless, our tutorial writting team is working on it. If you have a tutorial suggestion or you have writen yourself a tutorial (or coded a sample code) that you would like to see here please contact us via our :opencv_group:`user group <>`. 
\ No newline at end of file
+   Unfortunetly we have no tutorials into this section. And you can help us with that, since OpenCV is a community effort. If you have a tutorial suggestion or you have written a tutorial yourself (or coded a sample code) that you would like to see here, please contact follow these instructions: :ref:`howToWriteTutorial` and :how_to_contribute:`How to contribute <>`.
\ No newline at end of file
diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index bd8b56ca2..604496862 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -9,7 +9,7 @@ is an *open source project*. This means that anyone has access to the full sourc
 code and may propose extensions. And a good tutorial is a valuable addition to the
 library! Please read instructions on contribution process here:
 http://opencv.org/contribute.html. You may also find this page helpful:
-http://code.opencv.org/projects/opencv/wiki/How_to_contribute.
+:how_to_contribute:`How to contribute <>`.
 
 While making a robust and practical library (like OpenCV) is great, the success of a
 library also depends on how user friendly it is. To improve on this aspect, the
@@ -376,12 +376,12 @@ your work **live** you may need to wait some time. The PDFs are updated usually
 the launch of a new OpenCV version. The web pages are a little more diverse. They are
 automatically rebuilt nightly. Currently we use ``2.4`` and ``master`` branches for
 daily builds. So, if your pull request was merged to any of these branches, your
-material will be published at **docs.opencv.org/2.4** or **docs.opencv.org/master**
-correspondingly. Everything that was added to ``2.4`` is merged to ``master`` branch
-every week. Although, we try to make a build every night, occasionally we might
-freeze any of the branches to fix upcoming issues. During this it may take a little
-longer to see your work online, however if you submitted it, be sure that eventually
-it will show up.
+material will be published at `docs.opencv.org/2.4 <http:/docs.opencv.org/2.4>`_ or
+`docs.opencv.org/master <http:/docs.opencv.org/master>`_ correspondingly. Everything
+that was added to ``2.4`` is merged to ``master`` branch every week. Although, we try
+to make a build every night, occasionally we might freeze any of the branches to fix
+upcoming issues. During this it may take a little longer to see your work online,
+however if you submitted it, be sure that eventually it will show up.
 
 If you have any questions or advices relating to this tutorial you can contact us at
 -delete-admin@-delete-opencv.org (delete the -delete- parts of that email address).
\ No newline at end of file

From f065c46fbe53f34861b719e057429e272ee30690 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 12:15:14 +0400
Subject: [PATCH 65/75] Completely get rid of opencv_group

---
 doc/conf.py                                                    | 2 +-
 doc/tutorials/introduction/windows_install/windows_install.rst | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/doc/conf.py b/doc/conf.py
index 5b3dce6ad..aa72b580d 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -311,7 +311,7 @@ extlinks = {
             'feature2d' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/feature_detection.html#%s', None ),
             'imgproc_geometric' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/geometric_transformations.html#%s', None ),
 
-            'opencv_group' : ('http://answers.opencv.org/%s', None),
+            # 'opencv_group' : ('http://answers.opencv.org/%s', None),
             'opencv_qa' : ('http://answers.opencv.org/%s', None),
             'how_to_contribute' : ('http://code.opencv.org/projects/opencv/wiki/How_to_contribute/%s', None),
 
diff --git a/doc/tutorials/introduction/windows_install/windows_install.rst b/doc/tutorials/introduction/windows_install/windows_install.rst
index d1ae8fa1f..cbfd0f66f 100644
--- a/doc/tutorials/introduction/windows_install/windows_install.rst
+++ b/doc/tutorials/introduction/windows_install/windows_install.rst
@@ -292,7 +292,7 @@ Building the library
 
    This will create an *Install* directory inside the *Build* one collecting all the built binaries into a single place. Use this only after you built both the *Release* and *Debug* versions.
 
-   To test your build just go into the :file:`Build/bin/Debug` or :file:`Build/bin/Release` directory and start a couple of applications like the *contours.exe*. If they run, you are done. Otherwise, something definitely went awfully wrong. In this case you should contact us via our :opencv_group:`user group <>`.
+   To test your build just go into the :file:`Build/bin/Debug` or :file:`Build/bin/Release` directory and start a couple of applications like the *contours.exe*. If they run, you are done. Otherwise, something definitely went awfully wrong. In this case you should contact us at our :opencv_qa:`Q&A forum <>`.
    If everything is okay the *contours.exe* output should resemble the following image (if built with Qt support):
 
    .. image:: images/WindowsQtContoursOutput.png

From cbed07bc1864d89797442e2f616b461cd42cf2d3 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 12:21:52 +0400
Subject: [PATCH 66/75] Removed references to YG from samples

---
 modules/highgui/src/cap_libv4l.cpp |  4 +++-
 modules/highgui/src/cap_v4l.cpp    |  4 +++-
 samples/cpp/stereo_calib.cpp       | 15 ++++++---------
 3 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/modules/highgui/src/cap_libv4l.cpp b/modules/highgui/src/cap_libv4l.cpp
index b081621b1..6027caec2 100644
--- a/modules/highgui/src/cap_libv4l.cpp
+++ b/modules/highgui/src/cap_libv4l.cpp
@@ -14,7 +14,9 @@ It has been tested with the motempl sample program
 First Patch:  August 24, 2004 Travis Wood   TravisOCV@tkwood.com
 For Release:  OpenCV-Linux Beta4  opencv-0.9.6
 Tested On:    LMLBT44 with 8 video inputs
-Problems?     Post problems/fixes to OpenCV group on groups.yahoo.com
+Problems?     Post your questions at answers.opencv.org, 
+              Report bugs at code.opencv.org,
+              Submit your fixes at https://github.com/Itseez/opencv/
 Patched Comments:
 
 TW: The cv cam utils that came with the initial release of OpenCV for LINUX Beta4
diff --git a/modules/highgui/src/cap_v4l.cpp b/modules/highgui/src/cap_v4l.cpp
index a788c903f..23497a595 100644
--- a/modules/highgui/src/cap_v4l.cpp
+++ b/modules/highgui/src/cap_v4l.cpp
@@ -14,7 +14,9 @@ It has been tested with the motempl sample program
 First Patch:  August 24, 2004 Travis Wood   TravisOCV@tkwood.com
 For Release:  OpenCV-Linux Beta4  opencv-0.9.6
 Tested On:    LMLBT44 with 8 video inputs
-Problems?     Post problems/fixes to OpenCV group on groups.yahoo.com
+Problems?     Post your questions at answers.opencv.org, 
+              Report bugs at code.opencv.org,
+              Submit your fixes at https://github.com/Itseez/opencv/
 Patched Comments:
 
 TW: The cv cam utils that came with the initial release of OpenCV for LINUX Beta4
diff --git a/samples/cpp/stereo_calib.cpp b/samples/cpp/stereo_calib.cpp
index 07621cef8..2c65fb099 100644
--- a/samples/cpp/stereo_calib.cpp
+++ b/samples/cpp/stereo_calib.cpp
@@ -14,15 +14,12 @@
      Or: http://oreilly.com/catalog/9780596516130/
      ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
 
-   OTHER OPENCV SITES:
-   * The source code is on sourceforge at:
-     http://sourceforge.net/projects/opencvlibrary/
-   * The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back):
-     http://opencvlibrary.sourceforge.net/
-   * An active user group is at:
-     http://tech.groups.yahoo.com/group/OpenCV/
-   * The minutes of weekly OpenCV development meetings are at:
-     http://code.opencv.org/projects/opencv/wiki/Meeting_notes
+   OPENCV WEBSITES:
+     Homepage:      http://opencv.org
+     Online docs:   http://docs.opencv.org
+     Q&A forum:     http://answers.opencv.org
+     Issue tracker: http://code.opencv.org
+     GitHub:        https://github.com/Itseez/opencv/
    ************************************************** */
 
 #include "opencv2/calib3d/calib3d.hpp"

From c73a10cb4d34dced5f7d54e0a0e5cb78ee24aa96 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 16:23:01 +0800
Subject: [PATCH 67/75] warnings fix

---
 samples/ocl/facedetect.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/samples/ocl/facedetect.cpp b/samples/ocl/facedetect.cpp
index ead99b07e..49148bdec 100644
--- a/samples/ocl/facedetect.cpp
+++ b/samples/ocl/facedetect.cpp
@@ -255,7 +255,7 @@ void Draw(Mat& img, vector<Rect>& faces, double scale)
     imwrite( outputName, img );
     if(abs(scale-1.0)>.001)
     {
-        resize(img, img, Size(img.cols/scale, img.rows/scale));
+        resize(img, img, Size((int)(img.cols/scale), (int)(img.rows/scale)));
     }
     imshow( "result", img );
     

From 0339dd51f1a1ff3bf6738c1c4d050636397cc3b4 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 12:38:44 +0400
Subject: [PATCH 68/75] Removed all references to trunk

---
 doc/_themes/blue/layout.html                                | 2 +-
 doc/conf.py                                                 | 6 +++---
 .../introduction/android_binary_package/O4A_SDK.rst         | 2 +-
 .../how_to_write_a_tutorial/how_to_write_a_tutorial.rst     | 2 +-
 .../windows_visual_studio_Opencv.rst                        | 2 +-
 5 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/doc/_themes/blue/layout.html b/doc/_themes/blue/layout.html
index a376c9759..d0d43031c 100644
--- a/doc/_themes/blue/layout.html
+++ b/doc/_themes/blue/layout.html
@@ -183,7 +183,7 @@
                   {% if theme_lang == 'c' %}
                   {% endif %}
                   {% if theme_lang == 'cpp' %}
-                    <li>Try the <a href="http://docs.opencv.org/trunk/opencv_cheatsheet.pdf">Cheatsheet</a>.</li>
+                    <li>Try the <a href="http://docs.opencv.org/opencv_cheatsheet.pdf">Cheatsheet</a>.</li>
                   {% endif %}
                   {% if theme_lang == 'py' %}
                     <li>Try the <a href="cookbook.html">Cookbook</a>.</li>
diff --git a/doc/conf.py b/doc/conf.py
index aa72b580d..f3564772f 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -307,9 +307,9 @@ extlinks = {
             'gpumatrixreduct' : ('http://opencv.itseez.com/modules/gpu/doc/matrix_reductions.html#%s', None),
             'filtering':('http://opencv.itseez.com/modules/imgproc/doc/filtering.html#%s', None),
             'flann' : ('http://opencv.itseez.com/modules/flann/doc/flann_fast_approximate_nearest_neighbor_search.html#%s', None ),
-            'calib3d' : ('http://opencv.itseez.com/trunk/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#%s', None ),
-            'feature2d' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/feature_detection.html#%s', None ),
-            'imgproc_geometric' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/geometric_transformations.html#%s', None ),
+            'calib3d' : ('http://opencv.itseez.com/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#%s', None ),
+            'feature2d' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html#%s', None ),
+            'imgproc_geometric' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html#%s', None ),
 
             # 'opencv_group' : ('http://answers.opencv.org/%s', None),
             'opencv_qa' : ('http://answers.opencv.org/%s', None),
diff --git a/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst b/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
index 20f0bf655..d2d38ab94 100644
--- a/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
+++ b/doc/tutorials/introduction/android_binary_package/O4A_SDK.rst
@@ -98,7 +98,7 @@ The structure of package contents looks as follows:
 * :file:`doc` folder contains various OpenCV documentation in PDF format.
   It's also available online at http://docs.opencv.org.
 
-  .. note:: The most recent docs (nightly build) are at http://docs.opencv.org/trunk/.
+  .. note:: The most recent docs (nightly build) are at http://docs.opencv.org/2.4.
             Generally, it's more up-to-date, but can refer to not-yet-released functionality.
 
 .. TODO: I'm not sure that this is the best place to talk about OpenCV Manager
diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index 604496862..f57217324 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -64,7 +64,7 @@ In our world achieving some tasks is possible in multiple ways. However, some of
 
 Now the best would be if you could make the integration yourself. For this you need first to have the source code. I recommend following the guides for your operating system on acquiring OpenCV sources. For Linux users look :ref:`here <Linux-Installation>` and for :ref:`Windows here <Windows_Installation>`. You must also install python and sphinx with its dependencies in order to be able to build the documentation.
 
-Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the trunk source files from :file:`git://github.com/Itseez/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact OpenCV administrator -delete-admin@-delete-opencv.org. Otherwise, you can just send the resulting files to us at -delete-admin@-delete-opencv.org and we'll add it.
+Once you have downloaded the repository to your hard drive you can take a look in the OpenCV directory to make sure you have both the samples and doc folder present. Anyone may download the latest source files from :file:`git://github.com/Itseez/opencv.git` . Nevertheless, not everyone has upload (commit/submit) rights. This is to protect the integrity of the library. If you plan doing more than one tutorial, and would like to have an account with commit user rights you should first register an account at http://code.opencv.org/ and then contact OpenCV administrator -delete-admin@-delete-opencv.org. Otherwise, you can just send the resulting files to us at -delete-admin@-delete-opencv.org and we'll add it.
 
 Format the Source Code
 ======================
diff --git a/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst b/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst
index 71be06f76..d5f80f2f1 100644
--- a/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst
+++ b/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst
@@ -86,7 +86,7 @@ The names of the libraries are as follow:
 
    opencv_(The Name of the module)(The version Number of the library you use)d.lib
 
-A full list, for the currently latest trunk version would contain:
+A full list, for the latest version would contain:
 
 .. code-block:: bash
 

From aef347e7b3dad14c67d9365faf043e4718057863 Mon Sep 17 00:00:00 2001
From: Kirill Kornyakov <kirill.kornyakov@itseez.com>
Date: Fri, 28 Jun 2013 12:48:12 +0400
Subject: [PATCH 69/75] Removed references to opencv.itseez.com

---
 doc/conf.py                                   | 216 +++++++++---------
 .../gpu-basics-similarity.rst                 |   2 +-
 .../how_to_write_a_tutorial.rst               |   6 +-
 .../introduction_to_svm.rst                   |   2 +-
 .../src/org/opencv/test/OpenCVTestRunner.java |   2 -
 .../src/java/highgui+VideoCapture.java        |   4 +-
 modules/python/test/test.py                   |   2 +-
 samples/cpp/freak_demo.cpp                    |   2 +-
 8 files changed, 117 insertions(+), 119 deletions(-)

diff --git a/doc/conf.py b/doc/conf.py
index f3564772f..312a1c2b9 100755
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -289,117 +289,117 @@ man_pages = [
 
 # ---- External links for tutorials -----------------
 extlinks = {
-            'basicstructures' : ('http://opencv.itseez.com/modules/core/doc/basic_structures.html#%s', None),
-            'oldbasicstructures' : ('http://opencv.itseez.com/modules/core/doc/old_basic_structures.html#%s', None),
-            'readwriteimagevideo' : ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None),
-            'operationsonarrays' : ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html#%s', None),
-            'utilitysystemfunctions':('http://opencv.itseez.com/modules/core/doc/utility_and_system_functions_and_macros.html#%s', None),
-            'imgprocfilter':('http://opencv.itseez.com/modules/imgproc/doc/filtering.html#%s', None),
-            'svms':('http://opencv.itseez.com/modules/ml/doc/support_vector_machines.html#%s', None),
-            'drawingfunc':('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#%s', None),
-            'xmlymlpers':('http://opencv.itseez.com/modules/core/doc/xml_yaml_persistence.html#%s', None),
-            'hgvideo' : ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None),
-            'gpuinit' : ('http://opencv.itseez.com/modules/gpu/doc/initalization_and_information.html#%s', None),
-            'gpudatastructure' : ('http://opencv.itseez.com/modules/gpu/doc/data_structures.html#%s', None),
-            'gpuopmatrices' : ('http://opencv.itseez.com/modules/gpu/doc/operations_on_matrices.html#%s', None),
-            'gpuperelement' : ('http://opencv.itseez.com/modules/gpu/doc/per_element_operations.html#%s', None),
-            'gpuimgproc' : ('http://opencv.itseez.com/modules/gpu/doc/image_processing.html#%s', None),
-            'gpumatrixreduct' : ('http://opencv.itseez.com/modules/gpu/doc/matrix_reductions.html#%s', None),
-            'filtering':('http://opencv.itseez.com/modules/imgproc/doc/filtering.html#%s', None),
-            'flann' : ('http://opencv.itseez.com/modules/flann/doc/flann_fast_approximate_nearest_neighbor_search.html#%s', None ),
-            'calib3d' : ('http://opencv.itseez.com/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#%s', None ),
-            'feature2d' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html#%s', None ),
-            'imgproc_geometric' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html#%s', None ),
+            'basicstructures' : ('http://docs.opencv.org/modules/core/doc/basic_structures.html#%s', None),
+            'oldbasicstructures' : ('http://docs.opencv.org/modules/core/doc/old_basic_structures.html#%s', None),
+            'readwriteimagevideo' : ('http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None),
+            'operationsonarrays' : ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#%s', None),
+            'utilitysystemfunctions':('http://docs.opencv.org/modules/core/doc/utility_and_system_functions_and_macros.html#%s', None),
+            'imgprocfilter':('http://docs.opencv.org/modules/imgproc/doc/filtering.html#%s', None),
+            'svms':('http://docs.opencv.org/modules/ml/doc/support_vector_machines.html#%s', None),
+            'drawingfunc':('http://docs.opencv.org/modules/core/doc/drawing_functions.html#%s', None),
+            'xmlymlpers':('http://docs.opencv.org/modules/core/doc/xml_yaml_persistence.html#%s', None),
+            'hgvideo' : ('http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None),
+            'gpuinit' : ('http://docs.opencv.org/modules/gpu/doc/initalization_and_information.html#%s', None),
+            'gpudatastructure' : ('http://docs.opencv.org/modules/gpu/doc/data_structures.html#%s', None),
+            'gpuopmatrices' : ('http://docs.opencv.org/modules/gpu/doc/operations_on_matrices.html#%s', None),
+            'gpuperelement' : ('http://docs.opencv.org/modules/gpu/doc/per_element_operations.html#%s', None),
+            'gpuimgproc' : ('http://docs.opencv.org/modules/gpu/doc/image_processing.html#%s', None),
+            'gpumatrixreduct' : ('http://docs.opencv.org/modules/gpu/doc/matrix_reductions.html#%s', None),
+            'filtering':('http://docs.opencv.org/modules/imgproc/doc/filtering.html#%s', None),
+            'flann' : ('http://docs.opencv.org/modules/flann/doc/flann_fast_approximate_nearest_neighbor_search.html#%s', None ),
+            'calib3d' : ('http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#%s', None ),
+            'feature2d' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#%s', None ),
+            'imgproc_geometric' : ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#%s', None ),
 
             # 'opencv_group' : ('http://answers.opencv.org/%s', None),
             'opencv_qa' : ('http://answers.opencv.org/%s', None),
             'how_to_contribute' : ('http://code.opencv.org/projects/opencv/wiki/How_to_contribute/%s', None),
 
-            'cvt_color': ('http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor%s', None),
-            'imread':    ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread%s', None),
-            'imwrite':   ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imwrite#imwrite%s', None),
-            'imshow':    ('http://opencv.itseez.com/modules/highgui/doc/user_interface.html?highlight=imshow#imshow%s', None),
-            'named_window': ('http://opencv.itseez.com/modules/highgui/doc/user_interface.html?highlight=namedwindow#namedwindow%s', None),
-            'wait_key': ('http://opencv.itseez.com/modules/highgui/doc/user_interface.html?highlight=waitkey#waitkey%s', None),
-            'add_weighted': ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=addweighted#addweighted%s', None),
-            'saturate_cast': ('http://opencv.itseez.com/modules/core/doc/utility_and_system_functions_and_macros.html?highlight=saturate_cast#saturate-cast%s', None),
-            'mat_zeros': ('http://opencv.itseez.com/modules/core/doc/basic_structures.html?highlight=zeros#mat-zeros%s', None),
-            'convert_to': ('http://opencv.itseez.com/modules/core/doc/basic_structures.html#mat-convertto%s', None),
-            'create_trackbar': ('http://opencv.itseez.com/modules/highgui/doc/user_interface.html?highlight=createtrackbar#createtrackbar%s', None),
-            'point': ('http://opencv.itseez.com/modules/core/doc/basic_structures.html#point%s', None),
-            'scalar': ('http://opencv.itseez.com/modules/core/doc/basic_structures.html#scalar%s', None),
-            'line': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#line%s', None),
-            'ellipse': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#ellipse%s', None),
-            'rectangle': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#rectangle%s', None),
-            'circle': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#circle%s', None),
-            'fill_poly': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#fillpoly%s', None),
-            'rng': ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=rng#rng%s', None),
-            'put_text': ('http://opencv.itseez.com/modules/core/doc/drawing_functions.html#puttext%s', None),
-            'gaussian_blur': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=gaussianblur#gaussianblur%s', None),
-            'blur': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=blur#blur%s', None),
-            'median_blur': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=medianblur#medianblur%s', None),
-            'bilateral_filter': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=bilateralfilter#bilateralfilter%s', None),
-            'erode': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=erode#erode%s', None),
-            'dilate': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=dilate#dilate%s', None),
-            'get_structuring_element': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=getstructuringelement#getstructuringelement%s', None),
-            'flood_fill': ( 'http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill#floodfill%s', None),
-            'morphology_ex': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=morphologyex#morphologyex%s', None),
-            'pyr_down': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=pyrdown#pyrdown%s', None),
-            'pyr_up': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=pyrup#pyrup%s', None),
-            'resize': ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=resize#resize%s', None),
-            'threshold': ('http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#threshold%s', None),
-            'filter2d': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=filter2d#filter2d%s', None),
-            'copy_make_border': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=copymakeborder#copymakeborder%s', None),
-            'sobel': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=sobel#sobel%s', None),
-            'scharr': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=scharr#scharr%s', None),
-            'laplacian': ('http://opencv.itseez.com/modules/imgproc/doc/filtering.html?highlight=laplacian#laplacian%s', None),
-            'canny': ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=canny#canny%s', None),
-            'copy_to': ('http://opencv.itseez.com/modules/core/doc/basic_structures.html?highlight=copyto#mat-copyto%s', None),
-            'hough_lines' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=houghlines#houghlines%s', None),
-            'hough_lines_p' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=houghlinesp#houghlinesp%s', None),
-            'hough_circles' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=houghcircles#houghcircles%s', None),
-            'remap' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap%s', None),
-            'warp_affine' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=warpaffine#warpaffine%s' , None),
-            'get_rotation_matrix_2d' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=getrotationmatrix2d#getrotationmatrix2d%s', None),
-            'get_affine_transform' : ('http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=getaffinetransform#getaffinetransform%s', None),
-            'equalize_hist' : ('http://opencv.itseez.com/modules/imgproc/doc/histograms.html?highlight=equalizehist#equalizehist%s', None),
-            'split' : ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=split#split%s', None),
-            'calc_hist' : ('http://opencv.itseez.com/modules/imgproc/doc/histograms.html?highlight=calchist#calchist%s', None),
-            'normalize' : ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=normalize#normalize%s', None),
-            'match_template' : ('http://opencv.itseez.com/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#matchtemplate%s', None),
-            'min_max_loc' : ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=minmaxloc#minmaxloc%s', None),
-            'mix_channels' : ( 'http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=mixchannels#mixchannels%s', None),
-            'calc_back_project' : ('http://opencv.itseez.com/modules/imgproc/doc/histograms.html?highlight=calcbackproject#calcbackproject%s', None),
-            'compare_hist' : ('http://opencv.itseez.com/modules/imgproc/doc/histograms.html?highlight=comparehist#comparehist%s', None),
-            'corner_harris' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=cornerharris#cornerharris%s', None),
-            'good_features_to_track' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=goodfeaturestotrack#goodfeaturestotrack%s', None),
-            'corner_min_eigenval' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=cornermineigenval#cornermineigenval%s', None),
-            'corner_eigenvals_and_vecs' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=cornereigenvalsandvecs#cornereigenvalsandvecs%s', None),
-            'corner_sub_pix' : ('http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html?highlight=cornersubpix#cornersubpix%s', None),
-            'find_contours' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours%s', None),
-            'convex_hull' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=convexhull#convexhull%s', None),
-            'draw_contours' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=drawcontours#drawcontours%s', None),
-            'bounding_rect' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=boundingrect#boundingrect%s', None),
-            'min_enclosing_circle' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minenclosingcircle#minenclosingcircle%s', None),
-            'min_area_rect' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minarearect#minarearect%s', None),
-            'fit_ellipse' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=fitellipse#fitellipse%s', None),
-            'moments' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moments#moments%s', None),
-            'contour_area' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=contourarea#contourarea%s', None),
-            'arc_length' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=arclength#arclength%s', None),
-            'point_polygon_test' : ('http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=pointpolygontest#pointpolygontest%s', None),
-            'feature_detector' : ( 'http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=featuredetector#FeatureDetector%s', None),
-            'feature_detector_detect' : ('http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=detect#featuredetector-detect%s', None ),
-            'surf_feature_detector' : ('http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=surffeaturedetector#surffeaturedetector%s', None ),
-            'draw_keypoints' : ('http://opencv.itseez.com/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html?highlight=drawkeypoints#drawkeypoints%s', None ),
-            'descriptor_extractor': ( 'http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=descriptorextractor#descriptorextractor%s', None ),
-            'descriptor_extractor_compute' : ( 'http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=compute#descriptorextractor-compute%s', None ),
-            'surf_descriptor_extractor' : ( 'http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=surfdescriptorextractor#surfdescriptorextractor%s', None ),
-            'draw_matches' : ( 'http://opencv.itseez.com/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html?highlight=drawmatches#drawmatches%s', None ),
-            'find_homography' : ('http://opencv.itseez.com/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html?highlight=findhomography#findhomography%s', None),
-            'perspective_transform' : ('http://opencv.itseez.com/modules/core/doc/operations_on_arrays.html?highlight=perspectivetransform#perspectivetransform%s', None ),
-            'flann_based_matcher' : ('http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html?highlight=flannbasedmatcher#flannbasedmatcher%s', None),
-            'brute_force_matcher' : ('http://opencv.itseez.com/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html?highlight=bruteforcematcher#bruteforcematcher%s', None ),
-            'cascade_classifier' : ('http://opencv.itseez.com/modules/objdetect/doc/cascade_classification.html?highlight=cascadeclassifier#cascadeclassifier%s', None ),
-            'cascade_classifier_load' : ('http://opencv.itseez.com/modules/objdetect/doc/cascade_classification.html?highlight=load#cascadeclassifier-load%s', None ),
-            'cascade_classifier_detect_multiscale' : ('http://opencv.itseez.com/modules/objdetect/doc/cascade_classification.html?highlight=detectmultiscale#cascadeclassifier-detectmultiscale%s', None )
+            'cvt_color': ('http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor%s', None),
+            'imread':    ('http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread%s', None),
+            'imwrite':   ('http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imwrite#imwrite%s', None),
+            'imshow':    ('http://docs.opencv.org/modules/highgui/doc/user_interface.html?highlight=imshow#imshow%s', None),
+            'named_window': ('http://docs.opencv.org/modules/highgui/doc/user_interface.html?highlight=namedwindow#namedwindow%s', None),
+            'wait_key': ('http://docs.opencv.org/modules/highgui/doc/user_interface.html?highlight=waitkey#waitkey%s', None),
+            'add_weighted': ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=addweighted#addweighted%s', None),
+            'saturate_cast': ('http://docs.opencv.org/modules/core/doc/utility_and_system_functions_and_macros.html?highlight=saturate_cast#saturate-cast%s', None),
+            'mat_zeros': ('http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=zeros#mat-zeros%s', None),
+            'convert_to': ('http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-convertto%s', None),
+            'create_trackbar': ('http://docs.opencv.org/modules/highgui/doc/user_interface.html?highlight=createtrackbar#createtrackbar%s', None),
+            'point': ('http://docs.opencv.org/modules/core/doc/basic_structures.html#point%s', None),
+            'scalar': ('http://docs.opencv.org/modules/core/doc/basic_structures.html#scalar%s', None),
+            'line': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#line%s', None),
+            'ellipse': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#ellipse%s', None),
+            'rectangle': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#rectangle%s', None),
+            'circle': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#circle%s', None),
+            'fill_poly': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#fillpoly%s', None),
+            'rng': ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=rng#rng%s', None),
+            'put_text': ('http://docs.opencv.org/modules/core/doc/drawing_functions.html#puttext%s', None),
+            'gaussian_blur': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=gaussianblur#gaussianblur%s', None),
+            'blur': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=blur#blur%s', None),
+            'median_blur': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=medianblur#medianblur%s', None),
+            'bilateral_filter': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=bilateralfilter#bilateralfilter%s', None),
+            'erode': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=erode#erode%s', None),
+            'dilate': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=dilate#dilate%s', None),
+            'get_structuring_element': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=getstructuringelement#getstructuringelement%s', None),
+            'flood_fill': ( 'http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill#floodfill%s', None),
+            'morphology_ex': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=morphologyex#morphologyex%s', None),
+            'pyr_down': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=pyrdown#pyrdown%s', None),
+            'pyr_up': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=pyrup#pyrup%s', None),
+            'resize': ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=resize#resize%s', None),
+            'threshold': ('http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#threshold%s', None),
+            'filter2d': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=filter2d#filter2d%s', None),
+            'copy_make_border': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=copymakeborder#copymakeborder%s', None),
+            'sobel': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=sobel#sobel%s', None),
+            'scharr': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=scharr#scharr%s', None),
+            'laplacian': ('http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=laplacian#laplacian%s', None),
+            'canny': ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=canny#canny%s', None),
+            'copy_to': ('http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=copyto#mat-copyto%s', None),
+            'hough_lines' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=houghlines#houghlines%s', None),
+            'hough_lines_p' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=houghlinesp#houghlinesp%s', None),
+            'hough_circles' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=houghcircles#houghcircles%s', None),
+            'remap' : ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=remap#remap%s', None),
+            'warp_affine' : ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=warpaffine#warpaffine%s' , None),
+            'get_rotation_matrix_2d' : ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=getrotationmatrix2d#getrotationmatrix2d%s', None),
+            'get_affine_transform' : ('http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html?highlight=getaffinetransform#getaffinetransform%s', None),
+            'equalize_hist' : ('http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=equalizehist#equalizehist%s', None),
+            'split' : ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=split#split%s', None),
+            'calc_hist' : ('http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=calchist#calchist%s', None),
+            'normalize' : ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=normalize#normalize%s', None),
+            'match_template' : ('http://docs.opencv.org/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#matchtemplate%s', None),
+            'min_max_loc' : ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=minmaxloc#minmaxloc%s', None),
+            'mix_channels' : ( 'http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=mixchannels#mixchannels%s', None),
+            'calc_back_project' : ('http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=calcbackproject#calcbackproject%s', None),
+            'compare_hist' : ('http://docs.opencv.org/modules/imgproc/doc/histograms.html?highlight=comparehist#comparehist%s', None),
+            'corner_harris' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=cornerharris#cornerharris%s', None),
+            'good_features_to_track' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=goodfeaturestotrack#goodfeaturestotrack%s', None),
+            'corner_min_eigenval' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=cornermineigenval#cornermineigenval%s', None),
+            'corner_eigenvals_and_vecs' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=cornereigenvalsandvecs#cornereigenvalsandvecs%s', None),
+            'corner_sub_pix' : ('http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=cornersubpix#cornersubpix%s', None),
+            'find_contours' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours%s', None),
+            'convex_hull' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=convexhull#convexhull%s', None),
+            'draw_contours' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=drawcontours#drawcontours%s', None),
+            'bounding_rect' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=boundingrect#boundingrect%s', None),
+            'min_enclosing_circle' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minenclosingcircle#minenclosingcircle%s', None),
+            'min_area_rect' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minarearect#minarearect%s', None),
+            'fit_ellipse' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=fitellipse#fitellipse%s', None),
+            'moments' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moments#moments%s', None),
+            'contour_area' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=contourarea#contourarea%s', None),
+            'arc_length' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=arclength#arclength%s', None),
+            'point_polygon_test' : ('http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=pointpolygontest#pointpolygontest%s', None),
+            'feature_detector' : ( 'http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=featuredetector#FeatureDetector%s', None),
+            'feature_detector_detect' : ('http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=detect#featuredetector-detect%s', None ),
+            'surf_feature_detector' : ('http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html?highlight=surffeaturedetector#surffeaturedetector%s', None ),
+            'draw_keypoints' : ('http://docs.opencv.org/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html?highlight=drawkeypoints#drawkeypoints%s', None ),
+            'descriptor_extractor': ( 'http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=descriptorextractor#descriptorextractor%s', None ),
+            'descriptor_extractor_compute' : ( 'http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=compute#descriptorextractor-compute%s', None ),
+            'surf_descriptor_extractor' : ( 'http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html?highlight=surfdescriptorextractor#surfdescriptorextractor%s', None ),
+            'draw_matches' : ( 'http://docs.opencv.org/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html?highlight=drawmatches#drawmatches%s', None ),
+            'find_homography' : ('http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html?highlight=findhomography#findhomography%s', None),
+            'perspective_transform' : ('http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=perspectivetransform#perspectivetransform%s', None ),
+            'flann_based_matcher' : ('http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html?highlight=flannbasedmatcher#flannbasedmatcher%s', None),
+            'brute_force_matcher' : ('http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html?highlight=bruteforcematcher#bruteforcematcher%s', None ),
+            'cascade_classifier' : ('http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html?highlight=cascadeclassifier#cascadeclassifier%s', None ),
+            'cascade_classifier_load' : ('http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html?highlight=load#cascadeclassifier-load%s', None ),
+            'cascade_classifier_detect_multiscale' : ('http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html?highlight=detectmultiscale#cascadeclassifier-detectmultiscale%s', None )
            }
diff --git a/doc/tutorials/gpu/gpu-basics-similarity/gpu-basics-similarity.rst b/doc/tutorials/gpu/gpu-basics-similarity/gpu-basics-similarity.rst
index 9983098c2..715ffdf19 100644
--- a/doc/tutorials/gpu/gpu-basics-similarity/gpu-basics-similarity.rst
+++ b/doc/tutorials/gpu/gpu-basics-similarity/gpu-basics-similarity.rst
@@ -62,7 +62,7 @@ The GPU has its own memory. When you read data from the hard drive with OpenCV i
 
    I1 = gI1;       // Download, gI1.download(I1) will work too
 
-Once you have your data up in the GPU memory you may call GPU enabled functions of OpenCV. Most of the functions keep the same name just as on the CPU, with the difference that they only accept *GpuMat* inputs. A full list of these you will find in the documentation: `online here <http://opencv.itseez.com/modules/gpu/doc/gpu.html>`_ or the OpenCV reference manual that comes with the source code.
+Once you have your data up in the GPU memory you may call GPU enabled functions of OpenCV. Most of the functions keep the same name just as on the CPU, with the difference that they only accept *GpuMat* inputs. A full list of these you will find in the documentation: `online here <http://docs.opencv.org/modules/gpu/doc/gpu.html>`_ or the OpenCV reference manual that comes with the source code.
 
 Another thing to keep in mind is that not for all channel numbers you can make efficient algorithms on the GPU. Generally, I found that the input images for the GPU images need to be either one or four channel ones and one of the char or float type for the item sizes. No double support on the GPU, sorry. Passing other types of objects for some functions will result in an exception thrown, and an error message on the error output. The documentation details in most of the places the types accepted for the inputs. If you have three channel images as an input you can do two things: either adds a new channel (and use char elements) or split up the image and call the function for each image. The first one isn't really recommended as you waste memory.
 
diff --git a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
index f57217324..ee89a4e9c 100644
--- a/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
+++ b/doc/tutorials/introduction/how_to_write_a_tutorial/how_to_write_a_tutorial.rst
@@ -310,13 +310,13 @@ Now here's our recommendation for the structure of the tutorial (although, remem
 
      After the directive you specify a relative path to the file from what to import. It has four options: the language to use, if you add the ``:linenos:`` the line numbers will be shown, you can specify the tab size with the ``:tab-width:`` and you do not need to load the whole file, you can show just the important lines. Use the *lines* option to do not show redundant information (such as the *help* function). Here basically you specify ranges, if the second range line number is missing than that means that until the end of the file. The ranges specified here do no need to be in an ascending order, you may even reorganize the structure of how you want to show your sample inside the tutorial.
    + The tutorial. Well here goes the explanation for why and what have you used. Try to be short, clear, concise and yet a thorough one. There's no magic formula. Look into a few already made tutorials and start out from there. Try to mix sample OpenCV code with your explanations. If with words is hard to describe something do not hesitate to add in a reasonable size image, to overcome this issue.
-     When you present OpenCV functionality it's a good idea to give a link to the used OpenCV data structure or function. Because the OpenCV tutorials and reference manual are in separate PDF files it is not possible to make this link work for the PDF format. Therefore, we use here only web page links to the **opencv.itseez.com** website. The OpenCV functions and data structures may be used for multiple tasks. Nevertheless, we want to avoid that every users creates its own reference to a commonly used function. So for this we use the global link collection of *Sphinx*. This is defined in the file:`opencv/doc/conf.py` configuration file. Open it and go all the way down to the last entry:
+     When you present OpenCV functionality it's a good idea to give a link to the used OpenCV data structure or function. Because the OpenCV tutorials and reference manual are in separate PDF files it is not possible to make this link work for the PDF format. Therefore, we use here only web page links to the http://docs.opencv.org website. The OpenCV functions and data structures may be used for multiple tasks. Nevertheless, we want to avoid that every users creates its own reference to a commonly used function. So for this we use the global link collection of *Sphinx*. This is defined in the file:`opencv/doc/conf.py` configuration file. Open it and go all the way down to the last entry:
 
      .. code-block:: py
 
        # ---- External links for tutorials -----------------
        extlinks = {
-           'hgvideo' : ('http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None)
+           'hgvideo' : ('http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#%s', None)
            }
 
      In short here we defined a new **hgvideo** directive that refers to an external webpage link. Its usage is:
@@ -325,7 +325,7 @@ Now here's our recommendation for the structure of the tutorial (although, remem
 
        A sample function of the highgui modules image write and read page is the :hgvideo:`imread() function <imread>`.
 
-     Which turns to: A sample function of the highgui modules image write and read page is the :hgvideo:`imread() function <imread>`. The argument you give between the <> will be put in place of the ``%s`` in the upper definition, and as the link will anchor to the correct function. To find out the anchor of a given function just open up a web page, search for the function and click on it. In the address bar it should appear like: ``http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#imread`` .  Look here for the name of the directives for each page of the OpenCV reference manual. If none present for one of them feel free to add one for it.
+     Which turns to: A sample function of the highgui modules image write and read page is the :hgvideo:`imread() function <imread>`. The argument you give between the <> will be put in place of the ``%s`` in the upper definition, and as the link will anchor to the correct function. To find out the anchor of a given function just open up a web page, search for the function and click on it. In the address bar it should appear like: ``http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imread`` .  Look here for the name of the directives for each page of the OpenCV reference manual. If none present for one of them feel free to add one for it.
      For formulas you can add LATEX code that will translate in the web pages into images. You do this by using the *math* directive. A usage tip:
 
      .. code-block:: latex
diff --git a/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.rst b/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.rst
index cdad3de65..6cd66e52b 100644
--- a/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.rst
+++ b/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.rst
@@ -129,7 +129,7 @@ Explanation
 
 3. **Train the SVM**
 
-   We call the method `CvSVM::train <http://opencv.itseez.com/modules/ml/doc/support_vector_machines.html#cvsvm-train>`_ to build the SVM model.
+   We call the method `CvSVM::train <http://docs.opencv.org/modules/ml/doc/support_vector_machines.html#cvsvm-train>`_ to build the SVM model.
 
    .. code-block:: cpp
 
diff --git a/modules/java/android_test/src/org/opencv/test/OpenCVTestRunner.java b/modules/java/android_test/src/org/opencv/test/OpenCVTestRunner.java
index 2dc4aead8..9425e2644 100644
--- a/modules/java/android_test/src/org/opencv/test/OpenCVTestRunner.java
+++ b/modules/java/android_test/src/org/opencv/test/OpenCVTestRunner.java
@@ -17,8 +17,6 @@ import android.util.Log;
 
 /**
  * This only class is Android specific.
- *
- * @see <a href="http://opencv.itseez.com">OpenCV</a>
  */
 
 public class OpenCVTestRunner extends InstrumentationTestRunner {
diff --git a/modules/java/generator/src/java/highgui+VideoCapture.java b/modules/java/generator/src/java/highgui+VideoCapture.java
index b8569bb9c..6f3b03540 100644
--- a/modules/java/generator/src/java/highgui+VideoCapture.java
+++ b/modules/java/generator/src/java/highgui+VideoCapture.java
@@ -56,7 +56,7 @@ public class VideoCapture {
  *   * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream.
  *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
  *
- * @see <a href="http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get">org.opencv.highgui.VideoCapture.get</a>
+ * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get">org.opencv.highgui.VideoCapture.get</a>
  */
     public double get(int propId)
     {
@@ -178,7 +178,7 @@ public class VideoCapture {
  *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
  * @param value value of the property.
  *
- * @see <a href="http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-set">org.opencv.highgui.VideoCapture.set</a>
+ * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-set">org.opencv.highgui.VideoCapture.set</a>
  */
     public boolean set(int propId, double value)
     {
diff --git a/modules/python/test/test.py b/modules/python/test/test.py
index 48138cbda..10f32260b 100755
--- a/modules/python/test/test.py
+++ b/modules/python/test/test.py
@@ -1646,7 +1646,7 @@ class AreaTests(OpenCVTests):
             cv.SetData(imagefiledata, filedata, len(filedata))
             return cv.DecodeImageM(imagefiledata)
 
-        urllib.urlretrieve("http://opencv.itseez.com/data/camera_calibration.tar.gz", "camera_calibration.tar.gz")
+        urllib.urlretrieve("http://docs.opencv.org/data/camera_calibration.tar.gz", "camera_calibration.tar.gz")
         tf = tarfile.open("camera_calibration.tar.gz")
 
         num_x_ints = 8
diff --git a/samples/cpp/freak_demo.cpp b/samples/cpp/freak_demo.cpp
index 5112eae12..fd4eea42c 100644
--- a/samples/cpp/freak_demo.cpp
+++ b/samples/cpp/freak_demo.cpp
@@ -56,7 +56,7 @@ static void help( char** argv )
 }
 
 int main( int argc, char** argv ) {
-    // check http://opencv.itseez.com/doc/tutorials/features2d/table_of_content_features2d/table_of_content_features2d.html
+    // check http://docs.opencv.org/doc/tutorials/features2d/table_of_content_features2d/table_of_content_features2d.html
     // for OpenCV general detection/matching framework details
 
     if( argc != 3 ) {

From 7b06592dea217a792148d4ba0fd0b70230143554 Mon Sep 17 00:00:00 2001
From: Alexander Shishkov <alexander.shishkov@itseez.com>
Date: Fri, 28 Jun 2013 13:26:54 +0400
Subject: [PATCH 70/75] added conversions between UIImage and cv::Mat

---
 modules/highgui/CMakeLists.txt                |   2 +-
 modules/highgui/include/opencv2/highgui/ios.h |  49 ++++++++
 modules/highgui/src/ios_conversions.mm        | 117 ++++++++++++++++++
 3 files changed, 167 insertions(+), 1 deletion(-)
 create mode 100644 modules/highgui/include/opencv2/highgui/ios.h
 create mode 100644 modules/highgui/src/ios_conversions.mm

diff --git a/modules/highgui/CMakeLists.txt b/modules/highgui/CMakeLists.txt
index 05ab99a78..2b0a23209 100644
--- a/modules/highgui/CMakeLists.txt
+++ b/modules/highgui/CMakeLists.txt
@@ -234,7 +234,7 @@ endif()
 
 if(IOS)
   add_definitions(-DHAVE_IOS=1)
-  list(APPEND highgui_srcs src/cap_ios_abstract_camera.mm src/cap_ios_photo_camera.mm src/cap_ios_video_camera.mm)
+  list(APPEND highgui_srcs src/ios_conversions.mm src/cap_ios_abstract_camera.mm src/cap_ios_photo_camera.mm src/cap_ios_video_camera.mm)
   list(APPEND HIGHGUI_LIBRARIES "-framework Accelerate" "-framework AVFoundation" "-framework CoreGraphics" "-framework CoreImage" "-framework CoreMedia" "-framework CoreVideo" "-framework QuartzCore" "-framework AssetsLibrary")
 endif()
 
diff --git a/modules/highgui/include/opencv2/highgui/ios.h b/modules/highgui/include/opencv2/highgui/ios.h
new file mode 100644
index 000000000..a78fbf72c
--- /dev/null
+++ b/modules/highgui/include/opencv2/highgui/ios.h
@@ -0,0 +1,49 @@
+
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                          License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's 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.
+//
+//   * The name of the copyright holders may not 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 Intel Corporation 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.
+//
+//M*/
+
+#include "opencv2/core/core.hpp"
+#import "opencv2/highgui/cap_ios.h"
+
+UIImage* MatToUIImage(const cv::Mat& image);
+void UIImageToMat(const UIImage* image,
+                         cv::Mat& m, bool alphaExist = false);
\ No newline at end of file
diff --git a/modules/highgui/src/ios_conversions.mm b/modules/highgui/src/ios_conversions.mm
new file mode 100644
index 000000000..7295743c5
--- /dev/null
+++ b/modules/highgui/src/ios_conversions.mm
@@ -0,0 +1,117 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                          License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's 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.
+//
+//   * The name of the copyright holders may not 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 Intel Corporation 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.
+//
+//M*/
+
+#import "opencv2/highgui/cap_ios.h"
+#include "precomp.hpp"
+
+UIImage* MatToUIImage(const cv::Mat& image) {
+    
+    NSData *data = [NSData dataWithBytes:image.data
+                                  length:image.elemSize()*image.total()];
+    
+    CGColorSpaceRef colorSpace;
+    
+    if (image.elemSize() == 1) {
+        colorSpace = CGColorSpaceCreateDeviceGray();
+    } else {
+        colorSpace = CGColorSpaceCreateDeviceRGB();
+    }
+    
+    CGDataProviderRef provider =
+            CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
+    
+    // Creating CGImage from cv::Mat
+    CGImageRef imageRef = CGImageCreate(image.cols,
+                                        image.rows,
+                                        8,
+                                        8 * image.elemSize(),
+                                        image.step.p[0],
+                                        colorSpace,
+                                        kCGImageAlphaNone|
+                                        kCGBitmapByteOrderDefault,
+                                        provider,
+                                        NULL,
+                                        false,
+                                        kCGRenderingIntentDefault
+                                        );
+    
+    
+    // Getting UIImage from CGImage
+    UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
+    CGImageRelease(imageRef);
+    CGDataProviderRelease(provider);
+    CGColorSpaceRelease(colorSpace);
+    
+    return finalImage;
+}
+
+void UIImageToMat(const UIImage* image,
+                         cv::Mat& m, bool alphaExist) {
+    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
+    CGFloat cols = image.size.width, rows = image.size.height;
+    CGContextRef contextRef;
+    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
+    if (CGColorSpaceGetModel(colorSpace) == 0)
+    {
+        m.create(rows, cols, CV_8UC1); // 8 bits per component, 1 channel
+        bitmapInfo = kCGImageAlphaNone;
+        if (!alphaExist)
+            bitmapInfo = kCGImageAlphaNone;
+        contextRef = CGBitmapContextCreate(m.data, m.cols, m.rows, 8,
+                                           m.step[0], colorSpace,
+                                           bitmapInfo);
+    }
+    else
+    {
+        m.create(rows, cols, CV_8UC4); // 8 bits per component, 4 channels
+        if (!alphaExist)
+            bitmapInfo = kCGImageAlphaNoneSkipLast |
+                                kCGBitmapByteOrderDefault;
+        contextRef = CGBitmapContextCreate(m.data, m.cols, m.rows, 8,
+                                           m.step[0], colorSpace,
+                                           bitmapInfo);
+    }
+    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows),
+                       image.CGImage);
+    CGContextRelease(contextRef);
+    CGColorSpaceRelease(colorSpace);
+}
\ No newline at end of file

From c66e27d49e8c40a98149e6c3a53075a18dfa6878 Mon Sep 17 00:00:00 2001
From: yao <bitwangyaoyao@gmail.com>
Date: Fri, 28 Jun 2013 17:45:39 +0800
Subject: [PATCH 71/75] stereoBM fix an error on Linux when running full
 performance test

---
 modules/ocl/src/opencl/stereobm.cl | 37 +++++++++++-------------------
 1 file changed, 13 insertions(+), 24 deletions(-)

diff --git a/modules/ocl/src/opencl/stereobm.cl b/modules/ocl/src/opencl/stereobm.cl
index 552874d42..f1b958812 100644
--- a/modules/ocl/src/opencl/stereobm.cl
+++ b/modules/ocl/src/opencl/stereobm.cl
@@ -258,27 +258,13 @@ float sobel(__global unsigned char *input, int x, int y, int rows, int cols)
 
 float CalcSums(__local float *cols, __local float *cols_cache, int winsz)
 {
-    float cache = 0;
-    float cache2 = 0;
-    int winsz2 = winsz/2;
+    unsigned int cache = cols[0];
 
-    int x = get_local_id(0);
-    int group_size_x = get_local_size(0);
-
-    for(int i = 1; i <= winsz2; i++)
+#pragma unroll
+    for(int i = 1; i <= winsz; i++)
         cache += cols[i];
 
-    cols_cache[0] = cache;
-
-    barrier(CLK_LOCAL_MEM_FENCE);
-
-    if (x < group_size_x - winsz2)
-        cache2 = cols_cache[winsz2];
-    else
-        for(int i = winsz2 + 1; i < winsz; i++)
-            cache2 += cols[i];
-
-    return cols[0] + cache + cache2;
+    return cache;
 }
 
 #define RpT (2 * ROWSperTHREAD)  // got experimentally
@@ -301,8 +287,7 @@ __kernel void textureness_kernel(__global unsigned char *disp, int disp_rows, in
     int beg_row = group_id_y * RpT;
     int end_row = min(beg_row + RpT, disp_rows);
 
-//   if (x < disp_cols)
-//   {
+
     int y = beg_row;
 
     float sum = 0;
@@ -340,11 +325,15 @@ __kernel void textureness_kernel(__global unsigned char *disp, int disp_rows, in
         }
 
         barrier(CLK_LOCAL_MEM_FENCE);
-        float sum_win = CalcSums(cols, cols_cache + local_id_x, winsz) * 255;
-        if (sum_win < threshold)
-            disp[y * disp_step + x] = 0;
+
+        if (x < disp_cols)
+        {
+            float sum_win = CalcSums(cols, cols_cache + local_id_x, winsz) * 255;
+            if (sum_win < threshold)
+                disp[y * disp_step + x] = 0;
+        }
 
         barrier(CLK_LOCAL_MEM_FENCE);
     }
-    //  }
+
 }

From 67d4d9e9f4e296dbce1a1546afa88db79bb297cb Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Fri, 28 Jun 2013 16:48:27 +0400
Subject: [PATCH 72/75] Path to OpenCV dll libs fixes.

---
 .../ImageManipulations/MediaCapture.vcxproj   | 34 +++++++++----------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/samples/winrt/ImageManipulations/MediaCapture.vcxproj b/samples/winrt/ImageManipulations/MediaCapture.vcxproj
index f4eceef61..b8b8990e2 100644
--- a/samples/winrt/ImageManipulations/MediaCapture.vcxproj
+++ b/samples/winrt/ImageManipulations/MediaCapture.vcxproj
@@ -167,7 +167,7 @@
     </ProjectReference>
   </ItemGroup>
   <ItemGroup>
-    <None Include="..\..\..\..\build\install\bin\opencv_calib3d245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_calib3d245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -175,7 +175,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_contrib245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_contrib245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -183,7 +183,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_core245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_core245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -191,7 +191,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_features2d245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_features2d245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -199,7 +199,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_flann245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_flann245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -207,7 +207,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_highgui245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_highgui245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -215,7 +215,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_imgproc245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_imgproc245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -223,7 +223,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_legacy245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_legacy245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -231,7 +231,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_ml245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_ml245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -239,7 +239,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_nonfree245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_nonfree245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -247,7 +247,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_objdetect245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_objdetect245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -255,7 +255,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_photo245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_photo245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -263,7 +263,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_stitching245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_stitching245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -271,7 +271,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_superres245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_superres245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -279,7 +279,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_ts245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_ts245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -287,7 +287,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_video245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_video245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>
@@ -295,7 +295,7 @@
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</DeploymentContent>
     </None>
-    <None Include="..\..\..\..\build\install\bin\opencv_videostab245.dll">
+    <None Include="$(OPENCV_DIR)\bin\opencv_videostab245.dll">
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">true</DeploymentContent>
       <DeploymentContent Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</DeploymentContent>

From 6069967109ee10afd0b262e47ac961c674c9659e Mon Sep 17 00:00:00 2001
From: Andrey Pavlenko <andrey.pavlenko@itseez.com>
Date: Fri, 28 Jun 2013 17:28:57 +0400
Subject: [PATCH 73/75] removing unused import

---
 modules/java/generator/src/java/android+JavaCameraView.java | 1 -
 1 file changed, 1 deletion(-)

diff --git a/modules/java/generator/src/java/android+JavaCameraView.java b/modules/java/generator/src/java/android+JavaCameraView.java
index 0dcdad2fb..3bef2e0c3 100644
--- a/modules/java/generator/src/java/android+JavaCameraView.java
+++ b/modules/java/generator/src/java/android+JavaCameraView.java
@@ -6,7 +6,6 @@ import android.content.Context;
 import android.graphics.ImageFormat;
 import android.graphics.SurfaceTexture;
 import android.hardware.Camera;
-import android.hardware.Camera.CameraInfo;
 import android.hardware.Camera.PreviewCallback;
 import android.os.Build;
 import android.util.AttributeSet;

From 8b6f1d9bd9a0a5e033220efd07332bfbf35a7a3c Mon Sep 17 00:00:00 2001
From: Alexander Smorkalov <alexander.smorkalov@itseez.com>
Date: Fri, 28 Jun 2013 18:25:53 +0400
Subject: [PATCH 74/75] OpenCV Version++; Manager Version++

---
 platforms/android/service/readme.txt | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/platforms/android/service/readme.txt b/platforms/android/service/readme.txt
index f4e65eb36..e68bf5249 100644
--- a/platforms/android/service/readme.txt
+++ b/platforms/android/service/readme.txt
@@ -14,20 +14,20 @@ manually using adb tool:
 
 .. code-block:: sh
 
-    adb install OpenCV-2.4.5-android-sdk/apk/OpenCV_2.4.5_Manager_2.7_<platform>.apk
+    adb install OpenCV-2.4.6-android-sdk/apk/OpenCV_2.4.6_Manager_2.8_<platform>.apk
 
 Use the table below to determine proper OpenCV Manager package for your device:
 
 +------------------------------+--------------+---------------------------------------------------+
 | Hardware Platform            | Android ver. | Package name                                      |
 +==============================+==============+===================================================+
-| armeabi-v7a (ARMv7-A + NEON) |    >= 2.3    | OpenCV_2.4.5_Manager_2.7_armv7a-neon.apk          |
+| armeabi-v7a (ARMv7-A + NEON) |    >= 2.3    | OpenCV_2.4.6_Manager_2.8_armv7a-neon.apk          |
 +------------------------------+--------------+---------------------------------------------------+
-| armeabi-v7a (ARMv7-A + NEON) |     = 2.2    | OpenCV_2.4.5_Manager_2.7_armv7a-neon-android8.apk |
+| armeabi-v7a (ARMv7-A + NEON) |     = 2.2    | OpenCV_2.4.6_Manager_2.8_armv7a-neon-android8.apk |
 +------------------------------+--------------+---------------------------------------------------+
-| armeabi (ARMv5, ARMv6)       |    >= 2.3    | OpenCV_2.4.5_Manager_2.7_armeabi.apk              |
+| armeabi (ARMv5, ARMv6)       |    >= 2.3    | OpenCV_2.4.6_Manager_2.8_armeabi.apk              |
 +------------------------------+--------------+---------------------------------------------------+
-| Intel x86                    |    >= 2.3    | OpenCV_2.4.5_Manager_2.7_x86.apk                  |
+| Intel x86                    |    >= 2.3    | OpenCV_2.4.6_Manager_2.8_x86.apk                  |
 +------------------------------+--------------+---------------------------------------------------+
-| MIPS                         |    >= 2.3    | OpenCV_2.4.5_Manager_2.7_mips.apk                 |
+| MIPS                         |    >= 2.3    | OpenCV_2.4.6_Manager_2.8_mips.apk                 |
 +------------------------------+--------------+---------------------------------------------------+

From 97b939195fd9923fd89877ccef653b108582f1c9 Mon Sep 17 00:00:00 2001
From: Andrey Pavlenko <andrey.pavlenko@itseez.com>
Date: Mon, 1 Jul 2013 10:03:08 +0400
Subject: [PATCH 75/75] adding 'ios.h' to ignore list should work on non-Mac)

---
 platforms/scripts/ABI_compat_generator.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/platforms/scripts/ABI_compat_generator.py b/platforms/scripts/ABI_compat_generator.py
index fdabf0061..d7cc3728a 100755
--- a/platforms/scripts/ABI_compat_generator.py
+++ b/platforms/scripts/ABI_compat_generator.py
@@ -6,7 +6,7 @@ import os
 
 
 architecture = 'armeabi'
-excludedHeaders = set(['hdf5.h', 'cap_ios.h', 'eigen.hpp', 'cxeigen.hpp']) #TOREMOVE
+excludedHeaders = set(['hdf5.h', 'cap_ios.h', 'ios.h', 'eigen.hpp', 'cxeigen.hpp']) #TOREMOVE
 systemIncludes = ['sources/cxx-stl/gnu-libstdc++/4.6/include', \
     '/opt/android-ndk-r8c/platforms/android-8/arch-arm', # TODO: check if this one could be passed as command line arg
     'sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include']