-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
892 lines (763 loc) · 22.5 KB
/
decoder.go
File metadata and controls
892 lines (763 loc) · 22.5 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
//go:build !ios && !android && (amd64 || arm64)
package ffgo
import (
"errors"
"strconv"
"strings"
"sync"
"time"
"github.com/obinnaokechukwu/ffgo/avcodec"
"github.com/obinnaokechukwu/ffgo/avformat"
"github.com/obinnaokechukwu/ffgo/avutil"
"github.com/obinnaokechukwu/ffgo/internal/bindings"
)
// Decoder decodes media files.
type Decoder struct {
mu sync.Mutex
formatCtx avformat.FormatContext
videoCodecCtx avcodec.Context
audioCodecCtx avcodec.Context
codecCtx avcodec.Context // Deprecated: use videoCodecCtx
packet avcodec.Packet
frame avutil.Frame
videoStreamIdx int
audioStreamIdx int
videoInfo *StreamInfo
audioInfo *StreamInfo
videoDecoderOpen bool
audioDecoderOpen bool
customIO *CustomIOContext
cleanup func()
closed bool
}
// DecoderOptions configures decoder behavior.
type DecoderOptions struct {
// Format hint (e.g., "mp4", "mkv") - optional
Format string
// FFmpeg options passed to avformat_open_input
AVOptions map[string]string
// Typed probing controls (mapped to avformat_open_input AVDictionary).
ProbeSizeBytes int
AnalyzeDuration time.Duration
MaxProbePackets int
FormatWhitelist []string
CodecWhitelist []string
// ProbeScore, when >0, requires the detected probe score to be at least this value.
// If TryMultipleFormats is enabled, ffgo will attempt additional forced demuxers when the
// auto-detected probe score is below this threshold.
ProbeScore int
// FormatBlacklist excludes demuxers from TryMultipleFormats attempts.
// Note: this is an ffgo-side filter; it is not passed as an avformat_open_input option.
FormatBlacklist []string
// TryMultipleFormats, when true, retries avformat_open_input with forced demuxers if
// auto-detection fails or yields a low probe score.
TryMultipleFormats bool
// Streams specifies which stream types to decode (nil = all streams)
Streams []MediaType
// ProgramID selects a specific program to decode in multi-program inputs (e.g. MPEG-TS).
// When set, ffgo will pick the best video/audio streams within the program.
ProgramID int
// HWDevice specifies the hardware device for hardware acceleration (e.g., "cuda", "vaapi")
HWDevice string
}
// DecoderOption is a functional option for configuring a decoder.
type DecoderOption func(*DecoderOptions)
// WithFormat sets the format hint for the decoder.
func WithFormat(format string) DecoderOption {
return func(o *DecoderOptions) {
o.Format = format
}
}
// WithStreams specifies which stream types to decode.
// Only the specified stream types will be available for decoding.
func WithStreams(types ...MediaType) DecoderOption {
return func(o *DecoderOptions) {
o.Streams = types
}
}
// WithProgramID selects a specific program to decode in multi-program inputs (e.g. MPEG-TS).
func WithProgramID(id int) DecoderOption {
return func(o *DecoderOptions) {
o.ProgramID = id
}
}
// WithHWDevice enables hardware acceleration using the specified device.
// Common values: "cuda" (NVIDIA), "vaapi" (Linux VA-API), "videotoolbox" (macOS).
// Note: Hardware acceleration support depends on FFmpeg build and available hardware.
func WithHWDevice(device string) DecoderOption {
return func(o *DecoderOptions) {
o.HWDevice = device
}
}
// WithAVOptions sets FFmpeg options passed to avformat_open_input.
func WithAVOptions(options map[string]string) DecoderOption {
return func(o *DecoderOptions) {
o.AVOptions = options
}
}
// WithProbeSize sets the maximum probing size in bytes (FFmpeg "probesize").
func WithProbeSize(n int) DecoderOption {
return func(o *DecoderOptions) {
o.ProbeSizeBytes = n
}
}
// WithAnalyzeDuration sets the maximum analyze duration (FFmpeg "analyzeduration").
func WithAnalyzeDuration(d time.Duration) DecoderOption {
return func(o *DecoderOptions) {
o.AnalyzeDuration = d
}
}
// WithMaxProbePackets sets the maximum number of probe packets (FFmpeg "max_probe_packets").
func WithMaxProbePackets(n int) DecoderOption {
return func(o *DecoderOptions) {
o.MaxProbePackets = n
}
}
// WithFormatWhitelist sets the demuxer format whitelist (FFmpeg "format_whitelist").
func WithFormatWhitelist(v ...string) DecoderOption {
return func(o *DecoderOptions) {
o.FormatWhitelist = v
}
}
// WithCodecWhitelist sets the codec whitelist (FFmpeg "codec_whitelist").
func WithCodecWhitelist(v ...string) DecoderOption {
return func(o *DecoderOptions) {
o.CodecWhitelist = v
}
}
// WithProbeScore requires a minimum probe score for the detected format.
func WithProbeScore(min int) DecoderOption {
return func(o *DecoderOptions) {
o.ProbeScore = min
}
}
// WithFormatBlacklist excludes demuxers from TryMultipleFormats attempts.
func WithFormatBlacklist(v ...string) DecoderOption {
return func(o *DecoderOptions) {
o.FormatBlacklist = v
}
}
// WithTryMultipleFormats enables retries with forced demuxers when probing is ambiguous.
func WithTryMultipleFormats(enabled bool) DecoderOption {
return func(o *DecoderOptions) {
o.TryMultipleFormats = enabled
}
}
func buildDecoderAVOptions(opts *DecoderOptions) map[string]string {
if opts == nil {
return nil
}
out := make(map[string]string, len(opts.AVOptions)+8)
for k, v := range opts.AVOptions {
out[k] = v
}
// Typed fields override raw AVOptions for clarity/determinism.
if opts.ProbeSizeBytes > 0 {
out["probesize"] = strconv.Itoa(opts.ProbeSizeBytes)
}
if opts.AnalyzeDuration > 0 {
out["analyzeduration"] = strconv.FormatInt(opts.AnalyzeDuration.Microseconds(), 10)
}
if opts.MaxProbePackets > 0 {
out["max_probe_packets"] = strconv.Itoa(opts.MaxProbePackets)
}
if len(opts.FormatWhitelist) > 0 {
out["format_whitelist"] = strings.Join(opts.FormatWhitelist, ",")
}
if len(opts.CodecWhitelist) > 0 {
out["codec_whitelist"] = strings.Join(opts.CodecWhitelist, ",")
}
return out
}
// NewDecoder opens a media file for decoding.
// Optional functional options can be passed to configure the decoder.
func NewDecoder(path string, options ...DecoderOption) (*Decoder, error) {
opts := &DecoderOptions{}
for _, opt := range options {
opt(opts)
}
return NewDecoderWithOptions(path, opts)
}
// NewDecoderWithOptions opens a media file with custom options.
func NewDecoderWithOptions(path string, opts *DecoderOptions) (*Decoder, error) {
// Ensure FFmpeg is loaded
if err := bindings.Load(); err != nil {
return nil, err
}
d := &Decoder{
videoStreamIdx: -1,
audioStreamIdx: -1,
}
// Open input file (with optional retry logic for ambiguous probing).
var err error
d.formatCtx, err = openInputWithRetries(path, opts)
if err != nil {
return nil, err
}
// Find stream info
if err := avformat.FindStreamInfo(d.formatCtx, nil); err != nil {
avformat.CloseInput(&d.formatCtx)
return nil, err
}
// Stream selection.
wantVideo, wantAudio := true, true
if len(opts.Streams) > 0 {
wantVideo, wantAudio = false, false
for _, mt := range opts.Streams {
switch mt {
case MediaTypeVideo:
wantVideo = true
case MediaTypeAudio:
wantAudio = true
}
}
}
if opts != nil && opts.ProgramID > 0 {
if err := d.selectProgramStreams(opts.ProgramID, wantVideo, wantAudio); err != nil {
avformat.CloseInput(&d.formatCtx)
return nil, err
}
} else {
if wantVideo {
d.videoStreamIdx = int(avformat.FindBestStream(d.formatCtx, avutil.MediaTypeVideo, -1, -1, nil, 0))
if d.videoStreamIdx >= 0 {
d.videoInfo = d.getStreamInfo(d.videoStreamIdx)
}
}
if wantAudio {
d.audioStreamIdx = int(avformat.FindBestStream(d.formatCtx, avutil.MediaTypeAudio, -1, -1, nil, 0))
if d.audioStreamIdx >= 0 {
d.audioInfo = d.getStreamInfo(d.audioStreamIdx)
}
}
}
// Allocate packet and frame
d.packet = avcodec.PacketAlloc()
if d.packet == nil {
d.Close()
return nil, errors.New("ffgo: failed to allocate packet")
}
d.frame = avutil.FrameAlloc()
if d.frame == nil {
d.Close()
return nil, errors.New("ffgo: failed to allocate frame")
}
return d, nil
}
// getStreamInfo extracts stream information.
func (d *Decoder) getStreamInfo(streamIdx int) *StreamInfo {
stream := avformat.GetStream(d.formatCtx, streamIdx)
if stream == nil {
return nil
}
codecPar := avformat.GetStreamCodecPar(stream)
if codecPar == nil {
return nil
}
codecType := avformat.GetCodecParType(codecPar)
codecID := avformat.GetCodecParCodecID(codecPar)
// Get time base
tbNum, tbDen := avformat.GetStreamTimeBase(stream)
// Get codec name
var codecName string
if codec := avcodec.FindDecoder(codecID); codec != nil {
codecName = avcodec.GetCodecName(codec)
}
info := &StreamInfo{
Index: streamIdx,
Type: codecType,
CodecID: codecID,
CodecName: codecName,
TimeBase: avutil.NewRational(tbNum, tbDen),
codecPar: codecPar,
}
if codecType == avutil.MediaTypeVideo {
info.Width = int(avformat.GetCodecParWidth(codecPar))
info.Height = int(avformat.GetCodecParHeight(codecPar))
info.PixelFmt = PixelFormat(avformat.GetCodecParFormat(codecPar))
// Get frame rate
frNum, frDen := avformat.GetStreamAvgFrameRate(stream)
info.FrameRate = avutil.NewRational(frNum, frDen)
} else if codecType == avutil.MediaTypeAudio {
info.SampleRate = int(avformat.GetCodecParSampleRate(codecPar))
info.Channels = int(avformat.GetCodecParChannels(codecPar))
}
return info
}
// VideoStream returns information about the video stream.
// Returns nil if no video stream is present.
func (d *Decoder) VideoStream() *StreamInfo {
return d.videoInfo
}
// AudioStream returns information about the audio stream.
// Returns nil if no audio stream is present.
func (d *Decoder) AudioStream() *StreamInfo {
return d.audioInfo
}
// HasVideo returns true if the file has a video stream.
func (d *Decoder) HasVideo() bool {
return d.videoStreamIdx >= 0
}
// HasAudio returns true if the file has an audio stream.
func (d *Decoder) HasAudio() bool {
return d.audioStreamIdx >= 0
}
// NumStreams returns the total number of streams.
func (d *Decoder) NumStreams() int {
if d.formatCtx == nil {
return 0
}
return avformat.GetNumStreams(d.formatCtx)
}
// Duration returns the duration as time.Duration.
func (d *Decoder) Duration() time.Duration {
us := d.DurationMicroseconds()
if us <= 0 {
return 0
}
return time.Duration(us) * time.Microsecond
}
// DurationMicroseconds returns the duration in microseconds (AV_TIME_BASE units).
func (d *Decoder) DurationMicroseconds() int64 {
if d.formatCtx == nil {
return 0
}
return avformat.GetDuration(d.formatCtx)
}
// DurationTime is an alias for Duration for backward compatibility.
// Deprecated: Use Duration() instead.
func (d *Decoder) DurationTime() time.Duration {
return d.Duration()
}
// BitRate returns the bit rate.
func (d *Decoder) BitRate() int64 {
if d.formatCtx == nil {
return 0
}
return avformat.GetBitRate(d.formatCtx)
}
// ReadPacket reads the next packet from the file.
// Returns (nil, nil) on EOF.
//
// The returned packet is BORROWED (decoder-owned and internally reused).
// Do not free it; if you need to keep it, call PacketClone().
func (d *Decoder) ReadPacket() (*Packet, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.closed {
return nil, errors.New("ffgo: decoder is closed")
}
// Unref previous packet
avcodec.PacketUnref(d.packet)
// Read next packet
if err := avformat.ReadFrame(d.formatCtx, d.packet); err != nil {
if avutil.IsEOF(err) {
return nil, nil
}
return nil, err
}
return &Packet{ptr: d.packet, owned: false}, nil
}
// OpenVideoDecoder opens a codec context for video decoding.
// Must be called before DecodeVideoPacket.
func (d *Decoder) OpenVideoDecoder() error {
d.mu.Lock()
defer d.mu.Unlock()
if d.videoStreamIdx < 0 {
return errors.New("ffgo: no video stream")
}
if d.videoDecoderOpen {
return nil // Already opened
}
stream := avformat.GetStream(d.formatCtx, d.videoStreamIdx)
codecPar := avformat.GetStreamCodecPar(stream)
codecID := avformat.GetCodecParCodecID(codecPar)
// Find decoder
codec := avcodec.FindDecoder(codecID)
if codec == nil {
return errors.New("ffgo: decoder not found")
}
// Allocate codec context
d.videoCodecCtx = avcodec.AllocContext3(codec)
if d.videoCodecCtx == nil {
return errors.New("ffgo: failed to allocate codec context")
}
// Copy codec parameters
if err := avcodec.ParametersToContext(d.videoCodecCtx, codecPar); err != nil {
avcodec.FreeContext(&d.videoCodecCtx)
return err
}
// Open codec
if err := avcodec.Open2(d.videoCodecCtx, codec, nil); err != nil {
avcodec.FreeContext(&d.videoCodecCtx)
return err
}
d.codecCtx = d.videoCodecCtx // For backward compatibility
d.videoDecoderOpen = true
return nil
}
// OpenAudioDecoder opens a codec context for audio decoding.
func (d *Decoder) OpenAudioDecoder() error {
d.mu.Lock()
defer d.mu.Unlock()
if d.audioStreamIdx < 0 {
return errors.New("ffgo: no audio stream")
}
if d.audioDecoderOpen {
return nil // Already opened
}
stream := avformat.GetStream(d.formatCtx, d.audioStreamIdx)
codecPar := avformat.GetStreamCodecPar(stream)
codecID := avformat.GetCodecParCodecID(codecPar)
// Find decoder
codec := avcodec.FindDecoder(codecID)
if codec == nil {
return errors.New("ffgo: audio decoder not found")
}
// Allocate codec context
d.audioCodecCtx = avcodec.AllocContext3(codec)
if d.audioCodecCtx == nil {
return errors.New("ffgo: failed to allocate audio codec context")
}
// Copy codec parameters
if err := avcodec.ParametersToContext(d.audioCodecCtx, codecPar); err != nil {
avcodec.FreeContext(&d.audioCodecCtx)
return err
}
// Open codec
if err := avcodec.Open2(d.audioCodecCtx, codec, nil); err != nil {
avcodec.FreeContext(&d.audioCodecCtx)
return err
}
d.audioDecoderOpen = true
return nil
}
// DecodeVideoPacket decodes a video packet and returns the decoded frame.
// Returns nil frame if more data is needed (EAGAIN) or on EOF.
// The returned frame is owned by the decoder; copy it if you need to keep it.
func (d *Decoder) DecodeVideoPacket(pkt *Packet) (Frame, error) {
d.mu.Lock()
defer d.mu.Unlock()
if !d.videoDecoderOpen {
return Frame{}, errors.New("ffgo: video decoder not opened; call OpenVideoDecoder first")
}
// Send packet to decoder
var raw avcodec.Packet
if pkt != nil {
raw = pkt.ptr
}
if err := avcodec.SendPacket(d.videoCodecCtx, raw); err != nil {
return Frame{}, err
}
// Receive decoded frame
avutil.FrameUnref(d.frame)
err := avcodec.ReceiveFrame(d.videoCodecCtx, d.frame)
if err != nil {
if avutil.IsAgain(err) || avutil.IsEOF(err) {
return Frame{}, nil
}
return Frame{}, err
}
return Frame{ptr: d.frame, owned: false}, nil
}
// DecodeVideoPacketCopy decodes a video packet and returns an owned frame.
//
// Unlike DecodeVideoPacket (which returns a decoder-owned, internally reused frame),
// this method returns a cloned frame that the caller MUST free with FrameFree.
// Returns (nil, nil) if more data is needed (EAGAIN) or on EOF.
func (d *Decoder) DecodeVideoPacketCopy(pkt *Packet) (Frame, error) {
frame, err := d.DecodeVideoPacket(pkt)
if err != nil || frame.IsNil() {
return Frame{}, err
}
return FrameClone(frame)
}
// DecodeAudioPacket decodes an audio packet and returns the decoded frame.
// Returns nil frame if more data is needed (EAGAIN) or on EOF.
// The returned frame is owned by the decoder; copy it if you need to keep it.
func (d *Decoder) DecodeAudioPacket(pkt *Packet) (Frame, error) {
d.mu.Lock()
defer d.mu.Unlock()
if !d.audioDecoderOpen {
return Frame{}, errors.New("ffgo: audio decoder not opened; call OpenAudioDecoder first")
}
// Send packet to decoder
var raw avcodec.Packet
if pkt != nil {
raw = pkt.ptr
}
if err := avcodec.SendPacket(d.audioCodecCtx, raw); err != nil {
return Frame{}, err
}
// Receive decoded frame
avutil.FrameUnref(d.frame)
err := avcodec.ReceiveFrame(d.audioCodecCtx, d.frame)
if err != nil {
if avutil.IsAgain(err) || avutil.IsEOF(err) {
return Frame{}, nil
}
return Frame{}, err
}
return Frame{ptr: d.frame, owned: false}, nil
}
// DecodeAudioPacketCopy decodes an audio packet and returns an owned frame.
//
// Unlike DecodeAudioPacket (which returns a decoder-owned, internally reused frame),
// this method returns a cloned frame that the caller MUST free with FrameFree.
// Returns (nil, nil) if more data is needed (EAGAIN) or on EOF.
func (d *Decoder) DecodeAudioPacketCopy(pkt *Packet) (Frame, error) {
frame, err := d.DecodeAudioPacket(pkt)
if err != nil || frame.IsNil() {
return Frame{}, err
}
return FrameClone(frame)
}
// DecodeVideo reads and decodes the next video frame.
// This is a convenience method that handles packet reading internally.
// The returned frame is owned by the decoder; do not call FrameFree on it.
// If you need to keep the frame beyond the next decode call, make a copy.
// Returns nil frame on EOF.
func (d *Decoder) DecodeVideo() (Frame, error) {
if !d.videoDecoderOpen {
if err := d.OpenVideoDecoder(); err != nil {
return Frame{}, err
}
}
for {
pkt, err := d.ReadPacket()
if err != nil {
return Frame{}, err
}
if pkt == nil {
// EOF: Flush decoder
frame, err := d.DecodeVideoPacket(nil)
if err != nil || frame.IsNil() {
return Frame{}, err
}
return frame, nil
}
// Skip non-video packets
if pkt.StreamIndex() != d.videoStreamIdx {
continue
}
// Decode the packet
frame, err := d.DecodeVideoPacket(pkt)
if err != nil {
return Frame{}, err
}
if !frame.IsNil() {
return frame, nil
}
// Need more data, read next packet
}
}
// DecodeVideoCopy reads and decodes the next video frame and returns an owned frame.
//
// The caller MUST free the returned frame with FrameFree.
// Returns nil frame on EOF.
func (d *Decoder) DecodeVideoCopy() (Frame, error) {
frame, err := d.DecodeVideo()
if err != nil || frame.IsNil() {
return Frame{}, err
}
return FrameClone(frame)
}
// DecodeAudio reads and decodes the next audio frame.
// This is a convenience method that handles packet reading internally.
// The returned frame is owned by the decoder; do not call FrameFree on it.
// If you need to keep the frame beyond the next decode call, make a copy.
// Returns nil frame on EOF.
func (d *Decoder) DecodeAudio() (Frame, error) {
if !d.audioDecoderOpen {
if err := d.OpenAudioDecoder(); err != nil {
return Frame{}, err
}
}
for {
pkt, err := d.ReadPacket()
if err != nil {
return Frame{}, err
}
if pkt == nil {
// EOF: Flush decoder
frame, err := d.DecodeAudioPacket(nil)
if err != nil || frame.IsNil() {
return Frame{}, err
}
return frame, nil
}
// Skip non-audio packets
if pkt.StreamIndex() != d.audioStreamIdx {
continue
}
// Decode the packet
frame, err := d.DecodeAudioPacket(pkt)
if err != nil {
return Frame{}, err
}
if !frame.IsNil() {
return frame, nil
}
// Need more data, read next packet
}
}
// ReadFrame reads and decodes the next frame (video or audio).
// Returns a FrameWrapper with the MediaType set.
// The frame is owned by the decoder; call Copy() if you need to keep it.
// Returns nil, nil on EOF.
func (d *Decoder) ReadFrame() (*FrameWrapper, error) {
// Open decoders if needed
if d.HasVideo() && !d.videoDecoderOpen {
if err := d.OpenVideoDecoder(); err != nil {
return nil, err
}
}
if d.HasAudio() && !d.audioDecoderOpen {
if err := d.OpenAudioDecoder(); err != nil {
return nil, err
}
}
for {
pkt, err := d.ReadPacket()
if err != nil {
return nil, err
}
if pkt == nil {
// EOF: Flush video decoder first
if d.videoDecoderOpen {
frame, err := d.DecodeVideoPacket(nil)
if err != nil {
return nil, err
}
if !frame.IsNil() {
return WrapFrame(frame, MediaTypeVideo), nil
}
}
// Flush audio decoder
if d.audioDecoderOpen {
frame, err := d.DecodeAudioPacket(nil)
if err != nil {
return nil, err
}
if !frame.IsNil() {
return WrapFrame(frame, MediaTypeAudio), nil
}
}
return nil, nil // EOF
}
// Decode video packet
if pkt.StreamIndex() == d.videoStreamIdx && d.videoDecoderOpen {
frame, err := d.DecodeVideoPacket(pkt)
if err != nil {
return nil, err
}
if !frame.IsNil() {
return WrapFrame(frame, MediaTypeVideo), nil
}
}
// Decode audio packet
if pkt.StreamIndex() == d.audioStreamIdx && d.audioDecoderOpen {
frame, err := d.DecodeAudioPacket(pkt)
if err != nil {
return nil, err
}
if !frame.IsNil() {
return WrapFrame(frame, MediaTypeAudio), nil
}
}
}
}
// ReadFrameCopy reads and decodes the next frame (video or audio) and returns an owned frame wrapper.
//
// The returned wrapper owns its underlying frame; the caller MUST call Free() when done.
// Returns (nil, nil) on EOF.
func (d *Decoder) ReadFrameCopy() (*FrameWrapper, error) {
fw, err := d.ReadFrame()
if err != nil || fw == nil {
return nil, err
}
return fw.Copy()
}
// FlushDecoder flushes all decoder buffers.
func (d *Decoder) FlushDecoder() {
d.mu.Lock()
defer d.mu.Unlock()
if d.videoCodecCtx != nil {
avcodec.FlushBuffers(d.videoCodecCtx)
}
if d.audioCodecCtx != nil {
avcodec.FlushBuffers(d.audioCodecCtx)
}
}
// Seek seeks to a position in the file.
// The timestamp is specified as time.Duration from the start.
func (d *Decoder) Seek(ts time.Duration) error {
return d.SeekTimestamp(ts.Microseconds())
}
// SeekTimestamp seeks to a position in the file.
// timestamp is in AV_TIME_BASE (microseconds).
func (d *Decoder) SeekTimestamp(timestamp int64) error {
d.mu.Lock()
defer d.mu.Unlock()
if d.closed {
return errors.New("ffgo: decoder is closed")
}
// Seek to keyframe before target
if err := avformat.SeekFrame(d.formatCtx, -1, timestamp, avformat.SeekFlagBackward); err != nil {
return err
}
// Flush decoder buffers
if d.videoCodecCtx != nil {
avcodec.FlushBuffers(d.videoCodecCtx)
}
if d.audioCodecCtx != nil {
avcodec.FlushBuffers(d.audioCodecCtx)
}
return nil
}
// SeekTime is an alias for Seek for backwards compatibility.
// Deprecated: Use Seek instead.
func (d *Decoder) SeekTime(dur time.Duration) error {
return d.Seek(dur)
}
// Close releases all resources.
func (d *Decoder) Close() error {
d.mu.Lock()
defer d.mu.Unlock()
if d.closed {
return nil
}
d.closed = true
// Free frame
if d.frame != nil {
avutil.FrameFree(&d.frame)
}
// Free packet
if d.packet != nil {
avcodec.PacketFree(&d.packet)
}
// Free video codec context
if d.videoCodecCtx != nil {
avcodec.FreeContext(&d.videoCodecCtx)
}
// Free audio codec context
if d.audioCodecCtx != nil {
avcodec.FreeContext(&d.audioCodecCtx)
}
// Clear deprecated field
d.codecCtx = nil
// Close input
if d.formatCtx != nil {
avformat.CloseInput(&d.formatCtx)
}
// Cleanup any extra resources (e.g. custom I/O, temp files).
if d.cleanup != nil {
d.cleanup()
d.cleanup = nil
}
if d.customIO != nil {
_ = d.customIO.Close()
d.customIO = nil
}
return nil
}