-
Notifications
You must be signed in to change notification settings - Fork 15
/
avcut.c
1753 lines (1471 loc) · 53.9 KB
/
avcut.c
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
/*
* avcut
*
* Copyright (C) 2015 Mario Kicherer (dev@kicherer.org)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* To inspect how ffmpeg would decode frames:
*
* ffprobe -show_frames -of compact -select_streams v:0 -show_entries \
* frame=key_frame,pkt_pts,pkt_dts,best_effort_timestamp,pkt_pts_time \
* <file>
*
* fmpeg -i <file> -c copy -bsf:v trace_headers -f null - 2>&1 | less
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <sys/stat.h>
#include <unistd.h>
#include <inttypes.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavcodec/bsf.h>
#include <libavutil/opt.h>
#define AVCUT_DUMP_CHAR(var, length) { size_t i; for (i=0; i<(length); i++) { printf("%x ", ((char*) (var))[i]); } printf("\n"); }
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(56,56,0)
#ifndef AV_CODEC_FLAG_GLOBAL_HEADER
#define AV_CODEC_FLAG_GLOBAL_HEADER CODEC_FLAG_GLOBAL_HEADER
#endif
#ifndef AV_CODEC_CAP_DELAY
#define AV_CODEC_CAP_DELAY CODEC_CAP_DELAY
#endif
#endif
#ifdef DEBUG
// only enable debug output for this file
#define av_log(null, level, fmt, ...) printf(fmt, ##__VA_ARGS__)
#endif
// buffer management struct for a stream
struct packet_buffer {
unsigned int stream_index;
char stop_reading_stream; // do we have all required packets for this stream?
AVPacket *pkts;
size_t n_pkts; // number of pkts in .pkts
AVFrame **frames;
size_t n_frames; // number of frames in .frames
size_t length; // allocated array length of .pkts and .frames
unsigned long duration_dropped_in_pkts; // accumulated duration of dropped packets
double next_dts; // DTS of the next packet that will be written
long last_pts; // store last PTS in case we're dealing with AVIs where the
// last two frames may have a zero DTS
};
struct profile {
char *preset;
char *tune;
char *x264opts;
};
// project state context
struct project {
AVFormatContext *in_fctx;
AVFormatContext *out_fctx;
char has_b_frames;
struct profile *profile;
const char *video_encoder;
unsigned int n_stream_ids; // number of streams in output file
unsigned int *stream_ids; // mapping of output stream to input stream
AVCodecContext **in_codec_ctx;
AVCodecContext **out_codec_ctx;
double *cuts; // [ first_excluded_frame, first_included_frame, ...]
size_t n_cuts;
double stop_after_ts; // stop after this timestamp
char stop_reading; // signal to stop reading new packets
char last_flush;
unsigned long size_diff; // accept packet size differences with this value
size_t video_packets_read;
size_t other_packets_read;
size_t video_packets_decoded;
size_t video_frames_encoded;
size_t video_packets_written;
size_t other_packets_written;
struct AVBSFContext *bsf_h264_to_annexb;
struct AVBSFContext *bsf_dump_extra;
};
// private data avcut may store with each AVCodecContext
struct codeccontext {
char h264_avcc_format; // flag: h264 stream with annexb = 0, or avcc = 1
};
#if (LIBAVCODEC_VERSION_MAJOR < 55) || \
( (LIBAVCODEC_VERSION_MAJOR == 55) && (LIBAVCODEC_VERSION_MINOR < 55) )
// backported function to fix compilation with versions < v2.3
void av_packet_rescale_ts(AVPacket *pkt, AVRational src_tb, AVRational dst_tb)
{
if (pkt->pts != AV_NOPTS_VALUE)
pkt->pts = av_rescale_q(pkt->pts, src_tb, dst_tb);
if (pkt->dts != AV_NOPTS_VALUE)
pkt->dts = av_rescale_q(pkt->dts, src_tb, dst_tb);
if (pkt->duration > 0)
pkt->duration = av_rescale_q(pkt->duration, src_tb, dst_tb);
#if FF_API_CONVERGENCE_DURATION
FF_DISABLE_DEPRECATION_WARNINGS
if (pkt->convergence_duration > 0)
pkt->convergence_duration = av_rescale_q(pkt->convergence_duration, src_tb, dst_tb);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
}
#endif
// encode a frame and write the resulting packet into the output file
int encode_write_frame(struct project *pr, struct packet_buffer *s, AVFrame *frame) {
AVPacket *enc_pkt;
AVPacket *enc_pkt2;
int ret;
AVStream *ostream = pr->out_fctx->streams[s->stream_index];
AVCodecContext *codec_ctx = pr->out_codec_ctx[s->stream_index];
if (frame) {
av_log(NULL, AV_LOG_DEBUG, "enc frame pts: %" PRId64 " pkt_pts: %" PRId64 " pkt_dts: %" PRId64 " pkt_size: %d type: %c to %f\n",
frame->pts, frame->best_effort_timestamp, frame->pkt_dts, frame->pkt_size, av_get_picture_type_char(frame->pict_type),
frame->pts * av_q2d(codec_ctx->time_base)
);
// we have to unset the pict_type as an encoder might react to it
frame->pict_type = AV_PICTURE_TYPE_NONE;
}
// we send no or one frame to the library and receive zero or more frames in return below
ret = avcodec_send_frame(codec_ctx, frame);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "avcodec_send_frame() failed: %s\n", av_err2str(ret));
return ret;
}
while (1) {
enc_pkt = av_packet_alloc();
if (!enc_pkt) {
av_log(NULL, AV_LOG_ERROR, "av_packet_alloc() failed\n");
return ret;
}
ret = avcodec_receive_packet(codec_ctx, enc_pkt);
if (ret == -EAGAIN || ret == AVERROR_EOF) {
return ret;
}
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "avcodec_receive_packet failed: %s (%d)\n", av_err2str(ret), ret);
return ret;
}
pr->video_frames_encoded++;
enc_pkt->stream_index = s->stream_index;
if (enc_pkt->duration == 0) {
enc_pkt->duration = codec_ctx->ticks_per_frame;
av_packet_rescale_ts(enc_pkt, codec_ctx->time_base, ostream->time_base);
}
enc_pkt->dts = s->next_dts;
s->next_dts += enc_pkt->duration;
// copy the header to the beginning of each key frame if we use a global header
if (codec_ctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
ret = av_bsf_send_packet(pr->bsf_dump_extra, enc_pkt);
if (ret) {
av_log(NULL, AV_LOG_ERROR, "error av_bsf_send_packet(): %d\n", ret);
}
while (1) {
enc_pkt2 = av_packet_alloc();
if (!enc_pkt2) {
av_log(NULL, AV_LOG_ERROR, "av_packet_alloc() failed\n");
return ret;
}
ret = av_bsf_receive_packet(pr->bsf_dump_extra, enc_pkt2);
if (ret == -EAGAIN) {
break;
}
if (ret == AVERROR_EOF)
break;
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "av_bsf_receive_packet() failed: %s\n", av_err2str(ret));
exit(1);
}
av_log(NULL, AV_LOG_DEBUG,
"write video pkt (filtered), enc size: %d pts: %" PRId64 " dts: %" PRId64 " - to %f\n",
enc_pkt2->size, enc_pkt2->pts, enc_pkt2->dts,
enc_pkt2->pts*ostream->time_base.num/(double)ostream->time_base.den);
pr->video_packets_written++;
ret = av_interleaved_write_frame(pr->out_fctx, enc_pkt2);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "error while writing packet, error %d\n", ret);
return ret;
}
av_frame_free(&frame);
// TODO av_frame_unref?
av_packet_free(&enc_pkt);
av_packet_free(&enc_pkt2);
}
if (ret == -EAGAIN) {
continue;
}
} else {
av_log(NULL, AV_LOG_DEBUG,
"write video pkt, enc size: %d pts: %" PRId64 " dts: %" PRId64 " - to %f\n",
enc_pkt->size, enc_pkt->pts, enc_pkt->dts,
enc_pkt->pts*ostream->time_base.num/(double)ostream->time_base.den);
pr->video_packets_written++;
ret = av_interleaved_write_frame(pr->out_fctx, enc_pkt);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "error while writing packet, error %d\n", ret);
return ret;
}
av_frame_free(&frame);
// TODO av_frame_unref?
av_packet_free(&enc_pkt);
}
}
return 0;
}
// calculate stream timestamp of frame using its PTS
double frame_pts2ts(struct project *pr, struct packet_buffer *s, AVFrame *frame) {
return frame->pts * av_q2d(pr->in_codec_ctx[s->stream_index]->time_base);
}
// check if pkt/frame at timestamp $ts shall be included
char ts_included(struct project *pr, double ts) {
size_t i;
// check if timestampe lies in a cut interval
for (i=0; i < pr->n_cuts; i+=2) {
if (pr->cuts[i] <= ts && ts < pr->cuts[i+1])
return 0;
// list is ordered
if (ts < pr->cuts[i])
return 1;
}
return 1;
}
#define BUF_COPY_COMPLETE (1<<0)
#define BUF_DROP_COMPLETE (1<<1)
#define BUF_CUT_IN_BETWEEN (1<<2)
// check if the complete buffer will be used or if a cutpoint lies in this interval
char get_buffer_processing_mode(struct project *pr, struct packet_buffer *s, unsigned long last_iframe) {
double buf_start, buf_end;
size_t i;
char rv;
if (!last_iframe) {
buf_start = s->pkts[0].pts * av_q2d(pr->in_fctx->streams[s->stream_index]->time_base);
buf_end = s->pkts[s->n_pkts-1].pts * av_q2d(pr->in_fctx->streams[s->stream_index]->time_base);
} else {
buf_start = frame_pts2ts(pr, s, s->frames[0]);
buf_end = frame_pts2ts(pr, s, s->frames[last_iframe]);
}
rv = 0;
for (i=0; i < pr->n_cuts; i++) {
// check if any cutpoint lies between buffer start and end
if (buf_start < pr->cuts[i] && pr->cuts[i] < buf_end)
rv = BUF_CUT_IN_BETWEEN;
// check if buffer lies between cutpoints
if (pr->cuts[i] <= buf_start && buf_end <= pr->cuts[i+1]) {
if (i % 2 == 0)
rv = BUF_DROP_COMPLETE;
else
rv = BUF_COPY_COMPLETE;
}
// stop this loop if further cuts lie behind current buffer
if (buf_end < pr->cuts[i])
rv = BUF_COPY_COMPLETE;
if (rv)
break;
}
// if we are past all cutpoints, copy the remaining video
if (rv == 0)
rv = BUF_COPY_COMPLETE;
av_log(NULL, AV_LOG_DEBUG, "check buffer stream %u: %f to %f -> %s\n",
s->stream_index, buf_start, buf_end,
(rv == BUF_COPY_COMPLETE ? "copy": (rv == BUF_DROP_COMPLETE ? "drop": "cut in between"))
);
return rv;
}
char find_packet_for_frame(struct project *pr, struct packet_buffer *s, size_t frame_idx, size_t *packet_idx) {
size_t i;
for (i=0;i<s->n_pkts;i++) {
// we cannot compare packet.dts with frame.pkt_dts as they differ by 2 (maybe caused by multithreading)
if (
(s->pkts[i].pts != AV_NOPTS_VALUE &&
s->pkts[i].pts == s->frames[frame_idx]->best_effort_timestamp) ||
(s->pkts[i].pts == AV_NOPTS_VALUE && s->pkts[i].dts == AV_NOPTS_VALUE &&
s->frames[frame_idx]->pkt_size == s->pkts[i].size - pr->size_diff)
)
{
// libav is missing pkt_size
if (s->frames[frame_idx]->pkt_size != s->pkts[i].size - pr->size_diff) {
av_log(NULL, AV_LOG_ERROR,
"size mismatch %zu:%d %zu:%d (diff: %lu, try: %d)\n",
frame_idx, s->frames[frame_idx]->pkt_size, i,
s->pkts[i].size, pr->size_diff,
s->pkts[i].size - s->frames[frame_idx]->pkt_size);
continue;
}
*packet_idx = i;
return 1;
}
}
av_log(NULL, AV_LOG_ERROR, "packet for frame %zu not found\n",
frame_idx);
for (i=0;i<s->n_pkts;i++) {
av_log(NULL, AV_LOG_DEBUG, "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " - %d %d (NOPTS: %" PRId64 ")\n",
s->pkts[i].pts, s->pkts[i].dts, s->frames[frame_idx]->pkt_dts,
s->frames[frame_idx]->best_effort_timestamp,
s->frames[frame_idx]->pkt_size, s->pkts[i].size,
AV_NOPTS_VALUE);
}
return 0;
}
int open_encoder(struct project *pr, unsigned int enc_stream_idx) {
unsigned int i;
int ret;
AVStream *out_stream;
AVCodecContext *dec_cctx, *enc_cctx;
const AVCodec *encoder;
i = pr->stream_ids[enc_stream_idx];
// if (pr->in_fctx->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC)
// continue;
dec_cctx = pr->in_codec_ctx[i];
out_stream = avformat_new_stream(pr->out_fctx, NULL);
if (!out_stream) {
av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
return AVERROR_UNKNOWN;
}
// NOTE setting this will cause segfaults during app cleanup later, looks
// like it's automatically registered
if (0)
pr->out_fctx->streams[enc_stream_idx] = out_stream;
// copy stream metadata
av_dict_copy(&out_stream->metadata, pr->in_fctx->streams[i]->metadata, 0);
if (dec_cctx->codec_type == AVMEDIA_TYPE_VIDEO) {
if (!pr->video_encoder) {
encoder = avcodec_find_encoder(dec_cctx->codec_id);
} else {
encoder = avcodec_find_encoder_by_name(pr->video_encoder);
if (!encoder) {
const AVCodecDescriptor *desc;
desc = avcodec_descriptor_get_by_name(pr->video_encoder);
if (desc)
encoder = avcodec_find_encoder(desc->id);
}
}
if (!encoder) {
av_log(NULL, AV_LOG_ERROR, "Encoder not found (%s)\n", pr->video_encoder?pr->video_encoder:"");
return AVERROR_INVALIDDATA;
}
} else {
encoder = NULL;
}
enc_cctx = avcodec_alloc_context3(encoder);
if (!enc_cctx) {
av_log(NULL, AV_LOG_ERROR, "Failed to alloc video decoder context\n");
return AVERROR_UNKNOWN;
}
ret = avcodec_parameters_copy(out_stream->codecpar, pr->in_fctx->streams[i]->codecpar);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to copy codec parameters to decoder context\n");
return AVERROR_UNKNOWN;
}
out_stream->time_base = pr->in_fctx->streams[i]->time_base;
ret = avcodec_parameters_to_context(enc_cctx, out_stream->codecpar);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to copy codec parameters to decoder context\n");
return AVERROR_UNKNOWN;
}
pr->out_codec_ctx[enc_stream_idx] = enc_cctx;
if (dec_cctx->codec_type == AVMEDIA_TYPE_VIDEO) {
enc_cctx->time_base = dec_cctx->time_base;
enc_cctx->ticks_per_frame = dec_cctx->ticks_per_frame;
enc_cctx->delay = dec_cctx->delay;
enc_cctx->width = dec_cctx->width;
enc_cctx->height = dec_cctx->height;
enc_cctx->pix_fmt = dec_cctx->pix_fmt;
enc_cctx->sample_aspect_ratio = dec_cctx->sample_aspect_ratio;
enc_cctx->color_primaries = dec_cctx->color_primaries;
enc_cctx->color_trc = dec_cctx->color_trc;
enc_cctx->colorspace = dec_cctx->colorspace;
enc_cctx->color_range = dec_cctx->color_range;
enc_cctx->chroma_sample_location = dec_cctx->chroma_sample_location;
enc_cctx->profile = dec_cctx->profile;
enc_cctx->level = dec_cctx->level;
if (pr->profile) {
av_log(NULL, AV_LOG_INFO, "Settings from profile:\n");
av_log(NULL, AV_LOG_INFO, " Preset: %s\n", pr->profile->preset);
av_log(NULL, AV_LOG_INFO, " Tune: %s\n", pr->profile->tune);
av_log(NULL, AV_LOG_INFO, " x264opts: %s\n", pr->profile->x264opts);
av_opt_set(enc_cctx->priv_data, "preset", pr->profile->preset, AV_OPT_SEARCH_CHILDREN);
av_opt_set(enc_cctx->priv_data, "tune", pr->profile->tune, AV_OPT_SEARCH_CHILDREN);
av_opt_set(enc_cctx->priv_data, "x264opts", pr->profile->x264opts, AV_OPT_SEARCH_CHILDREN);
} else {
// TODO good values?
enc_cctx->qmin = 16;
enc_cctx->qmax = 26;
enc_cctx->max_qdiff = 4;
}
if (dec_cctx->has_b_frames) {
enc_cctx->max_b_frames = 3;
if (pr->has_b_frames < dec_cctx->has_b_frames)
pr->has_b_frames = dec_cctx->has_b_frames;
}
// enc_cctx->keyint_min = 200;
// enc_cctx->gop_size = 250;
enc_cctx->thread_count = 1; // spawning more threads causes avcodec_close to free threads multiple times
enc_cctx->codec_tag = 0; // reset tag to avoid incompatibilities while changing container
out_stream->sample_aspect_ratio = pr->in_fctx->streams[i]->sample_aspect_ratio;
// we do not want a global header, we need the data "in stream" as the
// resulting stream is a concatenation of streams with (possibly)
// different properties
if (0)
if (pr->out_fctx->oformat->flags & AVFMT_GLOBALHEADER)
enc_cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
ret = avcodec_open2(enc_cctx, encoder, NULL);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to open encoder for stream %u, error %d\n", i, ret);
return ret;
}
} else if (dec_cctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
av_log(NULL, AV_LOG_ERROR, "Error: input stream #%d is of unknown type\n", i);
avcodec_free_context(&dec_cctx);
avcodec_free_context(&enc_cctx);
return AVERROR_INVALIDDATA;
} else {
AVCodecParameters params = {0};
ret = avcodec_parameters_from_context(¶ms, dec_cctx);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to copy codec parameters 1\n");
avcodec_free_context(&dec_cctx);
avcodec_free_context(&enc_cctx);
return ret;
}
ret = avcodec_parameters_to_context(enc_cctx, ¶ms);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to copy codec parameters 2\n");
avcodec_free_context(&dec_cctx);
avcodec_free_context(&enc_cctx);
return ret;
}
enc_cctx->codec_tag = 0;
if (pr->out_fctx->oformat->flags & AVFMT_GLOBALHEADER)
enc_cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
// We have to call this here as avformat_write_header() changes the time_base
// and if we reopen the encoder we do not call that fct again to set the same
// time base as before.
ret = avformat_init_output(pr->out_fctx, 0);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "avformat_init_output failed: %s\n", av_err2str(ret));
return ret;
}
return 0;
}
// process packet buffer - either copy, ignore or reencode packets in the packet buffer according to the cut list
void flush_packet_buffer(struct project *pr, struct packet_buffer *s, char last_flush) {
size_t i, j, last_pkt;
int ret;
char buffer_mode = 0;
double ts;
size_t last_frame;
if (!s->pkts || s->n_pkts == 0)
return;
if (pr->in_fctx->streams[s->stream_index]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
// check if we can copy/drop the complete buffer or if we have to check each packet individually
buffer_mode = get_buffer_processing_mode(pr, s, 0);
for (i=0;i<s->n_pkts;i++) {
ts = s->pkts[i].pts * av_q2d(pr->in_fctx->streams[s->stream_index]->time_base);
if (pr->stop_after_ts < ts)
s->stop_reading_stream = 1;
if ( !( buffer_mode & BUF_DROP_COMPLETE) &&
( (buffer_mode & BUF_COPY_COMPLETE) || ts_included(pr, ts) )
)
{
s->pkts[i].pts -= s->duration_dropped_in_pkts;
// calculate duration precisely to avoid deviation between PTS and DTS
double dur = s->pkts[i].duration * av_q2d(pr->in_fctx->streams[s->stream_index]->time_base) /
av_q2d( pr->out_fctx->streams[s->stream_index]->time_base);
av_packet_rescale_ts(&s->pkts[i], pr->in_fctx->streams[s->stream_index]->time_base,
pr->out_fctx->streams[s->stream_index]->time_base);
#define ROUND(x) ((int64_t)((x)+0.5))
s->pkts[i].dts = ROUND(s->next_dts);
s->next_dts += dur;
av_log(NULL, AV_LOG_DEBUG,
"write stream %d copy, pts: %" PRId64 " dts: %" PRId64 " - %f to %f\n",
s->stream_index, s->pkts[i].pts, s->pkts[i].dts, ts,
s->pkts[i].pts * av_q2d(pr->out_fctx->streams[s->stream_index]->time_base));
pr->other_packets_written++;
ret = av_interleaved_write_frame(pr->out_fctx, &s->pkts[i]);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "error while writing packet, error %d\n", ret);
exit(ret);
}
} else {
s->duration_dropped_in_pkts += s->pkts[i].duration;
}
av_packet_unref(&s->pkts[i]);
}
s->n_pkts = 0;
return;
}
if (s->n_frames > 1) {
// If this is the last flush, process all frames. If not, ignore the last
// frame (that is an I frame) as we process it during the next buffer flush
if (last_flush)
last_frame = s->n_frames-1;
else
last_frame = s->n_frames-2;
// check if we can copy the complete buffer or if we have to check each packet individually
buffer_mode = get_buffer_processing_mode(pr, s, last_frame);
} else {
buffer_mode = BUF_COPY_COMPLETE;
}
// determine the last packet we have to look at for this GOP
if (last_flush) {
// we consider all packets during the last flush
last_pkt = s->n_pkts-1;
} else {
// find the packet with the highest DTS in this GOP
/*
* The packet that belongs to the last frame in a GOP might not have
* the highest DTS of the GOP's packets. Hence, we search backwards
* for the packet with the highest DTS. Otherwise, we might miss packets,
* e.g., if the last frame is a P frame, its DTS is lower as the DTS
* of the preceding B frames.
*
* We stop with the search if we have found two P frames or after a
* B frame and a P frame has been found.
*/
size_t pkt_idx;
char b_found = 0;
char n_p_frames = 0;
last_pkt = 0;
for (i = s->n_frames-2; i > 0; i--) {
if (s->frames[i]->pict_type == AV_PICTURE_TYPE_B)
b_found=1;
if (s->frames[i]->pict_type == AV_PICTURE_TYPE_P) {
n_p_frames++;
if (b_found || n_p_frames > 2)
break;
}
if (!find_packet_for_frame(pr, s, i, &pkt_idx))
exit(1);
if (pkt_idx > last_pkt)
last_pkt = pkt_idx;
}
if (buffer_mode & BUF_CUT_IN_BETWEEN) {
// if we encode all frames we don't need the original packets
for (i=0;i<=last_pkt;i++)
av_packet_unref(&s->pkts[i]);
}
}
// TODO: check if we can simply cut if the last frame is a P-frame?
if (buffer_mode & BUF_CUT_IN_BETWEEN) {
char frame_written = 0;
// check which frames will be included and encode them
for (i=0;i<s->n_frames-1;i++) {
if (!s->frames[i]) {
av_log(NULL, AV_LOG_ERROR, "no frame %zu\n", i);
exit(1);
}
ts = frame_pts2ts(pr, s, s->frames[i]);
// calculate the output PTS from the input PTS by substracting the
// number of dropped frames which we calculate by rescaling from
// the number of dropped packets (stream- to codec timebase)
s->frames[i]->pts -= av_rescale_q(s->duration_dropped_in_pkts,
pr->in_fctx->streams[s->stream_index]->time_base,
pr->in_codec_ctx[s->stream_index]->time_base);
if (pr->stop_after_ts < ts)
s->stop_reading_stream = 1;
if (ts_included(pr, ts)) {
ret = encode_write_frame(pr, s, s->frames[i]);
if (ret == -EAGAIN) {
// ignore, no complete pkt to write yet
} else
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "encode_write_frame failed: %s\n", av_err2str(ret));
exit(ret);
}
frame_written = 1;
} else {
#if (LIBAVUTIL_VERSION_MAJOR >= 59)
s->duration_dropped_in_pkts += av_rescale_q(s->frames[i]->duration,
pr->in_codec_ctx[s->stream_index]->time_base,
pr->in_fctx->streams[s->stream_index]->time_base);
#else
s->duration_dropped_in_pkts += s->frames[i]->pkt_duration;
#endif
av_frame_free(&s->frames[i]);
}
}
// if the encoder emits packets delayed in time, flush the encoder to receive all remaining packets in the queue
if (frame_written && pr->out_codec_ctx[s->stream_index]->codec->capabilities & AV_CODEC_CAP_DELAY) {
av_log(NULL, AV_LOG_DEBUG, "Local flushing stream #%u\n", s->stream_index);
while (1) {
ret = encode_write_frame(pr, s, 0);
if (ret == AVERROR_EOF) {
av_log(NULL, AV_LOG_DEBUG, "flush end\n");
break;
}
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "encode_write_frame failed, error %d: %s\n", ret, av_err2str(ret));
exit(ret);
}
}
}
if (frame_written) {
// Some encoders do not like new frames after we flushed them.
// Hence, we restart the encoder.
AVCodecContext *out_cctx = pr->out_codec_ctx[s->stream_index];
// if the encoder does not support a restart after a flush, we have
// to close and reopen the encoder
#ifndef AV_CODEC_CAP_ENCODER_FLUSH
#define AV_CODEC_CAP_ENCODER_FLUSH 0
#endif
if (out_cctx->codec->capabilities & AV_CODEC_CAP_ENCODER_FLUSH) {
avcodec_flush_buffers(out_cctx);
} else {
avcodec_close(out_cctx);
ret = open_encoder(pr, s->stream_index);
if (ret) {
av_log(NULL, AV_LOG_ERROR, "reopening encoder failed\n");
exit(1);
}
}
}
} else
if (buffer_mode & BUF_COPY_COMPLETE) {
for (i=0;i<=last_pkt;i++) {
AVFrame *frame;
// find frame for current packet to determine the PTS
frame = 0;
for (j=0;j<s->n_frames;j++) {
if (
(s->pkts[i].pts != AV_NOPTS_VALUE &&
s->pkts[i].pts == s->frames[j]->best_effort_timestamp) ||
(s->pkts[i].pts == AV_NOPTS_VALUE && s->pkts[i].dts == AV_NOPTS_VALUE &&
s->frames[j]->pkt_size == s->pkts[i].size - pr->size_diff)
)
{
// libav is missing pkt_size
if (s->frames[j]->pkt_size != s->pkts[i].size - pr->size_diff) {
av_log(NULL, AV_LOG_ERROR,
"size mismatch %zu:%d %zu:%d (diff %lu, dts %" PRId64 ")\n",
j, s->frames[j]->pkt_size, i, s->pkts[i].size, - pr->size_diff, s->pkts[i].dts);
continue;
}
frame = s->frames[j];
break;
}
}
if (!frame) {
av_log(NULL, AV_LOG_ERROR,
"frame for pkt #%zd (dts %" PRId64 " pts %" PRId64 ") not found\n",
i, s->pkts[i].dts, s->pkts[i].pts);
av_log(NULL, AV_LOG_DEBUG, "pkt_pts pkt_dts frame->pkt_dts frame->pts frame->best_eff - frame->pkt_size pkt_size - cpn\n");
for (j=0;j<s->n_frames;j++) {
av_log(NULL, AV_LOG_DEBUG, "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " - %6d %6d - type: %c (NOPTS: %" PRId64 ")\n",
s->pkts[i].pts, s->pkts[i].dts, s->frames[j]->pkt_dts,
s->frames[j]->pts,
s->frames[j]->best_effort_timestamp,
s->frames[j]->pkt_size, s->pkts[i].size,
av_get_picture_type_char(s->frames[j]->pict_type),
AV_NOPTS_VALUE);
}
// TODO should we continue und discard this pkt as it may provide
// a frame we do not use? An example to verify this is needed.
exit(1);
// s->pkts[i].size = 0;
// continue;
}
ts = frame_pts2ts(pr, s, frame);
if (pr->stop_after_ts < ts)
s->stop_reading_stream = 1;
if (ts_included(pr, ts)) {
AVPacket *pkt;
// rescale the frame PTS to packet PTS
s->pkts[i].pts = av_rescale_q(frame->pts,
pr->in_codec_ctx[s->stream_index]->time_base,
pr->in_fctx->streams[s->stream_index]->time_base);
// now we can just substract the number of dropped packets
s->pkts[i].pts -= s->duration_dropped_in_pkts;
// switch from input timebase to output timebase
av_packet_rescale_ts(&s->pkts[i], pr->in_fctx->streams[s->stream_index]->time_base,
pr->out_fctx->streams[s->stream_index]->time_base);
s->pkts[i].dts = s->next_dts;
s->next_dts += s->pkts[i].duration;
// if the original h264 stream is in AVCC format, convert it to Annex B
if (pr->in_codec_ctx[s->stream_index]->opaque &&
((struct codeccontext*) pr->in_codec_ctx[s->stream_index]->opaque)->h264_avcc_format)
{
ret = av_bsf_send_packet(pr->bsf_h264_to_annexb, &s->pkts[i]);
if (ret) {
av_log(NULL, AV_LOG_ERROR, "error av_bsf_send_packet(bsf_h264_to_annexb): %d\n", ret);
}
while (1) {
pkt = av_packet_alloc();
if (!pkt) {
av_log(NULL, AV_LOG_ERROR, "av_packet_alloc() failed\n");
exit(1);
}
ret = av_bsf_receive_packet(pr->bsf_h264_to_annexb, pkt);
if (ret == -EAGAIN) {
break;
}
if (ret == AVERROR_EOF)
break;
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "av_bsf_receive_packet(bsf_h264_to_annexb) failed: %s\n", av_err2str(ret));
exit(1);
}
av_log(NULL, AV_LOG_DEBUG,
"write v cpy pkt_size: %d pkt_pts: %" PRId64 " pkt_dts: %" PRId64 " - frame pts %" PRId64 " - %f to %f\n",
pkt->size, pkt->pts, pkt->dts, frame->pts, ts,
pkt->pts * pr->out_fctx->streams[s->stream_index]->time_base.num /
(double)pr->out_fctx->streams[s->stream_index]->time_base.den
);
pr->video_packets_written++;
ret = av_interleaved_write_frame(pr->out_fctx, pkt);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "error while writing packet, error %d\n", ret);
exit(ret);
}
av_packet_free(&pkt);
}
if (ret == -EAGAIN) {
continue;
}
}
av_log(NULL, AV_LOG_DEBUG,
"write v cpy pkt_size: %d pkt_pts: %" PRId64 " pkt_dts: %" PRId64 " - frame pts %" PRId64 " - %f to %f\n",
s->pkts[i].size, s->pkts[i].pts, s->pkts[i].dts, frame->pts, ts,
s->pkts[i].pts * pr->out_fctx->streams[s->stream_index]->time_base.num /
(double)pr->out_fctx->streams[s->stream_index]->time_base.den
);
pr->video_packets_written++;
ret = av_interleaved_write_frame(pr->out_fctx, &s->pkts[i]);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "error while writing packet, error %d\n", ret);
exit(ret);
}
} else {
s->duration_dropped_in_pkts += s->pkts[i].duration;
}
av_packet_unref(&s->pkts[i]);
}
for (j=0;j<s->n_frames-1;j++)
av_frame_free(&s->frames[j]);
} else {
for (i=0;i<=last_pkt;i++) {
s->duration_dropped_in_pkts += s->pkts[i].duration;
av_packet_unref(&s->pkts[i]);
}
for (j=0;j<s->n_frames-1;j++)
av_frame_free(&s->frames[j]);
}
// update buffer structures
AVPacket *newpkts = (AVPacket*) av_realloc(0, sizeof(AVPacket)*s->length);
j = 0;
for (i=0;i<s->n_pkts;i++) {
if (s->pkts[i].size != 0 && s->pkts[i].data != NULL) {
memcpy(&newpkts[j], &s->pkts[i], sizeof(AVPacket));
j++;
}
}
av_freep(&s->pkts);
s->pkts = newpkts;
s->n_pkts = j;
s->frames[0] = s->frames[s->n_frames-1];
s->n_frames = 1;
}
// decode a video packet and store it in the buffer
int decode_packet(struct project *pr, struct packet_buffer *sbuffer, unsigned int stream_index, AVPacket *packet) {
enum AVMediaType mtype;
int ret, i;
AVFrame *frame = NULL;
AVPacket nullpacket = { .data = NULL, .size = 0 };
if (!packet)
packet = &nullpacket;
mtype = pr->in_fctx->streams[stream_index]->codecpar->codec_type;
if (mtype == AVMEDIA_TYPE_VIDEO) {
av_log(NULL, AV_LOG_DEBUG, "dec packet %" PRId64 " %" PRId64 " %d\n",
packet->pts, packet->dts, packet->size);
// similar to encoding, we can send zero or one packet and get zero or more frames in return
ret = avcodec_send_packet(pr->in_codec_ctx[stream_index], packet);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "avcodec_send_packet() failed: %d\n", ret);
return ret;
}
while (1) {
if (!(frame = av_frame_alloc())) {
av_log(NULL, AV_LOG_ERROR, "error while allocating frame\n");
return AVERROR(ENOMEM);
}
ret = avcodec_receive_frame(pr->in_codec_ctx[stream_index], frame);
if (ret == -EAGAIN || ret == AVERROR_EOF) {
av_frame_free(&frame);
return 0;
}
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "avcodec_receive_frame failed: %s\n", av_err2str(ret));
av_frame_free(&frame);
return ret;
}
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(56,56,0)
av_log(NULL, AV_LOG_DEBUG, "dec frame pts: %" PRId64 " pkt_pts: %" PRId64 " pkt_dts: %" PRId64 " pkt_size: %d type: %c from %f\n",
frame->pts, frame->pkt_pts, frame->pkt_dts, frame->pkt_size, av_get_picture_type_char(frame->pict_type),
frame->pts*av_q2d(pr->in_fctx->streams[stream_index]->codec->time_base)
);
#endif
sbuffer[stream_index].frames[sbuffer[stream_index].n_frames] = frame;
sbuffer[stream_index].n_frames++;
pr->video_packets_decoded++;
frame->pts = frame->best_effort_timestamp;
// if pts is set from pkt_dts (e.g., through ->best_effort_timestamp),
// convert from packet (/stream) to frame (/codec) time_base
if (frame->pts == frame->pkt_dts)
frame->pts = av_rescale_q(frame->pkt_dts,
pr->in_fctx->streams[stream_index]->time_base,
pr->in_codec_ctx[stream_index]->time_base
);