1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

// The transcript track is identified by the MIME type in its `mett` sample
// entry. This is the string Google Recorder writes; the trailing digit is a
// format version, so it is matched by prefix in case a later version bumps it.
const transcriptMIMEPrefix = "application/transcription"

type probeResult struct {
	DurationMs int64
	Bytes      int64
	AudioCodec string
	// TranscriptStream is the ffmpeg stream index of the transcription track,
	// or -1 when the file has none.
	TranscriptStream int
	// DataMIMEs maps stream index to the MIME type of each data track, for
	// diagnostics when the expected track is missing.
	DataMIMEs map[int]string
}

type ffprobeOutput struct {
	Streams []struct {
		Index     int    `json:"index"`
		CodecType string `json:"codec_type"`
		CodecName string `json:"codec_name"`
	} `json:"streams"`
	Format struct {
		Duration string `json:"duration"`
		Size     string `json:"size"`
	} `json:"format"`
}

// probe inspects a recording. Duration and size come from ffprobe; the
// transcript track has to be found by parsing the container directly.
//
// ffprobe is not able to identify it: all three of the recorder's data tracks
// appear as `codec_tag=mett, handler_name=Meta` with no distinguishing field,
// and the MIME type that actually names them lives in the `mett` sample entry,
// which ffprobe does not surface. Picking "the first data track" would work
// today and break silently the day the recorder reorders them, so the boxes
// are read instead.
func probe(ffprobeBin, path string) (*probeResult, error) {
	cmd := exec.Command(ffprobeBin,
		"-v", "error",
		"-print_format", "json",
		"-show_format",
		"-show_streams",
		path,
	)
	var out, stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("ffprobe %s: %w: %s", path, err, strings.TrimSpace(stderr.String()))
	}

	var fo ffprobeOutput
	if err := json.Unmarshal(out.Bytes(), &fo); err != nil {
		return nil, fmt.Errorf("parsing ffprobe output: %w", err)
	}

	res := &probeResult{TranscriptStream: -1, DataMIMEs: map[int]string{}}

	secs, err := strconv.ParseFloat(fo.Format.Duration, 64)
	if err != nil {
		return nil, fmt.Errorf("ffprobe reported no usable duration (%q)", fo.Format.Duration)
	}
	res.DurationMs = int64(secs * 1000)

	res.Bytes, err = strconv.ParseInt(fo.Format.Size, 10, 64)
	if err != nil {
		return nil, fmt.Errorf("ffprobe reported no usable size (%q)", fo.Format.Size)
	}

	for _, s := range fo.Streams {
		if s.CodecType == "audio" && res.AudioCodec == "" {
			res.AudioCodec = s.CodecName
		}
	}

	// Track order in the container is the order ffmpeg assigns stream
	// indices, so the nth track is stream n.
	mimes, err := trackMIMEs(path)
	if err != nil {
		return nil, err
	}
	for i, m := range mimes {
		if m == "" {
			continue
		}
		res.DataMIMEs[i] = m
		if strings.HasPrefix(m, transcriptMIMEPrefix) && res.TranscriptStream < 0 {
			res.TranscriptStream = i
		}
	}
	return res, nil
}

// trackMIMEs returns, per track index, the MIME type declared in a `mett`
// sample entry, or "" for tracks that are not timed metadata.
func trackMIMEs(path string) ([]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	moov, err := findBox(f, "moov")
	if err != nil {
		return nil, fmt.Errorf("%s: %w", path, err)
	}

	var mimes []string
	for _, trak := range childBoxes(moov, "trak") {
		mime := ""
		for _, mdia := range childBoxes(trak, "mdia") {
			for _, minf := range childBoxes(mdia, "minf") {
				for _, stbl := range childBoxes(minf, "stbl") {
					for _, stsd := range childBoxes(stbl, "stsd") {
						// stsd: 4 bytes version/flags, 4 bytes entry count,
						// then sample entries.
						if len(stsd) < 8 {
							continue
						}
						for _, mett := range childBoxes(stsd[8:], "mett") {
							// MetaDataSampleEntry: 6 reserved bytes,
							// 2 data_reference_index, then an optional
							// content_encoding string and the mime_format
							// string, both NUL terminated.
							if len(mett) < 8 {
								continue
							}
							parts := bytes.Split(mett[8:], []byte{0})
							for _, p := range parts {
								if bytes.Contains(p, []byte("/")) {
									mime = string(p)
									break
								}
							}
						}
					}
				}
			}
		}
		mimes = append(mimes, mime)
	}
	return mimes, nil
}

// findBox scans top level boxes for one of the given type and returns its
// payload. Only the top level is scanned, which is all that is needed to
// reach `moov`.
func findBox(r io.ReadSeeker, want string) ([]byte, error) {
	if _, err := r.Seek(0, io.SeekStart); err != nil {
		return nil, err
	}
	var hdr [8]byte
	for {
		if _, err := io.ReadFull(r, hdr[:]); err != nil {
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				return nil, fmt.Errorf("no %s box found (not an MP4?)", want)
			}
			return nil, err
		}
		size := int64(binary.BigEndian.Uint32(hdr[0:4]))
		typ := string(hdr[4:8])

		switch size {
		case 0:
			// Extends to end of file.
			if typ != want {
				return nil, fmt.Errorf("no %s box found", want)
			}
			return io.ReadAll(r)
		case 1:
			// 64 bit size follows the header.
			var ext [8]byte
			if _, err := io.ReadFull(r, ext[:]); err != nil {
				return nil, err
			}
			size = int64(binary.BigEndian.Uint64(ext[:])) - 16
			if size < 0 {
				return nil, fmt.Errorf("invalid 64 bit box size in %s", typ)
			}
			if typ == want {
				buf := make([]byte, size)
				_, err := io.ReadFull(r, buf)
				return buf, err
			}
			if _, err := r.Seek(size, io.SeekCurrent); err != nil {
				return nil, err
			}
		default:
			if size < 8 {
				return nil, fmt.Errorf("invalid box size %d for %s", size, typ)
			}
			if typ == want {
				buf := make([]byte, size-8)
				_, err := io.ReadFull(r, buf)
				return buf, err
			}
			if _, err := r.Seek(size-8, io.SeekCurrent); err != nil {
				return nil, err
			}
		}
	}
}

// childBoxes returns the payloads of every immediate child box of the given
// type. Malformed input yields no children rather than an error: this is a
// best effort read of a file we did not write, and the caller treats "no
// transcript track" as a condition to report, not a crash.
func childBoxes(buf []byte, want string) [][]byte {
	var out [][]byte
	for off := 0; off+8 <= len(buf); {
		size := int(binary.BigEndian.Uint32(buf[off : off+4]))
		typ := string(buf[off+4 : off+8])
		if size < 8 || off+size > len(buf) {
			break
		}
		if typ == want {
			out = append(out, buf[off+8:off+size])
		}
		off += size
	}
	return out
}

// extractStream copies one stream out of the container without re-encoding.
func extractStream(ffmpegBin, path string, index int) ([]byte, error) {
	cmd := exec.Command(ffmpegBin,
		"-v", "error",
		"-i", path,
		"-map", fmt.Sprintf("0:%d", index),
		"-c", "copy",
		"-f", "data", "-",
	)
	var out, stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("ffmpeg extracting stream %d: %w: %s", index, err, strings.TrimSpace(stderr.String()))
	}
	return out.Bytes(), nil
}