├── .gitignore ├── LICENSE ├── MetalRenderCamera.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ └── contents.xcworkspacedata └── xcshareddata │ └── xcschemes │ └── Metal Camera.xcscheme ├── MetalRenderCamera ├── AppDelegate.swift ├── Assets.xcassets │ ├── AppIcon.appiconset │ │ ├── AppIcon.png │ │ └── Contents.json │ ├── Contents.json │ └── metal_icon.imageset │ │ ├── Contents.json │ │ ├── metal_icon.png │ │ ├── metal_icon@2x.png │ │ └── metal_icon@3x.png ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── CameraViewController.swift ├── Info.plist ├── MTKViewController.swift ├── MetalCameraCaptureDevice.swift ├── MetalCameraSession.swift ├── MetalCameraSessionTypes.swift ├── MetalRenderCameraTests │ ├── Info.plist │ ├── MetalCameraSessionTests.swift │ └── MetalCameraSessionTestsDelegates.swift └── Shaders.metal └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata 19 | 20 | ## Other 21 | *.xccheckout 22 | *.moved-aside 23 | *.xcuserstate 24 | *.xcscmblueprint 25 | 26 | ## Obj-C/Swift specific 27 | *.hmap 28 | *.ipa 29 | 30 | ## Playgrounds 31 | timeline.xctimeline 32 | playground.xcworkspace 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | # Packages/ 38 | .build/ 39 | 40 | # CocoaPods 41 | # 42 | # We recommend against adding the Pods directory to your .gitignore. However 43 | # you should judge for yourself, the pros and cons are mentioned at: 44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 45 | # 46 | # Pods/ 47 | 48 | # Carthage 49 | # 50 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 51 | # Carthage/Checkouts 52 | 53 | Carthage/Build 54 | 55 | # fastlane 56 | # 57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 58 | # screenshots whenever they are needed. 59 | # For more information about the recommended setup visit: 60 | # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md 61 | 62 | fastlane/report.xml 63 | fastlane/screenshots 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MetalRenderCamera.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 54; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | FA00A6B21CD54552005CF485 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6B11CD54552005CF485 /* AppDelegate.swift */; }; 11 | FA00A6B71CD54552005CF485 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA00A6B51CD54552005CF485 /* Main.storyboard */; }; 12 | FA00A6B91CD54552005CF485 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FA00A6B81CD54552005CF485 /* Assets.xcassets */; }; 13 | FA00A6BC1CD54552005CF485 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA00A6BA1CD54552005CF485 /* LaunchScreen.storyboard */; }; 14 | FA00A6CB1CD545F4005CF485 /* CameraViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6C51CD545F4005CF485 /* CameraViewController.swift */; }; 15 | FA00A6CC1CD545F4005CF485 /* MetalCameraSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6C61CD545F4005CF485 /* MetalCameraSession.swift */; }; 16 | FA00A6CD1CD545F4005CF485 /* MetalCameraSessionTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6C71CD545F4005CF485 /* MetalCameraSessionTypes.swift */; }; 17 | FA00A6CE1CD545F4005CF485 /* MTKViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6C81CD545F4005CF485 /* MTKViewController.swift */; }; 18 | FA00A6CF1CD545F4005CF485 /* Shaders.metal in Sources */ = {isa = PBXBuildFile; fileRef = FA00A6C91CD545F4005CF485 /* Shaders.metal */; }; 19 | FABBE88B1D491220006D3416 /* MetalCameraSessionTestsDelegates.swift in Sources */ = {isa = PBXBuildFile; fileRef = FABBE8891D4911EE006D3416 /* MetalCameraSessionTestsDelegates.swift */; }; 20 | FABC1DE91D46296C00F0B64B /* MetalCameraCaptureDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = FABC1DE81D46296C00F0B64B /* MetalCameraCaptureDevice.swift */; }; 21 | FABC1DFC1D46373A00F0B64B /* MetalCameraSessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FABC1DFB1D46373A00F0B64B /* MetalCameraSessionTests.swift */; }; 22 | /* End PBXBuildFile section */ 23 | 24 | /* Begin PBXContainerItemProxy section */ 25 | FABC1DF51D4636D500F0B64B /* PBXContainerItemProxy */ = { 26 | isa = PBXContainerItemProxy; 27 | containerPortal = FA00A6A61CD54552005CF485 /* Project object */; 28 | proxyType = 1; 29 | remoteGlobalIDString = FA00A6AD1CD54552005CF485; 30 | remoteInfo = "Metal Camera"; 31 | }; 32 | /* End PBXContainerItemProxy section */ 33 | 34 | /* Begin PBXFileReference section */ 35 | FA00A6AE1CD54552005CF485 /* Metal Camera.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Metal Camera.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 36 | FA00A6B11CD54552005CF485 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 37 | FA00A6B61CD54552005CF485 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 38 | FA00A6B81CD54552005CF485 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 39 | FA00A6BB1CD54552005CF485 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 40 | FA00A6BD1CD54552005CF485 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 41 | FA00A6C51CD545F4005CF485 /* CameraViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CameraViewController.swift; sourceTree = ""; }; 42 | FA00A6C61CD545F4005CF485 /* MetalCameraSession.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalCameraSession.swift; sourceTree = ""; }; 43 | FA00A6C71CD545F4005CF485 /* MetalCameraSessionTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalCameraSessionTypes.swift; sourceTree = ""; }; 44 | FA00A6C81CD545F4005CF485 /* MTKViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MTKViewController.swift; sourceTree = ""; }; 45 | FA00A6C91CD545F4005CF485 /* Shaders.metal */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.metal; path = Shaders.metal; sourceTree = ""; }; 46 | FABBE8891D4911EE006D3416 /* MetalCameraSessionTestsDelegates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalCameraSessionTestsDelegates.swift; sourceTree = ""; }; 47 | FABC1DE81D46296C00F0B64B /* MetalCameraCaptureDevice.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalCameraCaptureDevice.swift; sourceTree = ""; }; 48 | FABC1DF01D4636D500F0B64B /* MetalRenderCameraTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MetalRenderCameraTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 49 | FABC1DF41D4636D500F0B64B /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50 | FABC1DFB1D46373A00F0B64B /* MetalCameraSessionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalCameraSessionTests.swift; sourceTree = ""; }; 51 | /* End PBXFileReference section */ 52 | 53 | /* Begin PBXFrameworksBuildPhase section */ 54 | FA00A6AB1CD54552005CF485 /* Frameworks */ = { 55 | isa = PBXFrameworksBuildPhase; 56 | buildActionMask = 2147483647; 57 | files = ( 58 | ); 59 | runOnlyForDeploymentPostprocessing = 0; 60 | }; 61 | FABC1DED1D4636D500F0B64B /* Frameworks */ = { 62 | isa = PBXFrameworksBuildPhase; 63 | buildActionMask = 2147483647; 64 | files = ( 65 | ); 66 | runOnlyForDeploymentPostprocessing = 0; 67 | }; 68 | /* End PBXFrameworksBuildPhase section */ 69 | 70 | /* Begin PBXGroup section */ 71 | FA00A6A51CD54552005CF485 = { 72 | isa = PBXGroup; 73 | children = ( 74 | FA00A6B01CD54552005CF485 /* MetalRenderCamera */, 75 | FABC1DF11D4636D500F0B64B /* MetalRenderCameraTests */, 76 | FA00A6AF1CD54552005CF485 /* Products */, 77 | ); 78 | sourceTree = ""; 79 | }; 80 | FA00A6AF1CD54552005CF485 /* Products */ = { 81 | isa = PBXGroup; 82 | children = ( 83 | FA00A6AE1CD54552005CF485 /* Metal Camera.app */, 84 | FABC1DF01D4636D500F0B64B /* MetalRenderCameraTests.xctest */, 85 | ); 86 | name = Products; 87 | sourceTree = ""; 88 | }; 89 | FA00A6B01CD54552005CF485 /* MetalRenderCamera */ = { 90 | isa = PBXGroup; 91 | children = ( 92 | FA00A6D11CD54611005CF485 /* Metal Camera Session */, 93 | FA00A6D01CD545FE005CF485 /* MetalKit View Controller */, 94 | FA00A6C51CD545F4005CF485 /* CameraViewController.swift */, 95 | FA00A6B11CD54552005CF485 /* AppDelegate.swift */, 96 | FA00A6C31CD545DE005CF485 /* Resources */, 97 | FA00A6BD1CD54552005CF485 /* Info.plist */, 98 | ); 99 | path = MetalRenderCamera; 100 | sourceTree = ""; 101 | }; 102 | FA00A6C31CD545DE005CF485 /* Resources */ = { 103 | isa = PBXGroup; 104 | children = ( 105 | FA00A6B81CD54552005CF485 /* Assets.xcassets */, 106 | FA00A6B51CD54552005CF485 /* Main.storyboard */, 107 | FA00A6BA1CD54552005CF485 /* LaunchScreen.storyboard */, 108 | ); 109 | name = Resources; 110 | sourceTree = ""; 111 | }; 112 | FA00A6D01CD545FE005CF485 /* MetalKit View Controller */ = { 113 | isa = PBXGroup; 114 | children = ( 115 | FA00A6C81CD545F4005CF485 /* MTKViewController.swift */, 116 | FA00A6C91CD545F4005CF485 /* Shaders.metal */, 117 | ); 118 | name = "MetalKit View Controller"; 119 | sourceTree = ""; 120 | }; 121 | FA00A6D11CD54611005CF485 /* Metal Camera Session */ = { 122 | isa = PBXGroup; 123 | children = ( 124 | FA00A6C61CD545F4005CF485 /* MetalCameraSession.swift */, 125 | FA00A6C71CD545F4005CF485 /* MetalCameraSessionTypes.swift */, 126 | FABC1DE81D46296C00F0B64B /* MetalCameraCaptureDevice.swift */, 127 | ); 128 | name = "Metal Camera Session"; 129 | sourceTree = ""; 130 | }; 131 | FABC1DF11D4636D500F0B64B /* MetalRenderCameraTests */ = { 132 | isa = PBXGroup; 133 | children = ( 134 | FABBE8891D4911EE006D3416 /* MetalCameraSessionTestsDelegates.swift */, 135 | FABC1DFB1D46373A00F0B64B /* MetalCameraSessionTests.swift */, 136 | FABC1DF41D4636D500F0B64B /* Info.plist */, 137 | ); 138 | name = MetalRenderCameraTests; 139 | path = MetalRenderCamera/MetalRenderCameraTests; 140 | sourceTree = ""; 141 | }; 142 | /* End PBXGroup section */ 143 | 144 | /* Begin PBXNativeTarget section */ 145 | FA00A6AD1CD54552005CF485 /* Metal Camera */ = { 146 | isa = PBXNativeTarget; 147 | buildConfigurationList = FA00A6C01CD54552005CF485 /* Build configuration list for PBXNativeTarget "Metal Camera" */; 148 | buildPhases = ( 149 | FA00A6AA1CD54552005CF485 /* Sources */, 150 | FA00A6AB1CD54552005CF485 /* Frameworks */, 151 | FA00A6AC1CD54552005CF485 /* Resources */, 152 | ); 153 | buildRules = ( 154 | ); 155 | dependencies = ( 156 | ); 157 | name = "Metal Camera"; 158 | productName = MetalRenderCamera; 159 | productReference = FA00A6AE1CD54552005CF485 /* Metal Camera.app */; 160 | productType = "com.apple.product-type.application"; 161 | }; 162 | FABC1DEF1D4636D500F0B64B /* MetalRenderCameraTests */ = { 163 | isa = PBXNativeTarget; 164 | buildConfigurationList = FABC1DF71D4636D500F0B64B /* Build configuration list for PBXNativeTarget "MetalRenderCameraTests" */; 165 | buildPhases = ( 166 | FABC1DEC1D4636D500F0B64B /* Sources */, 167 | FABC1DED1D4636D500F0B64B /* Frameworks */, 168 | FABC1DEE1D4636D500F0B64B /* Resources */, 169 | ); 170 | buildRules = ( 171 | ); 172 | dependencies = ( 173 | FABC1DF61D4636D500F0B64B /* PBXTargetDependency */, 174 | ); 175 | name = MetalRenderCameraTests; 176 | productName = MetalRenderCameraTests; 177 | productReference = FABC1DF01D4636D500F0B64B /* MetalRenderCameraTests.xctest */; 178 | productType = "com.apple.product-type.bundle.unit-test"; 179 | }; 180 | /* End PBXNativeTarget section */ 181 | 182 | /* Begin PBXProject section */ 183 | FA00A6A61CD54552005CF485 /* Project object */ = { 184 | isa = PBXProject; 185 | attributes = { 186 | BuildIndependentTargetsInParallel = YES; 187 | LastSwiftUpdateCheck = 0730; 188 | LastUpgradeCheck = 1600; 189 | ORGANIZATIONNAME = "Old Yellow Bricks"; 190 | TargetAttributes = { 191 | FA00A6AD1CD54552005CF485 = { 192 | CreatedOnToolsVersion = 7.3; 193 | LastSwiftMigration = 0900; 194 | }; 195 | FABC1DEF1D4636D500F0B64B = { 196 | CreatedOnToolsVersion = 7.3.1; 197 | LastSwiftMigration = 0900; 198 | TestTargetID = FA00A6AD1CD54552005CF485; 199 | }; 200 | }; 201 | }; 202 | buildConfigurationList = FA00A6A91CD54552005CF485 /* Build configuration list for PBXProject "MetalRenderCamera" */; 203 | compatibilityVersion = "Xcode 3.2"; 204 | developmentRegion = en; 205 | hasScannedForEncodings = 0; 206 | knownRegions = ( 207 | en, 208 | Base, 209 | ); 210 | mainGroup = FA00A6A51CD54552005CF485; 211 | productRefGroup = FA00A6AF1CD54552005CF485 /* Products */; 212 | projectDirPath = ""; 213 | projectRoot = ""; 214 | targets = ( 215 | FA00A6AD1CD54552005CF485 /* Metal Camera */, 216 | FABC1DEF1D4636D500F0B64B /* MetalRenderCameraTests */, 217 | ); 218 | }; 219 | /* End PBXProject section */ 220 | 221 | /* Begin PBXResourcesBuildPhase section */ 222 | FA00A6AC1CD54552005CF485 /* Resources */ = { 223 | isa = PBXResourcesBuildPhase; 224 | buildActionMask = 2147483647; 225 | files = ( 226 | FA00A6BC1CD54552005CF485 /* LaunchScreen.storyboard in Resources */, 227 | FA00A6B91CD54552005CF485 /* Assets.xcassets in Resources */, 228 | FA00A6B71CD54552005CF485 /* Main.storyboard in Resources */, 229 | ); 230 | runOnlyForDeploymentPostprocessing = 0; 231 | }; 232 | FABC1DEE1D4636D500F0B64B /* Resources */ = { 233 | isa = PBXResourcesBuildPhase; 234 | buildActionMask = 2147483647; 235 | files = ( 236 | ); 237 | runOnlyForDeploymentPostprocessing = 0; 238 | }; 239 | /* End PBXResourcesBuildPhase section */ 240 | 241 | /* Begin PBXSourcesBuildPhase section */ 242 | FA00A6AA1CD54552005CF485 /* Sources */ = { 243 | isa = PBXSourcesBuildPhase; 244 | buildActionMask = 2147483647; 245 | files = ( 246 | FABC1DE91D46296C00F0B64B /* MetalCameraCaptureDevice.swift in Sources */, 247 | FA00A6CF1CD545F4005CF485 /* Shaders.metal in Sources */, 248 | FA00A6CD1CD545F4005CF485 /* MetalCameraSessionTypes.swift in Sources */, 249 | FA00A6B21CD54552005CF485 /* AppDelegate.swift in Sources */, 250 | FA00A6CB1CD545F4005CF485 /* CameraViewController.swift in Sources */, 251 | FA00A6CC1CD545F4005CF485 /* MetalCameraSession.swift in Sources */, 252 | FA00A6CE1CD545F4005CF485 /* MTKViewController.swift in Sources */, 253 | ); 254 | runOnlyForDeploymentPostprocessing = 0; 255 | }; 256 | FABC1DEC1D4636D500F0B64B /* Sources */ = { 257 | isa = PBXSourcesBuildPhase; 258 | buildActionMask = 2147483647; 259 | files = ( 260 | FABBE88B1D491220006D3416 /* MetalCameraSessionTestsDelegates.swift in Sources */, 261 | FABC1DFC1D46373A00F0B64B /* MetalCameraSessionTests.swift in Sources */, 262 | ); 263 | runOnlyForDeploymentPostprocessing = 0; 264 | }; 265 | /* End PBXSourcesBuildPhase section */ 266 | 267 | /* Begin PBXTargetDependency section */ 268 | FABC1DF61D4636D500F0B64B /* PBXTargetDependency */ = { 269 | isa = PBXTargetDependency; 270 | target = FA00A6AD1CD54552005CF485 /* Metal Camera */; 271 | targetProxy = FABC1DF51D4636D500F0B64B /* PBXContainerItemProxy */; 272 | }; 273 | /* End PBXTargetDependency section */ 274 | 275 | /* Begin PBXVariantGroup section */ 276 | FA00A6B51CD54552005CF485 /* Main.storyboard */ = { 277 | isa = PBXVariantGroup; 278 | children = ( 279 | FA00A6B61CD54552005CF485 /* Base */, 280 | ); 281 | name = Main.storyboard; 282 | sourceTree = ""; 283 | }; 284 | FA00A6BA1CD54552005CF485 /* LaunchScreen.storyboard */ = { 285 | isa = PBXVariantGroup; 286 | children = ( 287 | FA00A6BB1CD54552005CF485 /* Base */, 288 | ); 289 | name = LaunchScreen.storyboard; 290 | sourceTree = ""; 291 | }; 292 | /* End PBXVariantGroup section */ 293 | 294 | /* Begin XCBuildConfiguration section */ 295 | FA00A6BE1CD54552005CF485 /* Debug */ = { 296 | isa = XCBuildConfiguration; 297 | buildSettings = { 298 | ALWAYS_SEARCH_USER_PATHS = NO; 299 | ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; 300 | CLANG_ANALYZER_NONNULL = YES; 301 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 302 | CLANG_CXX_LIBRARY = "libc++"; 303 | CLANG_ENABLE_MODULES = YES; 304 | CLANG_ENABLE_OBJC_ARC = YES; 305 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 306 | CLANG_WARN_BOOL_CONVERSION = YES; 307 | CLANG_WARN_COMMA = YES; 308 | CLANG_WARN_CONSTANT_CONVERSION = YES; 309 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 310 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 311 | CLANG_WARN_EMPTY_BODY = YES; 312 | CLANG_WARN_ENUM_CONVERSION = YES; 313 | CLANG_WARN_INFINITE_RECURSION = YES; 314 | CLANG_WARN_INT_CONVERSION = YES; 315 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 316 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 317 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 318 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 319 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 320 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 321 | CLANG_WARN_STRICT_PROTOTYPES = YES; 322 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 323 | CLANG_WARN_UNREACHABLE_CODE = YES; 324 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 325 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 326 | COPY_PHASE_STRIP = NO; 327 | DEBUG_INFORMATION_FORMAT = dwarf; 328 | ENABLE_STRICT_OBJC_MSGSEND = YES; 329 | ENABLE_TESTABILITY = YES; 330 | ENABLE_USER_SCRIPT_SANDBOXING = YES; 331 | GCC_C_LANGUAGE_STANDARD = gnu99; 332 | GCC_DYNAMIC_NO_PIC = NO; 333 | GCC_NO_COMMON_BLOCKS = YES; 334 | GCC_OPTIMIZATION_LEVEL = 0; 335 | GCC_PREPROCESSOR_DEFINITIONS = ( 336 | "DEBUG=1", 337 | "$(inherited)", 338 | ); 339 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 340 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 341 | GCC_WARN_UNDECLARED_SELECTOR = YES; 342 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 343 | GCC_WARN_UNUSED_FUNCTION = YES; 344 | GCC_WARN_UNUSED_VARIABLE = YES; 345 | IPHONEOS_DEPLOYMENT_TARGET = 12.0; 346 | MTL_ENABLE_DEBUG_INFO = YES; 347 | ONLY_ACTIVE_ARCH = YES; 348 | SDKROOT = iphoneos; 349 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 350 | TARGETED_DEVICE_FAMILY = "1,2"; 351 | }; 352 | name = Debug; 353 | }; 354 | FA00A6BF1CD54552005CF485 /* Release */ = { 355 | isa = XCBuildConfiguration; 356 | buildSettings = { 357 | ALWAYS_SEARCH_USER_PATHS = NO; 358 | ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; 359 | CLANG_ANALYZER_NONNULL = YES; 360 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 361 | CLANG_CXX_LIBRARY = "libc++"; 362 | CLANG_ENABLE_MODULES = YES; 363 | CLANG_ENABLE_OBJC_ARC = YES; 364 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 365 | CLANG_WARN_BOOL_CONVERSION = YES; 366 | CLANG_WARN_COMMA = YES; 367 | CLANG_WARN_CONSTANT_CONVERSION = YES; 368 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 369 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 370 | CLANG_WARN_EMPTY_BODY = YES; 371 | CLANG_WARN_ENUM_CONVERSION = YES; 372 | CLANG_WARN_INFINITE_RECURSION = YES; 373 | CLANG_WARN_INT_CONVERSION = YES; 374 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 375 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 376 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 377 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 378 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 379 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 380 | CLANG_WARN_STRICT_PROTOTYPES = YES; 381 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 382 | CLANG_WARN_UNREACHABLE_CODE = YES; 383 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 384 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 385 | COPY_PHASE_STRIP = NO; 386 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 387 | ENABLE_NS_ASSERTIONS = NO; 388 | ENABLE_STRICT_OBJC_MSGSEND = YES; 389 | ENABLE_USER_SCRIPT_SANDBOXING = YES; 390 | GCC_C_LANGUAGE_STANDARD = gnu99; 391 | GCC_NO_COMMON_BLOCKS = YES; 392 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 393 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 394 | GCC_WARN_UNDECLARED_SELECTOR = YES; 395 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 396 | GCC_WARN_UNUSED_FUNCTION = YES; 397 | GCC_WARN_UNUSED_VARIABLE = YES; 398 | IPHONEOS_DEPLOYMENT_TARGET = 12.0; 399 | MTL_ENABLE_DEBUG_INFO = NO; 400 | SDKROOT = iphoneos; 401 | SWIFT_COMPILATION_MODE = wholemodule; 402 | SWIFT_OPTIMIZATION_LEVEL = "-O"; 403 | TARGETED_DEVICE_FAMILY = "1,2"; 404 | VALIDATE_PRODUCT = YES; 405 | }; 406 | name = Release; 407 | }; 408 | FA00A6C11CD54552005CF485 /* Debug */ = { 409 | isa = XCBuildConfiguration; 410 | buildSettings = { 411 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 412 | ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = NO; 413 | CODE_SIGN_IDENTITY = "iPhone Developer"; 414 | DEVELOPMENT_TEAM = JTKK646U9Z; 415 | INFOPLIST_FILE = MetalRenderCamera/Info.plist; 416 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 417 | LD_RUNPATH_SEARCH_PATHS = ( 418 | "$(inherited)", 419 | "@executable_path/Frameworks", 420 | ); 421 | PRODUCT_BUNDLE_IDENTIFIER = com.rationalmatter.MetalRenderCamera; 422 | PRODUCT_NAME = "$(TARGET_NAME)"; 423 | SWIFT_SWIFT3_OBJC_INFERENCE = Default; 424 | SWIFT_VERSION = 5.0; 425 | }; 426 | name = Debug; 427 | }; 428 | FA00A6C21CD54552005CF485 /* Release */ = { 429 | isa = XCBuildConfiguration; 430 | buildSettings = { 431 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 432 | ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = NO; 433 | CODE_SIGN_IDENTITY = "iPhone Developer"; 434 | DEVELOPMENT_TEAM = JTKK646U9Z; 435 | INFOPLIST_FILE = MetalRenderCamera/Info.plist; 436 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 437 | LD_RUNPATH_SEARCH_PATHS = ( 438 | "$(inherited)", 439 | "@executable_path/Frameworks", 440 | ); 441 | PRODUCT_BUNDLE_IDENTIFIER = com.rationalmatter.MetalRenderCamera; 442 | PRODUCT_NAME = "$(TARGET_NAME)"; 443 | SWIFT_SWIFT3_OBJC_INFERENCE = Default; 444 | SWIFT_VERSION = 5.0; 445 | }; 446 | name = Release; 447 | }; 448 | FABC1DF81D4636D500F0B64B /* Debug */ = { 449 | isa = XCBuildConfiguration; 450 | buildSettings = { 451 | BUNDLE_LOADER = "$(TEST_HOST)"; 452 | DEVELOPMENT_TEAM = JTKK646U9Z; 453 | INFOPLIST_FILE = MetalRenderCamera/MetalRenderCameraTests/Info.plist; 454 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 455 | LD_RUNPATH_SEARCH_PATHS = ( 456 | "$(inherited)", 457 | "@executable_path/Frameworks", 458 | "@loader_path/Frameworks", 459 | ); 460 | PRODUCT_BUNDLE_IDENTIFIER = com.rationalmatter.MetalRenderCameraTests; 461 | PRODUCT_NAME = "$(TARGET_NAME)"; 462 | SWIFT_SWIFT3_OBJC_INFERENCE = Default; 463 | SWIFT_VERSION = 4.0; 464 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Metal Camera.app/Metal Camera"; 465 | }; 466 | name = Debug; 467 | }; 468 | FABC1DF91D4636D500F0B64B /* Release */ = { 469 | isa = XCBuildConfiguration; 470 | buildSettings = { 471 | BUNDLE_LOADER = "$(TEST_HOST)"; 472 | DEVELOPMENT_TEAM = JTKK646U9Z; 473 | INFOPLIST_FILE = MetalRenderCamera/MetalRenderCameraTests/Info.plist; 474 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 475 | LD_RUNPATH_SEARCH_PATHS = ( 476 | "$(inherited)", 477 | "@executable_path/Frameworks", 478 | "@loader_path/Frameworks", 479 | ); 480 | PRODUCT_BUNDLE_IDENTIFIER = com.rationalmatter.MetalRenderCameraTests; 481 | PRODUCT_NAME = "$(TARGET_NAME)"; 482 | SWIFT_SWIFT3_OBJC_INFERENCE = Default; 483 | SWIFT_VERSION = 4.0; 484 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Metal Camera.app/Metal Camera"; 485 | }; 486 | name = Release; 487 | }; 488 | /* End XCBuildConfiguration section */ 489 | 490 | /* Begin XCConfigurationList section */ 491 | FA00A6A91CD54552005CF485 /* Build configuration list for PBXProject "MetalRenderCamera" */ = { 492 | isa = XCConfigurationList; 493 | buildConfigurations = ( 494 | FA00A6BE1CD54552005CF485 /* Debug */, 495 | FA00A6BF1CD54552005CF485 /* Release */, 496 | ); 497 | defaultConfigurationIsVisible = 0; 498 | defaultConfigurationName = Release; 499 | }; 500 | FA00A6C01CD54552005CF485 /* Build configuration list for PBXNativeTarget "Metal Camera" */ = { 501 | isa = XCConfigurationList; 502 | buildConfigurations = ( 503 | FA00A6C11CD54552005CF485 /* Debug */, 504 | FA00A6C21CD54552005CF485 /* Release */, 505 | ); 506 | defaultConfigurationIsVisible = 0; 507 | defaultConfigurationName = Release; 508 | }; 509 | FABC1DF71D4636D500F0B64B /* Build configuration list for PBXNativeTarget "MetalRenderCameraTests" */ = { 510 | isa = XCConfigurationList; 511 | buildConfigurations = ( 512 | FABC1DF81D4636D500F0B64B /* Debug */, 513 | FABC1DF91D4636D500F0B64B /* Release */, 514 | ); 515 | defaultConfigurationIsVisible = 0; 516 | defaultConfigurationName = Release; 517 | }; 518 | /* End XCConfigurationList section */ 519 | }; 520 | rootObject = FA00A6A61CD54552005CF485 /* Project object */; 521 | } 522 | -------------------------------------------------------------------------------- /MetalRenderCamera.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MetalRenderCamera.xcodeproj/xcshareddata/xcschemes/Metal Camera.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 9 | 10 | 16 | 22 | 23 | 24 | 25 | 26 | 32 | 33 | 35 | 41 | 42 | 43 | 44 | 45 | 55 | 57 | 63 | 64 | 65 | 66 | 72 | 74 | 80 | 81 | 82 | 83 | 85 | 86 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /MetalRenderCamera/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 24/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate { 13 | 14 | var window: UIWindow? 15 | 16 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 17 | return true 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/AppIcon.appiconset/AppIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexstaravoitau/MetalRenderCamera/0b487a3ce55a6e3807106bd0ae9ebe1a0a6c1f56/MetalRenderCamera/Assets.xcassets/AppIcon.appiconset/AppIcon.png -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "filename" : "AppIcon.png", 5 | "idiom" : "universal", 6 | "platform" : "ios", 7 | "size" : "1024x1024" 8 | }, 9 | { 10 | "appearances" : [ 11 | { 12 | "appearance" : "luminosity", 13 | "value" : "dark" 14 | } 15 | ], 16 | "idiom" : "universal", 17 | "platform" : "ios", 18 | "size" : "1024x1024" 19 | }, 20 | { 21 | "appearances" : [ 22 | { 23 | "appearance" : "luminosity", 24 | "value" : "tinted" 25 | } 26 | ], 27 | "idiom" : "universal", 28 | "platform" : "ios", 29 | "size" : "1024x1024" 30 | } 31 | ], 32 | "info" : { 33 | "author" : "xcode", 34 | "version" : 1 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/metal_icon.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "metal_icon.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "metal_icon@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "metal_icon@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexstaravoitau/MetalRenderCamera/0b487a3ce55a6e3807106bd0ae9ebe1a0a6c1f56/MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon.png -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexstaravoitau/MetalRenderCamera/0b487a3ce55a6e3807106bd0ae9ebe1a0a6c1f56/MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon@2x.png -------------------------------------------------------------------------------- /MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexstaravoitau/MetalRenderCamera/0b487a3ce55a6e3807106bd0ae9ebe1a0a6c1f56/MetalRenderCamera/Assets.xcassets/metal_icon.imageset/metal_icon@3x.png -------------------------------------------------------------------------------- /MetalRenderCamera/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /MetalRenderCamera/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /MetalRenderCamera/CameraViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.swift 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 24/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import Metal 11 | 12 | internal final class CameraViewController: MTKViewController { 13 | var session: MetalCameraSession? 14 | 15 | override func viewDidLoad() { 16 | super.viewDidLoad() 17 | session = MetalCameraSession(frameOrientation: .portrait, delegate: self) 18 | } 19 | 20 | override func viewWillAppear(_ animated: Bool) { 21 | super.viewWillAppear(animated) 22 | session?.start() 23 | } 24 | 25 | override func viewDidDisappear(_ animated: Bool) { 26 | super.viewDidDisappear(animated) 27 | session?.stop() 28 | } 29 | } 30 | 31 | // MARK: - MetalCameraSessionDelegate 32 | extension CameraViewController: MetalCameraSessionDelegate { 33 | func metalCameraSession(_ session: MetalCameraSession, didReceiveFrameAsTextures textures: [MTLTexture], withTimestamp timestamp: Double) { 34 | self.texture = textures[0] 35 | } 36 | 37 | func metalCameraSession(_ cameraSession: MetalCameraSession, didUpdateState state: MetalCameraSessionState, error: MetalCameraSessionError?) { 38 | switch state { 39 | case .error where error == .captureSessionRuntimeError: 40 | // Ignoring capture session runtime errors 41 | cameraSession.start() 42 | default: 43 | break 44 | } 45 | DispatchQueue.main.async { 46 | self.title = "Metal camera: \(state)" 47 | } 48 | NSLog("Session changed state to \(state) with error: \(error?.localizedDescription ?? "None").") 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /MetalRenderCamera/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSCameraUsageDescription 26 | Used to grab camera data. 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIMainStoryboardFile 30 | Main 31 | UIRequiredDeviceCapabilities 32 | 33 | metal 34 | 35 | UIRequiresFullScreen 36 | 37 | UIStatusBarHidden 38 | 39 | UISupportedInterfaceOrientations 40 | 41 | UIInterfaceOrientationPortrait 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /MetalRenderCamera/MTKViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MTKViewController.swift 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 26/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import Metal 11 | 12 | #if arch(i386) || arch(x86_64) 13 | #else 14 | import MetalKit 15 | #endif 16 | 17 | /** 18 | * A `UIViewController` that allows quick and easy rendering of Metal textures. Currently only supports textures from single-plane pixel buffers, e.g. it can only render a single RGB texture and won't be able to render multiple YCbCr textures. Although this functionality can be added by overriding `MTKViewController`'s `willRenderTexture` method. 19 | */ 20 | open class MTKViewController: UIViewController { 21 | // MARK: - Public interface 22 | 23 | /// Metal texture to be drawn whenever the view controller is asked to render its view. Please note that if you set this `var` too frequently some of the textures may not being drawn, as setting a texture does not force the view controller's view to render its content. 24 | open var texture: MTLTexture? 25 | 26 | /** 27 | This method is called prior rendering view's content. Use `inout` `texture` parameter to update the texture that is about to be drawn. 28 | 29 | - parameter texture: Texture to be drawn 30 | - parameter commandBuffer: Command buffer that will be used for drawing 31 | - parameter device: Metal device 32 | */ 33 | open func willRenderTexture(_ texture: inout MTLTexture, withCommandBuffer commandBuffer: MTLCommandBuffer, device: MTLDevice) { 34 | /** 35 | * Override if neccessary 36 | */ 37 | } 38 | 39 | /** 40 | This method is called after rendering view's content. 41 | 42 | - parameter texture: Texture that was drawn 43 | - parameter commandBuffer: Command buffer we used for drawing 44 | - parameter device: Metal device 45 | */ 46 | open func didRenderTexture(_ texture: MTLTexture, withCommandBuffer commandBuffer: MTLCommandBuffer, device: MTLDevice) { 47 | /** 48 | * Override if neccessary 49 | */ 50 | } 51 | 52 | // MARK: - Public overrides 53 | 54 | override open func loadView() { 55 | super.loadView() 56 | #if arch(i386) || arch(x86_64) 57 | NSLog("Failed creating a default system Metal device, since Metal is not available on iOS Simulator.") 58 | #else 59 | assert(device != nil, "Failed creating a default system Metal device. Please, make sure Metal is available on your hardware.") 60 | #endif 61 | initializeMetalView() 62 | initializeRenderPipelineState() 63 | } 64 | 65 | // MARK: - Private Metal-related properties and methods 66 | 67 | /** 68 | initializes and configures the `MTKView` we use as `UIViewController`'s view. 69 | 70 | */ 71 | fileprivate func initializeMetalView() { 72 | #if arch(i386) || arch(x86_64) 73 | #else 74 | metalView = MTKView(frame: view.bounds, device: device) 75 | metalView.delegate = self 76 | metalView.framebufferOnly = true 77 | metalView.colorPixelFormat = .bgra8Unorm 78 | metalView.contentScaleFactor = UIScreen.main.scale 79 | metalView.autoresizingMask = [.flexibleWidth, .flexibleHeight] 80 | view.insertSubview(metalView, at: 0) 81 | #endif 82 | } 83 | 84 | #if arch(i386) || arch(x86_64) 85 | #else 86 | /// `UIViewController`'s view 87 | internal var metalView: MTKView! 88 | #endif 89 | 90 | /// Metal device 91 | internal var device = MTLCreateSystemDefaultDevice() 92 | 93 | /// Metal device command queue 94 | lazy internal var commandQueue: MTLCommandQueue? = { 95 | return device?.makeCommandQueue() 96 | }() 97 | 98 | /// Metal pipeline state we use for rendering 99 | internal var renderPipelineState: MTLRenderPipelineState? 100 | 101 | /// A semaphore we use to syncronize drawing code. 102 | fileprivate let semaphore = DispatchSemaphore(value: 1) 103 | 104 | /** 105 | initializes render pipeline state with a default vertex function mapping texture to the view's frame and a simple fragment function returning texture pixel's value. 106 | */ 107 | fileprivate func initializeRenderPipelineState() { 108 | guard 109 | let device = device, 110 | let library = device.makeDefaultLibrary() 111 | else { return } 112 | 113 | let pipelineDescriptor = MTLRenderPipelineDescriptor() 114 | pipelineDescriptor.sampleCount = 1 115 | pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm 116 | pipelineDescriptor.depthAttachmentPixelFormat = .invalid 117 | 118 | /** 119 | * Vertex function to map the texture to the view controller's view 120 | */ 121 | pipelineDescriptor.vertexFunction = library.makeFunction(name: "mapTexture") 122 | /** 123 | * Fragment function to display texture's pixels in the area bounded by vertices of `mapTexture` shader 124 | */ 125 | pipelineDescriptor.fragmentFunction = library.makeFunction(name: "displayTexture") 126 | 127 | do { 128 | try renderPipelineState = device.makeRenderPipelineState(descriptor: pipelineDescriptor) 129 | } 130 | catch { 131 | assertionFailure("Failed creating a render state pipeline. Can't render the texture without one.") 132 | return 133 | } 134 | } 135 | } 136 | 137 | #if arch(i386) || arch(x86_64) 138 | #else 139 | 140 | // MARK: - MTKViewDelegate and rendering 141 | extension MTKViewController: MTKViewDelegate { 142 | public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { 143 | NSLog("MTKView drawable size will change to \(size)") 144 | } 145 | 146 | public func draw(in: MTKView) { 147 | _ = semaphore.wait(timeout: DispatchTime.distantFuture) 148 | 149 | autoreleasepool { 150 | guard 151 | var texture = texture, 152 | let device = device, 153 | let commandBuffer = commandQueue?.makeCommandBuffer() 154 | else { 155 | _ = semaphore.signal() 156 | return 157 | } 158 | 159 | willRenderTexture(&texture, withCommandBuffer: commandBuffer, device: device) 160 | render(texture: texture, withCommandBuffer: commandBuffer, device: device) 161 | } 162 | } 163 | 164 | /** 165 | Renders texture into the `UIViewController`'s view. 166 | 167 | - parameter texture: Texture to be rendered 168 | - parameter commandBuffer: Command buffer we will use for drawing 169 | */ 170 | private func render(texture: MTLTexture, withCommandBuffer commandBuffer: MTLCommandBuffer, device: MTLDevice) { 171 | guard 172 | let currentRenderPassDescriptor = metalView.currentRenderPassDescriptor, 173 | let currentDrawable = metalView.currentDrawable, 174 | let renderPipelineState = renderPipelineState, 175 | let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: currentRenderPassDescriptor) 176 | else { 177 | semaphore.signal() 178 | return 179 | } 180 | 181 | encoder.pushDebugGroup("RenderFrame") 182 | encoder.setRenderPipelineState(renderPipelineState) 183 | encoder.setFragmentTexture(texture, index: 0) 184 | encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1) 185 | encoder.popDebugGroup() 186 | encoder.endEncoding() 187 | 188 | commandBuffer.addScheduledHandler { [weak self] (buffer) in 189 | guard let unwrappedSelf = self else { return } 190 | 191 | unwrappedSelf.didRenderTexture(texture, withCommandBuffer: buffer, device: device) 192 | unwrappedSelf.semaphore.signal() 193 | } 194 | commandBuffer.present(currentDrawable) 195 | commandBuffer.commit() 196 | } 197 | } 198 | 199 | #endif 200 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalCameraCaptureDevice.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MetalCameraCaptureDevice.swift 3 | // MetalRenderCamera 4 | // 5 | // Created by Alex Staravoitau on 25/07/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import AVFoundation 10 | 11 | /// A wrapper for AVFoundation's `AVCaptureDevice`, providing instance methods instead of class methods. This wrapper simplifies unit testing. 12 | internal class MetalCameraCaptureDevice { 13 | 14 | /** 15 | Attempts to retrieve a capture device for the specified media type and position. 16 | 17 | - parameter mediaType: The media type of the device (e.g., video, audio). 18 | - parameter deviceType: The type of the capture device (e.g., built-in microphone, wide-angle camera). 19 | - parameter position: The position of the device (e.g., front, back). 20 | 21 | - returns: The capture device if available, otherwise `nil`. 22 | */ 23 | internal func device(for mediaType: AVMediaType, type deviceType: AVCaptureDevice.DeviceType, position: AVCaptureDevice.Position) -> AVCaptureDevice? { 24 | return AVCaptureDevice.DiscoverySession(deviceTypes: [deviceType], mediaType: mediaType, position: position).devices.first 25 | } 26 | 27 | /** 28 | Requests access to the capture device for the specified media type. 29 | 30 | - parameter mediaType: The media type for which access is requested (e.g., video, audio). 31 | - parameter handler: The completion handler to be called with the result of the access request, returning a `Bool` indicating success or failure. 32 | */ 33 | internal func requestAccess(for mediaType: AVMediaType, completionHandler handler: @escaping ((Bool) -> Void)) { 34 | AVCaptureDevice.requestAccess(for: mediaType, completionHandler: handler) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalCameraSession.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MetalCameraSession.swift 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 24/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import AVFoundation 10 | import Metal 11 | 12 | /** 13 | * A protocol for a delegate that may be notified about the capture session events. 14 | */ 15 | public protocol MetalCameraSessionDelegate { 16 | /** 17 | Camera session did receive a new frame and converted it to an array of Metal textures. For instance, if the RGB pixel format was selected, the array will have a single texture, whereas if YCbCr was selected, then there will be two textures: the Y texture at index 0, and CbCr texture at index 1 (following the order in a sample buffer). 18 | 19 | - parameter session: Session that triggered the update 20 | - parameter didReceiveFrameAsTextures: Frame converted to an array of Metal textures 21 | - parameter withTimestamp: Frame timestamp in seconds 22 | */ 23 | func metalCameraSession(_ session: MetalCameraSession, didReceiveFrameAsTextures: [MTLTexture], withTimestamp: Double) 24 | 25 | /** 26 | Camera session did update capture state 27 | 28 | - parameter session: Session that triggered the update 29 | - parameter didUpdateState: Capture session state 30 | - parameter error: Capture session error or `nil` 31 | */ 32 | func metalCameraSession(_ session: MetalCameraSession, didUpdateState: MetalCameraSessionState, error: MetalCameraSessionError?) 33 | } 34 | 35 | /** 36 | * A convenient hub for accessing camera data as a stream of Metal textures with corresponding timestamps. 37 | * 38 | * Frames are received in the specified orientation set during initialization. 39 | */ 40 | public final class MetalCameraSession: NSObject { 41 | // MARK: Public interface 42 | 43 | /// Frame orientation. 44 | public let frameOrientation: AVCaptureVideoOrientation? 45 | 46 | /// Requested capture device position, i.e. back/front camera 47 | public let captureDevicePosition: AVCaptureDevice.Position 48 | 49 | /// Requested capture device type 50 | public let captureDeviceType: AVCaptureDevice.DeviceType 51 | 52 | /// Delegate that will be notified about state changes and new frames 53 | public var delegate: MetalCameraSessionDelegate? 54 | 55 | /// Pixel format to be used for grabbing camera data and converting textures 56 | public let pixelFormat: MetalCameraPixelFormat 57 | 58 | /** 59 | Initializes a new instance with optional values. 60 | 61 | - parameter pixelFormat: Pixel format. Defaults to `.rgb` 62 | - parameter captureDevicePosition: Camera to be used for capturing. Defaults to `.back`. 63 | - parameter captureDeviceType: Device type to be used for capturing. Defaults to `.builtInWideAngleCamera`. 64 | - parameter frameOrientation: Desired frame orientation. Defaults to `nil`. 65 | - parameter delegate: Delegate. Defaults to `nil`. 66 | */ 67 | public init( 68 | pixelFormat: MetalCameraPixelFormat = .rgb, 69 | captureDevicePosition: AVCaptureDevice.Position = .back, 70 | captureDeviceType: AVCaptureDevice.DeviceType = .builtInWideAngleCamera, 71 | frameOrientation: AVCaptureVideoOrientation? = nil, 72 | delegate: MetalCameraSessionDelegate? = nil 73 | ) { 74 | self.pixelFormat = pixelFormat 75 | self.captureDevicePosition = captureDevicePosition 76 | self.captureDeviceType = captureDeviceType 77 | self.frameOrientation = frameOrientation 78 | self.delegate = delegate 79 | super.init() 80 | 81 | NotificationCenter.default.addObserver(self, selector: #selector(captureSessionRuntimeError), name: NSNotification.Name.AVCaptureSessionRuntimeError, object: nil) 82 | } 83 | 84 | /** 85 | Starts the capture session. Call this method to start receiving delegate updates with the sample buffers. 86 | */ 87 | public func start() { 88 | requestCameraAccess() 89 | 90 | captureSessionQueue.async(execute: { 91 | do { 92 | self.captureSession.beginConfiguration() 93 | try self.initializeInputDevice() 94 | try self.initializeOutputData() 95 | self.captureSession.commitConfiguration() 96 | try self.initializeTextureCache() 97 | self.captureSession.startRunning() 98 | self.state = .streaming 99 | } 100 | catch let error as MetalCameraSessionError { 101 | self.handleError(error) 102 | } 103 | catch { 104 | // We only throw `MetalCameraSessionError` errors. 105 | } 106 | }) 107 | } 108 | 109 | /** 110 | Stops the capture session. 111 | */ 112 | public func stop() { 113 | captureSessionQueue.async(execute: { 114 | self.captureSession.stopRunning() 115 | self.state = .stopped 116 | }) 117 | } 118 | 119 | // MARK: Private properties and methods 120 | 121 | /// Current session state. 122 | fileprivate var state: MetalCameraSessionState = .waiting { 123 | didSet { 124 | guard state != .error else { return } 125 | 126 | delegate?.metalCameraSession(self, didUpdateState: state, error: nil) 127 | } 128 | } 129 | 130 | /// `AVFoundation` capture session object. 131 | fileprivate var captureSession = AVCaptureSession() 132 | 133 | /// Our internal wrapper for the `AVCaptureDevice`. 134 | internal var captureDevice = MetalCameraCaptureDevice() 135 | 136 | /// Dispatch queue for capture session events. 137 | fileprivate var captureSessionQueue = DispatchQueue(label: "MetalCameraSessionQueue", attributes: []) 138 | 139 | #if arch(i386) || arch(x86_64) 140 | #else 141 | /// Texture cache we will use for converting frame images to textures 142 | internal var textureCache: CVMetalTextureCache? 143 | #endif 144 | 145 | /// `MTLDevice` we need to initialize texture cache 146 | fileprivate var metalDevice = MTLCreateSystemDefaultDevice() 147 | 148 | /// Current capture input device. 149 | internal var inputDevice: AVCaptureDeviceInput? { 150 | didSet { 151 | if let oldValue = oldValue { 152 | captureSession.removeInput(oldValue) 153 | } 154 | 155 | guard let inputDevice = inputDevice else { return } 156 | 157 | captureSession.addInput(inputDevice) 158 | } 159 | } 160 | 161 | /// Current capture output data stream. 162 | internal var outputData: AVCaptureVideoDataOutput? { 163 | didSet { 164 | if let oldValue = oldValue { 165 | captureSession.removeOutput(oldValue) 166 | } 167 | 168 | guard let outputData = outputData else { return } 169 | 170 | captureSession.addOutput(outputData) 171 | } 172 | } 173 | 174 | /** 175 | Requests access to camera hardware. 176 | */ 177 | fileprivate func requestCameraAccess() { 178 | captureDevice.requestAccess(for: .video) { granted in 179 | guard granted else { 180 | self.handleError(.noHardwareAccess) 181 | return 182 | } 183 | 184 | if self.state != .streaming && self.state != .error { 185 | self.state = .ready 186 | } 187 | } 188 | } 189 | 190 | fileprivate func handleError(_ error: MetalCameraSessionError) { 191 | if error.isStreamingError() { 192 | state = .error 193 | } 194 | 195 | delegate?.metalCameraSession(self, didUpdateState: state, error: error) 196 | } 197 | 198 | /** 199 | Initializes the texture cache. We use it to convert frames into textures. 200 | */ 201 | fileprivate func initializeTextureCache() throws { 202 | #if arch(i386) || arch(x86_64) 203 | throw MetalCameraSessionError.failedToCreateTextureCache 204 | #else 205 | guard 206 | let metalDevice = metalDevice, 207 | CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, metalDevice, nil, &textureCache) == kCVReturnSuccess 208 | else { 209 | throw MetalCameraSessionError.failedToCreateTextureCache 210 | } 211 | #endif 212 | } 213 | 214 | /** 215 | Initializes capture input device with specified media type and device position. 216 | 217 | - throws: `MetalCameraSessionError` if we failed to initialize and add input device. 218 | */ 219 | fileprivate func initializeInputDevice() throws { 220 | var captureInput: AVCaptureDeviceInput! 221 | 222 | guard let inputDevice = captureDevice.device(for: .video, type: captureDeviceType, position: captureDevicePosition) else { 223 | throw MetalCameraSessionError.requestedHardwareNotFound 224 | } 225 | 226 | do { 227 | captureInput = try AVCaptureDeviceInput(device: inputDevice) 228 | } 229 | catch { 230 | throw MetalCameraSessionError.inputDeviceNotAvailable 231 | } 232 | 233 | guard captureSession.canAddInput(captureInput) else { 234 | throw MetalCameraSessionError.failedToAddCaptureInputDevice 235 | } 236 | 237 | self.inputDevice = captureInput 238 | } 239 | 240 | /** 241 | Initializes capture output data stream. 242 | 243 | - throws: `MetalCameraSessionError` if we failed to initialize and add output data stream. 244 | */ 245 | fileprivate func initializeOutputData() throws { 246 | let outputData = AVCaptureVideoDataOutput() 247 | 248 | outputData.videoSettings = [ 249 | kCVPixelBufferPixelFormatTypeKey as String: Int(pixelFormat.coreVideoType) 250 | ] 251 | outputData.alwaysDiscardsLateVideoFrames = true 252 | outputData.setSampleBufferDelegate(self, queue: captureSessionQueue) 253 | 254 | guard captureSession.canAddOutput(outputData) else { 255 | throw MetalCameraSessionError.failedToAddCaptureOutput 256 | } 257 | 258 | self.outputData = outputData 259 | 260 | // Set the video orientation 261 | if let frameOrientation = frameOrientation, 262 | let videoConnection = outputData.connection(with: .video), 263 | videoConnection.isVideoOrientationSupported 264 | { 265 | videoConnection.videoOrientation = frameOrientation 266 | } 267 | } 268 | 269 | /** 270 | `AVCaptureSessionRuntimeErrorNotification` callback. 271 | */ 272 | @objc 273 | fileprivate func captureSessionRuntimeError() { 274 | if state == .streaming { 275 | handleError(.captureSessionRuntimeError) 276 | } 277 | } 278 | 279 | deinit { 280 | NotificationCenter.default.removeObserver(self) 281 | } 282 | } 283 | 284 | // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate 285 | extension MetalCameraSession: AVCaptureVideoDataOutputSampleBufferDelegate { 286 | 287 | #if arch(i386) || arch(x86_64) 288 | #else 289 | 290 | /** 291 | Converts a sample buffer received from camera to a Metal texture 292 | 293 | - parameter sampleBuffer: Sample buffer 294 | - parameter textureCache: Texture cache 295 | - parameter planeIndex: Index of the plane for planar buffers. Defaults to 0. 296 | - parameter pixelFormat: Metal pixel format. Defaults to `.bgra8Unorm`. 297 | 298 | - returns: Metal texture or nil 299 | */ 300 | private func texture(sampleBuffer: CMSampleBuffer?, textureCache: CVMetalTextureCache?, planeIndex: Int = 0, pixelFormat: MTLPixelFormat = .bgra8Unorm) throws -> MTLTexture { 301 | guard let sampleBuffer = sampleBuffer else { 302 | throw MetalCameraSessionError.missingSampleBuffer 303 | } 304 | guard let textureCache = textureCache else { 305 | throw MetalCameraSessionError.failedToCreateTextureCache 306 | } 307 | guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { 308 | throw MetalCameraSessionError.failedToGetImageBuffer 309 | } 310 | 311 | let isPlanar = CVPixelBufferIsPlanar(imageBuffer) 312 | let width = isPlanar ? CVPixelBufferGetWidthOfPlane(imageBuffer, planeIndex) : CVPixelBufferGetWidth(imageBuffer) 313 | let height = isPlanar ? CVPixelBufferGetHeightOfPlane(imageBuffer, planeIndex) : CVPixelBufferGetHeight(imageBuffer) 314 | 315 | var imageTexture: CVMetalTexture? 316 | 317 | let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, imageBuffer, nil, pixelFormat, width, height, planeIndex, &imageTexture) 318 | 319 | guard 320 | let unwrappedImageTexture = imageTexture, 321 | let texture = CVMetalTextureGetTexture(unwrappedImageTexture), 322 | result == kCVReturnSuccess 323 | else { 324 | throw MetalCameraSessionError.failedToCreateTextureFromImage 325 | } 326 | 327 | return texture 328 | } 329 | 330 | /** 331 | Strips out the timestamp value out of the sample buffer received from camera. 332 | 333 | - parameter sampleBuffer: Sample buffer with the frame data 334 | 335 | - returns: Double value for a timestamp in seconds or nil 336 | */ 337 | private func timestamp(sampleBuffer: CMSampleBuffer?) throws -> Double { 338 | guard let sampleBuffer = sampleBuffer else { 339 | throw MetalCameraSessionError.missingSampleBuffer 340 | } 341 | 342 | let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) 343 | 344 | guard time != CMTime.invalid else { 345 | throw MetalCameraSessionError.failedToRetrieveTimestamp 346 | } 347 | 348 | return Double(time.value) / Double(time.timescale) 349 | } 350 | 351 | public func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { 352 | do { 353 | var textures: [MTLTexture]! 354 | 355 | switch pixelFormat { 356 | case .rgb: 357 | let textureRGB = try texture(sampleBuffer: sampleBuffer, textureCache: textureCache) 358 | textures = [textureRGB] 359 | case .yCbCr: 360 | let textureY = try texture(sampleBuffer: sampleBuffer, textureCache: textureCache, planeIndex: 0, pixelFormat: .r8Unorm) 361 | let textureCbCr = try texture(sampleBuffer: sampleBuffer, textureCache: textureCache, planeIndex: 1, pixelFormat: .rg8Unorm) 362 | textures = [textureY, textureCbCr] 363 | } 364 | 365 | let timestamp = try self.timestamp(sampleBuffer: sampleBuffer) 366 | 367 | delegate?.metalCameraSession(self, didReceiveFrameAsTextures: textures, withTimestamp: timestamp) 368 | } 369 | catch let error as MetalCameraSessionError { 370 | self.handleError(error) 371 | } 372 | catch { 373 | // We only throw `MetalCameraSessionError` errors. 374 | } 375 | } 376 | 377 | #endif 378 | 379 | } 380 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalCameraSessionTypes.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MetalCameraSessionDelegate.swift 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 25/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import AVFoundation 10 | 11 | /** 12 | States of capturing session 13 | 14 | - Ready: Ready to start capturing 15 | - Streaming: Capture in progress 16 | - Stopped: Capturing stopped 17 | - Waiting: Waiting to get access to hardware 18 | - Error: An error has occured 19 | */ 20 | public enum MetalCameraSessionState { 21 | case ready 22 | case streaming 23 | case stopped 24 | case waiting 25 | case error 26 | } 27 | 28 | public enum MetalCameraPixelFormat { 29 | case rgb 30 | case yCbCr 31 | 32 | var coreVideoType: OSType { 33 | switch self { 34 | case .rgb: 35 | return kCVPixelFormatType_32BGRA 36 | case .yCbCr: 37 | return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange 38 | } 39 | } 40 | } 41 | 42 | /** 43 | Streaming error 44 | */ 45 | public enum MetalCameraSessionError: Error { 46 | /** 47 | * Streaming errors 48 | */// 49 | case noHardwareAccess 50 | case failedToAddCaptureInputDevice 51 | case failedToAddCaptureOutput 52 | case requestedHardwareNotFound 53 | case inputDeviceNotAvailable 54 | case captureSessionRuntimeError 55 | case frameRateNotSupported 56 | 57 | /** 58 | * Conversion errors 59 | */// 60 | case failedToCreateTextureCache 61 | case missingSampleBuffer 62 | case failedToGetImageBuffer 63 | case failedToCreateTextureFromImage 64 | case failedToRetrieveTimestamp 65 | 66 | /** 67 | Indicates if the error is related to streaming the media. 68 | 69 | - returns: True if the error is related to streaming, false otherwise 70 | */ 71 | public func isStreamingError() -> Bool { 72 | switch self { 73 | case .noHardwareAccess, .failedToAddCaptureInputDevice, .failedToAddCaptureOutput, .requestedHardwareNotFound, .inputDeviceNotAvailable, .captureSessionRuntimeError, .frameRateNotSupported: 74 | return true 75 | default: 76 | return false 77 | } 78 | } 79 | 80 | public var localizedDescription: String { 81 | switch self { 82 | case .noHardwareAccess: 83 | return "Failed to get access to the hardware for a given media type" 84 | case .failedToAddCaptureInputDevice: 85 | return "Failed to add a capture input device to the capture session" 86 | case .failedToAddCaptureOutput: 87 | return "Failed to add a capture output data channel to the capture session" 88 | case .requestedHardwareNotFound: 89 | return "Specified hardware is not available on this device" 90 | case .inputDeviceNotAvailable: 91 | return "Capture input device cannot be opened, probably because it is no longer available or because it is in use" 92 | case .captureSessionRuntimeError: 93 | return "AVCaptureSession runtime error" 94 | case .failedToCreateTextureCache: 95 | return "Failed to initialize texture cache" 96 | case .missingSampleBuffer: 97 | return "No sample buffer to convert the image from" 98 | case .failedToGetImageBuffer: 99 | return "Failed to retrieve an image buffer from camera's output sample buffer" 100 | case .failedToCreateTextureFromImage: 101 | return "Failed to convert the frame to a Metal texture" 102 | case .failedToRetrieveTimestamp: 103 | return "Failed to retrieve timestamp from the sample buffer" 104 | case .frameRateNotSupported: 105 | return "Specified frame rate is not supported by the camera" 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalRenderCameraTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalRenderCameraTests/MetalCameraSessionTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MetalCameraSessionTests.swift 3 | // MetalRenderCamera 4 | // 5 | // Created by Alex Staravoitau on 25/07/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | import AVFoundation 11 | 12 | @testable import Metal_Camera 13 | 14 | class MetalCameraSessionTests: XCTestCase { 15 | 16 | /** 17 | Test that camera session reports a corresponding error to its delegate if there is no access to hardware. 18 | */ 19 | func testErrorWithoutDeviceAccess() { 20 | /// A class faking `MetalCameraCaptureDevice` that would mock access requests and devices availability 21 | class StubCaptureDevice: MetalCameraCaptureDevice { 22 | override func requestAccess(for mediaType: AVMediaType, completionHandler handler: @escaping ((Bool) -> Void)) { handler(false) } 23 | } 24 | 25 | let delegate = ErrorTrackingDelegate() 26 | let session = MetalCameraSession(delegate: delegate) 27 | let expectation = self.expectation(description: "MetalCameraSession calls delegate with an updated state and error.") 28 | delegate.expectation = expectation 29 | session.captureDevice = StubCaptureDevice() 30 | session.start() 31 | 32 | waitForExpectations(timeout: 1) { error in 33 | if let error = error { 34 | /** 35 | Apparently the error was never reported and the expectation timed out. 36 | */ 37 | XCTFail(error.localizedDescription) 38 | } 39 | 40 | XCTAssert(delegate.error == .noHardwareAccess, "Camera session reported a inconsistent error.") 41 | } 42 | } 43 | 44 | /** 45 | Test that camera session reports a corresponding state to its delegate if access to hardware was successfully granted. 46 | */ 47 | func testStateWithDeviceAccess() { 48 | /// A class faking `MetalCameraCaptureDevice` that would mock access requests and devices availability 49 | class StubCaptureDevice: MetalCameraCaptureDevice { 50 | override func requestAccess(for mediaType: AVMediaType, completionHandler handler: @escaping ((Bool) -> Void)) { handler(true) } 51 | } 52 | 53 | let delegate = StateTrackingDelegate() 54 | let session = MetalCameraSession(delegate: delegate) 55 | let expectation = self.expectation(description: "MetalCameraSession calls delegate with an updated state and error.") 56 | delegate.expectation = expectation 57 | session.captureDevice = StubCaptureDevice() 58 | session.start() 59 | 60 | waitForExpectations(timeout: 1) { error in 61 | if let error = error { 62 | /** 63 | Apparently the status was never reported and the expectation timed out. 64 | */ 65 | XCTFail(error.localizedDescription) 66 | } 67 | 68 | XCTAssert(delegate.state == .ready) 69 | } 70 | } 71 | 72 | /** 73 | Test that camera session reports a corresponding error to its delegate if there is no required hardware available. 74 | */ 75 | func testErrorWithNoHardwareAvailable() { 76 | /// A class faking `MetalCameraCaptureDevice` that would mock access requests and devices availability 77 | class StubCaptureDevice: MetalCameraCaptureDevice { 78 | override func requestAccess(for mediaType: AVMediaType, completionHandler handler: @escaping ((Bool) -> Void)) { handler(true) } 79 | override func device(for mediaType: AVMediaType, type: AVCaptureDevice.DeviceType, position: AVCaptureDevice.Position) -> AVCaptureDevice? { return nil } 80 | } 81 | 82 | let delegate = ErrorTrackingDelegate() 83 | let session = MetalCameraSession(delegate: delegate) 84 | let expectation = self.expectation(description: "MetalCameraSession calls delegate with an updated state and error.") 85 | delegate.expectation = expectation 86 | session.captureDevice = StubCaptureDevice() 87 | session.start() 88 | 89 | waitForExpectations(timeout: 1) { error in 90 | if let error = error { 91 | /** 92 | Apparently the error was never reported and the expectation timed out. 93 | */ 94 | XCTFail(error.localizedDescription) 95 | } 96 | 97 | XCTAssert(delegate.error == .requestedHardwareNotFound, "Camera session reported a inconsistent error.") 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /MetalRenderCamera/MetalRenderCameraTests/MetalCameraSessionTestsDelegates.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MetalCameraSessionTestsDelegates.swift 3 | // MetalRenderCamera 4 | // 5 | // Created by Alex Staravoitau on 27/07/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | import Metal 11 | 12 | @testable import Metal_Camera 13 | 14 | /// This class is acting as a `MetalCameraSessionDelegate` that tracks the first error received from the camera session and reports it with a `XCTestExpectation`. 15 | internal final class ErrorTrackingDelegate: MetalCameraSessionDelegate { 16 | 17 | /// Stores the camera session error, so that it's available for a test 18 | var error: MetalCameraSessionError? 19 | 20 | /// Expectation that is waiting for the delegate 21 | var expectation: XCTestExpectation? 22 | 23 | internal func metalCameraSession(_ session: MetalCameraSession, didReceiveFrameAsTextures: [MTLTexture], withTimestamp: Double) { } 24 | 25 | internal func metalCameraSession(_ session: MetalCameraSession, didUpdateState: MetalCameraSessionState, error newError: MetalCameraSessionError?) { 26 | guard let expectation = expectation, (error == nil && newError != nil) else { return } 27 | 28 | error = newError 29 | expectation.fulfill() 30 | } 31 | } 32 | 33 | /// This class is acting as a `MetalCameraSessionDelegate` that tracks the first state received from the camera session and reports it with a `XCTestExpectation`. 34 | internal final class StateTrackingDelegate: MetalCameraSessionDelegate { 35 | 36 | /// Stores the camera session state, so that it's available for a test 37 | var state: MetalCameraSessionState? 38 | 39 | /// Expectation that is waiting for the delegate 40 | var expectation: XCTestExpectation? 41 | 42 | internal func metalCameraSession(_ session: MetalCameraSession, didReceiveFrameAsTextures: [MTLTexture], withTimestamp: Double) { } 43 | 44 | internal func metalCameraSession(_ session: MetalCameraSession, didUpdateState newState: MetalCameraSessionState, error: MetalCameraSessionError?) { 45 | guard let expectation = expectation, state == nil else { return } 46 | 47 | state = newState 48 | expectation.fulfill() 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /MetalRenderCamera/Shaders.metal: -------------------------------------------------------------------------------- 1 | // 2 | // Shaders.metal 3 | // MetalShaderCamera 4 | // 5 | // Created by Alex Staravoitau on 28/04/2016. 6 | // Copyright © 2016 Old Yellow Bricks. All rights reserved. 7 | // 8 | 9 | #include 10 | using namespace metal; 11 | 12 | typedef struct { 13 | float4 renderedCoordinate [[position]]; 14 | float2 textureCoordinate; 15 | } TextureMappingVertex; 16 | 17 | vertex TextureMappingVertex mapTexture(unsigned int vertex_id [[ vertex_id ]]) { 18 | float4x4 renderedCoordinates = float4x4(float4( -1.0, -1.0, 0.0, 1.0 ), 19 | float4( 1.0, -1.0, 0.0, 1.0 ), 20 | float4( -1.0, 1.0, 0.0, 1.0 ), 21 | float4( 1.0, 1.0, 0.0, 1.0 )); 22 | 23 | float4x2 textureCoordinates = float4x2(float2( 0.0, 1.0 ), 24 | float2( 1.0, 1.0 ), 25 | float2( 0.0, 0.0 ), 26 | float2( 1.0, 0.0 )); 27 | TextureMappingVertex outVertex; 28 | outVertex.renderedCoordinate = renderedCoordinates[vertex_id]; 29 | outVertex.textureCoordinate = textureCoordinates[vertex_id]; 30 | 31 | return outVertex; 32 | } 33 | 34 | fragment half4 displayTexture(TextureMappingVertex mappingVertex [[ stage_in ]], 35 | texture2d texture [[ texture(0) ]]) { 36 | constexpr sampler s(address::clamp_to_edge, filter::linear); 37 | 38 | return half4(texture.sample(s, mappingVertex.textureCoordinate)); 39 | } 40 | 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MetalRenderCamera 2 | A simple app that grabs raw camera data, converts to textures and renders on screen using `Metal`. 3 | 4 | The app uses two reusable components with (hopefully!) simple and straightforward interfaces: `MetalCameraSession` and `MTKViewController`. 5 | 6 | #### `MetalCameraSession` 7 | `MetalCameraSession` helps you grab raw camera data as pixel buffers with either of two pixel formats and convert it to a Metal texture (or textures). You can choose either of two pixel formats: `RGB` or `YCbCr`, `RGB` being a default option, since it produces a single texture that can be drawn on screen right away. `YCbCr` would be a better choice in some cases though, since it is a hardware native format, hence works faster and produces textures of smaller size. 8 | 9 | #### `MTKViewController` 10 | `MTKViewController` is a `UIViewController` subclass containing a `MTKView` that renders an arbitrary texture on screen with the help of a couple of small `Metal` shaders. 11 | --------------------------------------------------------------------------------