Repository navigation
Expand file tree
/
Copy pathffmodule.cpp
More file actions
1332 lines (1158 loc) · 36.1 KB
/
Copy pathffmodule.cpp
File metadata and controls
1332 lines (1158 loc) · 36.1 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
#include "ffmodule.h"
enum AVPixelFormat hw_pix_fmt;
ffmodule::ffmodule()
{
//_format_context = avformat_alloc_context();
}
ffmodule::~ffmodule()
{
//avformat_close_input(&_format_context);
}
/*Public*/
static enum AVPixelFormat get_hw_format(AVCodecContext* ctx, const enum AVPixelFormat* pix_fmts)
{
const enum AVPixelFormat* p;
for (p = pix_fmts; *p != -1; p++)
{
if (*p == hw_pix_fmt)
return *p;
}
return AV_PIX_FMT_NONE;
}
MediaInfo ffmodule::GetMediaInfo(std::string inputfile)
{
MediaInfo ret;
AVFormatContext* _format_context = NULL;
if ((ret.ret.ret_code = avformat_open_input(&_format_context, inputfile.c_str(), NULL, NULL)) < 0)
{
ret.ret.ret_str = "Cannot open file.";
return ret;
}
if ((ret.ret.ret_code = avformat_find_stream_info(_format_context, NULL)) < 0)
{
ret.ret.ret_str = "Cannot find stream information.";
return ret;
}
ret.video_bitrate = _format_context->bit_rate / 1000.0;//Bitrate Kbit/s(also Kbps)
ret.duration = _format_context->duration / 1000000.0;//Duration s
for (unsigned int i = 0; i < _format_context->nb_streams; i++)
{
AVStream* input_stream = _format_context->streams[i];
if (input_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
{
ret.video_framerate = (float)input_stream->avg_frame_rate.num / input_stream->avg_frame_rate.den;
AVCodecParameters* codec_par = input_stream->codecpar;
ret.width = codec_par->width;
ret.height = codec_par->height;
ret.video_frames = input_stream->nb_frames;
AVCodecContext* avctx_video;
avctx_video = avcodec_alloc_context3(NULL);
ret.ret.ret_code = avcodec_parameters_to_context(avctx_video, codec_par);
if (ret.ret.ret_code < 0)
{
ret.ret.ret_str = "Video avcodec_parameters_to_context() failed.";
avcodec_free_context(&avctx_video);
return ret;
}
char buf[128];
avcodec_string(buf, sizeof(buf), avctx_video, 0);
ret.video_encodename = avcodec_get_name((codec_par->codec_id));
avcodec_free_context(&avctx_video);
}
else if (input_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
{
AVCodecParameters* codec_par = input_stream->codecpar;
AVCodecContext* avctx_audio;
avctx_audio = avcodec_alloc_context3(NULL);
ret.ret.ret_code = avcodec_parameters_to_context(avctx_audio, codec_par);
if (ret.ret.ret_code < 0)
{
ret.ret.ret_str = "Audio avcodec_parameters_to_context() failed.";
avcodec_free_context(&avctx_audio);
return ret;
}
ret.audio_encodename = avcodec_get_name(avctx_audio->codec_id);
ret.audio_bitrate = codec_par->bit_rate / 1000.0;
ret.audio_channels = codec_par->channels;
ret.sample_rate = codec_par->sample_rate;
avcodec_free_context(&avctx_audio);
}
}
avformat_close_input(&_format_context);
return ret;
}
ReturnInfo ffmodule::Frame2PNG(AVFrame* pFrame, std::string out_file)
{
ReturnInfo ret;
AVFormatContext* pFormatCtx = NULL;
AVStream* video_st = NULL;
AVCodecContext* pCodecCtx = NULL;
AVCodec* pCodec = NULL;
AVPacket* pkt = NULL;
pFormatCtx = avformat_alloc_context();
ret.ret_code = avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file.c_str());
if (ret.ret_code < 0)
{
ret.ret_str = "avformat_alloc_output_context2() failed.";
return ret;
}
AVFrame* rgbFrame = av_frame_alloc();
rgbFrame->width = pFrame->width;
rgbFrame->height = pFrame->height;
rgbFrame->format = AV_PIX_FMT_RGB24;
struct SwsContext* swCtx = sws_getContext(
pFrame->width,
pFrame->height,
AVPixelFormat(pFrame->format),
pFrame->width,
pFrame->height,
AV_PIX_FMT_RGB24,
SWS_GAUSS, 0, 0, 0);
av_image_alloc(rgbFrame->data, rgbFrame->linesize, pFrame->width, pFrame->height, AV_PIX_FMT_RGB24, 1);
sws_scale(swCtx, pFrame->data, pFrame->linesize, 0, pFrame->height, rgbFrame->data, rgbFrame->linesize);
pCodecCtx = avcodec_alloc_context3(NULL);
pCodecCtx->codec_id = AV_CODEC_ID_PNG;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->pix_fmt = AV_PIX_FMT_RGB24;
pCodecCtx->width = pFrame->width;
pCodecCtx->height = pFrame->height;
pCodecCtx->time_base = { 1, 30 };
pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
if (!pCodec)
{
ret.ret_str = "Encodec not found.";
ret.ret_code = -1;
return ret;
}
ret.ret_code = avcodec_open2(pCodecCtx, pCodec, NULL);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
return ret;
}
// start encoder
ret.ret_code = avcodec_send_frame(pCodecCtx, rgbFrame);
if (ret.ret_code < 0)
{
ret.ret_str = "avcodec_send_frame() failed.";
return ret;
}
pkt = av_packet_alloc();
av_new_packet(pkt, pFrame->width * pFrame->height * 3);
//Read encoded data from the encoder.
ret.ret_code = avcodec_receive_packet(pCodecCtx, pkt);
if (ret.ret_code < 0)
{
ret.ret_str = "avcodec_receive_packet() failed.";
return ret;
}
video_st = avformat_new_stream(pFormatCtx, 0);
//Write Header
avformat_write_header(pFormatCtx, NULL);
//Write body
av_write_frame(pFormatCtx, pkt);
//Write Trailer
av_write_trailer(pFormatCtx);
avcodec_close(pCodecCtx);
av_freep(&rgbFrame->data[0]);
av_frame_free(&rgbFrame); //av_frame_alloc()
av_packet_free(&pkt); //av_packet_alloc()
avformat_free_context(pFormatCtx); //avformat_alloc_context()
sws_freeContext(swCtx);
pkt = NULL;
rgbFrame = NULL;
pFormatCtx = NULL;
return ret;
}
ReturnInfo ffmodule::SeparateFrames(std::string inputfile, std::string output, int startframe, int framecount, enum AVHWDeviceType decoder)
{
ReturnInfo ret; //Return information.
AVFormatContext* pFormatCtx = NULL; //ffmpeg format context.
AVStream* video_st = NULL; //ffmpeg stream.
AVCodecContext* pCodecCtx = NULL; //ffmpeg codec context.
AVCodec* pCodec = NULL; //ffmpeg codec.
AVPacket* packet = (AVPacket*)av_malloc(sizeof(AVPacket)); //ffmpeg packet.
AVFrame* pFrame = av_frame_alloc(), //ffmpeg frame, recive from packet.
* hw_frame = av_frame_alloc(), //ffmpeg frame, store frame datas transfered from device
* tmp_frame = NULL; //ffmpeg frame, store frame temporary.
AVBufferRef* hw_device_ctx = NULL; //ffmpeg buffer reference.
int frame_read = 0, //av_read_frame counter.
frame_process = 0; //Frames after processing.
int v_stream_idx = -1; //Stream ID from ffmpeg format context.
ret.ret_code = avformat_open_input(&pFormatCtx, inputfile.c_str(), NULL, NULL);
if (ret.ret_code != 0)
{
ret.ret_str = "avformat_open_input() failed.";
goto end;
}
ret.ret_code = avformat_find_stream_info(pFormatCtx, NULL);
if(ret.ret_code < 0)
{
ret.ret_str = "Cannot find input stream information.";
goto end;
}
/* find the video stream information */
v_stream_idx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0);
if (v_stream_idx < 0)
{
ret.ret_str = "Cannot find a video stream in the input file";
ret.ret_code = -1;
goto end;
}
if (startframe < 0 || startframe > pFormatCtx->streams[v_stream_idx]->nb_frames)
{
ret.ret_str = "Startframe out of range.";
ret.ret_code = -1;
goto end;
}
if (decoder != AV_HWDEVICE_TYPE_NONE)
{
for (int i = 0;; i++)
{
const AVCodecHWConfig* config = avcodec_get_hw_config(pCodec, i);
if (!config)
{
ret.ret_code = -1;
ret.ret_str = string_format("Decoder %s does not support device type %s.\n", pCodec->name, av_hwdevice_get_type_name(decoder));
goto end;
}
if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == decoder)
{
hw_pix_fmt = config->pix_fmt;
break;
}
}
}
pCodecCtx = avcodec_alloc_context3(pCodec);
video_st = pFormatCtx->streams[v_stream_idx];
avcodec_parameters_to_context(pCodecCtx, video_st->codecpar);
if (decoder != AV_HWDEVICE_TYPE_NONE)
{
pCodecCtx->get_format = get_hw_format;
if ((ret.ret_code = av_hwdevice_ctx_create(&hw_device_ctx, decoder, NULL, NULL, 0)) < 0)
{
ret.ret_str = "Failed to create specified hardware device.";
goto end;
}
pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
}
if ((ret.ret_code = avcodec_open2(pCodecCtx, pCodec, NULL)) < 0)
{
ret.ret_str = "Failed to open codec.";
goto end;
}
while (av_read_frame(pFormatCtx, packet) >= 0)
{
if (packet->stream_index == v_stream_idx)
{
if (frame_read >= startframe)
{
ret.ret_code = avcodec_send_packet(pCodecCtx, packet);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
if (avcodec_receive_frame(pCodecCtx, pFrame) != 0)
continue;
if (decoder != AV_HWDEVICE_TYPE_NONE && pFrame->format == hw_pix_fmt)
{
/* retrieve data from GPU to CPU */
if ((ret.ret_code = av_hwframe_transfer_data(hw_frame, pFrame, 0)) < 0)
{
ret.ret_str = "Error transferring the data to system memory";
goto end;
}
tmp_frame = hw_frame;// printf("hw:%d\n", frame_read);
}
else
{
tmp_frame = pFrame;// printf("sw:%d\n", frame_read);
}
std::string savefile = string_format(".\\opt\\img-%06d.png", frame_read);
Frame2PNG(tmp_frame, savefile);
frame_process++;
}
if (frame_process == framecount)
{
av_packet_unref(packet);
break;
}
frame_read++;
}av_packet_unref(packet);
}
/*flush*/
packet->data = NULL;
packet->size = 0;
ret.ret_code = avcodec_send_packet(pCodecCtx, packet);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
while (1)
{
ret.ret_code = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret.ret_code == AVERROR(EAGAIN) || ret.ret_code == AVERROR_EOF)
{
break;
}
if (decoder != AV_HWDEVICE_TYPE_NONE && pFrame->format == hw_pix_fmt)
{
/* retrieve data from GPU to CPU */
if ((ret.ret_code = av_hwframe_transfer_data(hw_frame, pFrame, 0)) < 0)
{
ret.ret_str = "Error transferring the data to system memory";
goto end;
}
tmp_frame = hw_frame; printf("hw:%d\n", frame_read);
}
else
{
tmp_frame = pFrame; printf("sw:%d\n", frame_read);
}
std::string savefile = string_format(".\\opt\\img-%06d.png", frame_read);
Frame2PNG(tmp_frame, savefile);
frame_process++;
}av_packet_unref(packet);
end:
av_frame_free(&pFrame);
av_frame_free(&hw_frame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
if (decoder != AV_HWDEVICE_TYPE_NONE)
av_buffer_unref(&hw_device_ctx);
return ret;
}
ReturnInfo ffmodule::SeparateFrames(std::string inputfile, Frames* output, int startframe, int framecount, enum AVHWDeviceType decoder)
{
ReturnInfo ret; //Return information.
AVFormatContext* pFormatCtx = NULL; //ffmpeg format context.
AVStream* video_st = NULL; //ffmpeg stream.
AVCodecContext* pCodecCtx = NULL; //ffmpeg codec context.
AVCodec* pCodec = NULL; //ffmpeg codec.
AVPacket* packet = (AVPacket*)av_malloc(sizeof(AVPacket)); //ffmpeg packet.
AVFrame* pFrame = av_frame_alloc(), //ffmpeg frame, recive from packet.
* hw_frame = av_frame_alloc(); //ffmpeg frame, store frame datas transfered from device
AVBufferRef* hw_device_ctx = NULL; //ffmpeg buffer reference.
int frame_read = 0, //av_read_frame counter.
frame_process = 0; //Frames after processing.
int v_stream_idx = -1; //Stream ID from ffmpeg format context.
ret.ret_code = avformat_open_input(&pFormatCtx, inputfile.c_str(), NULL, NULL);
if (ret.ret_code != 0)
{
ret.ret_str = "avformat_open_input() failed.";
goto end;
}
ret.ret_code = avformat_find_stream_info(pFormatCtx, NULL);
if (ret.ret_code < 0)
{
ret.ret_str = "Cannot find input stream information.";
goto end;
}
/* find the video stream information */
v_stream_idx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0);
if (v_stream_idx < 0)
{
ret.ret_str = "Cannot find a video stream in the input file";
ret.ret_code = -1;
goto end;
}
if (startframe < 0 || startframe > pFormatCtx->streams[v_stream_idx]->nb_frames)
{
ret.ret_str = "Startframe out of range.";
ret.ret_code = -1;
goto end;
}
if (decoder != AV_HWDEVICE_TYPE_NONE)
{
for (int i = 0;; i++)
{
const AVCodecHWConfig* config = avcodec_get_hw_config(pCodec, i);
if (!config)
{
ret.ret_code = -1;
ret.ret_str = string_format("Decoder %s does not support device type %s.\n", pCodec->name, av_hwdevice_get_type_name(decoder));
goto end;
}
if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == decoder)
{
hw_pix_fmt = config->pix_fmt;
break;
}
}
}
pCodecCtx = avcodec_alloc_context3(pCodec);
video_st = pFormatCtx->streams[v_stream_idx];
avcodec_parameters_to_context(pCodecCtx, video_st->codecpar);
if (decoder != AV_HWDEVICE_TYPE_NONE)
{
pCodecCtx->get_format = get_hw_format;
if ((ret.ret_code = av_hwdevice_ctx_create(&hw_device_ctx, decoder, NULL, NULL, 0)) < 0)
{
ret.ret_str = "Failed to create specified hardware device.";
goto end;
}
pCodecCtx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
}
if ((ret.ret_code = avcodec_open2(pCodecCtx, pCodec, NULL)) < 0)
{
ret.ret_str = "Failed to open codec.";
goto end;
}
while (av_read_frame(pFormatCtx, packet) >= 0)
{
if (packet->stream_index == v_stream_idx)
{
if (frame_read >= startframe)
{
ret.ret_code = avcodec_send_packet(pCodecCtx, packet);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
while (1)
{
int _ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (_ret == AVERROR(EAGAIN) || _ret == AVERROR_EOF)
{
break;
}
output->push_back(av_frame_alloc());
if (decoder != AV_HWDEVICE_TYPE_NONE && pFrame->format == hw_pix_fmt)
{
/* retrieve data from GPU to CPU */
if ((ret.ret_code = av_hwframe_transfer_data((*output)[output->size() - 1], pFrame, 0)) < 0)
{
ret.ret_str = "Error transferring the data to system memory";
goto end;
}
//printf("hw:%d\n", frame_read);
}
else
{
(*output)[output->size() - 1] = av_frame_clone(pFrame);
//printf("sw:%d\n", frame_read);
}
frame_process++;
if (frame_process == framecount)
{
av_packet_unref(packet);
break;
}
}
}
frame_read++;
}av_packet_unref(packet);
}
/*flush*/
packet->data = NULL;
packet->size = 0;
ret.ret_code = avcodec_send_packet(pCodecCtx, packet);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
while (1)
{
int _ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (_ret == AVERROR(EAGAIN) || _ret == AVERROR_EOF)
{
break;
}
output->push_back(av_frame_alloc());
if (decoder != AV_HWDEVICE_TYPE_NONE && pFrame->format == hw_pix_fmt)
{
/* retrieve data from GPU to CPU */
if ((ret.ret_code = av_hwframe_transfer_data((*output)[output->size() - 1], pFrame, 0)) < 0)
{
ret.ret_str = "Error transferring the data to system memory";
goto end;
}
//printf("hw:%d\n", frame_read);
}
else
{
(*output)[output->size() - 1] = av_frame_clone(pFrame);
//printf("sw:%d\n", frame_read);
}
frame_process++;
}av_packet_unref(packet);
end:
av_frame_free(&pFrame);
av_frame_free(&hw_frame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
pFormatCtx = NULL;
if (decoder != AV_HWDEVICE_TYPE_NONE)
av_buffer_unref(&hw_device_ctx);
return ret;
}
ReturnInfo ffmodule::SeparateAudio(std::string inputfile, std::string output)
{
ReturnInfo ret; //Return information.
std::string outfile = ""; //Output file name.
AVFormatContext* fmt_ctx = NULL, //ffmpeg input format context.
* ofmt_ctx = NULL; //ffmpeg output format context.
AVOutputFormat* output_fmt = NULL; //ffmpeg output format.
AVCodecParameters* in_codecpar = NULL; //ffmpeg input codecpar.
AVStream* in_stream = NULL, //ffmpeg input stream.
* out_stream = NULL; //ffmpeg output stream.
AVPacket* pkt = av_packet_alloc(); //ffmpeg packet.
AVCodec* decodec = NULL, //ffmpeg decoder.
* encodec = NULL; //ffmpeg encoder.
AVCodecContext* en_CodecCtx = NULL, //ffmpeg encodec context.
* de_CodecCtx = NULL; //ffmpeg decodec context.
int audio_stream_index; //Audio stream index.
Frames audio; //Audio frame.
if ((ret.ret_code = avformat_open_input(&fmt_ctx, inputfile.c_str(), NULL, NULL)) < 0)
{
ret.ret_str = "avformat_open_input() failed.";
goto end;
}
if ((ret.ret_code = avformat_find_stream_info(fmt_ctx, NULL)) < 0)
{
ret.ret_str = "avformat_find_stream_info() failed.";
goto end;
}
if (fmt_ctx->nb_streams < 2) {
ret.ret_str = "Streams less than 2.";
ret.ret_code = -1;
goto end;
}
audio_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
if (audio_stream_index < 0)
{
ret.ret_str = "av_find_best_stream() failed.";
ret.ret_code = -1;
goto end;
}
in_stream = fmt_ctx->streams[audio_stream_index];
in_codecpar = in_stream->codecpar;
decodec = avcodec_find_decoder(in_codecpar->codec_id);
if (!decodec)
{
ret.ret_str = "Codec not found.";
ret.ret_code = -1;
goto end;
}
de_CodecCtx = avcodec_alloc_context3(decodec);
if (!de_CodecCtx)
{
ret.ret_str = "Could not allocate audio codec context.";
ret.ret_code = -1;
goto end;
}
avcodec_parameters_to_context(de_CodecCtx, in_codecpar);
/* open it */
if ((ret.ret_code = avcodec_open2(de_CodecCtx, decodec, NULL)) < 0)
{
ret.ret_str = "Could not open codec.";
goto end;
}
while (av_read_frame(fmt_ctx, pkt) >= 0)
{
if (pkt->stream_index == audio_stream_index)
{
ret.ret_code = avcodec_send_packet(de_CodecCtx, pkt);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
while (1)
{
AVFrame* pFrame = av_frame_alloc();
int _ret = avcodec_receive_frame(de_CodecCtx, pFrame);
if (_ret == AVERROR(EAGAIN) || _ret == AVERROR_EOF)
{
av_frame_free(&pFrame);
break;
}
audio.push_back(av_frame_alloc());
audio[audio.size() - 1] = av_frame_clone(pFrame);
av_frame_free(&pFrame);
av_packet_unref(pkt);
}
}
av_packet_unref(pkt);
}
/*Flush*/
ret.ret_code = avcodec_send_packet(de_CodecCtx, NULL);
if (ret.ret_code < 0)
{
ret.ret_str = "Codec open failed.";
goto end;
}
while (1)
{
AVFrame* pFrame = av_frame_alloc();
int _ret = avcodec_receive_frame(de_CodecCtx, pFrame);
if (_ret == AVERROR(EAGAIN) || _ret == AVERROR_EOF)
{
av_frame_free(&pFrame);
av_packet_unref(pkt);
break;
}
audio.push_back(av_frame_alloc());
audio[audio.size() - 1] = av_frame_clone(pFrame);
av_frame_free(&pFrame);
av_packet_unref(pkt);
}
//Encode
ofmt_ctx = avformat_alloc_context();
if (!ofmt_ctx)
{
ret.ret_code = -1;
ret.ret_str = "avformat_alloc_output_context2() failed.";
goto end;
}
if ((ret.ret_code = avio_open(&ofmt_ctx->pb, string_format("%s\\output_audio.aac", output.c_str()).c_str(), AVIO_FLAG_WRITE)) < 0)
{
ret.ret_str = "avio_open() failed.";
goto end;
}
/* Guess the desired container format based on the file extension. */
if (!(ofmt_ctx->oformat = av_guess_format(NULL, string_format("%s\\output_audio.aac", output.c_str()).c_str(), NULL)))
{
ret.ret_str = "Could not find output file format.";
ret.ret_code = -1;
goto end;
}
encodec = avcodec_find_encoder_by_name("aac");
//encodec = avcodec_find_encoder(AV_CODEC_ID_VORBIS);
if (!encodec)
{
ret.ret_str = "Encoder not found.";
ret.ret_code = -1;
goto end;
}
out_stream = avformat_new_stream(ofmt_ctx, NULL);
en_CodecCtx = avcodec_alloc_context3(encodec);
if (!en_CodecCtx)
{
ret.ret_str = "Could not allocate audio codec context.";
ret.ret_code = -1;
goto end;
}
en_CodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
en_CodecCtx->time_base = de_CodecCtx->time_base;
/* put sample parameters */
en_CodecCtx->bit_rate = de_CodecCtx->bit_rate;
/* check that the encoder supports s16 pcm input */
en_CodecCtx->sample_fmt = encodec->sample_fmts[0];
/* select other audio parameters supported by the encoder */
en_CodecCtx->sample_rate = de_CodecCtx->sample_rate;
en_CodecCtx->channel_layout = de_CodecCtx->channel_layout;
en_CodecCtx->channels = de_CodecCtx->channels;
if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
en_CodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
ofmt_ctx->duration = fmt_ctx->duration;
if ((ret.ret_code = avcodec_open2(en_CodecCtx, encodec, NULL)) < 0)
{
ret.ret_str = "Could not open codec.";
goto end;
}
ret.ret_code = avcodec_parameters_from_context(out_stream->codecpar, en_CodecCtx);
if (ret.ret_code < 0)
{
ret.ret_str = "Could not initialize stream parameters.";
goto end;
}
if ((ret.ret_code = avformat_write_header(ofmt_ctx, NULL)) < 0)
{
ret.ret_str = "avformat_write_header() failed.";
goto end;
}
for (int pos = 0; pos <= audio.size(); pos++)
{
if (pos < audio.size())
audio[pos]->pts = pos;
int retx = avcodec_send_frame(en_CodecCtx, ((pos == audio.size()) ? NULL : audio[pos]));
if (retx < 0)
{
ret.ret_str = "Error sending the frame to the encoder.";
ret.ret_code = retx;
goto end;
}
/* read all the available output packets (in general there may be any
* number of them */
while (retx >= 0)
{
retx = avcodec_receive_packet(en_CodecCtx, pkt);
if (retx == AVERROR(EAGAIN) || retx == AVERROR_EOF)
break;
else if (retx < 0)
{
ret.ret_str = "Error encoding audio frame.";
ret.ret_code = retx;
goto end;
}
av_interleaved_write_frame(ofmt_ctx, pkt);
av_packet_unref(pkt);
}
}
av_write_trailer(ofmt_ctx);
end:
av_packet_free(&pkt);
avformat_close_input(&fmt_ctx);
avformat_free_context(fmt_ctx);
avformat_free_context(ofmt_ctx);
free_frames(&audio);
return ret;
}
ReturnInfo ffmodule::ComposeVideo(std::string images_input, std::string outfile, std::string codec, AVPixelFormat pix_fmt, int bitrate, int framerate)
{
ReturnInfo ret; //Return information.
Frames frm; //Frames.
AVFormatContext* ofmt_ctx = NULL; //ffmpeg output format context.
AVPacket* pkt = NULL; //ffmpeg output packet.
std::string inputfile = ""; //Input file name.
//Init original information.
MediaInfo init = GetMediaInfo(string_format("%s\\img-%06d.png", images_input.c_str(), 0));
AVStream* v_out_stream; //ffmpeg output video stream.
AVCodecContext* enc_ctx; //ffmpeg output codec context.
AVCodec* encoder; //ffmpeg output codec.
int process = 0, frame = 0; //Counter.
ofmt_ctx = NULL;
ret.ret_code = avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, outfile.c_str());
if (ret.ret_code < 0)
{
ret.ret_str = "Could not create output context.";
goto end;
}
v_out_stream = avformat_new_stream(ofmt_ctx, NULL);
if (!v_out_stream)
{
ret.ret_str = "Failed allocating output video stream.";
ret.ret_code = -1;
goto end;
}
encoder = avcodec_find_encoder_by_name(codec.c_str());
//encoder = avcodec_find_encoder(AV_CODEC_ID_H265);
if (!encoder)
{
ret.ret_str = "Necessary encoder not found.";
ret.ret_code = -1;
goto end;
}
enc_ctx = avcodec_alloc_context3(encoder);
if (!enc_ctx)
{
ret.ret_str = "Failed to allocate the encoder context.";
ret.ret_code = -1;
goto end;
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
enc_ctx->bit_rate = bitrate;
enc_ctx->height = init.height;
enc_ctx->width = init.width;
enc_ctx->sample_aspect_ratio = { 1 , 1 };
/* take first format from list of supported formats */
if (encoder->pix_fmts)
{
const enum AVPixelFormat* p;
for (p = encoder->pix_fmts; *p != -1; p++)
{
if (*p == pix_fmt)
{
enc_ctx->pix_fmt = *p;
break;
}
}
enc_ctx->pix_fmt = encoder->pix_fmts[0];
}
else
{
ret.ret_str = "Pixel format not found.";
ret.ret_code = -1;
goto end;
}
/* video time_base can be set to whatever is handy and supported by encoder */
enc_ctx->time_base = av_inv_q({ framerate , 1 });
if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/* Third parameter can be used to pass settings to encoder */
ret.ret_code = avcodec_open2(enc_ctx, encoder, NULL);
if (ret.ret_code < 0)
{
ret.ret_str = "Cannot open video encoder for stream.";
goto end;
}
ret.ret_code = avcodec_parameters_from_context(v_out_stream->codecpar, enc_ctx);
if (ret.ret_code < 0)
{
ret.ret_str = "Failed to copy encoder parameters to output stream.";
goto end;
}
if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
{
ret.ret_code = avio_open(&ofmt_ctx->pb, outfile.c_str(), AVIO_FLAG_WRITE);
if (ret.ret_code < 0)
{
ret.ret_str = "Could not open output file.";
goto end;
}
}
/* init muxer, write output file header */
ret.ret_code = avformat_write_header(ofmt_ctx, NULL);
if (ret.ret_code< 0)
{
ret.ret_str = "Error occurred when opening output file.";
goto end;
}
while (1)
{
inputfile = string_format("%s\\img-%06d.png", images_input.c_str(), frame); frame++;
ret = SeparateFrames(inputfile, &frm, 0, 0, AV_HWDEVICE_TYPE_NONE);
if (ret.ret_code == -2)
{
if (frm.size() == 0)
{
goto flush;
}
goto proc;// break;
}
else if (ret.ret_code != -2 && ret.ret_code < 0)
{
goto end;
}
process++; //printf("Proc:%d\n", frame);
if (process >= 300)
{
proc:
/*Compose video*/
for (int compose_frm = 0; compose_frm < frm.size(); compose_frm++)
{
AVFrame* yuvFrame = av_frame_alloc();
yuvFrame->width = frm[compose_frm]->width;
yuvFrame->height = frm[compose_frm]->height;
yuvFrame->format = enc_ctx->pix_fmt;// AV_PIX_FMT_YUV420P;
struct SwsContext* swCtx = sws_getContext(
frm[compose_frm]->width,
frm[compose_frm]->height,
AVPixelFormat(frm[compose_frm]->format),
frm[compose_frm]->width,
frm[compose_frm]->height,
enc_ctx->pix_fmt,//AV_PIX_FMT_YUV420P,
SWS_GAUSS, 0, 0, 0);
av_image_alloc(yuvFrame->data, yuvFrame->linesize, frm[compose_frm]->width, frm[compose_frm]->height, enc_ctx->pix_fmt, 1);
sws_scale(swCtx, frm[compose_frm]->data, frm[compose_frm]->linesize, 0, frm[compose_frm]->height, yuvFrame->data, yuvFrame->linesize);
yuvFrame->pts = frame - (frm.size() - 1 - compose_frm);
pkt = av_packet_alloc();
av_new_packet(pkt, frm[compose_frm]->width * frm[compose_frm]->height * 3);
int retx = avcodec_send_frame(enc_ctx, yuvFrame);
if (retx < 0)
{
ret.ret_str = "Error sending a frame for encoding.";
ret.ret_code = retx;
goto end;
}
while (retx >= 0)
{