<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Opunundo on Medium]]></title>
        <description><![CDATA[Stories by Opunundo on Medium]]></description>
        <link>https://medium.com/@opunundo?source=rss-fce6601be83d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d8uytVmtBDsyAFSVjUjFVA.png</url>
            <title>Stories by Opunundo on Medium</title>
            <link>https://medium.com/@opunundo?source=rss-fce6601be83d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:35:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@opunundo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[failed assertion `Set Vertex Buffer Offset Validation invalid usage because encoding has ended.]]></title>
            <link>https://medium.com/@opunundo/failed-assertion-set-vertex-buffer-offset-validation-invalid-usage-because-encoding-has-ended-dc78e4aa5d12?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc78e4aa5d12</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[metal]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 15:06:55 GMT</pubDate>
            <atom:updated>2026-02-06T15:07:22.672Z</atom:updated>
            <content:encoded><![CDATA[<p>This error usually occurs when <strong><em>renderCommandEncoder.endEncoding()</em></strong> is placed incorrectly. In Metal, <strong><em>endEncoding()</em></strong> must be calledd exactly once, after all commands for the render pass have been encoded. However, if <strong><em>endEncodeing()</em></strong> is called inside a for loop as shown below, it will cause a problem.</p><p><strong><em>Incorrect example:</em></strong></p><pre>for node in nodes {<br>    ...<br>    renderCommandEncoder.setVertexBufferOffset(constantOffset, index: 2)<br>    ...<br>    renderCommandEncoder.endEncoding()<br>}</pre><p><strong><em>Correct example:</em></strong></p><pre>for node in nodes {<br>    ...<br>    renderCommandEncoder.setVertexBufferOffset(constantOffset, index: 2)<br>    ...<br>}<br>renderCommandEncoder.endEncoding()</pre><p>As nested blocks increase, it becomes easier to lose track. Be careful.</p><p>Now the shadows render correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pM_xi6Fwy9t5tZRCyUZKbQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc78e4aa5d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When loading an OBJ file using MDLAsset in Metal, the texture is missing]]></title>
            <link>https://medium.com/@opunundo/when-loading-an-obj-file-using-mdlasset-in-metal-the-texture-is-missing-cff17f068a8b?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff17f068a8b</guid>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[texture]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 09:30:11 GMT</pubDate>
            <atom:updated>2026-01-30T09:30:11.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Resource: <a href="https://medium.com/@warrenm/thirty-days-of-metal-day-17-assets-a5a72b3d105c"><strong><em>Thiry Days of Metal — Day 17: Assets.</em></strong></a></p><p><em>The model asset was sourced from the following link:</em><br><a href="https://www.cs.cmu.edu/~kmcrane/Projects/ModelRepository/"><strong><em>https://www.cs.cmu.edu/~kmcrane/Projects/ModelRepository/</em></strong></a></p><p>This time, I experimented with loading asset files. <br>As is often the cas, it didn’t work right away.<br>The texture image was missing when the model was rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FG0nijd2dR5feaZEsNKt-w.gif" /></figure><p>After comparing with the original code, I found that a file was missing.<br>Looking more closely, the <strong><em>spot_material.mtl</em></strong> file was not there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*p65PY3pJzc-kuccCHaxBpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*nA1rQmbQtyBbrIeOproZfg.png" /></figure><p>After further investigation, I learnes that the <strong><em>.mtl</em></strong> file serves as a link between the <strong><em>.obj</em></strong> file and the texture image files. <br>Opening the <strong><em>.mtl</em></strong> file reveals the following contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cr7f0c6Hmp4vHiKIDnWutQ.png" /><figcaption>mtl 파일 내용</figcaption></figure><p>Here, the important parts are <strong><em>newmtl</em></strong> and <strong><em>map_Kd</em></strong>. The <strong><em>newmtl</em></strong> keyword defines the material name, and <strong><em>map_Kd</em></strong> specifies the path to the texture image to be used. The entries between them — such as <strong><em>Ns, Kd, Ka</em></strong>, and <strong><em>Ks</em></strong> — are related to material properties. For more details on these, please refer to the following link.</p><p><a href="https://en.wikipedia.org/wiki/Wavefront_.obj_file#:~:text=%5B7%5D-,Basic%20materials,-%5Bedit%5D">Wavefront .obj file - Wikipedia</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtuGnTNfL3RS7IQ43sybUA.png" /></figure><p>To summarize, when a texture is missing, it is usually necessary to check whether the OBJ file, the texture image file, and the MTL file are all present.<br>If the MTL file is missing, a new file should be created and saved with the <strong><em>.mtl </em></strong>extension. In the MTL file, add the follwoing entries and save it:</p><p><strong><em>newmtl </em></strong><em>(arbitrary material name)</em><strong><em><br>map_Kd </em></strong><em>(path to the txture image to be used)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*xhB0baL7y0wQ0OtoUOidAQ.png" /></figure><p>Finally, open the OBJ file in a text editor and add the name of the newly created MTL file.</p><p>After that, the model is rendered correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pUCK6wk24Z_Or4SwHA0YUQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff17f068a8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a texture come out distorted in Metal]]></title>
            <link>https://medium.com/@opunundo/when-a-texture-come-out-distorted-in-metal-4845e35d4470?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4845e35d4470</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 10:03:35 GMT</pubDate>
            <atom:updated>2026-01-29T10:03:35.728Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Resource:</strong> <a href="https://medium.com/@warrenm/thirty-days-of-metal-day-16-textures-ecb7ea318d00"><strong><em>Thirty Days of Metal — Day 16</em></strong></a>. <br><em>This post is records an error caused by a mistake made during a Metal graphics exercise.</em></p><p>Today’s topic is textures. When looking at the result, the texture image appears strangely distorted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sNch5pPHjAzjpZIvuSq1_A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEY8OLZsP6EEESroa_QmEw.png" /></figure><p>After looking into the cause, I realized that I hadn’t specified the offset for the texture coordinates in the vertex descriptor.</p><p>It now renders correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*hBJo7_nsAYcb9GZ_b_7lfw.gif" /></figure><p>Then, why does this happen when the offet isn’t specified? It’s not something that’s easy to understand intuitively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZjEpgwVtV0-l72EOcjflA.png" /></figure><p>Still, I was curious, so I looked into it. The vertex we defined is a total 32 bytes: 12 bytes for position, 12 bytes for normal, and 8 bytes for texture coordinates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxWXjFeToXkrqXR0PGuehA.png" /></figure><p>Under normal circumstances, a single vertex would be read as follows: bytes 0–11 for position, 12–23 for normal, and 24–31 for texture UVs.</p><p>Howver, if the offset is not specified, the offset value of Attribute[2] remains 0.</p><p>This means that when the shader tries to read UVs, it instead reads the data located at bytes 0–7.</p><p>That region corresponds to part of the vertex’s position data, so the UVs end up being interpreted as incorrect values, which leads to visual artifacts.</p><p>That said, it’s still hard to intuitively explain why the result appears in that specific way.</p><p>My guess is that it has something to do with the vertex order and the distribution of position values, but veryfying that directly would be quite tedious, I’ll leave it at that.</p><p>Another interesting point is that even though the offset was missing only for attribute[2], the overall shape still changed noticeably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sI3VW8z1aUki1Ut6VrorA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhVVlZ1E7CC6QUto4mEehw.png" /></figure><p>There are two possible explanations.</p><p>(a) Because the offset forr attribute[2] was not specified, the layout mapping of the vertex data was broken, causing the shpae to change.</p><p>(b) The vertices themselves are actually in the correct positions, but the incorrect texture mapping merely makes the shape appear distorted.</p><p>Since MDLVertexDescriptor defines the spacing of vertex data using the stride, I suspected that the latter explanation was more likely.</p><p>To verity this, I checked it directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B__Tbf5lRCj8l-NrFBnhFw.png" /></figure><p>I commented out the attribute offset in the renderer,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAblJojUSIY83II5IUySWA.png" /></figure><p>and modified the fragment shader to output a solid color instead of sampling the texture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54V4N9sbRe1ZsJvPVSeHPg.png" /></figure><p>The shape changed. My guess was wrong.</p><p>I had assumed that as long as the stride for the vertex buffer was set correctly, there wouldn’t be any data misalignment between vertices — but that wasn’t case. I couldn’t find a clear explanation for why omitting the attribute offset leads to artifacts like this.</p><p>In any case, it made me realize that when setting up a vertex descriptor, you need to pay attention to the offst as well. Especially because you won’t necessarily get an error even if the offset is missing, which can make the cause harder to track down.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4845e35d4470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a 3D mesh renders flat]]></title>
            <link>https://medium.com/@opunundo/when-a-3d-mesh-renders-flat-607da7106d66?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/607da7106d66</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 13:24:22 GMT</pubDate>
            <atom:updated>2026-01-28T13:24:22.317Z</atom:updated>
            <content:encoded><![CDATA[<p>I followed Warren Moore’s post <a href="https://medium.com/@warrenm/thirty-days-of-metal-day-15-hierarchy-30d80c0f8f91"><strong><em>Thirty Days of Metal — Day 15: Hierarchy</em></strong> </a>and implemented the code, producing the following result.</p><p>The problem is that the blue and gray shapes are rendered as circles rather than spheres.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*rrqJLIPm50gANW1u3AUCfQ.gif" /></figure><p>The cause was simple — the position attribute was declared as float2, which dropped the Z component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA8d8xEkvPScdGO2FzZyOA.png" /></figure><p>Although the problem was obvious in retrospect, it took me around four hours to identify the cause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlcTAiYy5shJvcM5B2zRzA.png" /></figure><p>Once the type was changed to float3, it renders correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*bZnuzep8rDUee1iaiYcMhw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607da7106d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a runtime error occurs while applying a stencil buffer]]></title>
            <link>https://medium.com/@opunundo/when-a-runtime-error-occurs-while-applying-a-stencil-buffer-b20d794580b5?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20d794580b5</guid>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 15:49:37 GMT</pubDate>
            <atom:updated>2026-01-27T15:49:37.404Z</atom:updated>
            <content:encoded><![CDATA[<p>This post describes a troubleshooting case by a non-expert who encountered a runtime error while following the code exercises from <a href="https://medium.com/@warrenm/thirty-days-of-metal-day-13-depth-14e84e51b9d2"><em>Thirty Days of Metal — Day 13: Depth</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ny4IKkxGwmvbFzpjDpZt-g.png" /></figure><p>According to GPT, “Thread 1: hit program assert” means that an assert was triggered in a debug build (a fatal condition violation), causing the process to terminate via abort().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hn0xmEOwfX6W3DN8K3No2g.png" /></figure><p>If you open the log panel at the bottom right, you can see the detailed message. It says that the pixel formats of the pipeline and the framebuffer do not match. Looking more closely, it seems that the pipeline’s pixel format was not set.</p><p>It turned out that this was indeed the case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAqmZjTOIAGChffMPmH_Rw.png" /></figure><p>So I specified the depth-stencil pixel format in the pipeline descriptor.</p><p>Now it renders correctly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ghBS7_3d4HHKWcDSQB2ZQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20d794580b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parts I got stuck on Thirty Days of Metal — Day 11: Meshes]]></title>
            <link>https://medium.com/@opunundo/parts-i-got-stuck-on-thirty-days-of-metal-day-11-meshes-c70b90ab4d12?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70b90ab4d12</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 15:06:08 GMT</pubDate>
            <atom:updated>2026-01-26T15:06:08.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parts I got stuck on Thirty Days of Metal — Day 11: Meshes</h3><p>This post records the points where a graphics beginner got stuck while working through <strong><em>Warren Moore’s</em></strong> <a href="https://medium.com/@warrenm/thirty-days-of-metal-day-11-meshes-c9efe2ed6350"><strong><em>Thirty Days of Metal — Day 11: Meshes</em></strong></a><strong><em>.</em></strong></p><p>While revisiting the basics of computer graphics recently, I came across the <strong><em>Thirty Days of Metal</em></strong> blog series. The early parts were easy to follow, but as the series progressed, the amount of code increased and some details were either omitted in the posts or I missed them. So I decided to document those parts here.</p><p>Although this reflects my own experience, I hope it will help those who are facing similar issues — or may encounter them in the future — so they can continue their graphics studies with enjoyment.</p><p>I would also like to express my gratitude to <strong><em>Warren Moore</em></strong> for creating such an excellent resource on the Metal API.</p><p><strong>1. When the pentagon does not appear even after following the code from the blog.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NP2Vtzz-fci7dsum-Izgw.png" /></figure><ul><li>In the <strong>draw</strong> function of <strong>Renderer.swift</strong>, check whether the constant buffer binding takes precedence over the vertex buffer binding. You need to be aware that the order in which buffers are set can affect the draw call.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRh-OzQjTn4KxI8Y31Huag.png" /><figcaption>Non-working code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYS0b326GdGdXT4w3-lV6w.png" /><figcaption>working code</figcaption></figure><ul><li>In <strong>Shaders.metal</strong>, check that the dynamic constant buffer parameter in the vertex_main function is correctly bound to <strong>[[buffer(2)]].</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TAcOCL8J7pfo4Y8znX2KA.png" /><figcaption>Non-working code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OtVIcvyCkpXsFNpN3TcrYw.png" /><figcaption>Working code</figcaption></figure><p><strong>2. When the shape appears, but part of it is clipped.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDN1kaIFIYN0H5SxIccubA.png" /></figure><ul><li>In <strong>Renderer.swift</strong>, do not apply the translationMatrix and scaleMatrix to the modelMatrix in the <strong>updateConstants</strong> fuction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Py7l5S-VnsIjCEOgyQ-hLg.png" /><figcaption>I suspect the shape is getting clipped because the translation and scailing are being applied.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9giBImHtyBBL7RPRGCQXw.png" /><figcaption>Working code</figcaption></figure><p>Then the pentagon renders correctly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lqKf9wWLxVPJDD1md54Mw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70b90ab4d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does a computer actually draw a line?]]></title>
            <link>https://medium.com/@opunundo/how-does-a-computer-actually-draw-a-line-01cc952ecccc?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/01cc952ecccc</guid>
            <category><![CDATA[rasterization]]></category>
            <category><![CDATA[cad]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[rhino-3d]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 09:30:44 GMT</pubDate>
            <atom:updated>2026-01-16T09:30:44.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lytakrGQXv-Zs8R_63L4GA.png" /></figure><p>When using programs like Rhino3D or CAD, you may have wondered how they actually display lines on a monitor. This is because such programs are commonly described as vector-based, and may people understand vector-based programs as displaying lines defined <strong>mathematically</strong>.</p><p>However, the monitor we look at is made up of individual pixels. So how do vector-based programs turn mathematically defined lines into pixels on the screen?</p><p>To start with the conclusion, the answer is that they go through a process called <strong>rasterization</strong>. If you have ever tried to open an illustrator or CAD file in Photoshop for edidting, you may have seen a message saying, <em>“This smart object must be rasterized before it can be edited”</em>.</p><p>Rasterization is a process of converting data that is stored according to rules — such as mathematical formulas — into individual pixels that correspond to those formulas.</p><p>This may not feel very intuitive yet. If it already makes sense to you, feel free to skip this part.</p><p>Here is a single straight line drawn in Rhino 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc3RzIOI0K2mg7jy9jfSKg.png" /></figure><p>Try moving your eyes closer to the monitor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ChcVQhrtivKo4g7rH5HFw.jpeg" /></figure><p>Do you see the jagged shapes?</p><p>Let’s take an even closer to look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVnF4A3xGKNgRpI5NsYd-g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY3XwWGeHdZqY4Xqi4ciuQ.jpeg" /></figure><p>In the end, you can see that what’s actually there is a grid pattern with black dots unevenly plotted on it.</p><p>So, aren’t you curious how a line segment defined by a mathematical formula is converted into individual pixels?</p><p>There are several ways to rasterize a line segment, but in this post, I’ll introduce one of the simplest methods: the Digital Differential Analyzer (DDA) algorithm.</p><p>Despite its grand name, it isn’t very difficult if you know how to find the equation of a straight line. The overal steps are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHw8MwZNhZg9T3qzP4YKHw.png" /></figure><p>Below is the code that implements this logic.</p><pre>unction DDA(xStart, yStart, xEnd, yEnd) {<br> let dx = xEnd - xStart<br> let dy = yEnd - yStart<br> let steps, k;<br> let xIncrement, yIncrement;<br> let x = xStart;<br> let y = yStart;<br><br> if (Math.abs(dx) &gt; Math.abs(dy)) steps = Math.abs(dx);<br> else steps = Math.abs(dy);<br><br> xIncrement = dx / steps;<br> yIncrement = dy / steps;<br><br> for(k = 0; k &lt; steps; k++) {<br>  x += xIncrement;<br>  y += yIncrement;<br>  grid[Math.round(y)][Math.round(x)] = 1;<br> }<br>}</pre><p>I alse included an example in p5.js, which I hope will help you understand it more easily. You can play it.</p><p><a href="https://openprocessing.org/sketch/2848562">https://openprocessing.org/sketch/2848562</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwYhOBB67NGTwqk2jvzfVw.png" /></figure><p>If you want more rigorous and detailed explanation, you can refer to the following link: the DDA algorithm as described on Wikpedia.</p><p><a href="https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)">https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01cc952ecccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HIPPO는 Vision Pro에서 3D내시경 영상을 어떻게 출력하나요?]]></title>
            <link>https://medium.com/hungry-hippo/hippo%EB%8A%94-vision-pro%EC%97%90%EC%84%9C-3d%EB%82%B4%EC%8B%9C%EA%B2%BD-%EC%98%81%EC%83%81%EC%9D%84-%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%B6%9C%EB%A0%A5%ED%95%98%EB%82%98%EC%9A%94-48ab0140e749?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ab0140e749</guid>
            <category><![CDATA[avfoundation]]></category>
            <category><![CDATA[stereoscopic]]></category>
            <category><![CDATA[apple-vision-pro]]></category>
            <category><![CDATA[video-processing]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 15:04:57 GMT</pubDate>
            <atom:updated>2025-12-03T07:23:59.820Z</atom:updated>
            <content:encoded><![CDATA[<p>*<strong><em>이해를 위해 구조를 단순화한 설명입니다. 여기서는 핵심 흐름만 다루었기 때문에. 실제구현 시 추가 고려 사항이 존재합니다.</em></strong></p><p>기본적으로 <strong>visionOS의 3D 영상</strong>은 MPEG4 및 QuickTime에서 지원하는 <strong>Multiview - High Efficiency Video Encoding(MV-HEVC)</strong> 형식을 사용합니다. HIPPO 또한 이 방식을 이용합니다. 다음의 파이프라인은 다양한 포맷으로 출력될 수 있는 내시경 영상을 비전프로에서 MV-HEVC로 변환할 수 있도록 하기 위해 구성되었습니다.</p><p>HIPPO의 내시경 영상 송출 파이프라인의 물리적 연결은 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7JB9b1n0PrZCkDLwfUb_Q.png" /></figure><p>영상 데이터 처리과정의 큰 흐름은 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVyf0j3JH6w6VnfBIJo6_Q.png" /></figure><h4>1. 내시경 영상 캡쳐</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJZo4oAbYouT57CQWGnFrQ.png" /><figcaption>3D 내시경 기기는 단안 영상처리기 2개와 양안 영상처리기 1개, 그리고 광원장치로 이루어져 있습니다.</figcaption></figure><p>HIPPO의 스트리밍 파이프라인은 3D 영상처리기로부터 Side-by-Side(SBS) 형태의 스테레오 영상을 인풋으로 받는 것으 가정하고 설계되었습니다. 따라서 3D영상처리기가 SBS출력을 지원하는 경우, 그대로 받아 사용할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Br0qk06nB-hdMkCbVvzWQ.png" /><figcaption>side-by-side 영상의 좌우 프레임은 겉보기엔 같은 장면을 두 번 배치한 것처럼 보입니다. 하지만, 자세히 보면 두 영상이 미묘하게 다릅니다.</figcaption></figure><p>하지만 3D 내시경 영상처리기 중에는 SBS대신 frame-sequential 방식의 출력만 지원하는 경우가 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*1tK-qiMP_p9sm9tuRkbWbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*MzwqaB-D3Ej2DxqzWoL55g.png" /><figcaption>frame-sequential 방식은 side-by-side방식과 다르게 한 번에 하나의 프레임만 보여줍니다. 두 프레임이 빠르게 번갈아 나타나기 때문에 실제로는 두 장면이 겹쳐서 보입니다.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIF1hZciPYn4hVZ6yNPTpg.png" /></figure><p>이런 경우에는 3D 영상처리기와 연결된 단안 영상처리기로부터 각각의 단안 영상들을 받아 SBS로 합성하는 방식으로 처리합니다.</p><h4>2. SBS 합성(옵션)</h4><p>SBS 합성 시, 가장 중요한 부분은 서로 다른 인풋으로 들어온 영상 프레임의 시간 간격을 맞추는 것입니다. 왜냐하면 두 인풋의 프레임이 항상 같은 시점의 것이라고 단정할 수 없기 때문입니다. 그래서 HIPPO는 절대 PTS를 기준으로 두 프레임 간격이 일정 시간 오차 이내라면 같은 시점의 프레임으로 간주하고 짝을 지은 후 하나의 SBS프레임으로 합성합니다. 이 때 합성된 프레임의 시점은 좌우 프레임 타임스탬프의 평균값을 따라갑니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilnnpc9dyyPOuWOanpFlpg.png" /></figure><p>한 쌍의 프레임을 구했다면 두 프레임 픽셀버퍼의 크기(해상도)를 계산한 후, 새로운 픽셀버퍼로 복사 배치합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csP3mjq5QzTKgjSgEiGjmw.png" /></figure><h4>3. HEVC 인코딩</h4><p>앞서 캡쳐한 영상은 무손실 영상입니다. 그렇다는 것은 영상의 데이터가 크다는 뜻이며, 이는 비전프로로 영상을 전송하기에는 부담스러울 수 있다는 뜻입니다. 그래서 영상 데이터를 압축해야 합니다. HEVC는 압축 효율이 높은 코덱입니다. 영상을 전송하기에 적합한 포맷이므로 인코딩을 진행합니다.</p><p>인코딩은 Apple에서 제공하는 프레임워크인 <strong><em>VideoToolBox</em></strong>의 <strong><em>VTCompressionSession</em></strong>을 이용합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGfSm9mIve077p24HamOqg.png" /></figure><p>실제 인코딩은 <strong><em>VTCompressionSessionEncodeFrame</em></strong>이라는 매서드를 이용합니다. 이 때, 다음과 같은 정보들을 요구합니다.</p><ul><li>인코더 설정(<strong><em>VTCompressionSessionCreate</em></strong>로 만든 인코더 인스턴스)</li><li>인코딩할 입력 영상의 프레임</li><li>프레임의 타임스탬프</li><li>프레임의 지속시간</li><li>해당 프레임에만 적용되는 추가 설정</li><li>…</li></ul><p>그리고 인코더 설정을 생성하기 위해서 <strong><em>VTCompressionSessionCreate</em></strong>라는 메서드를 이용합니다. 여기서는<strong> “어떤 코덱으로 어떤 크기의 프레임을 넣을 것이며, 결과는 어디서 받을지”</strong>에 관한 부분들이 설정 되어야 합니다. 구체적으로는 다음과 같은 정보들이 필요합니다.</p><ul><li>압축 프로세스를 할당할 메모리</li><li>압축할 영상의 해상도</li><li>어떤 코덱으로 압축할 것인지</li><li>압축 시 추가 설정 사항(옵션)</li><li>압축에 투입할 영상의 특성(ex. 색영역, 해상도 등)</li><li>압축한 영상 프레임 데이터를 저장할 메모리</li><li>압축 결과가 나올 때마다 호출되는 콜백 함수 포인터</li></ul><p>인코딩된 프레임은 <strong><em>CMSamplebuffer</em></strong>의 형태로 <strong><em>VTCompressionOutputCallback</em></strong>을 통해 접근 가능합니다.</p><h4>4. 패킷화</h4><p>영상데이터를 전송하기 위해서는 영상의 각 프레임을 바이트로 변환하여야 합니다. 인코딩된 프레임은 <strong><em>CMSampleBuffer</em></strong>의 형태로 존재합니다. 이 <strong><em>CMSampleBuffer</em></strong>를 그대로 비전프로로 전송할 수 있다면 좋겠지만, 안타깝게도 <strong><em>CMSampleBuffer</em></strong>를 타입 그대로 전송할 수 없습니다.</p><p>전송을 위해서는 패킷화 과정이 필요합니다.</p><ul><li>HEVC 프레임을 NAL 단위로 분리</li><li>패킷 구성(RTP)</li></ul><p>NAL은 HEVC 프레임을 구성하는 기본 단위입니다. 각 프레임의 정보를 담고 있는 NAL Unit을 I-frame NAL, P/B frame NAL이라고 합니다. 하지만 이것만으로는 해당 NAL이 HEVC인지 알 수 없습니다. 왜냐하면, 다른 영상 코덱, 이를테면 H.264도 NAL Unit을 사용하기 때문입니다. 그래서 헤더코드를 통해 이를 구분합니다. 헤더 코드에서 32, 33, 34라는 값을 사용하는 NAL을 각각 VPS, SPS, PPS라고 하며, HEVC임을 구분하기 위한 중요한 단서가 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ig7GSN5Lg0ymCS4AlRjtkA.png" /></figure><p>*<strong>부가설명</strong></p><p>혹시, NAL 타입 값은 32, 33, 34인데 예시를 보면 헤더코드가 왜 40 01, 42 01, 44 01로 표시되어 있는지 궁금하지 않으신가요? <em>(궁금하지 않으시다면 이 부분은 넘어가 주세요.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*theR6Y7n2objVflCZw14qQ.png" /></figure><p>그 이유는 NAL의 헤더 코드는 NAL 타입에 관한 정보 뿐만 아니라 layer_id(계층 id), temporal_id(시간)에 관한 정보까지 함께 담아서 표현하기 때문입니다. 그래서 헤더코드만 분리해서 2진수로 변환하면</p><p><strong>01000000000000001</strong></p><p>이 되며, 이를 정보 단위로 분해하면</p><p><strong>0 100000 000000 001</strong></p><p>이 됩니다. 이 때 두 번째 덩어리 값이 NAL 타입에 관한 정보가 됩니다.</p><p>이진수 <strong>100000</strong> 이니 십진수로 변환하면 32가 됩니다. 즉, 앞서 언급한 VPS에 해당하는 NAL임을 알 수 있게 되는 것입니다. 하지만 표현은 바이트 단위로 끊기 때문에</p><p><strong>01000000 00000001</strong></p><p>이 되며, 16진수로 변환하면 <strong>40 01</strong>이 됩니다.</p><p>이렇게 HEVC 프레임을 NAL 단위로 분리했다면 이제는 여기에 실시간 송수신을 위한 데이터를 덧붙여야 합니다. 이 작업에 RTP 프로토콜이 사용됩니다. HIPPO에서는 RTP 패킷을 WebRTC 스택이 내부적으로 처리합니다.</p><p>여담으로, RTP 패킷은 12바이트로 구성되며, <strong>패킷 순서 복원 정보, 어떤 송신자로부터 온 스트림인지 구분하기 위한 정보, 타임스탬프, 미디어 타입, 프레임 경계</strong> 등의 정보가 담깁니다. 이 때 기존의 시작 코드(00 00 00 01)는 제거합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ab8aQ0Da13i2cLze63W04Q.png" /></figure><p>이제 영상 데이터 전송을 위한 준비과정을 모두 마쳤습니다.</p><h4>5. 송수신 연결 및 전송</h4><p>LiveKitWebRTC 스택 내부에서 시그널링 및 전송이 진행됩니다.</p><h4>6. 패킷복원</h4><p>LiveKitWebRTC 스택 내부에서 데이터를 수신합니다.</p><p>수신한 패킷을 CMSampleBuffer로 재조립하는 과정을 거칩니다.</p><h4>7. HEVC 디코딩</h4><p>인코딩을 <strong><em>VTCompressionSession</em></strong>을 이용하였듯, 디코딩은 <strong><em>VTDecompressionSessionDecodeFrame</em></strong>을 이용하여 진행됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKHSdcCZYd0uFqRTB6EX5g.png" /></figure><p>요구하는 정보는 다음과 같습니다.</p><ul><li>디코더 설정(어떤 해상도, 어떤 코덱, 어떤 설정인지)</li><li>디코딩할 CMSampleBuffer(여기에 프레임의 비트스트림과 타임스탬프, 그리고 포맷정보가 포함되어 있습니다.)</li><li>디코딩 옵션 플래그(어떻게 디코딩 할지 ex. 프레임 드랍 정책, 출력 프레임 생성 여부)</li><li>디코딩 콜백 컨텍스트 포인터:</li><li>디코드 결과 상태(디코드를 어떻게 처리했는지)</li></ul><p><strong><em>VTCompressionSession</em></strong>과 마찬가지로 디코더 설정이 필요합니다. <strong><em>VTDecompressionSessionCreate</em></strong>라는 메서드를 사용합니다. 이 역시 <strong>“어떤 스트림인지, 어떤 포맷으로 내보낼지, 디코딩된 프레임을 어디로 내보낼지”</strong>에 관한 부분의 설정이 필요합니다. 다음과 같은 세부 정보들을 요구합니다.</p><ul><li>디코딩 세션 메모리 할당 방식</li><li>포맷 정보(어떤 코덱/해상도/파라미터인지)</li><li>디코더 추가 요구사항</li><li>디코딩 결과 출력 프레임의 조건(색상 포맷, 해상도 등)</li><li>디코딩 완료 시 호출할 콜백 함수 포인터</li></ul><p>디코딩을 마치면 SBS프레임이 <strong><em>VTDecompressionOutputCallbackRecord</em></strong>에서 <strong><em>CVPixelBuffer</em></strong>로 제공됩니다.</p><h3>9. MV-HEVC 변환</h3><p>MV-HEVC 변환을 설명하기 이전에 MV-HEVC가 무엇인지 잠깐 설명하도록 하겠습니다. MV-HEVC는 HEVC를 기반으로 여러 시점을 동시에 압축·복원할 수 있게 만든 다중뷰 영상 코덱입니다. 비전프로에서는 이 포맷을 스테레오 비디오로 렌더링 합니다. 직접 비전프로의 좌안과 우안에 각각 영상을 렌더링 하지 않고도 재생할 수 있도록 Apple에서 제공합니다.</p><p>MV-HEVC는 스테레오 영상 뿐만 아니라 여러 시점의 영상을 담을 수 있도록 설계된 코덱입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qH8XjKLItn3GAZmmqHhSQw.png" /><figcaption>MV-HEVC는 양안 뿐 만 아니라, 다양한 시점의 영상을 담을 수 있습니다. 현재 HIPPO에서는 LeftAndRightViewIDs는 사용하고 있지 않습니다.</figcaption></figure><p>변환 과정의 큰 흐름은 다음 이미지와 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFVDz6i-h0ku8w-pMppG6w.png" /></figure><p>‘프레임 분할’ 부터 ‘출력버퍼에 전달’까지의 과정이 MV-HEVC의 핵심 과정이 됩니다. 이는 <strong><em>VideoToolBox</em></strong>의 메서드인 <strong><em>VTPixelTransferSessionTransferImage</em></strong>에 의해 이루어집니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rR1Hlarx8EXJlZq2ARGN5w.png" /></figure><ul><li><strong><em>VTPixelTransferSesion</em></strong> 객체(어떤 방식으로 픽셀을 변환, 복사할지)</li><li>원본 픽셀 버퍼: <strong><em>CVImageBuffer</em></strong></li><li>변환된 픽셀이 기록될 버퍼: <strong><em>CVPixelBuffer</em></strong></li></ul><p>마찬가지로 세션 구성을 진행합니다. <strong><em>VTPixelTransferSessionCreate</em></strong>에서는 다음 값들을 요구합니다.</p><ul><li>세션 메모리 할당 방식</li><li>생성된 <strong><em>VTPixelTransferSession</em></strong> 객체를 반환받는 포인터</li></ul><p>보시다시피, 픽셀 변환 세션 생성 시에는 특별한 설정이 없습니다. 대신 <strong><em>VTSessionSetProperty</em></strong>를 통해 상세 설정을 합니다.</p><ul><li><strong><em>VTPixelTransferSession</em></strong> 객체</li><li>어떤 방식으로 입력 픽셀을 변형할지</li><li>해당 <strong><em>VTSessionSetProperty</em></strong>의 구체적인 설정값 → 입력 소스를 <strong><em>cleanApeture</em></strong> 기준으로 크롭</li></ul><p>이 때, <strong><em>clenaApeture</em></strong> 관련 설정은 주로 다음 4가지에 해당합니다.</p><ul><li><strong><em>kCVImageBufferCleanApertureWidthKey</em></strong>: 폭(가로사이즈)</li><li><strong><em>kCVImageBufferCleanApertureHeightKey</em></strong>: 높이(세로사이즈)</li><li><strong><em>kCVImageBufferCleanApertureHorizontalOffsetKey</em></strong>: 수평오프셋(가로 시작지점)</li><li><strong><em>kCVImageBufferCleanApertureVerticalOffsetKey</em></strong>: 수직오프셋(세로 시작지점)</li></ul><p>예를 들어, 만약 3840*1080의 SBS영상을 두 개의 1920*1080영상으로 분할하고 싶다면 각 값은 다음과 같아집니다.</p><p>좌안</p><ul><li>가로사이즈: (원본영상 가로 사이즈)/2</li><li>세로사이즈: (원본영상 세로 사이즈)</li><li>수평오프셋: 0</li><li>수직오프셋: 0</li></ul><p>우안</p><ul><li>가로사이즈: (원본영상 가로 사이즈)/2</li><li>세로사이즈: (원본영상 세로 사이즈)</li><li>수평오프셋: (원본영상 가로 사이즈)/2</li><li>수직오프셋: 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMtU0DoFITYMSmJ9KtQUaQ.png" /></figure><p>이후, <strong><em>CVBufferSetAttachment</em></strong> 메서드를 이용하여 이 설정을 번갈아가면서 원본 픽셀버퍼에 부착해 줍니다. 그러면 <strong><em>VTPixelTransferSessionTransferImage</em></strong>에서 원본 픽셀버퍼를 인자로 받아서 설정값 범위만큼 프레임을 분할합니다.</p><p>마지막으로 분할된 <strong><em>CVPixelBuffer</em></strong> 프레임에 앞서 언급했던 <strong>layerId</strong>와 <strong>viewId</strong>, 그리고 <strong>미디어타입</strong>을 태깅한 후 하나의 <strong><em>CMSampleBuffer</em></strong>로 재조립을 진행합니다.</p><h3>10. 3D 영상 재생</h3><p>마지막입니다. 이렇게 분할된 프레임 정보를 담고 있는 <strong><em>CMSampleBuffer</em></strong>는 <strong><em>AVSampleBufferVideoRenderer</em></strong>의 <strong><em>enqueue</em></strong> 메서드를 이용하여 출력 준비를 마칩니다. 이 렌더러는 <strong><em>RealityView</em></strong> 내 엔티티의 <strong><em>VideoPlayerComponent</em></strong>에 연결되어 있습니다. 태깅 값에 따라 프레임이 각 눈으로 자동으로 분기되어 렌더링되고, 최종적으로 3D 영상이 출력됩니다.</p><p>더 정확하고 자세한 내용을 원하신다면 다음 애플 공식문서들을 참고해 주세요.</p><p><strong>멀티뷰 HEVC 변환 관련</strong></p><ul><li><a href="https://developer.apple.com/documentation/realitykit/rendering-stereoscopic-video-with-realitykit">https://developer.apple.com/documentation/realitykit/rendering-stereoscopic-video-with-realitykit</a></li></ul><p><strong>카메라 영상 연결 관련</strong></p><ul><li><a href="https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices">https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ab0140e749" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hungry-hippo/hippo%EB%8A%94-vision-pro%EC%97%90%EC%84%9C-3d%EB%82%B4%EC%8B%9C%EA%B2%BD-%EC%98%81%EC%83%81%EC%9D%84-%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%B6%9C%EB%A0%A5%ED%95%98%EB%82%98%EC%9A%94-48ab0140e749">HIPPO는 Vision Pro에서 3D내시경 영상을 어떻게 출력하나요?</a> was originally published in <a href="https://medium.com/hungry-hippo">HIPPO TechBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Displaying video from connected devices]]></title>
            <link>https://medium.com/hungry-hippo/displaying-video-from-connected-devices-d1b8d4700769?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b8d4700769</guid>
            <category><![CDATA[visionos-app-development]]></category>
            <category><![CDATA[visionos]]></category>
            <category><![CDATA[apple-vision-pro]]></category>
            <category><![CDATA[avfoundation]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 16:24:41 GMT</pubDate>
            <atom:updated>2025-11-05T16:26:44.115Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>The English version is provided below. <br></strong><a href="#5942"><strong>On a website, you could click this link to jump to that section automaticall</strong></a><strong>y.</strong></blockquote><p>이번에는 연결된 장치로부터 받아 온 영상을 화면에 띄우는 방법에 대해 학습한 내용을 공유 드릴려고 합니다. 이 포스팅은 애플 공식문서 “Displaying video from connected devices”를 기반으로 작성되었음을 알려 드립니다. 기본적인 내용은 해당 문서를 확인하시고, 이 포스팅은 보충자료로서 참고해주시길 바랍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93kOJeTioomGR-6cXXqiEw.png" /><figcaption>소스 링크: <a href="https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices">https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices</a></figcaption></figure><p>이 샘플코드는 UVC를 지원하는 카메라나 녹음장치로 받아들인 영상이나 음향 데이터를 연결된 맥북이나 아이폰 등으로 송출할 수 있게 만들어 주는 예제입니다. 사실, <strong>AVCaptureDevice.DiscoverySession</strong>과 <strong>AVCaptureSession</strong> 사용법에 대한 이해가 전부입니다.</p><p>샘플코드의 전반적인 구조는 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CL2c5wi13_5384dfZDgizQ.png" /></figure><h4><strong>Request the entitlement</strong></h4><p>공식 문서에서는 entitlemenet를 요구한다고 적혀 있지만, 현재 (2025. 11. 6.) 기준으로 entitlement요구가 사라진 것으로 알고 있습니다.</p><h4><strong>Add usage descriptions for camera access</strong></h4><p>애플의 개인정보보호정책으로 카메라 사용 시, 카메라 권한 요청 문구를 추가해야 합니다. 샘플코드에는 Info.plist에 이미 추가되어 있으니 그냥 확인하시면 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnBEroY_hYxs6GlEZ2bGEQ.png" /></figure><h4><strong>Create the device picker</strong></h4><p><strong>AVCaptureDevice.DiscoverySession</strong>이라는 메서드를 이용하여 현재 애플 기기(맥, 아이폰, 비전프로 등)와 연결된 카메라 장치를 조회할 수 있습니다.</p><p>여기서 AVCapture.DeviceDiscoverySession은 세 가지의 매개변수를 요구합니다.</p><ul><li>deviceTypes</li><li>mediaType</li><li>position</li></ul><p>deviceType은 AVCaptureDevice.DeviceType을 요구합니다. 그렇다면 AVCaptureDevice.DeviceType에는 어떤 것들이 있는지 의문이 생길 수 있습니다. 공식문서를 살펴보면 AVCaptureDevice.DeviceType에 다음과 같은 종류의 것들이 있음을 알 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHbE7DC4HCyeMT9pKgm3YQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9jbMYeHcv_mmSorHClW9Q.png" /></figure><p>잘 보시면 연결된 외부 기기 뿐만 아니라, 아이폰이나 맥북에 내장된 카메라, 마이크, 심지어 라이다센서까지도 연결할 수 있음을 알 수 있습니다. 지금은 연결된 장치로부터 영상을 받아오는 것이 목적이기에 deviceType은 [.external]을 넘겨 주도록 합니다.</p><p>다음은 mediaType입니다. mediaType은 AVMediaType을 요구합니다. 이 값에 해당하는 종류의 장치만 검색합니다. 예를 들어,</p><p>`mediaType: video`</p><p>라고 한다면, 영상 장치만 검색하는 방식입니다. 만약 아무런 값도 지정하지 않는다면 종류에 관계 없이 모든 장치를 가져오는 방식입니다.</p><p>마찬가지로 AVMediaType에도 audio, video 뿐 만 아니라 여러 종류가 존재합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfIdDUPpCMEnVN5o01hOBw.png" /></figure><p>마지막으로, position입니다. 장치(여기서는 아이폰이나 맥북)의 전면 후면 위치를 의미합니다. 만약 이 값을 .front라고 한다면 아이폰이나 맥북의 전면 카메라만 검색합니ㅏ. 그래서 보통 내장된 카메라나 마이크를 연결할 때 의미를 가집니다. 외장 카메라나 마이크는 위치 값이 존재하지 않으므로 .unspecified를 넘겨줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hLTwS0mc01skDizcuEkhg.png" /></figure><p>AVCaptureDevice.DiscoverySession에 필요한 모든 변수를 넘겨주면 AVCaptureDevice.DiscoverySession은 조건에 맞는 장치를 검색한 후, 해당 장치들을 <strong>AVCaptureDevice</strong>라는 타입으로 받아옵니다.</p><p>이후, 장치 연결상태를 모니터링하는 함수를 두어 외장 카메라가 연결되거나 분리되었을 때를 감지하여 애플기기와 연결된 장치 목록에 반영합니다.</p><p>그리고 연결된 장치 목록을 화면에 보여주는 피커를 ContentView에 하나 추가해주면 연결된 장치의 목록을 확인할 수 있습니다.</p><h4><strong>Display the selected device’s video feed</strong></h4><p>피커에서 연결된 장치 중 하나를 선택하면 해당 장치가 촬영하고 있는 장면을 표시해 주어야 합니다. 이를 위해 AVCaptureSession이 필요합니다. AVCaptureSession은 카메라/마이크 등 AVCaptureDevice에서 입력을 받고, 이를 미리보기, 파일 저장, 데이터 처리 출력 객체와 연결해주는 역할을 합니다.</p><p>다시 말해, 다음과 같은 과정이 필요하다는 뜻입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XFFp-xgY-G3VFNpaUbgig.png" /></figure><p>AVCaptureSession을 구성하는 방법을 비유적으로 표현한다면 다음과 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHzeEU9EewxwJJDZrm8MvQ.png" /></figure><p>이렇게 AVCaptureSession이 작동하면 우리는 captureOutput 내에서 sampleBuffer를 videoRenderer에 넘겨 줌으로써 연결된 장치의 영상을 받아올 수 있습니다.</p><p>영상을 받아왔다고 곧바로 재생할 수 있는 것은 아닙니다. CMSampleBuffer가 enqueu된 AVSampleBufferDisplayLayer는 마치 진열되기 전의 상품과 같습니다. 그래서 진열대에 올려야 하죠. 그 진열대가 바로 Devicepreview입니다. AVSampleBufferDisplayLayer는 CALayer의 일종입니다. 그래서 SwiftUI에서 바로 렌더링 할 수는 없습니다. 그래서 CALayer를 재생할 수 있도록 연결해주는 녀석이 필요합니다. 그것이 바로. DevicePreview라는 이름을 가진 UIViewRepresentable 객체입니다.</p><p>이제 다 되었습니다!</p><h3>English version</h3><p>This time, I’d like to share what I learned about how to display video received from a connected device. Please note that this is based on Apple’s official documentation, <strong><em>“Displaying video from connected devices.”</em></strong></p><p>I recommend reviewing the original document for the fundamentals, and using this post as supplementary reference material</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93kOJeTioomGR-6cXXqiEw.png" /><figcaption>Source Link: <a href="https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices">https://developer.apple.com/documentation/visionOS/displaying-video-from-connected-devices</a></figcaption></figure><p>This sample code demonstrates how to stream video or audio data received from a UVC-compatible camera or recording device to a connected MacBook or iPhone.</p><p>In fact, the key to understanding this example lies in how <strong><em>AVCaptureDevice.DiscoverySession</em></strong> and <strong><em>AVCaptureSession</em></strong> are used.</p><p>The overall structure of the sample code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyZG-3LIvPICIVXnKdHjeQ.png" /><figcaption>The overall structure of the sample code</figcaption></figure><h4>Request the entitlement</h4><p>The official documentation states that an entitlement is required. However, as of November 6, 2025, it appears that this requirement has been removed.</p><h4>Add usage descriptions for camera access</h4><p>Due to Apple’s privacy policy, you must include a camera usage description when accessing the camera. In the sample code, this string is already include in <strong><em>Info.plsit</em></strong>, so simply verify it is there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ8eUG2cplZsGqpgcCAqkw.png" /></figure><h4>Create the device picker</h4><p>You can use <strong><em>AVCaptureDevice.DiscoverySession</em></strong> to query camera devices currently connected to an Apple device(Mac, iPhone, Vision Pro, etc.). <strong><em>AVCaptureDevice.DiscoverySession</em></strong> takes three parameters.</p><ul><li>deviceTypes</li><li>mediaType</li><li>position</li></ul><p>The <strong><em>deviceTypes </em></strong>parameter expects values of type <strong><em>AVCaptureDevice.DeviceType</em></strong>. As this point, you may wonder what kinds of device types are available.</p><p>According to the official documentation, AVCaptureDevice.DeviceType includes the following options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHbE7DC4HCyeMT9pKgm3YQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9jbMYeHcv_mmSorHClW9Q.png" /></figure><p>If you look closely, you’ll notice that you can not only access externally connected devices, but also built-in components such as the iPhone or MacBook’s internal cameras, mircophones, and even Lidar sensors.</p><p>Since our goal here is to receivce video from a connected external device, we will pass <strong><em>.external</em></strong> as the deviceType.</p><p>Next is the media Type parameter. <strong><em>mediaType</em></strong> expects a value of type <strong><em>AVMedaType</em></strong>. Only devices that match the specified media type will be included. For example,</p><pre>mediaType: .video</pre><p>will limit the search to video-capable devices. If you do not specify a value, all device types will be returned regardless of category.</p><p>Similarly, <strong><em>AVMediaType</em></strong> includes not only <strong><em>.audio </em></strong>and <strong><em>.video</em></strong>, but several other types as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfIdDUPpCMEnVN5o01hOBw.png" /></figure><p>Lastly, there is the <strong><em>position</em></strong> parameter. This indicates the physical location of the device(in this case, the iPhone or MacBook), such as front-facing or back-facing. For example, if you pass <strong><em>.front</em></strong>, only the front-facing camera on the iPhone or MacBook will be returned. Therefore, this parameter is typically relevant when working with built-in cameras or microphones.</p><p>External cameras or microphones do not have a position value, so you should pass <strong><em>.unspecified </em></strong>for those cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hLTwS0mc01skDizcuEkhg.png" /></figure><p>Once all required parameters are passed to <strong><em>AVCaptureDevice.DiscoverySession</em></strong>, it searches for devices that match the given conditions and returns them as instances of <strong><em>AVCaptureDevice</em></strong>.</p><p>Next, we set up a function to monitor device connection status so that when an external camera is connected or disconnected, the list of devices linked to the Apple device is updated accordingly.</p><p>Then, by adding a <strong><em>Picker</em></strong> in the<strong><em> ContentView </em></strong>to display the list of connected devices, we can allow the user to view and select from available devices.</p><h4>Deisplay the selected device’s video feed</h4><p>When a device is selected from the <strong><em>Picker</em></strong>, we need to display the video feed coming from that device. To do this, we use <strong><em>AVCaptureSession</em></strong>.</p><p><strong><em>AVCaptureSession</em></strong> receives input from an <strong><em>AVCaptureDevice</em></strong> — such as a camera or microphone — and connects it to components responsible for previewing, file output, or data processing.</p><p>In other words, the following steps required:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XFFp-xgY-G3VFNpaUbgig.png" /></figure><p>If we were to describe how to configure an <strong><em>AVCaptureSession</em></strong> metaphorically, it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0X6gelpC-IC-MJltrhvfbQ.png" /></figure><p>Once the <strong><em>AVCaptureSession</em></strong> is running, we can receive video from the connected device by passing the <strong><em>sampleBuffer</em></strong> to the <strong><em>videoRenderer</em></strong> inside <strong><em>captureOutput</em></strong>.</p><p>However, receiving the video does not mean it can be immediately displayed. An <strong><em>AVSampleBufferDisplayLayer</em></strong> that has been enqueued with <strong><em>CMSampleBuffer</em></strong> is like a product that has not yet been placed on the shelf — it needs to be displayed somewhere. That “shelf” is the <strong><em>DevicePreview</em></strong>.</p><p><strong><em>AVSampleBufferDisplayLayer</em></strong> is a type of <strong><em>CALayer</em></strong>, which means it cannot be rendered directly in SwiftuUI. Therefore, we need a component that can host and display this layer in SwiftUI. That is the role of<strong><em> DevicePreview</em></strong>, a <strong><em>UIViewRepresentable</em></strong> object.</p><p>Now everything is ready!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b8d4700769" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hungry-hippo/displaying-video-from-connected-devices-d1b8d4700769">Displaying video from connected devices</a> was originally published in <a href="https://medium.com/hungry-hippo">HIPPO TechBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting side-by-side 3D video to multiview HEVC and spatial video]]></title>
            <link>https://medium.com/@opunundo/converting-side-by-side-3d-video-to-multiview-hevc-and-spatial-video-47013fe38aa7?source=rss-fce6601be83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/47013fe38aa7</guid>
            <category><![CDATA[hevc]]></category>
            <category><![CDATA[visionos-app-development]]></category>
            <category><![CDATA[stereoscopic]]></category>
            <category><![CDATA[3d-video]]></category>
            <dc:creator><![CDATA[Opunundo]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 12:53:16 GMT</pubDate>
            <atom:updated>2025-10-11T12:54:09.124Z</atom:updated>
            <content:encoded><![CDATA[<p>Long time no see. Recently, I’ve been developing a VisionOs app that displays stereo video. I’d like to share what I’ve learned from Apple’s document <strong><em>“Converteing Side-by-Side 3D video to Multiview HEVC and Spatial Video.”</em></strong></p><p>This post is meant as a complementary explanation, so I recommend reading Apple’s document first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9LA52dpImtxJ-i_yDgFVg.png" /><figcaption><em>Source Link: </em><a href="https://developer.apple.com/documentation/avfoundation/converting-side-by-side-3d-video-to-multiview-hevc-and-spatial-video#Load-the-side-by-side-video"><em>https://developer.apple.com/documentation/avfoundation/converting-side-by-side-3d-video-to-multiview-hevc-and-spatial-video#Load-the-side-by-side-video</em></a></figcaption></figure><p>This sample code is an example that converts an SBS-format video into MV-HEVC, a format that can be played as a stereoscopic video on VisionPro.</p><p>The overall conversion process is outlined below. However, this represents only the conceptual flow — the actual code flow may differ somewhat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnE716g-ln1-ZNyAKnQMnw.png" /></figure><p>The converted video generated by running this sample code is saved in the same directory as the input file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2vKd9FbvH5QsVXIJbQRcw.png" /></figure><p>For example,</p><pre>/Users/username/Desktop/ConvertingSideBySide3DVideoToMultiviewHEVCAndSpatialVideo/Hummingbird.mov</pre><h4>Configure the sample code project</h4><p>To run the app, you need to edit the app’s scheme.</p><p>In Xcode, go to Product → Scheme → Edit Scheme at the top menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0OS2s-QCr2fiFSUHO-_3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPS1k6WiI3FSKpr5clsYeQ.png" /></figure><p>Then, in the Augments tab, add the path of the file you want to convert to Arguments Passed On Launch. In the sample code, the path is set to an example file located wihtin the project folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*521YC8mx20NJIa6Lfwxg3Q.png" /></figure><p>A command line below is a command that adds metadata to the converted video. If you didn’t check this option, the video will be converted into a regular stereo video instead of a spatial video. Both the upper and lower options can be checked simultanesouly.</p><pre>--spatial --baseline 64.0 --fov 80.0 --disparityAdjustment 0.02</pre><p>What each command means:</p><ul><li>spatial: Adds spatial metadata.</li><li>baseline: Inter-lens distance of the source video (mm).</li><li>fov: Field of view dof the source video (degrees).</li><li>disparity adjustment: FOV correction value (percentage: 0.02 → 2%).</li></ul><h4>Load the side-by-side video</h4><p>The first code to look at is the<strong> init(from:)</strong> initializer inside <strong>SideBySideConverter</strong> in <strong>Converter.swift</strong>.</p><p>Here, the original video to be converted is loaded using <strong>AVAssetReader</strong>. Its structure is as follows, and the code is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7L_5Mkgbb2LaW0ypq5kag.png" /></figure><pre> /// Loads a video to read for conversion.<br>    /// - Parameter url: A URL to a side-by-side HEVC file.<br>    /// - Tag: ReadInputVideo<br> init(from url: URL) async throws {<br>        let asset = AVURLAsset(url: url)<br>        reader = try AVAssetReader(asset: asset)<br><br>        // Get the side-by-side video track.<br>        guard let videoTrack = try await asset.loadTracks(withMediaCharacteristic: .visual).first else {<br>            fatalError(&quot;Error loading side-by-side video input&quot;)<br>        }<br>        <br>        sideBySideFrameSize = try await videoTrack.load(.naturalSize)<br>        eyeFrameSize = CGSize(width: sideBySideFrameSize.width / 2, height: sideBySideFrameSize.height)<br><br>        let readerSettings: [String: Any] = [<br>            kCVPixelBufferIOSurfacePropertiesKey as String: [String: String]()<br>        ]<br><br>        sideBySideTrack = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: readerSettings)<br><br>        if reader.canAdd(sideBySideTrack) {<br>            reader.add(sideBySideTrack)<br>        }<br><br>        if !reader.startReading() {<br>            fatalError(reader.error?.localizedDescription ?? &quot;Unknown error during track read start&quot;)<br>        }<br>    }</pre><h4>Configure the output MV-HEVC file</h4><p>Once the import setup is complete, you need to configure the export settings. At this point, you can use the asynchronous method <strong>transcodeToMVHEVC(output:spatialMetadata:)</strong>. Then, you will configure the multiview compression properties — this determines how each video will separated. What you need to know here is that MV-HEVC is a codec that can handle not just two viewpoints, but more.</p><pre><br>/// The left eye is video layer ID 0 (the hero eye) and the right eye is layer ID 1.<br>/// - Tag: VideoLayers<br>let MVHEVCVideoLayerIDs = [0, 1]<br><br>// For simplicity, choose view IDs that match the layer IDs.<br>let MVHEVCViewIDs = [0, 1]<br><br>// The first element in this array is the view ID of the left eye.<br>let MVHEVCLeftAndRightViewIDs = [0, 1]</pre><ul><li><strong>MVHEVCVideoLayerIDs,</strong></li><li><strong>MVHEVCViewIDS,</strong></li><li><strong>MVHEVCLeftaAndRightViewIDs</strong></li></ul><p>It may be difficult to fully understand the differences among these three even after reading the explanations. Please refer to the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HDINNEXe71FWxDa3s3ksw.png" /></figure><p>A viewpoint can be from a stereo camera, a fisheye-lens camera, or a monocular-lens camera.</p><p>For the rest, you just need to match the three variables above each corresponding<strong> kVTComporessionPropertyKey_…</strong></p><pre>final class SideBySideConverter: Sendable {<br>    ...<br>    <br>    /// Transcodes side-by-side HEVC media to MV-HEVC.<br>    /// - Parameter output: The output URL to write the MV-HEVC file to.<br>    /// - Parameter spatialMetadata: Optional spatial metadata to add to the output file.<br>    /// - Tag: TranscodeVideo<br>    func transcodeToMVHEVC(output videoOutputURL: URL, spatialMetadata: SpatialMetadata?) async {<br>        await withCheckedContinuation { continuation in<br>            Task {<br>                let multiviewWriter = try AVAssetWriter(outputURL: videoOutputURL, fileType: AVFileType.mov)<br><br>                var multiviewCompressionProperties: [CFString: Any] = [<br>                    kVTCompressionPropertyKey_MVHEVCVideoLayerIDs: MVHEVCVideoLayerIDs,<br>                    kVTCompressionPropertyKey_MVHEVCViewIDs: MVHEVCViewIDs,<br>                    kVTCompressionPropertyKey_MVHEVCLeftAndRightViewIDs: MVHEVCLeftAndRightViewIDs,<br>                    kVTCompressionPropertyKey_HasLeftStereoEyeView: true,<br>                    kVTCompressionPropertyKey_HasRightStereoEyeView: true<br>                ]<br><br> ...<br>}</pre><h4>Include spatial metadata</h4><p>This is the process of adding spatial video metadata(actually side data) to the output file. You need to do this so that, when the video is later read, the interocular distance, field of view, and disparity adjustment are applied.</p><pre>if let spatialMetadata {<br><br>    let baselineInMicrometers = UInt32(1000.0 * spatialMetadata.baselineInMillimeters)<br>    let encodedHorizontalFOV = UInt32(1000.0 * spatialMetadata.horizontalFOV)<br>    let encodedDisparityAdjustment = Int32(10_000.0 * spatialMetadata.disparityAdjustment)<br><br>    multiviewCompressionProperties[kVTCompressionPropertyKey_ProjectionKind] = kCMFormatDescriptionProjectionKind_Rectilinear<br>    multiviewCompressionProperties[kVTCompressionPropertyKey_StereoCameraBaseline] = basnelineInMicrometers<br>    multiviewCompressionProperties[kVTCompressionPropertyKey_HorizontalFieldOfView] = encodedHorizontalFOV<br>    multiviewCompressionProperties[kVTCompressionPropertyKey_HorizontalDisparityAdjustment] = encodedDisparityAdjustment<br><br>}</pre><p>The reason for multiplying values such as <em>spatialMetadata.baseineInMillimeters, spatialMetadata.horizontalFOV, spatialMetadata.disparityAdjustment </em>by 1000.0 and 10_000.0 is that the units used in <strong>kVTComporessionPropertyKey</strong> are micrometers(µm) and millidegrees. As for disparity, it is said to use a normalized ratio value. I’m not sure about the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rslAMjU-7BxnzWUzxQx9LQ.png" /></figure><p>Anyway, once the settings are applied, you’ll be able to see that the metadata you configured earlier has been generated in the converted file.</p><h4>Configure the MV-HEVC input source</h4><p>Previously, we went through <strong>load input </strong>(loading the asset), <strong>configure output</strong> (setting up the output), and <strong>include metadata</strong> (adding spatial data).</p><p>To generate (write) the video, two components are requred. In this process, and input configuration for generation is needed — which is different from the source video. It’s important to understand this as: <strong>“providing input that defines how the final output file will be written.”</strong></p><p>Anyway, to generate the video, you need the following two:</p><ul><li><strong>AVAssetWriter</strong>: the converter that creates the output video</li><li><strong>AVAssetWriterInput</strong>: the original source to feed into the converter</li></ul><p>And to make it a multiview video, you also add:</p><ul><li><strong>AVAssetWriterInputTaggedPixelBufferGroupAdaptor</strong>: a multiview — left/right — tagged pixel buffer group used to deliver data to the original input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wia1Ms_dv_5x5X4ahAPMw.png" /></figure><h4>Process input as i becomes available</h4><p>Once you’ve decided in which format to generate the video, you now need to pass along the configuration you’ve set.</p><p>This is done by:</p><ul><li><strong>.startWriting()</strong>: switches to writing mode</li><li><strong>.startSession(atSourceTime: CMTime.zero)</strong>: specifies when to start generating</li><li>CMTime.zero: starts the session immediately</li></ul><p>When the session begins, you request that frames be sequentially processed (on: DispatchQueue …) as they become ready using <strong>.reaquestMediaDataWhenReady(on:)</strong>.</p><pre>guard multiviewWriter.startWriting() else {<br>    fatalError(&quot;Failed to start writing multiview output file&quot;)<br>}<br>multiviewWriter.startSession(atSourceTime: CMTime.zero)<br><br><br>// The dispatch queue executes the closure when media reads from the input file are available.<br>frameInput.requestMediaDataWhenReady(on: DispatchQueue(label: &quot;Multiview HEVC Writer&quot;)) {</pre><h4>Create the video frame transfer session and output pixel buffer pool</h4><p>A pixel buffer is required to copy the pixels from the source video to the video being newly generated. The object that supports copying between pixel buffer is <strong>VTPixelTransferSession</strong>.</p><pre>var session: VTPixelTransferSession? = nil<br>guard VTPixelTransferSessionCreate(allocator: kCFAllocatorDefault, pixelTransferSessionOut: &amp;session) == noErr, let session else {<br>    fatalError(&quot;Failed to create pixel transfer&quot;)<br>}<br>guard let pixelBufferPool = bufferInputAdapter.pixelBufferPool else {<br>    fatalError(&quot;Failed to retrieve existing pixel buffer pool&quot;)<br>}</pre><p>That’s why the VTPixelTransferSession and the buffer pool are created.</p><h4>Copy frame images from input to output</h4><p>After completing all the configurations and preparations, the frame images are finally copied. Strictly speaking, a loop is created that repeatedly copies each frame. The actual copying is handled by the <strong>convertFrame</strong> function within the loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCAiz_eCmWudemQqezzTtA.png" /></figure><pre>frameInput.requestMediaDataWhenReady(on: DispatchQueue(label: &quot;Multiview HEVC Writer&quot;)) {<br>                    var session: VTPixelTransferSession? = nil<br>                    guard VTPixelTransferSessionCreate(allocator: kCFAllocatorDefault, pixelTransferSessionOut: &amp;session) == noErr, let session else {<br>                        fatalError(&quot;Failed to create pixel transfer&quot;)<br>                    }<br>                    guard let pixelBufferPool = bufferInputAdapter.pixelBufferPool else {<br>                        fatalError(&quot;Failed to retrieve existing pixel buffer pool&quot;)<br>                    }<br>                   <br>                    while frameInput.isReadyForMoreMediaData &amp;&amp; bufferInputAdapter.assetWriterInput.isReadyForMoreMediaData {<br>                        if let sampleBuffer = self.sideBySideTrack.copyNextSampleBuffer() {<br>                            guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {<br>                                fatalError(&quot;Failed to load source samples as an image buffer&quot;)<br>                            }<br>                            let taggedBuffers = self.convertFrame(fromSideBySide: imageBuffer, with: pixelBufferPool, in: session)<br>                            let newPTS = sampleBuffer.outputPresentationTimeStamp<br>                            if !bufferInputAdapter.appendTaggedBuffers(taggedBuffers, withPresentationTime: newPTS) {<br>                                fatalError(&quot;Failed to append tagged buffers to multiview output&quot;)<br>                            }<br>                        } else {<br>                            frameInput.markAsFinished()<br>                            multiviewWriter.finishWriting {<br>                                continuation.resume()<br>                            }<br><br>                            break<br>                        }<br>                    }<br>                }</pre><h4>Convert side-by-side inputs into video layer outputs</h4><p>This <strong>convertFrame</strong> is the one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnE716g-ln1-ZNyAKnQMnw.png" /></figure><p>It is responsible for everything from <strong>“frame splitting to output buffer delivery”</strong>.</p><p>First, a buffer needs to be created.</p><pre>var pixelBuffer: CVPixelBuffer?<br>CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferPool, &amp;pixelBuffer)<br>guard let pixelBuffer else {<br>    fatalError(&quot;Failed to create pixel buffer for layer \(layerID)&quot;)<br>}</pre><p>A buffer is created using <strong>CVPixelBufferPoolCreatePixelBuffer</strong>, and after verifying with a guard unwrap that it was successfully created, the process proceeds to the next step.</p><p>The reason for creating the buffer in this way is that<strong> CoreVideo</strong> objects like <strong>CVPixelBuffe</strong>r are based on a <strong>C API</strong>. Therefore, the function creates the buffer internally and returns its reference by filling it through a pointer(out parameter).</p><p>The copying is done iteratively within a loop.</p><p>Since,<em> MVHEVCVideoLayerIDs = [0, 1]</em> and e<em>yes = [.leftEye, .rightEye]</em>, each frame is divided and copied alternately for the left and right sides within a single buffer, and a taggedBuffer is returnes — this is how each side-by-side video is converted into a stereo video.</p><pre>for (layerID, eye) in zip(MVHEVCVideoLayerIDs, eyes) {<br>            var pixelBuffer: CVPixelBuffer?<br>            CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferPool, &amp;pixelBuffer)<br>            guard let pixelBuffer else {<br>                fatalError(&quot;Failed to create pixel buffer for layer \(layerID)&quot;)<br>            }<br><br>            // Crop the transfer region to the current eye.<br>            let apertureOffset = -(self.eyeFrameSize.width / 2) + CGFloat(layerID) * self.eyeFrameSize.width<br>            let cropRectDict = [<br>                kCVImageBufferCleanApertureHorizontalOffsetKey: apertureOffset,<br>                kCVImageBufferCleanApertureVerticalOffsetKey: 0,<br>                kCVImageBufferCleanApertureWidthKey: self.eyeFrameSize.width,<br>                kCVImageBufferCleanApertureHeightKey: self.eyeFrameSize.height<br>            ]<br>            CVBufferSetAttachment(imageBuffer, kCVImageBufferCleanApertureKey, cropRectDict as CFDictionary, CVAttachmentMode.shouldPropagate)<br>            VTSessionSetProperty(session, key: kVTPixelTransferPropertyKey_ScalingMode, value: kVTScalingMode_CropSourceToCleanAperture)<br><br>            // Transfer the image to the pixel buffer.<br>            guard VTPixelTransferSessionTransferImage(session, from: imageBuffer, to: pixelBuffer) == noErr else {<br>                fatalError(&quot;Error during pixel transfer session for layer \(layerID)&quot;)<br>            }<br><br>            // Create and append a tagged buffer for this eye.<br>            let tags: [CMTag] = [.videoLayerID(Int64(layerID)), .stereoView(eye)]<br>            let buffer = CMTaggedBuffer(tags: tags, buffer: .pixelBuffer(pixelBuffer))<br>            taggedBuffers.append(buffer)<br>        }</pre><p>There are a lot of methods here as well, but since there are no particularly difficult concepts, we’ll skip the details.</p><p>After the conversion, the original SBS video is transformed into a stereoscopic video. Because Mac displays do not support stereoscopic playback, only the layer for one eye is output.</p><p><strong>Original SBS &amp; metadata</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*pEKvhvTRDMYHzISAcUTi1g.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIesh48sBTJSUyjjUHE6Pw.png" /></figure><p><strong>Stereo-converted video &amp; metadata</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1IB3BpImnt7ViS4vqbs0Hg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1z1IVHTRH47AV7ft5OE6Q.png" /></figure><p><strong>Spatial-converted video + metadata</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1IB3BpImnt7ViS4vqbs0Hg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lAaGa-rUTTlCFUfWwOJXA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47013fe38aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>