-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmuxer.go
More file actions
651 lines (564 loc) · 17.2 KB
/
Copy pathmuxer.go
File metadata and controls
651 lines (564 loc) · 17.2 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//go:build amd64 || arm64
package ffmpeg
import (
"errors"
"fmt"
"sync"
"github.com/bstkhq/go-ffmpeg-ffi/avcodec"
"github.com/bstkhq/go-ffmpeg-ffi/avformat"
"github.com/bstkhq/go-ffmpeg-ffi/avutil"
"github.com/bstkhq/go-ffmpeg-ffi/internal/bindings"
)
// Muxer combines multiple streams into a container.
// It provides low-level control over muxing, allowing stream copy mode
// or encoding with multiple audio/subtitle tracks.
type Muxer struct {
mu sync.Mutex
formatCtx avformat.FormatContext
ioCtx avformat.IOContext
streams []*MuxerStream
headerWritten bool
trailerWritten bool
path string
headerOptions map[string]string
closed bool
}
// MuxerStream represents a stream being muxed.
type MuxerStream struct {
muxer *Muxer
stream avformat.Stream
codecCtx avcodec.Context
index int
timeBase Rational
mediaType MediaType
encoder *streamEncoder // nil for copy mode
copyMode bool
}
// streamEncoder handles encoding for a muxer stream.
type streamEncoder struct {
codecCtx avcodec.Context
packet avcodec.Packet
frame Frame // reusable frame for format conversion if needed
state encoderCodecState
}
// NewMuxer creates a muxer for the given output path and format.
// The format parameter is the FFmpeg mux format name (e.g., "matroska", "mp4", "avi").
// If format is empty, it will be guessed from the file extension.
func NewMuxer(path string, format string) (*Muxer, error) {
if err := bindings.Load(); err != nil {
return nil, err
}
if path == "" {
return nil, errors.New("ffmpeg: output path cannot be empty")
}
// If format not specified, guess from extension
if format == "" {
format = guessFormatFromPath(path)
}
if format == "" {
return nil, errors.New("ffmpeg: cannot determine output format")
}
m := &Muxer{
path: path,
streams: make([]*MuxerStream, 0),
}
// Create output format context
if err := avformat.AllocOutputContext2(&m.formatCtx, nil, format, path); err != nil {
return nil, err
}
return m, nil
}
// VideoStreamConfig configures a video stream for the muxer.
type VideoStreamConfig struct {
Codec CodecID // Video codec (e.g., CodecIDH264)
Width int // Video width
Height int // Video height
PixelFormat PixelFormat // Pixel format (default: YUV420P)
FrameRate int // Frame rate in fps
BitRate int64 // Bitrate in bits/second
GOPSize int // GOP size (keyframe interval)
MaxBFrames int // Maximum number of B-frames
}
// AddVideoStream adds a video stream to the muxer with encoding.
func (m *Muxer) AddVideoStream(config *VideoStreamConfig) (*MuxerStream, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return nil, closedError("muxer")
}
if m.headerWritten {
return nil, errors.New("ffmpeg: cannot add streams after header is written")
}
if config == nil {
return nil, errors.New("ffmpeg: video config is required")
}
configCopy := *config
config = &configCopy
// Apply defaults
if config.Codec == CodecIDNone {
config.Codec = CodecIDH264
}
if config.PixelFormat == PixelFormatNone {
config.PixelFormat = PixelFormatYUV420P
}
if config.FrameRate <= 0 {
config.FrameRate = 30
}
if config.BitRate <= 0 {
config.BitRate = 2000000
}
if config.GOPSize <= 0 {
config.GOPSize = 12
}
// Find encoder
codec := avcodec.FindEncoder(config.Codec)
if codec == nil {
return nil, errors.New("ffmpeg: video encoder not found")
}
// Create codec context
codecCtx := avcodec.AllocContext3(codec)
if codecCtx == nil {
return nil, errors.New("ffmpeg: failed to allocate video codec context")
}
// Configure codec
avcodec.SetCtxWidth(codecCtx, int32(config.Width))
avcodec.SetCtxHeight(codecCtx, int32(config.Height))
avcodec.SetCtxPixFmt(codecCtx, int32(config.PixelFormat))
avcodec.SetCtxTimeBase(codecCtx, 1, int32(config.FrameRate))
avcodec.SetCtxFramerate(codecCtx, int32(config.FrameRate), 1)
avcodec.SetCtxBitRate(codecCtx, config.BitRate)
avcodec.SetCtxGopSize(codecCtx, int32(config.GOPSize))
avcodec.SetCtxMaxBFrames(codecCtx, int32(config.MaxBFrames))
if avformat.NeedsGlobalHeader(m.formatCtx) {
flags := avcodec.GetCtxFlags(codecCtx)
avcodec.SetCtxFlags(codecCtx, flags|avcodec.CodecFlagGlobalHeader)
}
// Open codec
if err := avcodec.Open2(codecCtx, codec, nil); err != nil {
avcodec.FreeContext(&codecCtx)
return nil, err
}
packet := avcodec.PacketAlloc()
if packet == nil {
avcodec.FreeContext(&codecCtx)
return nil, errors.New("ffmpeg: failed to allocate video packet")
}
// Register the stream only after encoder setup succeeds. AVStream entries
// cannot be removed from an AVFormatContext, so registering earlier would
// leave an unusable stream behind when avcodec_open2 fails.
stream := avformat.NewStream(m.formatCtx, codec)
if stream == nil {
avcodec.PacketFree(&packet)
avcodec.FreeContext(&codecCtx)
return nil, errors.New("ffmpeg: failed to create video stream")
}
// Copy parameters to stream
codecPar := avformat.GetStreamCodecPar(stream)
if err := avcodec.ParametersFromContext(codecPar, codecCtx); err != nil {
avcodec.PacketFree(&packet)
avcodec.FreeContext(&codecCtx)
return nil, err
}
ms := &MuxerStream{
muxer: m,
stream: stream,
codecCtx: codecCtx,
index: int(avformat.GetStreamIndex(stream)),
timeBase: NewRational(1, int32(config.FrameRate)),
mediaType: MediaTypeVideo,
encoder: &streamEncoder{
codecCtx: codecCtx,
packet: packet,
},
}
m.streams = append(m.streams, ms)
return ms, nil
}
// AudioStreamConfig configures an audio stream for the muxer.
type AudioStreamConfig struct {
Codec CodecID // Audio codec (e.g., CodecIDAAC)
SampleRate int // Sample rate in Hz
Channels int // Number of channels
SampleFormat SampleFormat // Sample format
BitRate int64 // Bitrate in bits/second
}
// AddAudioStream adds an audio stream to the muxer with encoding.
func (m *Muxer) AddAudioStream(config *AudioStreamConfig) (*MuxerStream, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return nil, closedError("muxer")
}
if m.headerWritten {
return nil, errors.New("ffmpeg: cannot add streams after header is written")
}
if config == nil {
return nil, errors.New("ffmpeg: audio config is required")
}
configCopy := *config
config = &configCopy
// Apply defaults
if config.Codec == CodecIDNone {
config.Codec = CodecIDAAC
}
if config.SampleRate <= 0 {
config.SampleRate = 48000
}
if config.Channels <= 0 {
config.Channels = 2
}
if config.SampleFormat == SampleFormatNone {
config.SampleFormat = SampleFormatFLTP
}
if config.BitRate <= 0 {
config.BitRate = 128000
}
// Find encoder
codec := avcodec.FindEncoder(config.Codec)
if codec == nil {
return nil, errors.New("ffmpeg: audio encoder not found")
}
// Create codec context
codecCtx := avcodec.AllocContext3(codec)
if codecCtx == nil {
return nil, errors.New("ffmpeg: failed to allocate audio codec context")
}
// Configure codec
avcodec.SetCtxSampleRate(codecCtx, int32(config.SampleRate))
avcodec.SetCtxSampleFmt(codecCtx, int32(config.SampleFormat))
avcodec.SetCtxBitRate(codecCtx, config.BitRate)
avcodec.SetCtxTimeBase(codecCtx, 1, int32(config.SampleRate))
// Set channel layout based on channel count
avcodec.SetCtxChannelLayout(codecCtx, int32(config.Channels))
if avformat.NeedsGlobalHeader(m.formatCtx) {
flags := avcodec.GetCtxFlags(codecCtx)
avcodec.SetCtxFlags(codecCtx, flags|avcodec.CodecFlagGlobalHeader)
}
// Open codec
if err := avcodec.Open2(codecCtx, codec, nil); err != nil {
avcodec.FreeContext(&codecCtx)
return nil, err
}
packet := avcodec.PacketAlloc()
if packet == nil {
avcodec.FreeContext(&codecCtx)
return nil, errors.New("ffmpeg: failed to allocate audio packet")
}
stream := avformat.NewStream(m.formatCtx, codec)
if stream == nil {
avcodec.PacketFree(&packet)
avcodec.FreeContext(&codecCtx)
return nil, errors.New("ffmpeg: failed to create audio stream")
}
// Copy parameters to stream
codecPar := avformat.GetStreamCodecPar(stream)
if err := avcodec.ParametersFromContext(codecPar, codecCtx); err != nil {
avcodec.PacketFree(&packet)
avcodec.FreeContext(&codecCtx)
return nil, err
}
ms := &MuxerStream{
muxer: m,
stream: stream,
codecCtx: codecCtx,
index: int(avformat.GetStreamIndex(stream)),
timeBase: NewRational(1, int32(config.SampleRate)),
mediaType: MediaTypeAudio,
encoder: &streamEncoder{
codecCtx: codecCtx,
packet: packet,
},
}
m.streams = append(m.streams, ms)
return ms, nil
}
// CopyStreamConfig configures a stream for copy mode (no re-encoding).
type CopyStreamConfig struct {
CodecParameters avcodec.Parameters // Source stream codec parameters
TimeBase Rational // Source stream time base
}
// AddCopyStream adds a stream in copy mode (no re-encoding).
// The codec parameters are copied from the source stream.
func (m *Muxer) AddCopyStream(config *CopyStreamConfig) (*MuxerStream, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return nil, closedError("muxer")
}
if m.headerWritten {
return nil, errors.New("ffmpeg: cannot add streams after header is written")
}
if config == nil || config.CodecParameters == nil {
return nil, errors.New("ffmpeg: codec parameters are required for copy stream")
}
// Create stream
stream := avformat.NewStream(m.formatCtx, nil)
if stream == nil {
return nil, errors.New("ffmpeg: failed to create copy stream")
}
// Copy codec parameters
codecPar := avformat.GetStreamCodecPar(stream)
if err := avcodec.ParametersCopy(codecPar, config.CodecParameters); err != nil {
return nil, err
}
// Set time base
avformat.SetStreamTimeBase(stream, config.TimeBase.Num, config.TimeBase.Den)
ms := &MuxerStream{
muxer: m,
stream: stream,
index: int(avformat.GetStreamIndex(stream)),
timeBase: config.TimeBase,
mediaType: avformat.GetCodecParType(codecPar),
copyMode: true,
}
m.streams = append(m.streams, ms)
return ms, nil
}
// WriteHeader writes the container header.
// Must be called after all streams are added and before writing any frames/packets.
func (m *Muxer) WriteHeader() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return closedError("muxer")
}
if m.headerWritten {
return errors.New("ffmpeg: header already written")
}
if len(m.streams) == 0 {
return errors.New("ffmpeg: no streams added")
}
return m.writeHeaderWithOptionsLocked(m.headerOptions)
}
// WriteHeaderWithOptions writes the container header with muxer-specific options.
// Options are passed to FFmpeg's avformat_write_header.
func (m *Muxer) WriteHeaderWithOptions(opts map[string]string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return closedError("muxer")
}
if m.headerWritten {
return errors.New("ffmpeg: header already written")
}
if len(m.streams) == 0 {
return errors.New("ffmpeg: no streams added")
}
merged := cloneStringMap(m.headerOptions)
if merged == nil && len(opts) > 0 {
merged = make(map[string]string, len(opts))
}
for k, v := range opts {
merged[k] = v
}
return m.writeHeaderWithOptionsLocked(merged)
}
func (m *Muxer) writeHeaderWithOptionsLocked(opts map[string]string) error {
var dict avutil.Dictionary
for k, v := range opts {
if v == "" {
continue
}
if err := avutil.DictSet(&dict, k, v, 0); err != nil {
if dict != nil {
avutil.DictFree(&dict)
}
return err
}
}
defer func() {
if dict != nil {
avutil.DictFree(&dict)
}
}()
return m.writeHeaderLocked(&dict)
}
func (m *Muxer) writeHeaderLocked(dict *avutil.Dictionary) error {
// Formats marked AVFMT_NOFILE, such as HLS and DASH, open and atomically
// replace their own manifests and segments. Holding the primary path open
// here prevents those replacements on Windows.
if !avformat.HasNoFile(m.formatCtx) {
if err := avformat.IOOpen(&m.ioCtx, m.path, avformat.IOFlagWrite); err != nil {
return err
}
avformat.SetIOContext(m.formatCtx, m.ioCtx)
}
// Write header
if err := avformat.WriteHeader(m.formatCtx, dict); err != nil {
return err
}
m.headerWritten = true
return nil
}
// WriteFrame encodes and writes a frame to a stream.
// Only valid for streams created with AddVideoStream or AddAudioStream.
func (m *Muxer) WriteFrame(ms *MuxerStream, frame Frame) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return closedError("muxer")
}
if !m.headerWritten {
return errors.New("ffmpeg: header not written")
}
if m.trailerWritten {
return errors.New("ffmpeg: trailer already written")
}
if ms == nil || ms.muxer != m {
return errors.New("ffmpeg: invalid stream")
}
if ms.copyMode {
return errors.New("ffmpeg: cannot write frames to copy-mode stream, use WritePacket")
}
if ms.encoder == nil {
return errors.New("ffmpeg: stream has no encoder")
}
if err := frame.poolLeaseError(); err != nil {
return err
}
return ms.encoder.state.encode(ms.codecCtx, frame.ptr, ms.encoder.packet, m.packetWriter(ms))
}
// WritePacket writes a packet directly to a stream.
// For copy-mode streams, timestamps should already be in the source time base.
func (m *Muxer) WritePacket(ms *MuxerStream, packet *Packet) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return closedError("muxer")
}
if !m.headerWritten {
return errors.New("ffmpeg: header not written")
}
if m.trailerWritten {
return errors.New("ffmpeg: trailer already written")
}
if ms == nil || ms.muxer != m {
return errors.New("ffmpeg: invalid stream")
}
if packet == nil || packet.ptr == nil {
return errors.New("ffmpeg: packet cannot be nil")
}
// Set stream index
avcodec.SetPacketStreamIndex(packet.ptr, int32(ms.index))
// Rescale timestamps for copy mode
if ms.copyMode {
streamTbNum, streamTbDen := avformat.GetStreamTimeBase(ms.stream)
streamTb := NewRational(streamTbNum, streamTbDen)
avcodec.RescalePacketTS(packet.ptr, ms.timeBase, streamTb)
}
// Write packet
return avformat.InterleavedWriteFrame(m.formatCtx, packet.ptr)
}
// WriteTrailer finalizes the container.
// Must be called after all frames/packets are written.
// It drains every encoded stream through codec EOF before writing the trailer.
func (m *Muxer) WriteTrailer() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return closedError("muxer")
}
if !m.headerWritten {
return errors.New("ffmpeg: header not written")
}
if m.trailerWritten {
return errors.New("ffmpeg: trailer already written")
}
return m.writeTrailerLocked()
}
func (m *Muxer) writeTrailerLocked() error {
var trailerErrors []error
for _, ms := range m.streams {
if ms.encoder != nil && ms.codecCtx != nil {
if err := m.flushEncoder(ms); err != nil {
trailerErrors = append(trailerErrors, fmt.Errorf("ffmpeg: flush stream %d: %w", ms.index, err))
}
}
}
if err := avformat.WriteTrailer(m.formatCtx); err != nil {
trailerErrors = append(trailerErrors, err)
} else {
m.trailerWritten = true
}
return errors.Join(trailerErrors...)
}
// flushEncoder flushes remaining packets from an encoder.
func (m *Muxer) flushEncoder(ms *MuxerStream) error {
return ms.encoder.state.encode(ms.codecCtx, nil, ms.encoder.packet, m.packetWriter(ms))
}
func (m *Muxer) packetWriter(ms *MuxerStream) func(avcodec.Packet) error {
return func(packet avcodec.Packet) error {
avcodec.SetPacketStreamIndex(packet, int32(ms.index))
// Some video encoders, including FFmpeg 9's native MPEG-4 encoder,
// leave CFR packet duration unset. MP4 then excludes the final delayed
// frame from the track duration and marks its packet for discard.
if ms.mediaType == MediaTypeVideo && avcodec.GetPacketDuration(packet) <= 0 {
avcodec.SetPacketDuration(packet, 1)
}
streamTbNum, streamTbDen := avformat.GetStreamTimeBase(ms.stream)
streamTb := NewRational(streamTbNum, streamTbDen)
avcodec.RescalePacketTS(packet, ms.timeBase, streamTb)
return avformat.InterleavedWriteFrame(m.formatCtx, packet)
}
}
// Close releases all resources.
func (m *Muxer) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return nil
}
var closeErr error
if m.headerWritten && !m.trailerWritten {
closeErr = m.writeTrailerLocked()
}
m.closed = true
// Free encoder resources
for _, ms := range m.streams {
if ms.encoder != nil {
if ms.encoder.packet != nil {
avcodec.PacketFree(&ms.encoder.packet)
}
if !ms.encoder.frame.IsNil() {
_ = ms.encoder.frame.Free()
}
}
if ms.codecCtx != nil && !ms.copyMode {
avcodec.FreeContext(&ms.codecCtx)
}
}
// Close I/O context (errors during cleanup are non-fatal)
if m.ioCtx != nil {
_ = avformat.IOCloseP(&m.ioCtx)
}
// Free format context
if m.formatCtx != nil {
avformat.FreeContext(m.formatCtx)
m.formatCtx = nil
}
return closeErr
}
// Streams returns all streams in the muxer.
func (m *Muxer) Streams() []*MuxerStream {
m.mu.Lock()
defer m.mu.Unlock()
streams := make([]*MuxerStream, len(m.streams))
copy(streams, m.streams)
return streams
}
// Index returns the stream index.
func (ms *MuxerStream) Index() int {
return ms.index
}
// MediaType returns the stream's media type.
func (ms *MuxerStream) MediaType() MediaType {
return ms.mediaType
}
// TimeBase returns the stream's time base.
func (ms *MuxerStream) TimeBase() Rational {
return ms.timeBase
}
// IsCopyMode returns true if the stream is in copy mode (no encoding).
func (ms *MuxerStream) IsCopyMode() bool {
return ms.copyMode
}