import CoreMedia
import CoreVideo
import Foundation
import ScreenCaptureKit
import VideoToolbox

signal(SIGPIPE, SIG_IGN)

let width = Int32(CommandLine.arguments.count > 1 ? Int(CommandLine.arguments[1]) ?? 1280 : 1280)
let height = Int32(CommandLine.arguments.count > 2 ? Int(CommandLine.arguments[2]) ?? 720 : 720)
let fps = Int32(CommandLine.arguments.count > 3 ? Int(CommandLine.arguments[3]) ?? 30 : 30)
let bitrate = Int32(CommandLine.arguments.count > 4 ? Int(CommandLine.arguments[4]) ?? 3_000_000 : 3_000_000)

final class Capture: NSObject, SCStreamOutput, SCStreamDelegate {
    let lock = NSLock()
    var session: VTCompressionSession?
    var stream: SCStream?
    var frameIndex = 0
    var wantKey = false
    var encodeStarted: [Int64: CFAbsoluteTime] = [:]
    var logged = 0

    func run() async throws {
        let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false)
        guard let display = content.displays.max(by: { $0.width * $0.height < $1.width * $1.height }) else {
            throw NSError(domain: "capture", code: 1, userInfo: [NSLocalizedDescriptionKey: "kein bildschirm"])
        }
        let filter = SCContentFilter(display: display, excludingWindows: [])
        let config = SCStreamConfiguration()
        config.width = Int(width)
        config.height = Int(height)
        config.pixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
        config.minimumFrameInterval = CMTime(value: 1, timescale: fps)
        config.queueDepth = 3
        config.showsCursor = false
        fputs("queueDepth \(config.queueDepth)\n", stderr)

        let callback: VTCompressionOutputCallback = { refcon, _, status, _, sample in
            guard status == noErr, let refcon, let sample else { return }
            Unmanaged<Capture>.fromOpaque(refcon).takeUnretainedValue().write(sample)
        }
        var compression: VTCompressionSession?
        let status = VTCompressionSessionCreate(
            allocator: nil,
            width: width,
            height: height,
            codecType: kCMVideoCodecType_H264,
            encoderSpecification: [
                kVTVideoEncoderSpecification_EnableLowLatencyRateControl: kCFBooleanTrue
            ] as CFDictionary,
            imageBufferAttributes: [
                kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
            ] as CFDictionary,
            compressedDataAllocator: nil,
            outputCallback: callback,
            refcon: Unmanaged.passUnretained(self).toOpaque(),
            compressionSessionOut: &compression
        )
        guard status == noErr, let compression else {
            throw NSError(domain: "capture", code: Int(status), userInfo: [NSLocalizedDescriptionKey: "encoder fehlt"])
        }
        session = compression
        func setProp(_ key: CFString, _ value: CFTypeRef) {
            let result = VTSessionSetProperty(compression, key: key, value: value)
            if result != noErr {
                fputs("encoder property \(key) \(result)\n", stderr)
            }
        }
        setProp(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue)
        setProp(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse)
        setProp(kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality, kCFBooleanTrue)
        setProp(kVTCompressionPropertyKey_MaxFrameDelayCount, 0 as CFNumber)
        setProp(kVTCompressionPropertyKey_ExpectedFrameRate, fps as CFNumber)
        setProp(kVTCompressionPropertyKey_AverageBitRate, bitrate as CFNumber)
        setProp(kVTCompressionPropertyKey_MaxKeyFrameInterval, 180 as CFNumber)
        VTCompressionSessionPrepareToEncodeFrames(compression)

        DispatchQueue.global(qos: .userInitiated).async {
            while let line = readLine() {
                if line == "k" {
                    self.lock.lock()
                    self.wantKey = true
                    self.lock.unlock()
                }
            }
        }

        let output = SCStream(filter: filter, configuration: config, delegate: self)
        try output.addStreamOutput(self, type: .screen, sampleHandlerQueue: DispatchQueue(label: "heimstream.capture"))
        try await output.startCapture()
        stream = output
        fputs("capture läuft \(width)x\(height)\n", stderr)
        fflush(stderr)
        while true {
            try await Task.sleep(nanoseconds: 1_000_000_000)
        }
    }

    func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) {
        guard type == .screen,
              CMSampleBufferIsValid(sampleBuffer),
              let pixel = CMSampleBufferGetImageBuffer(sampleBuffer),
              let session else { return }
        let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
        let host = CMClockGetTime(CMClockGetHostTimeClock())
        let ageMs = (CMTimeGetSeconds(host) - CMTimeGetSeconds(pts)) * 1000
        frameIndex += 1
        if frameIndex % 30 == 1 {
            fputs(String(format: "aufnahme %.0f ms\n", ageMs), stderr)
            fflush(stderr)
        }
        lock.lock()
        encodeStarted[pts.value] = CFAbsoluteTimeGetCurrent()
        let forceKey = wantKey || frameIndex == 1
        wantKey = false
        lock.unlock()
        var flags = VTEncodeInfoFlags()
        let props: CFDictionary? = forceKey
            ? [kVTEncodeFrameOptionKey_ForceKeyFrame: kCFBooleanTrue] as CFDictionary
            : nil
        VTCompressionSessionEncodeFrame(
            session,
            imageBuffer: pixel,
            presentationTimeStamp: pts,
            duration: CMTime(value: 1, timescale: fps),
            frameProperties: props,
            sourceFrameRefcon: nil,
            infoFlagsOut: &flags
        )
    }

    func write(_ sample: CMSampleBuffer) {
        guard let block = CMSampleBufferGetDataBuffer(sample) else { return }
        var length = 0
        var data: UnsafeMutablePointer<Int8>?
        guard CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &length, dataPointerOut: &data) == kCMBlockBufferNoErr,
              let data else { return }
        let bytes = UnsafeRawBufferPointer(start: data, count: length)
        var nals: [(Bool, Data)] = []
        var offset = 0
        var key = false
        while offset + 4 <= bytes.count {
            let size = Int(bytes[offset]) << 24 | Int(bytes[offset + 1]) << 16 | Int(bytes[offset + 2]) << 8 | Int(bytes[offset + 3])
            let start = offset + 4
            let end = start + size
            if size <= 0 || end > bytes.count { break }
            let nal = Data(bytes[start..<end])
            let kind = nal.first.map { $0 & 0x1F } ?? 0
            if kind == 5 { key = true }
            if kind == 1 || kind == 5 { nals.append((kind == 5, nal)) }
            offset = end
        }
        guard !nals.isEmpty else { return }
        let encodedPts = CMSampleBufferGetPresentationTimeStamp(sample).value
        lock.lock()
        if let started = encodeStarted.removeValue(forKey: encodedPts) {
            logged += 1
            if logged % 30 == 1 {
                fputs(String(format: "encoder %.0f ms\n", (CFAbsoluteTimeGetCurrent() - started) * 1000), stderr)
                fflush(stderr)
            }
        }
        defer { lock.unlock() }
        if key, let format = CMSampleBufferGetFormatDescription(sample) {
            var count = 0
            CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: 0, parameterSetPointerOut: nil, parameterSetSizeOut: nil, parameterSetCountOut: &count, nalUnitHeaderLengthOut: nil)
            for index in 0..<count {
                var pointer: UnsafePointer<UInt8>?
                var size = 0
                guard CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: index, parameterSetPointerOut: &pointer, parameterSetSizeOut: &size, parameterSetCountOut: nil, nalUnitHeaderLengthOut: nil) == noErr,
                      let pointer else { continue }
                writeStartCode(Data(bytes: pointer, count: size))
            }
        }
        for (_, nal) in nals {
            writeStartCode(nal)
        }
        fflush(stdout)
    }

    func writeStartCode(_ nal: Data) {
        let start = Data([0, 0, 0, 1])
        start.withUnsafeBytes { _ = fwrite($0.baseAddress, 1, $0.count, stdout) }
        nal.withUnsafeBytes { _ = fwrite($0.baseAddress, 1, $0.count, stdout) }
    }
}

let capture = Capture()
Task {
    do {
        try await capture.run()
    } catch {
        fputs("capture fehler: \(error.localizedDescription)\n", stderr)
        fflush(stderr)
        exit(1)
    }
}
dispatchMain()
