/
rgy_output_avcodec.cpp
3687 lines (3495 loc) · 198 KB
/
rgy_output_avcodec.cpp
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
// -----------------------------------------------------------------------------------------
// QSVEnc/NVEnc by rigaya
// -----------------------------------------------------------------------------------------
// The MIT License
//
// Copyright (c) 2011-2016 rigaya
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// ------------------------------------------------------------------------------------------
#include <fcntl.h>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <memory>
#include "rgy_osdep.h"
#include "rgy_util.h"
#include "rgy_output_avcodec.h"
#include "rgy_avlog.h"
#include "rgy_bitstream.h"
#include "rgy_codepage.h"
#define WRITE_PTS_DEBUG (0)
#if ENABLE_AVSW_READER
#if USE_CUSTOM_IO
static int funcReadPacket(void *opaque, uint8_t *buf, int buf_size) {
RGYOutputAvcodec *writer = reinterpret_cast<RGYOutputAvcodec *>(opaque);
return writer->readPacket(buf, buf_size);
}
static int funcWritePacket(void *opaque, uint8_t *buf, int buf_size) {
RGYOutputAvcodec *writer = reinterpret_cast<RGYOutputAvcodec *>(opaque);
return writer->writePacket(buf, buf_size);
}
static int64_t funcSeek(void *opaque, int64_t offset, int whence) {
RGYOutputAvcodec *writer = reinterpret_cast<RGYOutputAvcodec *>(opaque);
return writer->seek(offset, whence);
}
#endif //USE_CUSTOM_IO
const AVRational RGYOutputAvcodec::QUEUE_DTS_TIMEBASE = av_make_q(1, 90000);
RGYOutputAvcodec::RGYOutputAvcodec() {
memset(&m_Mux.format, 0, sizeof(m_Mux.format));
memset(&m_Mux.video, 0, sizeof(m_Mux.video));
m_strWriterName = _T("avout");
}
RGYOutputAvcodec::~RGYOutputAvcodec() {
Close();
}
void RGYOutputAvcodec::CloseOther(AVMuxOther *muxOther) {
//close decoder
if (muxOther->outCodecDecodeCtx) {
avcodec_close(muxOther->outCodecDecodeCtx);
av_free(muxOther->outCodecDecodeCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed outCodecDecodeCtx.\n"));
}
//close encoder
if (muxOther->outCodecEncodeCtx) {
avcodec_close(muxOther->outCodecEncodeCtx);
av_free(muxOther->outCodecEncodeCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed outCodecEncodeCtx.\n"));
}
if (muxOther->bufConvert) {
av_free(muxOther->bufConvert);
}
if (muxOther->bsfc) {
av_bsf_free(&muxOther->bsfc);
}
if (muxOther->datahandler) {
free(muxOther->datahandler);
}
memset(muxOther, 0, sizeof(muxOther[0]));
AddMessage(RGY_LOG_DEBUG, _T("Closed other.\n"));
}
void RGYOutputAvcodec::CloseAudio(AVMuxAudio *muxAudio) {
//close decoder
if (muxAudio->outCodecDecodeCtx
&& muxAudio->inSubStream == 0) { //サブストリームのものは単なるコピーなので開放不要
avcodec_close(muxAudio->outCodecDecodeCtx);
av_free(muxAudio->outCodecDecodeCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed outCodecDecodeCtx.\n"));
}
//close encoder
if (muxAudio->outCodecEncodeCtx) {
avcodec_close(muxAudio->outCodecEncodeCtx);
av_free(muxAudio->outCodecEncodeCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed outCodecEncodeCtx.\n"));
}
//close filter
if (muxAudio->filterGraph) {
avfilter_graph_free(&muxAudio->filterGraph);
}
if (muxAudio->bsfc) {
av_bsf_free(&muxAudio->bsfc);
}
memset(muxAudio, 0, sizeof(muxAudio[0]));
AddMessage(RGY_LOG_DEBUG, _T("Closed audio.\n"));
}
void RGYOutputAvcodec::CloseVideo(AVMuxVideo *muxVideo) {
#if ENCODER_VCEENC
if (muxVideo->parserCtx) {
av_parser_close(muxVideo->parserCtx);
}
#endif //#if ENCODER_VCEENC
if (muxVideo->codecCtx) {
avcodec_free_context(&muxVideo->codecCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed video context.\n"));
}
if (m_Mux.video.fpTsLogFile) {
fclose(m_Mux.video.fpTsLogFile);
}
m_Mux.video.timestampList.clear();
if (m_Mux.video.bsfc) {
av_bsf_free(&m_Mux.video.bsfc);
}
memset(muxVideo, 0, sizeof(muxVideo[0]));
AddMessage(RGY_LOG_DEBUG, _T("Closed video.\n"));
}
void RGYOutputAvcodec::CloseFormat(AVMuxFormat *muxFormat) {
if (muxFormat->formatCtx) {
if (!muxFormat->streamError && m_Mux.format.fileHeaderWritten) {
av_write_trailer(muxFormat->formatCtx);
}
#if USE_CUSTOM_IO
if (!muxFormat->fpOutput) {
#endif
avio_close(muxFormat->formatCtx->pb);
AddMessage(RGY_LOG_DEBUG, _T("Closed AVIO Context.\n"));
#if USE_CUSTOM_IO
}
#endif
avformat_free_context(muxFormat->formatCtx);
AddMessage(RGY_LOG_DEBUG, _T("Closed avformat context.\n"));
}
#if USE_CUSTOM_IO
if (muxFormat->fpOutput) {
fflush(muxFormat->fpOutput);
fclose(muxFormat->fpOutput);
AddMessage(RGY_LOG_DEBUG, _T("Closed File Pointer.\n"));
}
if (muxFormat->AVOutBuffer) {
av_free(muxFormat->AVOutBuffer);
}
if (muxFormat->outputBuffer) {
free(muxFormat->outputBuffer);
}
#endif //USE_CUSTOM_IO
memset(muxFormat, 0, sizeof(muxFormat[0]));
AddMessage(RGY_LOG_DEBUG, _T("Closed format.\n"));
}
void RGYOutputAvcodec::CloseQueues() {
#if ENABLE_AVCODEC_OUT_THREAD
m_Mux.thread.thAudEncodeAbort = true;
m_Mux.thread.thAudProcessAbort = true;
m_Mux.thread.abortOutput = true;
m_Mux.thread.qVideobitstream.close();
m_Mux.thread.qVideobitstreamFreeI.close([](RGYBitstream *pBitstream) { pBitstream->clear(); });
m_Mux.thread.qVideobitstreamFreePB.close([](RGYBitstream *pBitstream) { pBitstream->clear(); });
m_Mux.thread.qAudioPacketOut.close();
m_Mux.thread.qAudioFrameEncode.close();
m_Mux.thread.qAudioPacketProcess.close();
AddMessage(RGY_LOG_DEBUG, _T("closed queues...\n"));
#endif
}
void RGYOutputAvcodec::CloseThread() {
#if ENABLE_AVCODEC_OUT_THREAD
m_Mux.thread.thAudEncodeAbort = true;
if (m_Mux.thread.thAudEncode.joinable()) {
//下記同様に、m_Mux.thread.heEventThOutputClosingがセットされるまで、
//SetEvent(m_Mux.thread.heEventThOutputPktAdded)を実行し続ける必要がある。
while (WAIT_TIMEOUT == WaitForSingleObject(m_Mux.thread.heEventClosingAudEncode, 100)) {
SetEvent(m_Mux.thread.heEventPktAddedAudEncode);
}
m_Mux.thread.thAudEncode.join();
CloseEvent(m_Mux.thread.heEventPktAddedAudEncode);
CloseEvent(m_Mux.thread.heEventClosingAudEncode);
AddMessage(RGY_LOG_DEBUG, _T("closed audio encode thread...\n"));
}
m_Mux.thread.thAudProcessAbort = true;
if (m_Mux.thread.thAudProcess.joinable()) {
//下記同様に、m_Mux.thread.heEventThOutputClosingがセットされるまで、
//SetEvent(m_Mux.thread.heEventThOutputPktAdded)を実行し続ける必要がある。
while (WAIT_TIMEOUT == WaitForSingleObject(m_Mux.thread.heEventClosingAudProcess, 100)) {
SetEvent(m_Mux.thread.heEventPktAddedAudProcess);
}
m_Mux.thread.thAudProcess.join();
CloseEvent(m_Mux.thread.heEventPktAddedAudProcess);
CloseEvent(m_Mux.thread.heEventClosingAudProcess);
AddMessage(RGY_LOG_DEBUG, _T("closed audio process thread...\n"));
}
m_Mux.thread.abortOutput = true;
if (m_Mux.thread.thOutput.joinable()) {
//ここに来た時に、まだメインスレッドがループ中の可能性がある
//その場合、SetEvent(m_Mux.thread.heEventPktAddedOutput)を一度やるだけだと、
//そのあとにResetEvent(m_Mux.thread.heEventPktAddedOutput)が発生してしまい、
//ここでスレッドが停止してしまう。
//これを回避するため、m_Mux.thread.heEventClosingOutputがセットされるまで、
//SetEvent(m_Mux.thread.heEventPktAddedOutput)を実行し続ける必要がある。
while (WAIT_TIMEOUT == WaitForSingleObject(m_Mux.thread.heEventClosingOutput, 100)) {
SetEvent(m_Mux.thread.heEventPktAddedOutput);
}
m_Mux.thread.thOutput.join();
CloseEvent(m_Mux.thread.heEventPktAddedOutput);
CloseEvent(m_Mux.thread.heEventClosingOutput);
AddMessage(RGY_LOG_DEBUG, _T("closed output thread...\n"));
}
CloseQueues();
m_Mux.thread.abortOutput = false;
m_Mux.thread.thAudProcessAbort = false;
m_Mux.thread.thAudEncodeAbort = false;
#endif
}
void RGYOutputAvcodec::Close() {
AddMessage(RGY_LOG_DEBUG, _T("Closing...\n"));
CloseThread();
CloseFormat(&m_Mux.format);
for (int i = 0; i < (int)m_Mux.audio.size(); i++) {
CloseAudio(&m_Mux.audio[i]);
}
m_Mux.audio.clear();
for (int i = 0; i < (int)m_Mux.other.size(); i++) {
CloseOther(&m_Mux.other[i]);
}
m_Mux.other.clear();
CloseVideo(&m_Mux.video);
m_strOutputInfo.clear();
m_encSatusInfo.reset();
AddMessage(RGY_LOG_DEBUG, _T("Closed.\n"));
}
AVCodecID RGYOutputAvcodec::getAVCodecId(RGY_CODEC codec) {
for (int i = 0; i < _countof(HW_DECODE_LIST); i++)
if (HW_DECODE_LIST[i].rgy_codec == codec)
return HW_DECODE_LIST[i].avcodec_id;
return AV_CODEC_ID_NONE;
}
bool RGYOutputAvcodec::codecIDIsPCM(AVCodecID targetCodec) {
static const auto pcmCodecs = make_array<AVCodecID>(
AV_CODEC_ID_FIRST_AUDIO,
AV_CODEC_ID_PCM_S16LE,
AV_CODEC_ID_PCM_S16BE,
AV_CODEC_ID_PCM_U16LE,
AV_CODEC_ID_PCM_U16BE,
AV_CODEC_ID_PCM_S8,
AV_CODEC_ID_PCM_U8,
AV_CODEC_ID_PCM_MULAW,
AV_CODEC_ID_PCM_ALAW,
AV_CODEC_ID_PCM_S32LE,
AV_CODEC_ID_PCM_S32BE,
AV_CODEC_ID_PCM_U32LE,
AV_CODEC_ID_PCM_U32BE,
AV_CODEC_ID_PCM_S24LE,
AV_CODEC_ID_PCM_S24BE,
AV_CODEC_ID_PCM_U24LE,
AV_CODEC_ID_PCM_U24BE,
AV_CODEC_ID_PCM_S24DAUD,
AV_CODEC_ID_PCM_ZORK,
AV_CODEC_ID_PCM_S16LE_PLANAR,
AV_CODEC_ID_PCM_DVD,
AV_CODEC_ID_PCM_F32BE,
AV_CODEC_ID_PCM_F32LE,
AV_CODEC_ID_PCM_F64BE,
AV_CODEC_ID_PCM_F64LE,
AV_CODEC_ID_PCM_BLURAY,
AV_CODEC_ID_PCM_LXF,
AV_CODEC_ID_S302M,
AV_CODEC_ID_PCM_S8_PLANAR,
AV_CODEC_ID_PCM_S24LE_PLANAR,
AV_CODEC_ID_PCM_S32LE_PLANAR,
AV_CODEC_ID_PCM_S16BE_PLANAR
);
return (pcmCodecs.end() != std::find(pcmCodecs.begin(), pcmCodecs.end(), targetCodec));
}
AVCodecID RGYOutputAvcodec::PCMRequiresConversion(const AVCodecParameters *codecParm) {
static const std::pair<AVCodecID, AVCodecID> pcmConvertCodecs[] = {
{ AV_CODEC_ID_FIRST_AUDIO, AV_CODEC_ID_FIRST_AUDIO },
{ AV_CODEC_ID_PCM_DVD, AV_CODEC_ID_FIRST_AUDIO },
{ AV_CODEC_ID_PCM_BLURAY, AV_CODEC_ID_FIRST_AUDIO },
{ AV_CODEC_ID_PCM_S8_PLANAR, AV_CODEC_ID_PCM_S8 },
{ AV_CODEC_ID_PCM_S16LE_PLANAR, AV_CODEC_ID_PCM_S16LE },
{ AV_CODEC_ID_PCM_S16BE_PLANAR, AV_CODEC_ID_PCM_S16LE },
{ AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE },
{ AV_CODEC_ID_PCM_S24LE_PLANAR, AV_CODEC_ID_PCM_S24LE },
{ AV_CODEC_ID_PCM_S24BE, AV_CODEC_ID_PCM_S24LE },
{ AV_CODEC_ID_PCM_S32LE_PLANAR, AV_CODEC_ID_PCM_S32LE },
{ AV_CODEC_ID_PCM_S32BE, AV_CODEC_ID_PCM_S32LE },
{ AV_CODEC_ID_PCM_F32BE, AV_CODEC_ID_PCM_S32LE },
{ AV_CODEC_ID_PCM_F64BE, AV_CODEC_ID_PCM_S32LE },
};
AVCodecID prmCodec = AV_CODEC_ID_NONE;
for (int i = 0; i < _countof(pcmConvertCodecs); i++) {
if (pcmConvertCodecs[i].first == codecParm->codec_id) {
if (pcmConvertCodecs[i].second != AV_CODEC_ID_FIRST_AUDIO) {
return pcmConvertCodecs[i].second;
}
switch (codecParm->bits_per_raw_sample) {
case 32: prmCodec = AV_CODEC_ID_PCM_S32LE; break;
case 24: prmCodec = AV_CODEC_ID_PCM_S24LE; break;
case 8: prmCodec = AV_CODEC_ID_PCM_S16LE; break;
case 16:
default: prmCodec = AV_CODEC_ID_PCM_S16LE; break;
}
}
}
if (prmCodec != AV_CODEC_ID_NONE) {
AddMessage(RGY_LOG_DEBUG, _T("PCM requires conversion...\n"));
}
return prmCodec;
}
void RGYOutputAvcodec::SetExtraData(AVCodecContext *codecCtx, const uint8_t *data, uint32_t size) {
if (data == nullptr || size == 0)
return;
if (codecCtx->extradata)
av_free(codecCtx->extradata);
codecCtx->extradata_size = size;
codecCtx->extradata = (uint8_t *)av_malloc(codecCtx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
memcpy(codecCtx->extradata, data, size);
};
void RGYOutputAvcodec::SetExtraData(AVCodecParameters *codecParam, const uint8_t *data, uint32_t size) {
if (data == nullptr || size == 0)
return;
if (codecParam->extradata)
av_free(codecParam->extradata);
codecParam->extradata_size = size;
codecParam->extradata = (uint8_t *)av_malloc(codecParam->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
memcpy(codecParam->extradata, data, size);
};
//音声のchannel_layoutを自動選択する
uint64_t RGYOutputAvcodec::AutoSelectChannelLayout(const uint64_t *channelLayout, const AVCodecContext *srcAudioCtx) {
int srcChannels = av_get_channel_layout_nb_channels(srcAudioCtx->channel_layout);
if (srcChannels == 0) {
srcChannels = srcAudioCtx->channels;
}
if (channelLayout == nullptr) {
switch (srcChannels) {
case 1: return AV_CH_LAYOUT_MONO;
case 2: return AV_CH_LAYOUT_STEREO;
case 3: return AV_CH_LAYOUT_2_1;
case 4: return AV_CH_LAYOUT_QUAD;
case 5: return AV_CH_LAYOUT_5POINT0;
case 6: return AV_CH_LAYOUT_5POINT1;
case 7: return AV_CH_LAYOUT_6POINT1;
case 8: return AV_CH_LAYOUT_7POINT1;
default: return AV_CH_LAYOUT_NATIVE;
}
}
for (int i = 0; channelLayout[i]; i++) {
if (srcChannels == av_get_channel_layout_nb_channels(channelLayout[i])) {
return channelLayout[i];
}
}
return channelLayout[0];
}
int RGYOutputAvcodec::AutoSelectSamplingRate(const int *samplingRateList, int srcSamplingRate) {
if (samplingRateList == nullptr) {
return srcSamplingRate;
}
//一致するものがあれば、それを返す
int i = 0;
for (; samplingRateList[i]; i++) {
if (srcSamplingRate == samplingRateList[i]) {
return srcSamplingRate;
}
}
//相対誤差が最も小さいものを選択する
vector<double> diffrate(i);
for (i = 0; samplingRateList[i]; i++) {
diffrate[i] = std::abs(1 - samplingRateList[i] / (double)srcSamplingRate);
}
return samplingRateList[std::distance(diffrate.begin(), std::min_element(diffrate.begin(), diffrate.end()))];
}
AVSampleFormat RGYOutputAvcodec::AutoSelectSampleFmt(const AVSampleFormat *samplefmtList, const AVCodecContext *srcAudioCtx) {
AVSampleFormat srcFormat = srcAudioCtx->sample_fmt;
if (samplefmtList == nullptr) {
return srcFormat;
}
if (srcFormat == AV_SAMPLE_FMT_NONE) {
return samplefmtList[0];
}
for (int i = 0; samplefmtList[i] >= 0; i++) {
if (srcFormat == samplefmtList[i]) {
return samplefmtList[i];
}
}
static const auto sampleFmtLevel = make_array<std::pair<AVSampleFormat, int>>(
std::make_pair(AV_SAMPLE_FMT_DBLP, 8),
std::make_pair(AV_SAMPLE_FMT_DBL, 8),
std::make_pair(AV_SAMPLE_FMT_FLTP, 6),
std::make_pair(AV_SAMPLE_FMT_FLT, 6),
std::make_pair(AV_SAMPLE_FMT_S32P, 4),
std::make_pair(AV_SAMPLE_FMT_S32, 4),
std::make_pair(AV_SAMPLE_FMT_S16P, 2),
std::make_pair(AV_SAMPLE_FMT_S16, 2),
std::make_pair(AV_SAMPLE_FMT_U8P, 1),
std::make_pair(AV_SAMPLE_FMT_U8, 1)
);
int srcFormatLevel = std::find_if(sampleFmtLevel.begin(), sampleFmtLevel.end(),
[srcFormat](const std::pair<AVSampleFormat, int>& targetFormat) { return targetFormat.first == srcFormat;})->second;
auto foundFormat = std::find_if(sampleFmtLevel.begin(), sampleFmtLevel.end(),
[srcFormatLevel](const std::pair<AVSampleFormat, int>& targetFormat) { return targetFormat.second == srcFormatLevel; });
for (; foundFormat != sampleFmtLevel.end(); foundFormat++) {
for (int i = 0; samplefmtList[i] >= 0; i++) {
if (foundFormat->first == samplefmtList[i]) {
return samplefmtList[i];
}
}
}
return samplefmtList[0];
}
//音声のプロファイルを取得する
int RGYOutputAvcodec::AudioGetCodecProfile(tstring profile, AVCodecID codecId) {
int selectedProfile = FF_PROFILE_UNKNOWN;
auto codecDesc = avcodec_descriptor_get(codecId);
if (codecDesc != nullptr) {
const std::string codec_profile = tchar_to_string(profile);
for (auto avprofile = codecDesc->profiles;
avprofile != nullptr && avprofile->profile != FF_PROFILE_UNKNOWN;
avprofile++) {
if (_stricmp(avprofile->name, codec_profile.c_str()) == 0) {
selectedProfile = avprofile->profile;
break;
}
}
}
return selectedProfile;
}
//音声のプロファイル(文字列)を取得する
tstring RGYOutputAvcodec::AudioGetCodecProfileStr(int profile, AVCodecID codecId) {
auto codecDesc = avcodec_descriptor_get(codecId);
if (codecDesc != nullptr) {
for (auto avprofile = codecDesc->profiles;
avprofile != nullptr && avprofile->profile != FF_PROFILE_UNKNOWN;
avprofile++) {
if (avprofile->profile == profile && avprofile->name != nullptr) {
return char_to_tstring(avprofile->name);
}
}
}
return _T("default");
}
RGY_ERR RGYOutputAvcodec::SetMetadata(AVDictionary **metadata, const AVDictionary *srcMetadata, const std::vector<tstring> &metadataOpt, const RGYMetadataCopyDefault defaultCopy, const tstring& trackName) {
bool metadataCopyAll = false;
bool metadataCopyLang = false;
//デフォルトの操作
switch (defaultCopy) {
case RGY_METADATA_DEFAULT_CLEAR:
metadataCopyAll = false;
metadataCopyLang = false;
break;
case RGY_METADATA_DEFAULT_COPY_LANG_ONLY:
metadataCopyAll = false;
metadataCopyLang = true;
break;
case RGY_METADATA_DEFAULT_COPY:
metadataCopyAll = true;
metadataCopyLang = true;
break;
default:
AddMessage(RGY_LOG_DEBUG, _T("Unknown default setting %d for %s metadata setting!\n"), defaultCopy, trackName.c_str());
return RGY_ERR_UNSUPPORTED;
}
if (metadata_clear(metadataOpt)) {
metadataCopyAll = false;
metadataCopyLang = false;
} else if (metadata_copy(metadataOpt)) {
metadataCopyAll = true;
metadataCopyLang = true;
}
if (srcMetadata == nullptr) {
metadataCopyAll = false;
metadataCopyLang = false;
}
if (metadataCopyLang) {
const auto language_data = av_dict_get(srcMetadata, "language", NULL, AV_DICT_MATCH_CASE);
if (language_data) {
av_dict_set(metadata, language_data->key, language_data->value, AV_DICT_IGNORE_SUFFIX);
AddMessage(RGY_LOG_DEBUG, _T("Set %s language: key %s, value %s\n"), trackName.c_str(), char_to_tstring(language_data->key).c_str(), char_to_tstring(language_data->value).c_str());
}
}
if (metadataCopyAll) {
for (AVDictionaryEntry *entry = nullptr;
nullptr != (entry = av_dict_get(srcMetadata, "", entry, AV_DICT_IGNORE_SUFFIX));) {
av_dict_set(metadata, entry->key, entry->value, AV_DICT_IGNORE_SUFFIX);
AddMessage(RGY_LOG_DEBUG, _T("Copy %s Metadata: key %s, value %s\n"), trackName.c_str(), char_to_tstring(entry->key).c_str(), char_to_tstring(entry->value).c_str());
}
}
//このあたりは矛盾することがあるので消去
av_dict_set(&m_Mux.format.formatCtx->metadata, "duration", NULL, 0);
av_dict_set(&m_Mux.format.formatCtx->metadata, "creation_time", NULL, 0);
//ユーザー指定のパラメータの指定
for (const auto& m : metadataOpt) {
if (m == RGY_METADATA_CLEAR || m == RGY_METADATA_COPY) {
continue;
}
const std::string m_utf8 = tchar_to_string(m, CODE_PAGE_UTF8);
if (av_dict_parse_string(metadata, m_utf8.c_str(), "=", "", 0)) {
AddMessage(RGY_LOG_WARN, _T("Failed to parse metadata \"%s\" for %s, ignored!\n"), m.c_str(), trackName.c_str());
} else {
AddMessage(RGY_LOG_DEBUG, _T("Set/Overwrite metadata \"%s\" for %s\n"), m.c_str(), trackName.c_str());
}
}
return RGY_ERR_NONE;
}
#pragma warning (push)
#pragma warning (disable: 4127) //warning C4127: 条件式が定数です。
RGY_ERR RGYOutputAvcodec::InitVideo(const VideoInfo *videoOutputInfo, const AvcodecWriterPrm *prm) {
m_Mux.format.formatCtx->video_codec_id = getAVCodecId(videoOutputInfo->codec);
if (m_Mux.format.formatCtx->video_codec_id == AV_CODEC_ID_NONE) {
AddMessage(RGY_LOG_ERROR, _T("failed to find codec id for video.\n"));
return RGY_ERR_INVALID_CODEC;
}
m_Mux.format.formatCtx->oformat->video_codec = m_Mux.format.formatCtx->video_codec_id;
if (NULL == (m_Mux.video.codec = avcodec_find_decoder(m_Mux.format.formatCtx->video_codec_id))) {
AddMessage(RGY_LOG_ERROR, _T("failed to codec for video codec %s.\n"), char_to_tstring(avcodec_get_name(m_Mux.format.formatCtx->video_codec_id)).c_str());
return RGY_ERR_INVALID_CODEC;
}
if (NULL == (m_Mux.video.codecCtx = avcodec_alloc_context3(m_Mux.video.codec))) {
AddMessage(RGY_LOG_ERROR, _T("failed to allocate context for video codec %s.\n"), char_to_tstring(avcodec_get_name(m_Mux.format.formatCtx->video_codec_id)).c_str());
return RGY_ERR_INVALID_CODEC;
}
m_Mux.video.outputFps = av_make_q(videoOutputInfo->fpsN, videoOutputInfo->fpsD);
AddMessage(RGY_LOG_DEBUG, _T("output video stream fps: %d/%d\n"), m_Mux.video.outputFps.num, m_Mux.video.outputFps.den);
m_Mux.video.codecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
m_Mux.video.codecCtx->codec_id = m_Mux.format.formatCtx->video_codec_id;
m_Mux.video.codecCtx->width = videoOutputInfo->dstWidth;
m_Mux.video.codecCtx->height = videoOutputInfo->dstHeight;
m_Mux.video.codecCtx->pix_fmt = csp_rgy_to_avpixfmt(videoOutputInfo->csp);
m_Mux.video.codecCtx->level = videoOutputInfo->codecLevel;
m_Mux.video.codecCtx->profile = videoOutputInfo->codecProfile;
m_Mux.video.codecCtx->sample_aspect_ratio.num = videoOutputInfo->sar[0];
m_Mux.video.codecCtx->sample_aspect_ratio.den = videoOutputInfo->sar[1];
m_Mux.video.codecCtx->chroma_sample_location = (AVChromaLocation)clamp(videoOutputInfo->vui.chromaloc, 0, 6);
m_Mux.video.codecCtx->field_order = picstrcut_rgy_to_avfieldorder(videoOutputInfo->picstruct);
m_Mux.video.codecCtx->delay = videoOutputInfo->videoDelay;
if (prm->videoCodecTag.length() > 0) {
m_Mux.video.codecCtx->codec_tag = tagFromStr(prm->videoCodecTag);
AddMessage(RGY_LOG_DEBUG, _T("Set Video Codec Tag: %s\n"), char_to_tstring(tagToStr(m_Mux.video.codecCtx->codec_tag)).c_str());
}
if (videoOutputInfo->vui.descriptpresent
//atcSeiを設定する場合は、コンテナ側にはVUI情報をもたせないようにする
//コンテナ側にはatcの情報をもたせられないので、勝ちあってしまう
&& prm->HEVCHdrSei->getprm().atcSei == RGY_TRANSFER_UNKNOWN) {
m_Mux.video.codecCtx->colorspace = (AVColorSpace)videoOutputInfo->vui.matrix;
m_Mux.video.codecCtx->color_primaries = (AVColorPrimaries)videoOutputInfo->vui.colorprim;
m_Mux.video.codecCtx->color_range = (AVColorRange)videoOutputInfo->vui.colorrange;
m_Mux.video.codecCtx->color_trc = (AVColorTransferCharacteristic)videoOutputInfo->vui.transfer;
AddMessage(RGY_LOG_DEBUG, _T("Set VUI Params: %s\n"), videoOutputInfo->vui.print_all().c_str());
}
if (m_Mux.format.outputFmt->flags & AVFMT_GLOBALHEADER) {
m_Mux.video.codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
if (0 > avcodec_open2(m_Mux.video.codecCtx, m_Mux.video.codec, NULL)) {
AddMessage(RGY_LOG_ERROR, _T("failed to open codec %s for video.\n"), char_to_tstring(avcodec_get_name(m_Mux.format.formatCtx->video_codec_id)).c_str());
return RGY_ERR_NULL_PTR;
}
AddMessage(RGY_LOG_DEBUG, _T("opened video avcodec\n"));
if (NULL == (m_Mux.video.streamOut = avformat_new_stream(m_Mux.format.formatCtx, m_Mux.video.codec))) {
AddMessage(RGY_LOG_ERROR, _T("failed to create new stream for video.\n"));
return RGY_ERR_NULL_PTR;
}
if (avcodec_parameters_from_context(m_Mux.video.streamOut->codecpar, m_Mux.video.codecCtx) < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to open codec %s for video.\n"), char_to_tstring(avcodec_get_name(m_Mux.format.formatCtx->video_codec_id)).c_str());
return RGY_ERR_UNKNOWN;
}
m_Mux.video.bitstreamTimebase = (av_isvalid_q(prm->bitstreamTimebase)) ? prm->bitstreamTimebase : HW_NATIVE_TIMEBASE;
m_Mux.video.streamOut->time_base = (av_isvalid_q(prm->bitstreamTimebase)) ? prm->bitstreamTimebase : av_inv_q(m_Mux.video.outputFps);
if (m_Mux.format.isMatroska) {
m_Mux.video.streamOut->time_base = av_make_q(1, 1000);
}
m_Mux.video.streamOut->sample_aspect_ratio.num = videoOutputInfo->sar[0]; //mkvではこちらの指定も必要
m_Mux.video.streamOut->sample_aspect_ratio.den = videoOutputInfo->sar[1];
m_Mux.video.streamOut->avg_frame_rate.num = videoOutputInfo->fpsN; //mkvのTRACKDEFAULTDURATIONの出力に必要
m_Mux.video.streamOut->avg_frame_rate.den = videoOutputInfo->fpsD;
m_Mux.video.streamOut->start_time = 0;
m_Mux.video.dtsUnavailable = prm->bVideoDtsUnavailable;
m_Mux.video.inputFirstKeyPts = prm->videoInputFirstKeyPts;
m_Mux.video.timestamp = prm->vidTimestamp;
m_Mux.video.afs = prm->afs;
auto retm = SetMetadata(&m_Mux.video.streamOut->metadata, (prm->videoInputStream) ? prm->videoInputStream->metadata : nullptr, prm->videoMetadata, RGY_METADATA_DEFAULT_COPY_LANG_ONLY, _T("Video"));
if (retm != RGY_ERR_NONE) {
return retm;
}
if (prm->videoInputStream) {
m_Mux.video.inputStreamTimebase = prm->videoInputStream->time_base;
m_Mux.video.streamOut->disposition = prm->videoInputStream->disposition;
int side_data_size = 0;
auto side_data = av_stream_get_side_data(prm->videoInputStream, AV_PKT_DATA_DISPLAYMATRIX, &side_data_size);
if (side_data) {
unique_ptr<uint8_t, decltype(&av_freep)> side_data_copy((uint8_t *)av_malloc(side_data_size), av_freep);
memcpy(side_data_copy.get(), side_data, side_data_size);
auto rotation = av_display_rotation_get((const int *)side_data_copy.get());
int err = av_stream_add_side_data(m_Mux.video.streamOut, AV_PKT_DATA_DISPLAYMATRIX, side_data_copy.get(), side_data_size);
if (err < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to copy rotation %d from input\n"), rotation);
return RGY_ERR_INVALID_CALL;
}
AddMessage(RGY_LOG_DEBUG, _T("copied rotation %d from input\n"), rotation);
side_data_copy.release();
}
#if 0
if (videoOutputInfo->codec == RGY_CODEC_HEVC && prm->HEVCHdrSei == nullptr) {
side_data = av_stream_get_side_data(prm->videoInputStream, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, &side_data_size);
if (side_data) {
unique_ptr<uint8_t, decltype(&av_freep)> side_data_copy((uint8_t *)av_malloc(side_data_size), av_freep);
memcpy(side_data_copy.get(), side_data, side_data_size);
AVContentLightMetadata *coll = (AVContentLightMetadata *)side_data_copy.get();
AddMessage(RGY_LOG_DEBUG, _T("MaxCLL=%d, MaxFALL=%d\n"), coll->MaxCLL, coll->MaxFALL);
int err = av_stream_add_side_data(m_Mux.video.streamOut, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)side_data_copy.get(), side_data_size);
if (err < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to copy AV_PKT_DATA_CONTENT_LIGHT_LEVEL\n"));
return RGY_ERR_INVALID_CALL;
}
AddMessage(RGY_LOG_DEBUG, _T("copied AV_PKT_DATA_CONTENT_LIGHT_LEVEL from input\n"));
side_data_copy.release();
}
side_data = av_stream_get_side_data(prm->videoInputStream, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, &side_data_size);
if (side_data && side_data_size == sizeof(AVMasteringDisplayMetadata)) {
unique_ptr<uint8_t, decltype(&av_freep)> side_data_copy((uint8_t *)av_malloc(side_data_size), av_freep);
memcpy(side_data_copy.get(), side_data, side_data_size);
AVMasteringDisplayMetadata *mastering = (AVMasteringDisplayMetadata *)side_data_copy.get();
AddMessage(RGY_LOG_DEBUG, _T("Mastering Display: R(%f,%f) G(%f,%f) B(%f %f) WP(%f, %f) L(%f,%f)\n"),
av_q2d(mastering->display_primaries[0][0]),
av_q2d(mastering->display_primaries[0][1]),
av_q2d(mastering->display_primaries[1][0]),
av_q2d(mastering->display_primaries[1][1]),
av_q2d(mastering->display_primaries[2][0]),
av_q2d(mastering->display_primaries[2][1]),
av_q2d(mastering->white_point[0]), av_q2d(mastering->white_point[1]),
av_q2d(mastering->min_luminance), av_q2d(mastering->max_luminance));
int err = av_stream_add_side_data(m_Mux.video.streamOut, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)side_data_copy.get(), side_data_size);
if (err < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to copy AV_PKT_DATA_MASTERING_DISPLAY_METADATA\n"));
return RGY_ERR_INVALID_CALL;
}
AddMessage(RGY_LOG_DEBUG, _T("copied AV_PKT_DATA_MASTERING_DISPLAY_METADATA from input\n"));
side_data_copy.release();
}
}
#endif
}
m_Mux.video.timestampList.clear();
if (videoOutputInfo->codec == RGY_CODEC_HEVC && prm->HEVCHdrSei != nullptr) {
auto seiNal = prm->HEVCHdrSei->gen_nal();
if (seiNal.size() > 0) {
m_Mux.video.seiNal.copy(seiNal.data(), (uint32_t)seiNal.size());
AddMessage(RGY_LOG_DEBUG, char_to_tstring(prm->HEVCHdrSei->print()));
const auto HEVCHdrSeiPrm = prm->HEVCHdrSei->getprm();
if (false && HEVCHdrSeiPrm.masterdisplay_set) {
unique_ptr<AVMasteringDisplayMetadata, decltype(&av_freep)> mastering(av_mastering_display_metadata_alloc(), av_freep);
//streamのside dataとしてmasteringdisplay等を設定する
mastering->display_primaries[1][0] = av_make_q(HEVCHdrSeiPrm.masterdisplay[0], 50000); //G
mastering->display_primaries[1][1] = av_make_q(HEVCHdrSeiPrm.masterdisplay[1], 50000); //G
mastering->display_primaries[2][0] = av_make_q(HEVCHdrSeiPrm.masterdisplay[2], 50000); //B
mastering->display_primaries[2][1] = av_make_q(HEVCHdrSeiPrm.masterdisplay[3], 50000); //B
mastering->display_primaries[0][0] = av_make_q(HEVCHdrSeiPrm.masterdisplay[4], 50000); //R
mastering->display_primaries[0][1] = av_make_q(HEVCHdrSeiPrm.masterdisplay[5], 50000); //R
mastering->white_point[0] = av_make_q(HEVCHdrSeiPrm.masterdisplay[6], 50000);
mastering->white_point[1] = av_make_q(HEVCHdrSeiPrm.masterdisplay[7], 50000);
mastering->max_luminance = av_make_q(HEVCHdrSeiPrm.masterdisplay[8], 10000);
mastering->min_luminance = av_make_q(HEVCHdrSeiPrm.masterdisplay[9], 10000);
mastering->has_primaries = 1;
mastering->has_luminance = 1;
AddMessage(RGY_LOG_DEBUG, _T("Mastering Display: R(%f,%f) G(%f,%f) B(%f %f) WP(%f, %f) L(%f,%f)\n"),
av_q2d(mastering->display_primaries[0][0]),
av_q2d(mastering->display_primaries[0][1]),
av_q2d(mastering->display_primaries[1][0]),
av_q2d(mastering->display_primaries[1][1]),
av_q2d(mastering->display_primaries[2][0]),
av_q2d(mastering->display_primaries[2][1]),
av_q2d(mastering->white_point[0]), av_q2d(mastering->white_point[1]),
av_q2d(mastering->max_luminance), av_q2d(mastering->min_luminance));
int err = av_stream_add_side_data(m_Mux.video.streamOut, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)mastering.get(), sizeof(mastering.get()[0]));
if (err < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to set AV_PKT_DATA_MASTERING_DISPLAY_METADATA\n"));
return RGY_ERR_INVALID_CALL;
}
mastering.release(); //av_stream_add_side_dataされたデータはこちらで開放してはいけない
AddMessage(RGY_LOG_DEBUG, _T("set AV_PKT_DATA_MASTERING_DISPLAY_METADATA\n"));
}
if (false && HEVCHdrSeiPrm.contentlight_set) {
size_t coll_size = 0;
unique_ptr<AVContentLightMetadata, decltype(&av_freep)> coll(av_content_light_metadata_alloc(&coll_size), av_freep);
coll->MaxCLL = HEVCHdrSeiPrm.maxcll;
coll->MaxFALL = HEVCHdrSeiPrm.maxfall;
AddMessage(RGY_LOG_DEBUG, _T("MaxCLL=%d, MaxFALL=%d\n"),
coll->MaxCLL, coll->MaxFALL);
int err = av_stream_add_side_data(m_Mux.video.streamOut, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)coll.get(), coll_size);
if (err < 0) {
AddMessage(RGY_LOG_ERROR, _T("failed to set AV_PKT_DATA_CONTENT_LIGHT_LEVEL\n"));
return RGY_ERR_INVALID_CALL;
}
coll.release(); //av_stream_add_side_dataされたデータはこちらで開放してはいけない
AddMessage(RGY_LOG_DEBUG, _T("set AV_PKT_DATA_CONTENT_LIGHT_LEVEL\n"));
}
}
}
if ((ENCODER_NVENC
&& (videoOutputInfo->codec == RGY_CODEC_H264 || videoOutputInfo->codec == RGY_CODEC_HEVC)
&& videoOutputInfo->sar[0] * videoOutputInfo->sar[1] > 0)
|| (ENCODER_QSV
&& videoOutputInfo->vui.chromaloc != 0)
|| (ENCODER_VCEENC
&& (videoOutputInfo->vui.format != 5
|| videoOutputInfo->vui.colorprim != 2
|| videoOutputInfo->vui.transfer != 2
|| videoOutputInfo->vui.matrix != 2
|| videoOutputInfo->vui.chromaloc != 0))) {
const char *bsf_name = nullptr;
switch (videoOutputInfo->codec) {
case RGY_CODEC_H264: bsf_name = "h264_metadata"; break;
case RGY_CODEC_HEVC: bsf_name = "hevc_metadata"; break;
default:
break;
}
if (bsf_name == nullptr) {
AddMessage(RGY_LOG_ERROR, _T("invalid codec to set metadata filter.\n"));
return RGY_ERR_INVALID_CALL;
}
const auto bsf_tname = char_to_tstring(bsf_name);
AddMessage(RGY_LOG_DEBUG, _T("start initialize %s filter...\n"), bsf_tname.c_str());
auto filter = av_bsf_get_by_name(bsf_name);
if (filter == nullptr) {
AddMessage(RGY_LOG_ERROR, _T("failed to find %s.\n"), bsf_tname.c_str());
return RGY_ERR_NOT_FOUND;
}
unique_ptr<AVCodecParameters, RGYAVDeleter<AVCodecParameters>> codecpar(avcodec_parameters_alloc(), RGYAVDeleter<AVCodecParameters>(avcodec_parameters_free));
codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
codecpar->codec_id = getAVCodecId(videoOutputInfo->codec);
codecpar->width = videoOutputInfo->dstWidth;
codecpar->height = videoOutputInfo->dstHeight;
codecpar->format = csp_rgy_to_avpixfmt(videoOutputInfo->csp);
codecpar->level = videoOutputInfo->codecLevel;
codecpar->profile = videoOutputInfo->codecProfile;
codecpar->sample_aspect_ratio.num = videoOutputInfo->sar[0];
codecpar->sample_aspect_ratio.den = videoOutputInfo->sar[1];
codecpar->chroma_location = (AVChromaLocation)videoOutputInfo->vui.chromaloc;
codecpar->field_order = picstrcut_rgy_to_avfieldorder(videoOutputInfo->picstruct);
codecpar->video_delay = videoOutputInfo->videoDelay;
if (videoOutputInfo->vui.descriptpresent) {
codecpar->color_space = (AVColorSpace)videoOutputInfo->vui.matrix;
codecpar->color_primaries = (AVColorPrimaries)videoOutputInfo->vui.colorprim;
codecpar->color_range = (AVColorRange)videoOutputInfo->vui.colorrange;
codecpar->color_trc = (AVColorTransferCharacteristic)videoOutputInfo->vui.transfer;
}
int ret = 0;
if (0 > (ret = av_bsf_alloc(filter, &m_Mux.video.bsfc))) {
AddMessage(RGY_LOG_ERROR, _T("failed to allocate memory for %s: %s.\n"), bsf_tname.c_str(), qsv_av_err2str(ret).c_str());
return RGY_ERR_NULL_PTR;
}
if (0 > (ret = avcodec_parameters_copy(m_Mux.video.bsfc->par_in, codecpar.get()))) {
AddMessage(RGY_LOG_ERROR, _T("failed to copy parameter for %s: %s.\n"), bsf_tname.c_str(), qsv_av_err2str(ret).c_str());
return RGY_ERR_UNKNOWN;
}
AVDictionary *bsfPrm = nullptr;
unique_ptr<AVDictionary*, decltype(&av_dict_free)> bsfPrmDictDeleter(&bsfPrm, av_dict_free);
if (ENCODER_NVENC) {
char sar[128];
sprintf_s(sar, "%d/%d", videoOutputInfo->sar[0], videoOutputInfo->sar[1]);
av_dict_set(&bsfPrm, "sample_aspect_ratio", sar, 0);
AddMessage(RGY_LOG_DEBUG, _T("set sar %d:%d by %s filter\n"), videoOutputInfo->sar[0], videoOutputInfo->sar[1], bsf_tname.c_str());
}
if (ENCODER_VCEENC) {
if (videoOutputInfo->vui.format != 5 /*undef*/) {
av_dict_set_int(&bsfPrm, "video_format", videoOutputInfo->vui.format, 0);
AddMessage(RGY_LOG_DEBUG, _T("set video_format %d by %s filter\n"), videoOutputInfo->vui.format, bsf_tname.c_str());
}
if (videoOutputInfo->vui.colorprim != 2 /*undef*/) {
av_dict_set_int(&bsfPrm, "colour_primaries", videoOutputInfo->vui.colorprim, 0);
AddMessage(RGY_LOG_DEBUG, _T("set colorprim %d by %s filter\n"), videoOutputInfo->vui.colorprim, bsf_tname.c_str());
}
if (videoOutputInfo->vui.transfer != 2 /*undef*/) {
av_dict_set_int(&bsfPrm, "transfer_characteristics", videoOutputInfo->vui.transfer, 0);
AddMessage(RGY_LOG_DEBUG, _T("set transfer %d by %s filter\n"), videoOutputInfo->vui.transfer, bsf_tname.c_str());
}
if (videoOutputInfo->vui.matrix != 2 /*undef*/) {
av_dict_set_int(&bsfPrm, "matrix_coefficients", videoOutputInfo->vui.matrix, 0);
AddMessage(RGY_LOG_DEBUG, _T("set matrix %d by %s filter\n"), videoOutputInfo->vui.matrix, bsf_tname.c_str());
}
}
if (ENCODER_QSV || ENCODER_VCEENC) {
if (videoOutputInfo->vui.chromaloc != 0) {
av_dict_set_int(&bsfPrm, "chroma_sample_loc_type", videoOutputInfo->vui.chromaloc-1, 0);
AddMessage(RGY_LOG_DEBUG, _T("set chromaloc %d by %s filter\n"), videoOutputInfo->vui.chromaloc-1, bsf_tname.c_str());
}
}
if (0 > (ret = av_opt_set_dict2(m_Mux.video.bsfc, &bsfPrm, AV_OPT_SEARCH_CHILDREN))) {
AddMessage(RGY_LOG_ERROR, _T("failed to set parameters for %s: %s.\n"), bsf_tname.c_str(), qsv_av_err2str(ret).c_str());
return RGY_ERR_UNKNOWN;
}
if (0 > (ret = av_bsf_init(m_Mux.video.bsfc))) {
AddMessage(RGY_LOG_ERROR, _T("failed to init %s: %s.\n"), bsf_tname.c_str(), qsv_av_err2str(ret).c_str());
return RGY_ERR_UNKNOWN;
}
AddMessage(RGY_LOG_DEBUG, _T("initialized %s filter\n"), bsf_tname.c_str());
}
#if ENCODER_VCEENC
//parserを初期化 (VCEのみで必要)
if (nullptr == (m_Mux.video.parserCtx = av_parser_init(m_Mux.format.formatCtx->video_codec_id))) {
AddMessage(RGY_LOG_ERROR, _T("failed to init parser for %s.\n"), char_to_tstring(avcodec_get_name(m_Mux.format.formatCtx->video_codec_id)).c_str());
return RGY_ERR_NULL_PTR;
}
m_Mux.video.parserCtx->flags |= PARSER_FLAG_COMPLETE_FRAMES;
m_Mux.video.parserStreamPos = 0;
#endif //#if ENCODER_VCEENC
if (prm->muxVidTsLogFile.length() > 0) {
if (_tfopen_s(&m_Mux.video.fpTsLogFile, prm->muxVidTsLogFile.c_str(), _T("a"))) {
AddMessage(RGY_LOG_WARN, _T("failed to open mux timestamp log file: \"%s\""), prm->muxVidTsLogFile.c_str());
m_Mux.video.fpTsLogFile = NULL;
} else {
AddMessage(RGY_LOG_DEBUG, _T("Opened mux timestamp log file: \"%s\""), prm->muxVidTsLogFile.c_str());
tstring strFileHeadSep;
for (int i = 0; i < 78; i++) {
strFileHeadSep += _T("-");
}
_ftprintf(m_Mux.video.fpTsLogFile, _T("%s\n"), strFileHeadSep.c_str());
_ftprintf(m_Mux.video.fpTsLogFile, _T("%s\n"), m_Mux.format.filename);
_ftprintf(m_Mux.video.fpTsLogFile, _T("%s\n"), strFileHeadSep.c_str());
}
}
AddMessage(RGY_LOG_DEBUG, _T("output video stream timebase: %d/%d\n"), m_Mux.video.streamOut->time_base.num, m_Mux.video.streamOut->time_base.den);
AddMessage(RGY_LOG_DEBUG, _T("bDtsUnavailable: %s\n"), (m_Mux.video.dtsUnavailable) ? _T("on") : _T("off"));
return RGY_ERR_NONE;
}
#pragma warning (pop)
//音声フィルタの初期化
RGY_ERR RGYOutputAvcodec::InitAudioFilter(AVMuxAudio *muxAudio, int channels, uint64_t channel_layout, int sample_rate, AVSampleFormat sample_fmt) {
//必要ならfilterを初期化
if ((!muxAudio->filterGraph && (
//フィルタが初期化されていない場合
muxAudio->filter
|| bSplitChannelsEnabled(muxAudio->streamChannelSelect)
|| bSplitChannelsEnabled(muxAudio->streamChannelOut)
|| muxAudio->outCodecDecodeCtx->frame_size != muxAudio->outCodecEncodeCtx->frame_size
|| muxAudio->filterInChannels != channels
|| muxAudio->filterInChannelLayout != channel_layout
|| muxAudio->filterInSampleRate != sample_rate
|| muxAudio->filterInSampleFmt != sample_fmt
))
||
//フィルタがすでに初期化されている場合
( muxAudio->filterInChannels != channels
|| muxAudio->filterInChannelLayout != channel_layout
|| muxAudio->filterInSampleRate != sample_rate
|| muxAudio->filterInSampleFmt != sample_fmt
)) {
if (muxAudio->filterGraph) {
//filterをflush
auto filteredFrames = AudioFilterFrameFlush(muxAudio);
WriteNextPacketToAudioSubtracks(filteredFrames);
//filterをclose
avfilter_graph_free(&muxAudio->filterGraph);
}
muxAudio->filterInChannels = channels;
muxAudio->filterInChannelLayout = channel_layout;
muxAudio->filterInSampleRate = sample_rate;
muxAudio->filterInSampleFmt = sample_fmt;
if (!channel_layout) {
//時折channel_layoutが設定されていない場合がある
channel_layout = av_get_default_channel_layout(channels);
}
int ret = 0;
muxAudio->filterGraph = avfilter_graph_alloc();
av_opt_set_int(muxAudio->filterGraph, "threads", 1, 0);
auto filterchain = tchar_to_string(muxAudio->filter);
//チャンネルレイアウトの変更
if (bSplitChannelsEnabled(muxAudio->streamChannelSelect)
&& muxAudio->streamChannelSelect[muxAudio->inSubStream] != channel_layout
&& av_get_channel_layout_nb_channels(muxAudio->streamChannelSelect[muxAudio->inSubStream]) < channels) {
//初期化
for (int inChannel = 0; inChannel < _countof(muxAudio->channelMapping); inChannel++) {
muxAudio->channelMapping[inChannel] = -1;
}
//時折channel_layoutが設定されていない場合がある
const auto channelLayoutDec = (muxAudio->outCodecDecodeCtx->channel_layout) ? muxAudio->outCodecDecodeCtx->channel_layout : av_get_default_channel_layout(muxAudio->outCodecDecodeCtx->channels);
//オプションによって指定されている、入力音声から抽出するべき音声レイアウト
const auto select_channel_layout = muxAudio->streamChannelSelect[muxAudio->inSubStream];
const int select_channel_count = av_get_channel_layout_nb_channels(select_channel_layout);
std::string channel_map = "pan=" + getChannelLayoutChar(select_channel_count, av_get_default_channel_layout(select_channel_count));
for (int inChannel = 0; inChannel < select_channel_count; inChannel++) {
//オプションによって指定されているチャンネルレイアウトから、抽出する音声のチャンネルを順に取得する
//実際には、「オプションによって指定されているチャンネルレイアウト」が入力音声に存在しない場合がある
auto select_channel = av_channel_layout_extract_channel(select_channel_layout, std::min(inChannel, select_channel_count-1));
//対象のチャンネルのインデックスを取得する
auto select_channel_index = av_get_channel_layout_channel_index(channelLayoutDec, select_channel);
if (select_channel_index < 0) {
//対応するチャンネルがもともとの入力音声ストリームにはない場合
const auto nChannels = (std::min)(inChannel, av_get_channel_layout_nb_channels(channelLayoutDec)-1);
//入力音声のストリームから、抽出する音声のチャンネルを順に取得する
select_channel = av_channel_layout_extract_channel(channelLayoutDec, nChannels);
//対象のチャンネルのインデックスを取得する
select_channel_index = av_get_channel_layout_channel_index(channelLayoutDec, select_channel);
}
muxAudio->channelMapping[inChannel] = select_channel_index;
channel_map += "|c" + std::to_string(inChannel) + "=c" + std::to_string(select_channel_index);
}
if (filterchain.length() > 0) filterchain += ",";
filterchain += channel_map;
if (RGY_LOG_DEBUG >= m_printMes->getLogLevel()) {
tstring channel_layout_str = strsprintf(_T("channel layout for track %d.%d:\n["), trackID(muxAudio->inTrackId), muxAudio->inSubStream);
for (int inChannel = 0; inChannel < channels; inChannel++) {
channel_layout_str += strsprintf(_T("%4d"), muxAudio->channelMapping[inChannel]);
}
channel_layout_str += _T("]\n");
AddMessage(RGY_LOG_DEBUG, channel_layout_str.c_str());
}
}
if (filterchain.length() > 0) filterchain += ",";
filterchain += strsprintf("aformat=sample_fmts=%s:sample_rates=%d:channel_layouts=0x%llx",
av_get_sample_fmt_name(muxAudio->outCodecEncodeCtx->sample_fmt),
muxAudio->outCodecEncodeCtx->sample_rate,
(unsigned long long int)muxAudio->outCodecEncodeCtx->channel_layout);
AVFilterInOut *filter_inputs = nullptr;
AVFilterInOut *filter_outputs = nullptr;
if (0 > (ret = avfilter_graph_parse2(muxAudio->filterGraph, filterchain.c_str(), &filter_inputs, &filter_outputs))) {
AddMessage(RGY_LOG_ERROR, _T("Failed to parse filter description: %s: \"%s\"\n"), qsv_av_err2str(ret).c_str(), muxAudio->filter);
return RGY_ERR_INVALID_AUDIO_PARAM;
}
unique_ptr<AVFilterInOut, RGYAVDeleter<AVFilterInOut>> inputs(filter_inputs, RGYAVDeleter<AVFilterInOut>(avfilter_inout_free));
unique_ptr<AVFilterInOut, RGYAVDeleter<AVFilterInOut>> outputs(filter_outputs, RGYAVDeleter<AVFilterInOut>(avfilter_inout_free));
AddMessage(RGY_LOG_DEBUG, _T("Parsed filter: %s\n"), muxAudio->filter);
const int nOutputCount = !!inputs + (inputs && inputs->next);
const int nInputCount = !!outputs + (outputs && outputs->next);
if (nOutputCount != 1 || nInputCount != 1) {
const TCHAR *pFilterCountStr[] = { _T("0"), _T("1"), _T(">1") };
AddMessage(RGY_LOG_ERROR, _T("filtergraph has %s input(s) and %s output(s).\n"), pFilterCountStr[nInputCount], pFilterCountStr[nOutputCount]);
AddMessage(RGY_LOG_ERROR, _T("only 1 in -> 1 out filtering is supported.\n"));
return RGY_ERR_UNSUPPORTED;
}
//入力の設定