|
| 1 | +using System.Text; |
| 2 | +using Serilog; |
| 3 | + |
| 4 | +namespace Segra.Backend.Media |
| 5 | +{ |
| 6 | + /// <summary> |
| 7 | + /// Minimal ISO-BMFF (MP4) box reader used to extract per-track audio names |
| 8 | + /// from Segra/OBS recordings. OBS writes each audio encoder's name into a |
| 9 | + /// custom `trak/udta/name` atom that FFmpeg's mov demuxer does not surface, |
| 10 | + /// so we walk the box tree ourselves. |
| 11 | + /// </summary> |
| 12 | + internal static class Mp4BoxReader |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// Returns the raw per-track names of all audio tracks in the file, in |
| 16 | + /// container order. An entry is null when the track has no `udta/name` |
| 17 | + /// atom, which lets callers fall back to other probes (e.g. ffmpeg's |
| 18 | + /// standard title/handler_name tags) before labeling. Returns null |
| 19 | + /// when the file isn't parsable as ISO-BMFF, or when it contains fewer |
| 20 | + /// than two audio tracks. |
| 21 | + /// </summary> |
| 22 | + public static async Task<List<string?>?> ReadAudioTrackNamesAsync(string filePath) |
| 23 | + { |
| 24 | + try |
| 25 | + { |
| 26 | + await using var fs = new FileStream( |
| 27 | + filePath, |
| 28 | + FileMode.Open, |
| 29 | + FileAccess.Read, |
| 30 | + FileShare.Read, |
| 31 | + bufferSize: 65536, |
| 32 | + useAsync: true); |
| 33 | + |
| 34 | + byte[]? moov = await ReadTopLevelBoxPayloadAsync(fs, "moov"); |
| 35 | + if (moov == null) return null; |
| 36 | + |
| 37 | + var rawNames = new List<string?>(); |
| 38 | + ParseMoov(moov, rawNames); |
| 39 | + |
| 40 | + return rawNames.Count >= 2 ? rawNames : null; |
| 41 | + } |
| 42 | + catch (Exception ex) |
| 43 | + { |
| 44 | + Log.Warning($"Mp4BoxReader failed for {filePath}: {ex.Message}"); |
| 45 | + return null; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + // Scans top-level boxes and returns the payload bytes of the first box |
| 50 | + // matching `fourCc`, or null if not found. Handles both 32-bit and |
| 51 | + // 64-bit box sizes and the "extends to end-of-file" sentinel. |
| 52 | + private static async Task<byte[]?> ReadTopLevelBoxPayloadAsync(FileStream fs, string fourCc) |
| 53 | + { |
| 54 | + long fileSize = fs.Length; |
| 55 | + long pos = 0; |
| 56 | + byte[] header = new byte[16]; |
| 57 | + |
| 58 | + while (pos + 8 <= fileSize) |
| 59 | + { |
| 60 | + fs.Position = pos; |
| 61 | + await fs.ReadExactlyAsync(header.AsMemory(0, 8)); |
| 62 | + |
| 63 | + uint boxSize32 = ReadUInt32BE(header, 0); |
| 64 | + string type = Encoding.ASCII.GetString(header, 4, 4); |
| 65 | + |
| 66 | + long payloadStart; |
| 67 | + long totalBoxSize; |
| 68 | + if (boxSize32 == 1) |
| 69 | + { |
| 70 | + await fs.ReadExactlyAsync(header.AsMemory(8, 8)); |
| 71 | + totalBoxSize = (long)ReadUInt64BE(header, 8); |
| 72 | + payloadStart = pos + 16; |
| 73 | + } |
| 74 | + else if (boxSize32 == 0) |
| 75 | + { |
| 76 | + totalBoxSize = fileSize - pos; |
| 77 | + payloadStart = pos + 8; |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + totalBoxSize = boxSize32; |
| 82 | + payloadStart = pos + 8; |
| 83 | + } |
| 84 | + |
| 85 | + if (totalBoxSize < 8 || pos + totalBoxSize > fileSize) return null; |
| 86 | + |
| 87 | + if (type == fourCc) |
| 88 | + { |
| 89 | + long payloadSize = (pos + totalBoxSize) - payloadStart; |
| 90 | + if (payloadSize < 0 || payloadSize > int.MaxValue) return null; |
| 91 | + byte[] payload = new byte[payloadSize]; |
| 92 | + fs.Position = payloadStart; |
| 93 | + await fs.ReadExactlyAsync(payload); |
| 94 | + return payload; |
| 95 | + } |
| 96 | + |
| 97 | + pos += totalBoxSize; |
| 98 | + } |
| 99 | + |
| 100 | + return null; |
| 101 | + } |
| 102 | + |
| 103 | + // Walks `trak` boxes inside the moov payload and, for each audio trak, |
| 104 | + // appends its `udta/name` content (or null if absent) in container order. |
| 105 | + private static void ParseMoov(byte[] moov, List<string?> audioTrackNames) |
| 106 | + { |
| 107 | + foreach (var trak in EnumerateBoxes(moov, 0, moov.Length)) |
| 108 | + { |
| 109 | + if (trak.Type != "trak") continue; |
| 110 | + |
| 111 | + bool isAudio = false; |
| 112 | + string? trackName = null; |
| 113 | + |
| 114 | + foreach (var child in EnumerateBoxes(moov, trak.PayloadStart, trak.PayloadLength)) |
| 115 | + { |
| 116 | + if (child.Type == "mdia") |
| 117 | + { |
| 118 | + foreach (var mdiaChild in EnumerateBoxes(moov, child.PayloadStart, child.PayloadLength)) |
| 119 | + { |
| 120 | + if (mdiaChild.Type != "hdlr") continue; |
| 121 | + // hdlr: fullbox(4) + pre_defined(4) + handler_type(4) + ... |
| 122 | + if (mdiaChild.PayloadLength >= 12) |
| 123 | + { |
| 124 | + string handlerType = Encoding.ASCII.GetString(moov, mdiaChild.PayloadStart + 8, 4); |
| 125 | + isAudio = handlerType == "soun"; |
| 126 | + } |
| 127 | + break; |
| 128 | + } |
| 129 | + } |
| 130 | + else if (child.Type == "udta") |
| 131 | + { |
| 132 | + foreach (var udtaChild in EnumerateBoxes(moov, child.PayloadStart, child.PayloadLength)) |
| 133 | + { |
| 134 | + if (udtaChild.Type != "name") continue; |
| 135 | + int len = udtaChild.PayloadLength; |
| 136 | + while (len > 0 && moov[udtaChild.PayloadStart + len - 1] == 0) len--; |
| 137 | + if (len > 0) |
| 138 | + { |
| 139 | + trackName = Encoding.UTF8.GetString(moov, udtaChild.PayloadStart, len); |
| 140 | + } |
| 141 | + break; |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + if (isAudio) |
| 147 | + { |
| 148 | + audioTrackNames.Add(trackName); |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + // Iterates direct children of a box region, yielding each child's |
| 154 | + // four-cc type and payload span. |
| 155 | + private static IEnumerable<BoxSpan> EnumerateBoxes(byte[] data, int start, int length) |
| 156 | + { |
| 157 | + int pos = start; |
| 158 | + int end = start + length; |
| 159 | + while (pos + 8 <= end) |
| 160 | + { |
| 161 | + uint boxSize32 = ReadUInt32BE(data, pos); |
| 162 | + string type = Encoding.ASCII.GetString(data, pos + 4, 4); |
| 163 | + |
| 164 | + int payloadStart; |
| 165 | + int totalSize; |
| 166 | + if (boxSize32 == 1) |
| 167 | + { |
| 168 | + if (pos + 16 > end) yield break; |
| 169 | + ulong large = ReadUInt64BE(data, pos + 8); |
| 170 | + if (large > int.MaxValue) yield break; |
| 171 | + totalSize = (int)large; |
| 172 | + payloadStart = pos + 16; |
| 173 | + } |
| 174 | + else if (boxSize32 == 0) |
| 175 | + { |
| 176 | + totalSize = end - pos; |
| 177 | + payloadStart = pos + 8; |
| 178 | + } |
| 179 | + else |
| 180 | + { |
| 181 | + totalSize = (int)boxSize32; |
| 182 | + payloadStart = pos + 8; |
| 183 | + } |
| 184 | + |
| 185 | + if (totalSize < 8 || pos + totalSize > end) yield break; |
| 186 | + |
| 187 | + int payloadLength = (pos + totalSize) - payloadStart; |
| 188 | + yield return new BoxSpan(type, payloadStart, payloadLength); |
| 189 | + pos += totalSize; |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + private readonly record struct BoxSpan(string Type, int PayloadStart, int PayloadLength); |
| 194 | + |
| 195 | + private static uint ReadUInt32BE(byte[] buf, int offset) |
| 196 | + { |
| 197 | + return ((uint)buf[offset] << 24) |
| 198 | + | ((uint)buf[offset + 1] << 16) |
| 199 | + | ((uint)buf[offset + 2] << 8) |
| 200 | + | buf[offset + 3]; |
| 201 | + } |
| 202 | + |
| 203 | + private static ulong ReadUInt64BE(byte[] buf, int offset) |
| 204 | + { |
| 205 | + return ((ulong)ReadUInt32BE(buf, offset) << 32) | ReadUInt32BE(buf, offset + 4); |
| 206 | + } |
| 207 | + } |
| 208 | +} |
0 commit comments