-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.go
More file actions
1310 lines (1134 loc) · 35.7 KB
/
Copy pathencoder.go
File metadata and controls
1310 lines (1134 loc) · 35.7 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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build amd64 || arm64
package ffmpeg
import (
"errors"
"fmt"
"runtime"
"strings"
"sync"
"unsafe"
"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"
)
// Encoder encodes video and/or audio frames to a file.
//
// Do not call encoder operations concurrently. Close may be called to cancel a
// cooperative context-aware custom I/O callback before final cleanup.
type Encoder struct {
mu sync.Mutex
closeSignal sync.Once
formatCtx avformat.FormatContext
ioCtx avformat.IOContext
customIO *CustomIOContext
path string
// Optional: used when I/O is opened lazily (e.g. network outputs) or needs avio_open2 options.
ioOptions map[string]string
headerOptions map[string]string
// Video encoding
videoCodecCtx avcodec.Context
videoStream avformat.Stream
videoPacket avcodec.Packet
videoState encoderCodecState
// Audio encoding
audioCodecCtx avcodec.Context
audioStream avformat.Stream
audioPacket avcodec.Packet
audioFrameSize int // Number of samples per frame for codec
audioState encoderCodecState
// Stream copy mode
copyVideo bool
copyAudio bool
copyStreams map[int]streamCopyTarget
videoStreamIdx int // Output video stream index
audioStreamIdx int // Output audio stream index
width int
height int
pixFmt PixelFormat
frameCount int64
timeBaseNum int32
timeBaseDen int32
// Audio properties
sampleRate int
channels int
sampleFormat SampleFormat
audioFrameCnt int64
headerWritten bool
closed bool
hasVideo bool
hasAudio bool
}
type streamCopyTarget struct {
stream avformat.Stream
sourceTimeBase Rational
}
// VideoEncoderConfig configures video encoding parameters.
type VideoEncoderConfig struct {
// Codec specifies the video codec (default: CodecIDH264).
Codec CodecID
// Width is the video width in pixels.
Width int
// Height is the video height in pixels.
Height int
// FrameRate is the target frame rate (default: 30/1).
FrameRate Rational
// Bitrate is the target bit rate in bits/second (default: 2000000).
// Used for ABR/CBR rate control modes.
Bitrate int64
// PixelFormat is the pixel format (default: PixelFormatYUV420P).
PixelFormat PixelFormat
// GOPSize is the group of pictures size (default: 12).
GOPSize int
// MaxBFrames is the maximum number of B-frames (default: 0).
MaxBFrames int
// Preset controls speed/quality tradeoff (e.g., PresetMedium, PresetFast).
// Slower presets produce smaller files. Empty string uses codec default.
Preset EncoderPreset
// Tune optimizes for specific content types (e.g., TuneFilm, TuneAnimation).
// Empty string uses codec default.
Tune EncoderTune
// Profile specifies H.264/H.265 profile (e.g., ProfileHigh, ProfileMain).
// Higher profiles support more features. Empty string uses codec default.
Profile VideoProfile
// Level specifies H.264/H.265 level (e.g., Level4_1 for 1080p60).
// Higher levels support higher resolutions. Empty string uses auto.
Level VideoLevel
// RateControl specifies the rate control mode (default: RateControlABR).
RateControl RateControlMode
// CRF is the Constant Rate Factor (0-51 for x264, 0-63 for x265).
// Used when RateControl is RateControlCRF.
// Lower values = higher quality, larger files. Typical: 18-28.
CRF int
// CQP is the Constant Quantization Parameter.
// Used when RateControl is RateControlCQP.
CQP int
// MinBitrate is the minimum bitrate for VBV (bits/second).
// Used for rate-constrained encoding.
MinBitrate int64
// MaxBitrate is the maximum bitrate for VBV (bits/second).
// Used for rate-constrained encoding.
MaxBitrate int64
// BufferSize is the VBV buffer size (bits).
// Controls rate variation. Larger = more variation allowed.
BufferSize int64
// BFrameStrategy controls B-frame placement (0-2).
// 0=off, 1=fast, 2=best (slower).
BFrameStrategy int
// RefFrames is the number of reference frames (1-16).
// More reference frames = better compression, slower encoding.
RefFrames int
// Threads is the number of encoding threads (default: auto).
// 0 = auto-detect based on CPU cores.
Threads int
// CodecOptions allows setting arbitrary codec-specific options.
// Keys and values are passed directly to av_opt_set.
// Example: {"x264-params": "rc-lookahead=40"}
CodecOptions map[string]string
}
// AudioEncoderConfig configures audio encoding parameters.
// Note: Audio encoding is not yet fully implemented.
type AudioEncoderConfig struct {
// Codec specifies the audio codec (default: CodecIDAACj).
Codec CodecID
// SampleRate is the sample rate in Hz (default: 48000).
SampleRate int
// Channels is the number of audio channels (default: 2).
Channels int
// Bitrate is the target bit rate in bits/second (default: 128000).
Bitrate int64
}
// StreamCopySource provides source codec parameters for stream copy mode.
type StreamCopySource struct {
// VideoParams is the video codec parameters from the source stream.
VideoParams avcodec.Parameters
// VideoTimeBase is the time base of the source video stream.
VideoTimeBase Rational
// VideoStreamIndex is the index reported by source video packets.
VideoStreamIndex int
// AudioParams is the audio codec parameters from the source stream.
AudioParams avcodec.Parameters
// AudioTimeBase is the time base of the source audio stream.
AudioTimeBase Rational
// AudioStreamIndex is the index reported by source audio packets.
AudioStreamIndex int
videoInfo *StreamInfo
audioInfo *StreamInfo
}
// NewStreamCopySource builds stream-copy configuration from decoder stream
// information. Pass nil for a media type that will not be copied. The source
// retains the StreamInfo values until the encoder copies their parameters.
func NewStreamCopySource(video, audio *StreamInfo) *StreamCopySource {
source := &StreamCopySource{}
if video != nil {
source.VideoParams = video.CodecParameters()
source.VideoStreamIndex = video.Index
source.VideoTimeBase = video.TimeBase
source.videoInfo = video
}
if audio != nil {
source.AudioParams = audio.CodecParameters()
source.AudioStreamIndex = audio.Index
source.AudioTimeBase = audio.TimeBase
source.audioInfo = audio
}
return source
}
// EncoderOptions configures encoder behavior with separate video and audio settings.
type EncoderOptions struct {
// Format optionally overrides output format selection (muxer short name, e.g. "flv", "mpegts", "rtp").
// If empty, ffmpeg will attempt to guess from the output path/extension.
Format string
// IOOptions are passed to avio_open2 when opening the output (useful for streaming/network outputs).
IOOptions map[string]string
// MuxerOptions are passed to avformat_write_header.
MuxerOptions map[string]string
// Video contains video encoding settings. Required for video output when not copying.
Video *VideoEncoderConfig
// Audio contains audio encoding settings. Optional.
// Note: Audio encoding is not yet fully implemented.
Audio *AudioEncoderConfig
// CopyVideo enables video stream copy mode (no re-encoding).
// When true, SourceStreams.VideoParams must be set.
CopyVideo bool
// CopyAudio enables audio stream copy mode (no re-encoding).
// When true, SourceStreams.AudioParams must be set.
CopyAudio bool
// SourceStreams provides codec parameters from the source for stream copy.
// Required when CopyVideo or CopyAudio is true.
SourceStreams *StreamCopySource
// Pass enables 2-pass encoding when set to 1 or 2.
// 0 disables multi-pass.
Pass int
// PassLogFile is the passlogfile base path used by the encoder (e.g. x264/x265).
// If empty, TwoPassTranscode may generate a temporary base.
PassLogFile string
// PassOutput optionally overrides the output path for pass 1.
// If empty, TwoPassTranscode will create a temporary file.
PassOutput string
}
func normalizeVideoFrameRate(frameRate Rational) Rational {
if frameRate.Num <= 0 || frameRate.Den <= 0 {
return NewRational(30, 1)
}
return frameRate
}
func cloneEncoderOptions(opts *EncoderOptions) *EncoderOptions {
if opts == nil {
return nil
}
clone := *opts
clone.IOOptions = cloneStringMap(opts.IOOptions)
clone.MuxerOptions = cloneStringMap(opts.MuxerOptions)
if opts.Video != nil {
video := *opts.Video
video.CodecOptions = cloneStringMap(opts.Video.CodecOptions)
clone.Video = &video
}
if opts.Audio != nil {
audio := *opts.Audio
clone.Audio = &audio
}
return &clone
}
// NewEncoder creates a new encoder with separate video and audio configuration.
// It supports advanced codec options like presets, profiles, CRF, etc.
// For stream copy mode, set CopyVideo/CopyAudio and provide SourceStreams.
func NewEncoder(path string, opts *EncoderOptions) (*Encoder, error) {
return newEncoder(path, opts, nil)
}
func newEncoder(path string, opts *EncoderOptions, customIO *CustomIOContext) (*Encoder, error) {
if opts == nil {
return nil, errors.New("ffmpeg: EncoderOptions is required")
}
opts = cloneEncoderOptions(opts)
// Validate options - must have either encoding config or stream copy
hasVideoEncode := opts.Video != nil
hasAudioEncode := opts.Audio != nil
hasVideoCopy := opts.CopyVideo
hasAudioCopy := opts.CopyAudio
if !hasVideoEncode && !hasAudioEncode && !hasVideoCopy && !hasAudioCopy {
return nil, errors.New("ffmpeg: must specify Video config, Audio config, CopyVideo, or CopyAudio")
}
// Validate stream copy options
if hasVideoCopy && (opts.SourceStreams == nil || opts.SourceStreams.VideoParams == nil) {
return nil, errors.New("ffmpeg: SourceStreams.VideoParams required when CopyVideo is true")
}
if hasAudioCopy && (opts.SourceStreams == nil || opts.SourceStreams.AudioParams == nil) {
return nil, errors.New("ffmpeg: SourceStreams.AudioParams required when CopyAudio is true")
}
if hasVideoCopy && opts.SourceStreams.VideoStreamIndex < 0 {
return nil, errors.New("ffmpeg: SourceStreams.VideoStreamIndex must be non-negative")
}
if hasAudioCopy && opts.SourceStreams.AudioStreamIndex < 0 {
return nil, errors.New("ffmpeg: SourceStreams.AudioStreamIndex must be non-negative")
}
if hasVideoCopy && (opts.SourceStreams.VideoTimeBase.Num <= 0 || opts.SourceStreams.VideoTimeBase.Den <= 0) {
return nil, errors.New("ffmpeg: SourceStreams.VideoTimeBase must be positive")
}
if hasAudioCopy && (opts.SourceStreams.AudioTimeBase.Num <= 0 || opts.SourceStreams.AudioTimeBase.Den <= 0) {
return nil, errors.New("ffmpeg: SourceStreams.AudioTimeBase must be positive")
}
if hasVideoCopy && hasAudioCopy && opts.SourceStreams.VideoStreamIndex == opts.SourceStreams.AudioStreamIndex {
return nil, errors.New("ffmpeg: source video and audio stream indices must differ")
}
// Ensure FFmpeg is loaded
if err := bindings.Load(); err != nil {
return nil, err
}
// Handle stream copy mode
if hasVideoCopy || hasAudioCopy {
return newEncoderStreamCopy(path, opts, customIO)
}
// Clone video config so we can safely inject encoder-specific options (e.g. 2-pass for libx265)
// without mutating caller-owned config.
videoCfg := *opts.Video
video := &videoCfg
// Apply defaults for encoding mode
if video.Width <= 0 || video.Height <= 0 {
return nil, errors.New("ffmpeg: width and height must be positive")
}
pixFmt := video.PixelFormat
if pixFmt == PixelFormatNone {
pixFmt = PixelFormatYUV420P
}
codecID := video.Codec
if codecID == CodecIDNone {
codecID = CodecIDH264
}
bitrate := video.Bitrate
if bitrate <= 0 && video.RateControl != RateControlCRF && video.RateControl != RateControlCQP {
bitrate = 2000000
}
gopSize := video.GOPSize
if gopSize <= 0 {
gopSize = 12
}
// Handle frame rate
frameRate := normalizeVideoFrameRate(video.FrameRate)
timeBase := frameRate.Invert()
e := &Encoder{
width: video.Width,
height: video.Height,
pixFmt: pixFmt,
timeBaseNum: timeBase.Num,
timeBaseDen: timeBase.Den,
hasVideo: true,
path: path,
ioOptions: opts.IOOptions,
headerOptions: opts.MuxerOptions,
customIO: customIO,
}
if customIO != nil {
e.ioCtx = customIO.AVIOContext()
}
// Determine output format (optionally forced).
formatName := opts.Format
if formatName == "" {
formatName = guessFormatFromPath(path)
}
if formatName == "" {
return nil, errors.New("ffmpeg: cannot determine output format from filename")
}
// Create output format context
if err := avformat.AllocOutputContext2(&e.formatCtx, nil, formatName, path); err != nil {
e.cleanup()
return nil, err
}
if customIO != nil {
avformat.SetIOContext(e.formatCtx, customIO.AVIOContext())
avformat.AddFlags(e.formatCtx, avformat.AVFMT_FLAG_CUSTOM_IO)
}
// Find encoder
codec := avcodec.FindEncoder(codecID)
if codec == nil {
e.cleanup()
return nil, errors.New("ffmpeg: encoder not found")
}
// Encoder-specific: libx265 does not expose passlogfile/stats AVOptions via FFmpeg,
// but does support 2-pass via x265-params (pass=N:stats=FILE).
if opts.Pass != 0 && strings.HasPrefix(avcodec.GetCodecName(codec), "libx265") {
if video.CodecOptions == nil {
video.CodecOptions = make(map[string]string)
}
// Only inject if user didn't already specify pass/stats.
xp := video.CodecOptions["x265-params"]
if !strings.Contains(xp, "pass=") && !strings.Contains(xp, "stats=") {
if xp != "" && !strings.HasSuffix(xp, ":") {
xp += ":"
}
xp += "pass=" + intToString(opts.Pass) + ":stats=" + opts.PassLogFile
video.CodecOptions["x265-params"] = xp
}
}
// Create video stream
e.videoStream = avformat.NewStream(e.formatCtx, codec)
if e.videoStream == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to create stream")
}
// Create video codec context
e.videoCodecCtx = avcodec.AllocContext3(codec)
if e.videoCodecCtx == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to allocate codec context")
}
// Configure basic codec context parameters
avcodec.SetCtxWidth(e.videoCodecCtx, int32(video.Width))
avcodec.SetCtxHeight(e.videoCodecCtx, int32(video.Height))
avcodec.SetCtxPixFmt(e.videoCodecCtx, int32(pixFmt))
avcodec.SetCtxTimeBase(e.videoCodecCtx, timeBase.Num, timeBase.Den)
avcodec.SetCtxFramerate(e.videoCodecCtx, frameRate.Num, frameRate.Den)
avcodec.SetCtxGopSize(e.videoCodecCtx, int32(gopSize))
avcodec.SetCtxMaxBFrames(e.videoCodecCtx, int32(video.MaxBFrames))
// Set bitrate for ABR/CBR modes
if bitrate > 0 {
avcodec.SetCtxBitRate(e.videoCodecCtx, bitrate)
}
// Apply advanced codec options via av_opt_set (before opening codec)
if err := applyVideoOptions(unsafe.Pointer(e.videoCodecCtx), video); err != nil {
e.cleanup()
return nil, err
}
// Set global header flag if needed by container format
if avformat.NeedsGlobalHeader(e.formatCtx) {
flags := avcodec.GetCtxFlags(e.videoCodecCtx)
avcodec.SetCtxFlags(e.videoCodecCtx, flags|avcodec.CodecFlagGlobalHeader)
}
// Configure multi-pass flags (FFmpeg uses codec context flags, not an option named "pass").
if opts.Pass != 0 {
flags := avcodec.GetCtxFlags(e.videoCodecCtx)
flags &^= (avcodec.CodecFlagPass1 | avcodec.CodecFlagPass2)
if opts.Pass == 1 {
flags |= avcodec.CodecFlagPass1
} else if opts.Pass == 2 {
flags |= avcodec.CodecFlagPass2
}
avcodec.SetCtxFlags(e.videoCodecCtx, flags)
}
// Open codec (pass pass/passlogfile via AVDictionary** to ensure the encoder's
// private options (e.g. libx264/libx265) are applied before priv_data is allocated).
var openDict avutil.Dictionary
if opts.Pass != 0 {
if opts.Pass != 1 && opts.Pass != 2 {
e.cleanup()
return nil, errors.New("ffmpeg: Pass must be 0, 1, or 2")
}
if opts.PassLogFile == "" {
e.cleanup()
return nil, errors.New("ffmpeg: PassLogFile is required when Pass is set")
}
// Set stats filename (libx264/libx265 accept both keys).
if err := avutil.DictSet(&openDict, "passlogfile", opts.PassLogFile, 0); err != nil {
if openDict != nil {
avutil.DictFree(&openDict)
}
e.cleanup()
return nil, err
}
_ = avutil.DictSet(&openDict, "stats", opts.PassLogFile, 0)
}
// Open codec
if err := avcodec.Open2(e.videoCodecCtx, codec, &openDict); err != nil {
if openDict != nil {
avutil.DictFree(&openDict)
}
e.cleanup()
return nil, err
}
if openDict != nil {
avutil.DictFree(&openDict)
}
// Copy codec parameters to stream
codecPar := avformat.GetStreamCodecPar(e.videoStream)
if err := avcodec.ParametersFromContext(codecPar, e.videoCodecCtx); err != nil {
e.cleanup()
return nil, err
}
// Set stream time base
avformat.SetStreamTimeBase(e.videoStream, timeBase.Num, timeBase.Den)
// Open output file if needed
if customIO == nil && !avformat.HasNoFile(e.formatCtx) {
// For network-style outputs (or when IOOptions are provided), open lazily on header write.
// This avoids connecting during encoder construction.
if !looksLikeURL(path) && len(opts.IOOptions) == 0 {
if err := avformat.IOOpen(&e.ioCtx, path, avformat.IOFlagWrite); err != nil {
e.cleanup()
return nil, err
}
avformat.SetIOContext(e.formatCtx, e.ioCtx)
}
}
// Allocate video packet
e.videoPacket = avcodec.PacketAlloc()
if e.videoPacket == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to allocate packet")
}
// Setup audio if configured
if opts.Audio != nil {
if err := e.setupAudio(opts.Audio); err != nil {
e.Close()
return nil, err
}
}
return e, nil
}
func intToString(v int) string {
switch v {
case 1:
return "1"
case 2:
return "2"
default:
return ""
}
}
func looksLikeURL(s string) bool {
return strings.Contains(s, "://")
}
func (e *Encoder) ensureIOOpenLocked() error {
if e.closed {
return ErrEncoderClosed
}
if e.formatCtx == nil {
return errors.New("ffmpeg: encoder is not initialized")
}
if avformat.HasNoFile(e.formatCtx) {
return nil
}
if e.ioCtx != nil {
return nil
}
if e.path == "" {
return errors.New("ffmpeg: output path is not set")
}
// Build IO options for avio_open2 if provided.
if len(e.ioOptions) > 0 {
var dict avutil.Dictionary
for k, v := range e.ioOptions {
if v == "" {
continue
}
if err := avutil.DictSet(&dict, k, v, 0); err != nil {
if dict != nil {
avutil.DictFree(&dict)
}
return err
}
}
err := avformat.IOOpen2(&e.ioCtx, e.path, avformat.IOFlagWrite, &dict)
if dict != nil {
avutil.DictFree(&dict)
}
if err != nil {
return err
}
avformat.SetIOContext(e.formatCtx, e.ioCtx)
return nil
}
if err := avformat.IOOpen(&e.ioCtx, e.path, avformat.IOFlagWrite); err != nil {
return err
}
avformat.SetIOContext(e.formatCtx, e.ioCtx)
return nil
}
func (e *Encoder) writeHeaderLocked() error {
if e.headerWritten {
return nil
}
if err := e.ensureIOOpenLocked(); err != nil {
return err
}
var dict avutil.Dictionary
for k, v := range e.headerOptions {
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)
}
}()
if err := e.writeOutputHeaderLocked(&dict); err != nil {
return err
}
e.headerWritten = true
return nil
}
// newEncoderStreamCopy creates an encoder in stream copy mode.
// Packets are copied directly without decoding/encoding.
func newEncoderStreamCopy(path string, opts *EncoderOptions, customIO *CustomIOContext) (*Encoder, error) {
// Determine output format (optionally forced).
formatName := ""
if opts != nil {
formatName = opts.Format
}
if formatName == "" {
formatName = guessFormatFromPath(path)
}
if formatName == "" {
return nil, errors.New("ffmpeg: cannot determine output format from filename")
}
e := &Encoder{
copyVideo: opts.CopyVideo,
copyAudio: opts.CopyAudio,
copyStreams: make(map[int]streamCopyTarget, 2),
videoStreamIdx: -1,
audioStreamIdx: -1,
path: path,
ioOptions: opts.IOOptions,
headerOptions: opts.MuxerOptions,
customIO: customIO,
}
if customIO != nil {
e.ioCtx = customIO.AVIOContext()
}
// Create output format context
if err := avformat.AllocOutputContext2(&e.formatCtx, nil, formatName, path); err != nil {
e.cleanup()
return nil, err
}
if customIO != nil {
avformat.SetIOContext(e.formatCtx, customIO.AVIOContext())
avformat.AddFlags(e.formatCtx, avformat.AVFMT_FLAG_CUSTOM_IO)
}
// Setup video stream for copy mode
if opts.CopyVideo && opts.SourceStreams != nil && opts.SourceStreams.VideoParams != nil {
// Create stream without codec
stream := avformat.NewStream(e.formatCtx, nil)
if stream == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to create video stream for copy")
}
e.videoStream = stream
e.videoStreamIdx = int(avformat.GetStreamIndex(stream))
// Copy codec parameters from source
codecPar := avformat.GetStreamCodecPar(stream)
err := avcodec.ParametersCopy(codecPar, opts.SourceStreams.VideoParams)
runtime.KeepAlive(opts.SourceStreams)
if err != nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to copy video codec parameters")
}
// Request the source time base. The muxer may adjust it when writing the
// header, so WritePacket reads the final destination value later.
avformat.SetStreamTimeBase(stream, opts.SourceStreams.VideoTimeBase.Num, opts.SourceStreams.VideoTimeBase.Den)
e.copyStreams[opts.SourceStreams.VideoStreamIndex] = streamCopyTarget{
stream: stream,
sourceTimeBase: opts.SourceStreams.VideoTimeBase,
}
e.hasVideo = true
}
// Setup audio stream for copy mode
if opts.CopyAudio && opts.SourceStreams != nil && opts.SourceStreams.AudioParams != nil {
// Create stream without codec
stream := avformat.NewStream(e.formatCtx, nil)
if stream == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to create audio stream for copy")
}
e.audioStream = stream
e.audioStreamIdx = int(avformat.GetStreamIndex(stream))
// Copy codec parameters from source
codecPar := avformat.GetStreamCodecPar(stream)
err := avcodec.ParametersCopy(codecPar, opts.SourceStreams.AudioParams)
runtime.KeepAlive(opts.SourceStreams)
if err != nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to copy audio codec parameters")
}
avformat.SetStreamTimeBase(stream, opts.SourceStreams.AudioTimeBase.Num, opts.SourceStreams.AudioTimeBase.Den)
e.copyStreams[opts.SourceStreams.AudioStreamIndex] = streamCopyTarget{
stream: stream,
sourceTimeBase: opts.SourceStreams.AudioTimeBase,
}
e.hasAudio = true
}
// Setup audio encoding if CopyVideo but encoding audio
if opts.CopyVideo && opts.Audio != nil && !opts.CopyAudio {
if err := e.setupAudio(opts.Audio); err != nil {
e.Close()
return nil, err
}
}
// Open output file if needed
if customIO == nil && !avformat.HasNoFile(e.formatCtx) {
if !looksLikeURL(path) && len(opts.IOOptions) == 0 {
if err := avformat.IOOpen(&e.ioCtx, path, avformat.IOFlagWrite); err != nil {
e.cleanup()
return nil, err
}
avformat.SetIOContext(e.formatCtx, e.ioCtx)
}
}
// Allocate packet for WritePacket
e.videoPacket = avcodec.PacketAlloc()
if e.videoPacket == nil {
e.cleanup()
return nil, errors.New("ffmpeg: failed to allocate packet")
}
return e, nil
}
// WritePacket writes a packet directly to the output (for stream copy mode).
// The packet's stream index should match the source stream.
// For video packets, set streamIndex to match the source video stream.
// For audio packets, set streamIndex to match the source audio stream.
// WritePacket retains its own packet reference and leaves packet unchanged.
func (e *Encoder) WritePacket(packet *Packet) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.closed {
return ErrEncoderClosed
}
if !e.copyVideo && !e.copyAudio {
return errors.New("ffmpeg: WritePacket only available in stream copy mode")
}
if packet == nil || packet.ptr == nil {
return errors.New("ffmpeg: packet cannot be nil")
}
sourceStreamIndex := int(avcodec.GetPacketStreamIndex(packet.ptr))
target, ok := e.copyStreams[sourceStreamIndex]
if !ok {
return fmt.Errorf("ffmpeg: source stream %d is not configured for copy", sourceStreamIndex)
}
// Write header if not yet written. This can change the destination time
// base, so read that value only after the header succeeds.
if !e.headerWritten {
if err := e.writeHeaderLocked(); err != nil {
return err
}
}
avcodec.PacketUnref(e.videoPacket)
if err := avcodec.PacketRef(e.videoPacket, packet.ptr); err != nil {
return err
}
defer avcodec.PacketUnref(e.videoPacket)
dstNum, dstDen := avformat.GetStreamTimeBase(target.stream)
avcodec.RescalePacketTS(e.videoPacket, target.sourceTimeBase, NewRational(dstNum, dstDen))
avcodec.SetPacketStreamIndex(e.videoPacket, avformat.GetStreamIndex(target.stream))
return e.writeOutputPacketLocked(e.videoPacket)
}
// applyVideoOptions applies advanced video encoding options via av_opt_set.
// This must be called BEFORE avcodec_open2.
func applyVideoOptions(ctx unsafe.Pointer, cfg *VideoEncoderConfig) error {
if ctx == nil {
return nil
}
// Preset (speed/quality tradeoff)
if cfg.Preset != "" {
if err := avutil.OptSet(ctx, "preset", string(cfg.Preset), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
// Some codecs don't support preset, ignore error
_ = err
}
}
// Tune (content-specific optimization)
if cfg.Tune != "" {
if err := avutil.OptSet(ctx, "tune", string(cfg.Tune), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Profile
if cfg.Profile != "" {
if err := avutil.OptSet(ctx, "profile", string(cfg.Profile), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Level
if cfg.Level != "" {
if err := avutil.OptSet(ctx, "level", string(cfg.Level), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Rate control
switch cfg.RateControl {
case RateControlCRF:
if cfg.CRF > 0 {
if err := avutil.OptSetInt(ctx, "crf", int64(cfg.CRF), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
case RateControlCQP:
if cfg.CQP > 0 {
if err := avutil.OptSetInt(ctx, "qp", int64(cfg.CQP), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
}
// VBV buffer settings (for CBR/constrained VBR)
if cfg.MinBitrate > 0 {
if err := avutil.OptSetInt(ctx, "minrate", cfg.MinBitrate, avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
if cfg.MaxBitrate > 0 {
if err := avutil.OptSetInt(ctx, "maxrate", cfg.MaxBitrate, avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
if cfg.BufferSize > 0 {
if err := avutil.OptSetInt(ctx, "bufsize", cfg.BufferSize, avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
if cfg.BFrameStrategy > 0 {
if err := avutil.OptSetInt(ctx, "b_strategy", int64(cfg.BFrameStrategy), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Reference frames
if cfg.RefFrames > 0 {
if err := avutil.OptSetInt(ctx, "refs", int64(cfg.RefFrames), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Threading
if cfg.Threads > 0 {
if err := avutil.OptSetInt(ctx, "threads", int64(cfg.Threads), avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
_ = err
}
}
// Custom codec options
for key, value := range cfg.CodecOptions {
if err := avutil.OptSet(ctx, key, value, avutil.AV_OPT_SEARCH_CHILDREN); err != nil {
return fmt.Errorf("ffmpeg: set codec option %q: %w", key, err)
}
}
return nil
}
// setupAudio adds an audio stream to the encoder.
func (e *Encoder) setupAudio(cfg *AudioEncoderConfig) error {
// Apply defaults
codecID := cfg.Codec
if codecID == CodecIDNone {
codecID = CodecIDAAC
}
sampleRate := cfg.SampleRate
if sampleRate <= 0 {
sampleRate = 48000
}
channels := cfg.Channels
if channels <= 0 {
channels = 2
}
bitrate := cfg.Bitrate
if bitrate <= 0 {
bitrate = 128000
}
// Find audio encoder
audioCodec := avcodec.FindEncoder(codecID)
if audioCodec == nil {
return errors.New("ffmpeg: audio encoder not found")
}
// Create audio stream
e.audioStream = avformat.NewStream(e.formatCtx, audioCodec)
if e.audioStream == nil {
return errors.New("ffmpeg: failed to create audio stream")
}
// Create audio codec context
e.audioCodecCtx = avcodec.AllocContext3(audioCodec)
if e.audioCodecCtx == nil {
return errors.New("ffmpeg: failed to allocate audio codec context")
}
// Configure audio codec context
avcodec.SetCtxSampleRate(e.audioCodecCtx, int32(sampleRate))
avcodec.SetCtxChannelLayout(e.audioCodecCtx, int32(channels)) // FFmpeg 5.1+ requires ch_layout
avcodec.SetCtxSampleFmt(e.audioCodecCtx, int32(SampleFormatFLTP)) // AAC requires FLTP
avcodec.SetCtxBitRate(e.audioCodecCtx, bitrate)
avcodec.SetCtxTimeBase(e.audioCodecCtx, 1, int32(sampleRate))
// Set global header flag if needed
if avformat.NeedsGlobalHeader(e.formatCtx) {
flags := avcodec.GetCtxFlags(e.audioCodecCtx)
avcodec.SetCtxFlags(e.audioCodecCtx, flags|avcodec.CodecFlagGlobalHeader)
}
// Open audio codec
if err := avcodec.Open2(e.audioCodecCtx, audioCodec, nil); err != nil {
avcodec.FreeContext(&e.audioCodecCtx)
return err
}
// Copy codec parameters to stream
codecPar := avformat.GetStreamCodecPar(e.audioStream)
if err := avcodec.ParametersFromContext(codecPar, e.audioCodecCtx); err != nil {
return err
}
// Set stream time base
avformat.SetStreamTimeBase(e.audioStream, 1, int32(sampleRate))