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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main

// Decoding of the on-device transcript that Google Recorder embeds in its
// .m4a files.
//
// The recorder runs speech recognition while recording and stores the result
// *inside the container*, as an extra `mett` data track with the content type
// "application/transcription_2". The track carries word-level timings, which
// is the thing that makes it worth having: re-deriving it later means running
// a speech recogniser over the archive and getting a different, worse answer.
//
// The format is undocumented, so what follows was derived by inspecting a real
// recording and then checked against every segment of it (308 segments, 4051
// words, no anomalies, no trailing bytes). The wire format is:
//
//	stream  := segment*
//	segment := uint32be length, then `length` bytes of protobuf
//
// and the protobuf messages, in the usual field-number notation:
//
//	Segment:
//	  1 repeated Word   words
//	  2 fixed32         confidence   (0.0 in every sample seen)
//	  3 string          language     ("en-US")
//
//	Word:
//	  1 string   text       bare word, no punctuation ("Um")
//	  2 string   formatted  optional; punctuated form, and a leading "\n"
//	             marks a paragraph break ("\nUm,")
//	  3 varint   startMs
//	  4 varint   endMs
//	  7 bytes    flags      nested message, meaning unknown; ignored
//
// Only fields we understand are kept. Unknown fields are skipped rather than
// rejected: this is a format we do not control, and a future recorder version
// adding a field should not stop an episode from being published.
//
// A minimal protobuf reader is implemented here rather than pulling in
// google.golang.org/protobuf, because there is no .proto file to generate from
// — the schema above *is* the specification — and the whole decoder is smaller
// than the dependency's build cost.

import (
	"encoding/binary"
	"errors"
	"fmt"
	"strings"
)

// Word is a single recognised word with its position in the recording.
type Word struct {
	Text string `json:"text"`
	// Formatted is the punctuated form when the recogniser produced one.
	// Empty when it is identical to Text.
	Formatted string `json:"formatted,omitempty"`
	StartMs   int64  `json:"start_ms"`
	EndMs     int64  `json:"end_ms"`
	// Paragraph reports whether the recogniser marked a break before this
	// word (a leading newline in the formatted form).
	Paragraph bool `json:"paragraph,omitempty"`
}

// Segment is one utterance: a run of words the recogniser emitted together.
type Segment struct {
	Language string `json:"language,omitempty"`
	Words    []Word `json:"words"`
}

// Transcript is the whole decoded track.
type Transcript struct {
	Segments []Segment `json:"segments"`
}

// WordCount returns the number of words across all segments.
func (t *Transcript) WordCount() int {
	n := 0
	for _, s := range t.Segments {
		n += len(s.Words)
	}
	return n
}

// Text renders the transcript as prose, using the punctuated forms and the
// recogniser's paragraph breaks. It is a convenience for reading and
// searching; it is not a substitute for the timed data.
func (t *Transcript) Text() string {
	var b strings.Builder
	first := true
	for _, s := range t.Segments {
		for _, w := range s.Words {
			word := w.Formatted
			if word == "" {
				word = w.Text
			}
			switch {
			case first:
				first = false
			case w.Paragraph:
				b.WriteString("\n\n")
			default:
				b.WriteString(" ")
			}
			b.WriteString(word)
		}
	}
	return b.String()
}

// DecodeTranscript decodes a raw "application/transcription_2" track, as
// produced by:
//
//	ffmpeg -i rec.m4a -map 0:<n> -c copy -f data -
func DecodeTranscript(data []byte) (*Transcript, error) {
	var t Transcript
	for off := 0; off < len(data); {
		if off+4 > len(data) {
			return nil, fmt.Errorf("truncated segment length at byte %d", off)
		}
		n := int(binary.BigEndian.Uint32(data[off : off+4]))
		off += 4
		if n == 0 {
			// A zero length is how padding at the end of the track appears;
			// nothing meaningful can follow it.
			break
		}
		if off+n > len(data) {
			return nil, fmt.Errorf("segment at byte %d claims %d bytes, only %d remain", off-4, n, len(data)-off)
		}
		seg, err := decodeSegment(data[off : off+n])
		if err != nil {
			return nil, fmt.Errorf("segment %d: %w", len(t.Segments), err)
		}
		off += n
		t.Segments = append(t.Segments, seg)
	}
	return &t, nil
}

func decodeSegment(b []byte) (Segment, error) {
	var seg Segment
	err := eachField(b, func(field int, wire int, val []byte, num uint64) error {
		switch {
		case field == 1 && wire == wireBytes:
			w, err := decodeWord(val)
			if err != nil {
				return fmt.Errorf("word %d: %w", len(seg.Words), err)
			}
			seg.Words = append(seg.Words, w)
		case field == 3 && wire == wireBytes:
			seg.Language = string(val)
		}
		return nil
	})
	return seg, err
}

func decodeWord(b []byte) (Word, error) {
	var w Word
	err := eachField(b, func(field int, wire int, val []byte, num uint64) error {
		switch {
		case field == 1 && wire == wireBytes:
			w.Text = string(val)
		case field == 2 && wire == wireBytes:
			f := string(val)
			// A leading newline is the recogniser's paragraph break; it is
			// structure, not text, so it is lifted out of the string.
			if strings.HasPrefix(f, "\n") {
				w.Paragraph = true
				f = strings.TrimLeft(f, "\n")
			}
			if f != w.Text {
				w.Formatted = f
			}
		case field == 3 && wire == wireVarint:
			w.StartMs = int64(num)
		case field == 4 && wire == wireVarint:
			w.EndMs = int64(num)
		}
		return nil
	})
	return w, err
}

const (
	wireVarint  = 0
	wireFixed64 = 1
	wireBytes   = 2
	wireFixed32 = 5
)

// eachField walks a protobuf message, calling fn for each field. Length
// delimited fields pass their contents in val; varints pass their value in
// num. Unknown fields are passed too, and fn is free to ignore them.
func eachField(b []byte, fn func(field, wire int, val []byte, num uint64) error) error {
	for i := 0; i < len(b); {
		key, n, err := varint(b, i)
		if err != nil {
			return fmt.Errorf("field key at byte %d: %w", i, err)
		}
		i = n
		field, wire := int(key>>3), int(key&7)
		if field == 0 {
			return fmt.Errorf("invalid field number 0 at byte %d", i)
		}
		switch wire {
		case wireVarint:
			v, n, err := varint(b, i)
			if err != nil {
				return fmt.Errorf("field %d value at byte %d: %w", field, i, err)
			}
			i = n
			if err := fn(field, wire, nil, v); err != nil {
				return err
			}
		case wireBytes:
			l, n, err := varint(b, i)
			if err != nil {
				return fmt.Errorf("field %d length at byte %d: %w", field, i, err)
			}
			i = n
			if uint64(len(b)-i) < l {
				return fmt.Errorf("field %d claims %d bytes, only %d remain", field, l, len(b)-i)
			}
			val := b[i : i+int(l)]
			i += int(l)
			if err := fn(field, wire, val, 0); err != nil {
				return err
			}
		case wireFixed32:
			if len(b)-i < 4 {
				return fmt.Errorf("field %d: truncated fixed32", field)
			}
			val := b[i : i+4]
			i += 4
			if err := fn(field, wire, val, 0); err != nil {
				return err
			}
		case wireFixed64:
			if len(b)-i < 8 {
				return fmt.Errorf("field %d: truncated fixed64", field)
			}
			val := b[i : i+8]
			i += 8
			if err := fn(field, wire, val, 0); err != nil {
				return err
			}
		default:
			// Groups (3, 4) are deprecated and never appear here; anything
			// else means we have lost sync and must not guess.
			return fmt.Errorf("field %d: unsupported wire type %d", field, wire)
		}
	}
	return nil
}

var errTruncatedVarint = errors.New("truncated varint")

func varint(b []byte, i int) (uint64, int, error) {
	var v uint64
	var shift uint
	for {
		if i >= len(b) {
			return 0, 0, errTruncatedVarint
		}
		if shift >= 64 {
			return 0, 0, errors.New("varint overflows 64 bits")
		}
		c := b[i]
		i++
		v |= uint64(c&0x7f) << shift
		if c&0x80 == 0 {
			return v, i, nil
		}
		shift += 7
	}
}