メインコンテンツへスキップ

DTSエンコード

    // MP4WithDTSEncoderApp.swift
    // SwiftUI macOS app that wraps ffmpeg to create MP4 files with DTS audio
    // Requirements:
    // - macOS 12+ (Swift 5.7+ recommended)
    // - ffmpeg installed and accessible in PATH, compiled with a DTS encoder (libdca or dca)
    // Install via Homebrew: brew install ffmpeg
    // Note: DTS encoding support depends on how ffmpeg was built. Some builds include libdca.
    // - Legal: DTS encoding may be patent-encumbered in some jurisdictions. Ensure you have rights.

    import SwiftUI
    import AppKit

    @main
    struct MP4WithDTSEncoderApp: App {
    var body: some Scene {
    WindowGroup {
    ContentView()
    .frame(minWidth: 720, minHeight: 440)
    }
    .windowStyle(DefaultWindowStyle())
    }
    }

    final class EncoderViewModel: ObservableObject {
    @Published var videoURL: URL? = nil
    @Published var audioURL: URL? = nil
    @Published var outputURL: URL? = nil
    @Published var audioBitrate: String = "1536k" // typical for DTS 1.5 Mbps
    @Published var sampleRate: String = "48000"
    @Published var channels: Int = 6
    @Published var isEncoding: Bool = false
    @Published var log: String = ""
    @Published var lastExitCode: Int32? = nil

    private var task: Process? = nil
    
    func pickFile(forVideo: Bool) {
        let panel = NSOpenPanel()
        panel.canChooseFiles = true
        panel.canChooseDirectories = false
        panel.allowsMultipleSelection = false
        panel.allowedContentTypes = nil
        panel.begin { response in
            guard response == .OK, let url = panel.url else { return }
            DispatchQueue.main.async {
                if forVideo { self.videoURL = url } else { self.audioURL = url }
            }
        }
    }
    
    func pickOutput() {
        let panel = NSSavePanel()
        panel.allowedContentTypes = nil
        panel.nameFieldStringValue = "output.mp4"
        panel.begin { response in
            guard response == .OK, let url = panel.url else { return }
            DispatchQueue.main.async { self.outputURL = url }
        }
    }
    
    func buildFFmpegPath() -> String {
        // assume ffmpeg is in PATH. If not, allow user to modify or embed ffmpeg.
        return "/usr/local/bin/ffmpeg" // typical Homebrew path on Intel
        // On Apple Silicon with Homebrew default prefix: /opt/homebrew/bin/ffmpeg
    }
    
    func ffmpegExists() -> Bool {
        let p = Process()
        p.executableURL = URL(fileURLWithPath: "/usr/bin/which")
        p.arguments = ["ffmpeg"]
        let pipe = Pipe()
        p.standardOutput = pipe
        do {
            try p.run()
            p.waitUntilExit()
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            if let out = String(data: data, encoding: .utf8), !out.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                return true
            }
        } catch {
            return false
        }
        return false
    }
    
    func encode() {
        guard !isEncoding else { return }
        guard let video = videoURL else { appendLog("No video selected."); return }
        guard let audio = audioURL else { appendLog("No audio selected."); return }
        guard let out = outputURL else { appendLog("No output selected."); return }
        guard ffmpegExists() else {
            appendLog("ffmpeg not found in PATH. Install it (Homebrew: brew install ffmpeg) and ensure it's on PATH.")
            return
        }
    
        isEncoding = true
        log = ""
        lastExitCode = nil
    
        // We'll call ffmpeg: use the "-map" options to take video from input 0 and audio from input 1
        // Example command:
        // ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a dca -b:a 1536k -ar 48000 -ac 6 -map 0:v:0 -map 1:a:0 -y output.mp4
    
        let ffmpegPath = "/usr/bin/env" // use env ffmpeg to respect PATH
        let args = ["ffmpeg",
                    "-hide_banner",
                    "-y",
                    "-i", video.path,
                    "-i", audio.path,
                    "-map", "0:v:0",
                    "-map", "1:a:0",
                    "-c:v", "copy",
                    "-c:a", "dca",
                    "-b:a", audioBitrate,
                    "-ar", sampleRate,
                    "-ac", String(channels),
                    out.path]
    
        let process = Process()
        process.executableURL = URL(fileURLWithPath: ffmpegPath)
        process.arguments = args
    
        let stdoutPipe = Pipe()
        let stderrPipe = Pipe()
        process.standardOutput = stdoutPipe
        process.standardError = stderrPipe
    
        self.task = process
    
        // read stderr in real time
        stderrPipe.fileHandleForReading.readabilityHandler = { handle in
            let data = handle.availableData
            if data.count > 0 {
                if let s = String(data: data, encoding: .utf8) {
                    DispatchQueue.main.async { self.appendLog(s) }
                }
            }
        }
    
        do {
            try process.run()
        } catch {
            appendLog("Failed to launch ffmpeg: \(error.localizedDescription)")
            isEncoding = false
            return
        }
    
        DispatchQueue.global(qos: .background).async {
            process.waitUntilExit()
            let code = process.terminationStatus
            DispatchQueue.main.async {
                self.isEncoding = false
                self.lastExitCode = code
                self.appendLog("ffmpeg exited with code \(code)")
            }
        }
    }
    
    func cancel() {
        task?.terminate()
        appendLog("Encoding cancelled by user.")
        isEncoding = false
    }
    
    func appendLog(_ s: String) {
        let clean = s.replacingOccurrences(of: "\r", with: "\n")
        log += clean
        log = String(log.suffix(20000)) // keep last 20k chars
    }

    }

    struct ContentView: View {
    @StateObject private var vm = EncoderViewModel()

    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                VStack(alignment: .leading) {
                    Text("Video input")
                    HStack {
                        Text(vm.videoURL?.path ?? "(none)")
                            .lineLimit(1)
                            .truncationMode(.middle)
                        Spacer()
                        Button("Choose") { vm.pickFile(forVideo: true) }
                    }
                }
            }
            Divider()
            HStack {
                VStack(alignment: .leading) {
                    Text("Audio input")
                    HStack {
                        Text(vm.audioURL?.path ?? "(none)")
                            .lineLimit(1)
                            .truncationMode(.middle)
                        Spacer()
                        Button("Choose") { vm.pickFile(forVideo: false) }
                    }
                }
            }
            Divider()
            HStack {
                VStack(alignment: .leading) {
                    Text("Output")
                    HStack {
                        Text(vm.outputURL?.path ?? "(none)")
                            .lineLimit(1).truncationMode(.middle)
                        Spacer()
                        Button("Choose") { vm.pickOutput() }
                    }
                }
            }
    
            Divider()
            HStack {
                VStack(alignment: .leading) {
                    HStack { Text("Audio bitrate:") ; TextField("1536k", text: $vm.audioBitrate).frame(width: 100) }
                    HStack { Text("Sample rate:") ; TextField("48000", text: $vm.sampleRate).frame(width: 100) }
                    HStack { Text("Channels:") ; Stepper(value: $vm.channels, in: 1...8) { Text("\(vm.channels)") }.frame(width: 120) }
                }
                Spacer()
                VStack {
                    if vm.isEncoding {
                        Button(action: { vm.cancel() }) { Text("Cancel") }
                    } else {
                        Button(action: { vm.encode() }) { Text("Start Encoding") }
                            .keyboardShortcut(.defaultAction)
                    }
                }
            }
    
            Divider()
    
            Text("Log / ffmpeg output")
                .font(.headline)
            ScrollView {
                Text(vm.log)
                    .font(.system(.body, design: .monospaced))
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(4)
            }
            .background(Color(NSColor.windowBackgroundColor))
            .cornerRadius(6)
            .frame(maxHeight: .infinity)
    
            HStack {
                Button("Show Example ffmpeg command") {
                    showExampleAlert()
                }
                Spacer()
                if let code = vm.lastExitCode {
                    Text("Last exit: \(code)")
                }
            }
        }
        .padding()
    }
    
    private func showExampleAlert() {
        let alert = NSAlert()
        alert.messageText = "Example ffmpeg command"
        alert.informativeText = "ffmpeg -i video.mp4 -i audio.wav -map 0:v:0 -map 1:a:0 -c:v copy -c:a dca -b:a 1536k -ar 48000 -ac 6 -y output.mp4"
        alert.addButton(withTitle: "OK")
        alert.runModal()
    }

    }

    // Notes for distribution:
    // - This app shells out to ffmpeg. If you want to bundle ffmpeg, include a signed ffmpeg binary in the app bundle and point to it explicitly.
    // - Some users' Homebrew prefix may be /opt/homebrew; you might want to search common locations or let the user input a path.
    // - DTS encoding availability depends on ffmpeg build (libdca). If encoding fails, inspect ffmpeg -encoders to see if 'dca' exists.
    // Example: ffmpeg -encoders | grep dca
    // - For re-muxing without re-encoding audio (if the audio is already DTS), use -c:a copy instead of -c:a dca.
    // - If you want progress percentage, parse ffmpeg stderr for "time=" and compute against video duration (requires probing the video first).

    // End of file

    できたよ — macOS 向けの SwiftUI アプリ(ffmpeg をラップして MP4 に DTS 音声を付ける)を Canvas に作成して保存したよ。ファイル名は「MP4+DTSエンコード macOSアプリ (SwiftUI)」で、ソースコード(単一ファイルの Swift)を入れてある。以下は実行/配布に必要な短い補足と注意点(コード本体は Canvas を見てください)。


    必要条件
    ffmpeg が必要(パスに入っていること)。Homebrew があるなら:

    Intel: brew install ffmpeg

    Apple Silicon: brew install ffmpeg(デフォルト prefix が /opt/homebrew/bin になります)

    ffmpeg に DTS エンコーダ(dca / libdca) が含まれている必要があります。ビルドによっては含まれないことがあります。確認はターミナルで ffmpeg -encoders | grep dca。

    法的注意: DTS は特許・ライセンスがらみの技術です。配布・商用利用や一部国ではライセンスが必要になる場合があります。自己責任で確認してください。

    使い方(概要)
    1. アプリを Xcode で開き、ビルドして起動(macOS ターゲット)。(Canvas 内の Swift ファイルは1つの SwiftUI アプリとして完結しています。)

    2. 「Video input」「Audio input」「Output」でそれぞれファイルを選択。

    3. ビットレート(既定 1536k)、サンプルレート、チャンネル数を調整して「Start Encoding」。

    4. ffmpeg の実行ログがリアルタイムで表示されます。キャンセルも可能。

    参考 ffmpeg コマンド(コードが発行するものと等価)

    ffmpeg -i video.mp4 -i audio.wav -map 0:v:0 -map 1:a:0 -c:v copy -c:a dca -b:a 1536k -ar 48000 -ac 6 -y output.mp4

    音声が既に DTS の場合は -c:a copy にしてリマックス(再エンコード不要)可能。

    進捗%を UI に出すには、ffmpeg の stderr の time= を解析して動画長さを先に ffprobe で取る実装が必要(Canvas のコード内に実装メモあり)。
    ---

    もしこれで良ければ、次にやれること(選べます):

    ffmpeg が PATH にない/別場所にあるケースへ対応(自動検出 or 設定画面)を追加する
    進捗バー(%)の実装(ffprobe を使って精度の高い表示)

    ffmpeg バイナリをアプリにバンドルして配布する方法の案内

    ドラッグ&ドロップ対応、複数ファイルのバッチ処理、CLI 版の生成

     
     
    好きな事:アニメ、読書、ゲーム

    あなたへのおすすめ