/* -LICENSE-START-
** Copyright (c) 2024 Blackmagic Design
**  
** Permission is hereby granted, free of charge, to any person or organization 
** obtaining a copy of the software and accompanying documentation (the 
** "Software") to use, reproduce, display, distribute, sub-license, execute, 
** and transmit the Software, and to prepare derivative works of the Software, 
** and to permit third-parties to whom the Software is furnished to do so, in 
** accordance with:
** 
** (1) if the Software is obtained from Blackmagic Design, the End User License 
** Agreement for the Software Development Kit ("EULA") available at 
** https://www.blackmagicdesign.com/EULA/DeckLinkSDK; or
** 
** (2) if the Software is obtained from any third party, such licensing terms 
** as notified by that third party,
** 
** and all subject to the following:
** 
** (3) the copyright notices in the Software and this entire statement, 
** including the above license grant, this restriction and the following 
** disclaimer, must be included in all copies of the Software, in whole or in 
** part, and all derivative works of the Software, unless such copies or 
** derivative works are solely in the form of machine-executable object code 
** generated by a source language processor.
** 
** (4) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
** DEALINGS IN THE SOFTWARE.
** 
** A copy of the Software is available free of charge at 
** https://www.blackmagicdesign.com/desktopvideo_sdk under the EULA.
** 
** -LICENSE-END-
*/

using System;
using System.Drawing;
using System.Drawing.Imaging;
using DeckLinkAPI;

namespace StillsCSharp
{
    public class Bgra32VideoBuffer : IDeckLinkVideoBuffer
    {
        private Bitmap m_bitmap;
        private BitmapData m_bitmapData;
        private uint m_lockCount;

        // Constructor generates empty pixel buffer
        public Bgra32VideoBuffer(int width, int height)
        {
            // PixelFormat.Format32bppArgb has same endianess as _BMDPixelFormat.bmdFormat8BitBGRA
            m_bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            m_lockCount = 0;
        }

        // Constructor with external bitmap
        public Bgra32VideoBuffer(Bitmap bitmap)
        {
            var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            // If storage is not 32bpp, then perform pixel format conversion
            if ((bitmap.PixelFormat != PixelFormat.Format32bppArgb) && (bitmap.PixelFormat != PixelFormat.Format32bppRgb))
                m_bitmap = bitmap.Clone(rect, PixelFormat.Format32bppArgb);
            else
                m_bitmap = bitmap;

            m_lockCount = 0;
        }

        public Bitmap Bitmap
        {
            get
            {
                return m_bitmap;
            }
        }

        void IDeckLinkVideoBuffer.GetBytes(out IntPtr buffer)
        {
            if (m_lockCount == 0)
                throw new AccessViolationException();

            buffer = m_bitmapData.Scan0;
        }

        void IDeckLinkVideoBuffer.StartAccess(_BMDBufferAccessFlags flags)
        {
            Rectangle rect = new Rectangle(0, 0, m_bitmap.Width, m_bitmap.Height);
            ImageLockMode lockMode;
            if (flags.HasFlag(_BMDBufferAccessFlags.bmdBufferAccessReadAndWrite))
                lockMode = ImageLockMode.ReadWrite;
            else if (flags.HasFlag(_BMDBufferAccessFlags.bmdBufferAccessRead))
                lockMode = ImageLockMode.ReadOnly;
            else
                lockMode = ImageLockMode.WriteOnly;

            m_bitmapData = m_bitmap.LockBits(rect, lockMode, PixelFormat.Format32bppArgb);
            m_lockCount++;
        }

        void IDeckLinkVideoBuffer.EndAccess(_BMDBufferAccessFlags flags)
        {
            if (m_lockCount-- == 0)
                throw new InvalidOperationException();

            m_bitmap.UnlockBits(m_bitmapData);
        }
    }    
}
