/
transcode.cpp
1612 lines (1402 loc) · 52.7 KB
/
transcode.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
#include <fcntl.h>
#include <math.h>
#include <iostream>
#include <QStringList>
#include <QMap>
#include <QRegExp>
#include <QList>
#include <QWaitCondition>
#include <QMutex>
#include <QMutexLocker>
#include <QtAlgorithms>
#include "mythconfig.h"
#include "transcode.h"
#include "audiooutput.h"
#include "recordingprofile.h"
#include "mythcorecontext.h"
#include "jobqueue.h"
#include "exitcodes.h"
#include "mthreadpool.h"
#include "deletemap.h"
#include "tvremoteutil.h"
#include "NuppelVideoRecorder.h"
#include "mythplayer.h"
#include "programinfo.h"
#include "mythdbcon.h"
#include "avformatwriter.h"
#include "HLS/httplivestream.h"
#include "videodecodebuffer.h"
#include "cutter.h"
#include "audioreencodebuffer.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
}
using namespace std;
#define LOC QString("Transcode: ")
Transcode::Transcode(ProgramInfo *pginfo) :
m_proginfo(pginfo),
m_recProfile(new RecordingProfile("Transcoders")),
keyframedist(30),
nvr(NULL),
ctx(NULL),
outRingBuffer(NULL),
fifow(NULL),
kfa_table(NULL),
showprogress(false),
recorderOptions(""),
avfMode(false),
hlsMode(false), hlsStreamID(-1),
hlsDisableAudioOnly(false),
hlsMaxSegments(0),
cmdContainer("mpegts"), cmdAudioCodec("aac"),
cmdVideoCodec("libx264"),
cmdWidth(480), cmdHeight(0),
cmdBitrate(600000), cmdAudioBitrate(64000)
{
}
Transcode::~Transcode()
{
if (nvr)
delete nvr;
SetPlayerContext(NULL);
if (outRingBuffer)
delete outRingBuffer;
if (fifow)
delete fifow;
if (kfa_table)
delete kfa_table;
if (m_recProfile)
delete m_recProfile;
}
void Transcode::ReencoderAddKFA(long curframe, long lastkey, long num_keyframes)
{
long delta = curframe - lastkey;
if (delta != 0 && delta != keyframedist)
{
struct kfatable_entry kfate;
kfate.adjust = keyframedist - delta;
kfate.keyframe_number = num_keyframes;
kfa_table->push_back(kfate);
}
}
bool Transcode::GetProfile(QString profileName, QString encodingType,
int height, int frameRate)
{
if (profileName.toLower() == "autodetect")
{
if (height == 1088)
height = 1080;
QString autoProfileName = QObject::tr("Autodetect from %1").arg(height);
if (frameRate == 25 || frameRate == 30)
autoProfileName += "i";
if (frameRate == 50 || frameRate == 60)
autoProfileName += "p";
bool result = false;
LOG(VB_GENERAL, LOG_NOTICE,
QString("Transcode: Looking for autodetect profile: %1")
.arg(autoProfileName));
result = m_recProfile->loadByGroup(autoProfileName, "Transcoders");
if (!result && encodingType == "MPEG-2")
{
result = m_recProfile->loadByGroup("MPEG2", "Transcoders");
autoProfileName = "MPEG2";
}
if (!result && (encodingType == "MPEG-4" || encodingType == "RTjpeg"))
{
result = m_recProfile->loadByGroup("RTjpeg/MPEG4",
"Transcoders");
autoProfileName = "RTjpeg/MPEG4";
}
if (!result)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Transcode: Couldn't find profile for : %1")
.arg(encodingType));
return false;
}
LOG(VB_GENERAL, LOG_NOTICE,
QString("Transcode: Using autodetect profile: %1")
.arg(autoProfileName));
}
else
{
bool isNum;
int profileID;
profileID = profileName.toInt(&isNum);
// If a bad profile is specified, there will be trouble
if (isNum && profileID > 0)
m_recProfile->loadByID(profileID);
else if (!m_recProfile->loadByGroup(profileName, "Transcoders"))
{
LOG(VB_GENERAL, LOG_ERR, QString("Couldn't find profile #: %1")
.arg(profileName));
return false;
}
}
return true;
}
void Transcode::SetPlayerContext(PlayerContext *player_ctx)
{
if (player_ctx == ctx)
return;
delete ctx;
ctx = player_ctx;
}
static QString get_str_option(RecordingProfile *profile, const QString &name)
{
const Setting *setting = profile->byName(name);
if (setting)
return setting->getValue();
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("get_str_option(...%1): Option not in profile.").arg(name));
return QString::null;
}
static int get_int_option(RecordingProfile *profile, const QString &name)
{
QString ret_str = get_str_option(profile, name);
if (ret_str.isEmpty())
return 0;
bool ok = false;
int ret_int = ret_str.toInt(&ok);
if (!ok)
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("get_int_option(...%1): Option is not an int.").arg(name));
}
return ret_int;
}
static void TranscodeWriteText(void *ptr, unsigned char *buf, int len,
int timecode, int pagenr)
{
NuppelVideoRecorder *nvr = (NuppelVideoRecorder *)ptr;
nvr->WriteText(buf, len, timecode, pagenr);
}
int Transcode::TranscodeFile(const QString &inputname,
const QString &outputname,
const QString &profileName,
bool honorCutList, bool framecontrol,
int jobID, QString fifodir,
bool fifo_info, bool cleanCut,
frm_dir_map_t &deleteMap,
int AudioTrackNo,
bool passthru)
{
QDateTime curtime = MythDate::current();
QDateTime statustime = curtime;
int audioFrame = 0;
Cutter *cutter = NULL;
AVFormatWriter *avfw = NULL;
AVFormatWriter *avfw2 = NULL;
HTTPLiveStream *hls = NULL;
int hlsSegmentSize = 0;
int hlsSegmentFrames = 0;
if (jobID >= 0)
JobQueue::ChangeJobComment(jobID, "0% " + QObject::tr("Completed"));
if (hlsMode)
{
avfMode = true;
if (hlsStreamID != -1)
{
hls = new HTTPLiveStream(hlsStreamID);
hls->UpdateStatus(kHLSStatusStarting);
hls->UpdateStatusMessage("Transcoding Starting");
cmdWidth = hls->GetWidth();
cmdHeight = hls->GetHeight();
cmdBitrate = hls->GetBitrate();
cmdAudioBitrate = hls->GetAudioBitrate();
}
}
if (!avfMode)
{
nvr = new NuppelVideoRecorder(NULL, NULL);
if (!nvr)
{
LOG(VB_GENERAL, LOG_ERR,
"Transcoding aborted, error creating NuppelVideoRecorder.");
return REENCODE_ERROR;
}
}
// Input setup
PlayerContext *player_ctx = new PlayerContext(kTranscoderInUseID);
player_ctx->SetPlayingInfo(m_proginfo);
RingBuffer *rb = (hls && (hlsStreamID != -1)) ?
RingBuffer::Create(hls->GetSourceFile(), false, false) :
RingBuffer::Create(inputname, false, false);
if (!rb || !rb->GetLastError().isEmpty())
{
LOG(VB_GENERAL, LOG_ERR,
QString("Transcoding aborted, error: '%1'")
.arg(rb? rb->GetLastError() : ""));
delete player_ctx;
if (hls)
delete hls;
return REENCODE_ERROR;
}
player_ctx->SetRingBuffer(rb);
player_ctx->SetPlayer(new MythPlayer(kVideoIsNull));
SetPlayerContext(player_ctx);
GetPlayer()->SetPlayerInfo(NULL, NULL, GetPlayerContext());
if (m_proginfo->GetRecordingEndTime() > curtime)
{
player_ctx->SetRecorder(RemoteGetExistingRecorder(m_proginfo));
GetPlayer()->SetWatchingRecording(true);
}
if (showprogress)
{
statustime = statustime.addSecs(5);
}
AudioOutput *audioOutput = new AudioReencodeBuffer(FORMAT_NONE, 0,
passthru);
AudioReencodeBuffer *arb = ((AudioReencodeBuffer*)audioOutput);
GetPlayer()->GetAudio()->SetAudioOutput(audioOutput);
GetPlayer()->SetTranscoding(true);
if (GetPlayer()->OpenFile() < 0)
{
LOG(VB_GENERAL, LOG_ERR, "Transcoding aborted, error opening file.");
SetPlayerContext(NULL);
if (hls)
delete hls;
return REENCODE_ERROR;
}
if (AudioTrackNo > -1)
{
LOG(VB_GENERAL, LOG_INFO,
QString("Set audiotrack number to %1").arg(AudioTrackNo));
GetPlayer()->GetDecoder()->SetTrack(kTrackTypeAudio, AudioTrackNo);
}
long long total_frame_count = GetPlayer()->GetTotalFrameCount();
long long new_frame_count = total_frame_count;
if (honorCutList && m_proginfo)
{
LOG(VB_GENERAL, LOG_INFO, "Honoring the cutlist while transcoding");
frm_dir_map_t::const_iterator it;
QString cutStr;
long long lastStart = 0;
if (deleteMap.size() == 0)
m_proginfo->QueryCutList(deleteMap);
for (it = deleteMap.begin(); it != deleteMap.end(); ++it)
{
if (*it)
{
if (!cutStr.isEmpty())
cutStr += ",";
cutStr += QString("%1-").arg((long)it.key());
lastStart = it.key();
}
else
{
if (cutStr.isEmpty())
cutStr += "0-";
cutStr += QString("%1").arg((long)it.key());
new_frame_count -= (it.key() - lastStart);
}
}
if (cutStr.isEmpty())
cutStr = "Is Empty";
else if (cutStr.endsWith('-') && (total_frame_count > lastStart))
{
new_frame_count -= (total_frame_count - lastStart);
cutStr += QString("%1").arg(total_frame_count);
}
LOG(VB_GENERAL, LOG_INFO, QString("Cutlist : %1").arg(cutStr));
LOG(VB_GENERAL, LOG_INFO, QString("Original Length: %1 frames")
.arg((long)total_frame_count));
LOG(VB_GENERAL, LOG_INFO, QString("New Length : %1 frames")
.arg((long)new_frame_count));
if ((m_proginfo->QueryIsEditing()) ||
(JobQueue::IsJobRunning(JOB_COMMFLAG, *m_proginfo)))
{
LOG(VB_GENERAL, LOG_INFO, "Transcoding aborted, cutlist changed");
SetPlayerContext(NULL);
if (hls)
delete hls;
return REENCODE_CUTLIST_CHANGE;
}
m_proginfo->ClearMarkupFlag(MARK_UPDATED_CUT);
curtime = curtime.addSecs(60);
}
GetPlayer()->GetAudio()->ReinitAudio();
QString encodingType = GetPlayer()->GetEncodingType();
bool copyvideo = false, copyaudio = false;
QString vidsetting = NULL, audsetting = NULL, vidfilters = NULL;
QSize buf_size = GetPlayer()->GetVideoBufferSize();
int video_width = buf_size.width();
int video_height = buf_size.height();
if (video_height == 1088) {
LOG(VB_GENERAL, LOG_NOTICE,
"Found video height of 1088. This is unusual and "
"more than likely the video is actually 1080 so mythtranscode "
"will treat it as such.");
}
DecoderBase* dec = GetPlayer()->GetDecoder();
float video_aspect = dec ? dec->GetVideoAspect() : 4.0f / 3.0f;
float video_frame_rate = GetPlayer()->GetFrameRate();
int newWidth = video_width;
int newHeight = video_height;
bool halfFramerate = false;
bool skippedLastFrame = false;
kfa_table = new vector<struct kfatable_entry>;
if (avfMode)
{
newWidth = cmdWidth;
newHeight = cmdHeight;
// Absolutely no purpose is served by scaling video up beyond it's
// original resolution, quality is degraded, transcoding is
// slower and in future we may wish to scale bitrate according to
// resolution, so it would also waste bandwidth (when streaming)
//
// This change could be said to apply for all transcoding, but for now
// we're limiting it to HLS where it's uncontroversial
if (hlsMode)
{
// if (newWidth > video_width)
// newWidth = video_width;
if (newHeight > video_height)
{
newHeight = video_height;
newWidth = 0;
}
}
// TODO: is this necessary? It got commented out, but may still be
// needed.
// int actualHeight = (video_height == 1088 ? 1080 : video_height);
// If height or width are 0, then we need to calculate them
if (newHeight == 0 && newWidth > 0)
newHeight = (int)(1.0 * newWidth / video_aspect);
else if (newWidth == 0 && newHeight > 0)
newWidth = (int)(1.0 * newHeight * video_aspect);
else if (newWidth == 0 && newHeight == 0)
{
newHeight = 480;
newWidth = (int)(1.0 * 480 * video_aspect);
if (newWidth > 640)
{
newWidth = 640;
newHeight = (int)(1.0 * 640 / video_aspect);
}
}
// make sure dimensions are valid for MPEG codecs
newHeight = (newHeight + 15) & ~0xF;
newWidth = (newWidth + 15) & ~0xF;
avfw = new AVFormatWriter();
if (!avfw)
{
LOG(VB_GENERAL, LOG_ERR,
"Transcoding aborted, error creating AVFormatWriter.");
SetPlayerContext(NULL);
if (hls)
delete hls;
return REENCODE_ERROR;
}
avfw->SetVideoBitrate(cmdBitrate);
avfw->SetHeight(newHeight);
avfw->SetWidth(newWidth);
avfw->SetAspect(video_aspect);
avfw->SetAudioBitrate(cmdAudioBitrate);
avfw->SetAudioChannels(arb->m_channels);
avfw->SetAudioFrameRate(arb->m_eff_audiorate);
avfw->SetAudioFormat(FORMAT_S16);
if (hlsMode)
{
int segmentSize = 10;
int audioOnlyBitrate = 0;
if (!hlsDisableAudioOnly)
{
audioOnlyBitrate = 64000;
avfw2 = new AVFormatWriter();
avfw2->SetContainer("mpegts");
if (!gCoreContext->GetSetting("HLSAUDIO").isEmpty())
avfw2->SetAudioCodec(gCoreContext->GetSetting("HLSAUDIO"));
else
#if CONFIG_LIBFAAC_ENCODER
avfw2->SetAudioCodec("libfaac");
#else
# if CONFIG_LIBMP3LAME_ENCODER
avfw2->SetAudioCodec("libmp3lame");
# else
avfw2->SetAudioCodec("aac");
# endif
#endif
avfw2->SetAudioBitrate(audioOnlyBitrate);
avfw2->SetAudioChannels(arb->m_channels);
avfw2->SetAudioFrameRate(arb->m_eff_audiorate);
avfw2->SetAudioFormat(FORMAT_S16);
}
avfw->SetContainer("mpegts");
avfw->SetVideoCodec("libx264");
if (!gCoreContext->GetSetting("HLSAUDIO").isEmpty())
avfw->SetAudioCodec(gCoreContext->GetSetting("HLSAUDIO"));
else
#if CONFIG_LIBFAAC_ENCODER
avfw->SetAudioCodec("libfaac");
#else
# if CONFIG_LIBMP3LAME_ENCODER
avfw->SetAudioCodec("libmp3lame");
# else
avfw->SetAudioCodec("aac");
# endif
#endif
if (hlsStreamID == -1)
{
hls = new HTTPLiveStream(inputname, newWidth, newHeight,
cmdBitrate,
cmdAudioBitrate, hlsMaxSegments,
segmentSize, audioOnlyBitrate);
hlsStreamID = hls->GetStreamID();
if (!hls || hlsStreamID == -1)
{
LOG(VB_GENERAL, LOG_ERR, "Unable to create new stream");
SetPlayerContext(NULL);
delete avfw;
if (avfw2)
delete avfw2;
return REENCODE_ERROR;
}
}
hls->UpdateStatus(kHLSStatusStarting);
hls->UpdateStatusMessage("Transcoding Starting");
hls->UpdateSizeInfo(newWidth, newHeight, video_width, video_height);
if (!hls->InitForWrite())
{
LOG(VB_GENERAL, LOG_ERR, "hls->InitForWrite() failed");
SetPlayerContext(NULL);
delete hls;
delete avfw;
if (avfw2)
delete avfw2;
return REENCODE_ERROR;
}
if (video_frame_rate > 30)
{
halfFramerate = true;
avfw->SetFramerate(video_frame_rate/2);
if (avfw2)
avfw2->SetFramerate(video_frame_rate/2);
hlsSegmentSize = (int)(segmentSize * video_frame_rate / 2);
}
else
{
avfw->SetFramerate(video_frame_rate);
if (avfw2)
avfw2->SetFramerate(video_frame_rate);
hlsSegmentSize = (int)(segmentSize * video_frame_rate);
}
avfw->SetKeyFrameDist(30);
if (avfw2)
avfw2->SetKeyFrameDist(30);
hls->AddSegment();
avfw->SetFilename(hls->GetCurrentFilename());
if (avfw2)
avfw2->SetFilename(hls->GetCurrentFilename(true));
}
else
{
avfw->SetContainer(cmdContainer);
avfw->SetVideoCodec(cmdVideoCodec);
avfw->SetAudioCodec(cmdAudioCodec);
avfw->SetFilename(outputname);
avfw->SetFramerate(video_frame_rate);
avfw->SetKeyFrameDist(30);
}
int threads = gCoreContext->GetNumSetting("HTTPLiveStreamThreads", 2);
QString preset = gCoreContext->GetSetting("HTTPLiveStreamPreset", "medium");
QString tune = gCoreContext->GetSetting("HTTPLiveStreamTune", "film");
LOG(VB_GENERAL, LOG_NOTICE,
QString("x264 HLS using: %1 threads, '%2' profile and '%3' tune")
.arg(threads).arg(preset).arg(tune));
avfw->SetThreadCount(threads);
avfw->SetEncodingPreset(preset);
avfw->SetEncodingTune(tune);
if (avfw2)
avfw2->SetThreadCount(1);
if (!avfw->Init())
{
LOG(VB_GENERAL, LOG_ERR, "avfw->Init() failed");
SetPlayerContext(NULL);
if (hls)
delete hls;
delete avfw;
if (avfw2)
delete avfw2;
return REENCODE_ERROR;
}
if (!avfw->OpenFile())
{
LOG(VB_GENERAL, LOG_ERR, "avfw->OpenFile() failed");
SetPlayerContext(NULL);
if (hls)
delete hls;
delete avfw;
if (avfw2)
delete avfw2;
return REENCODE_ERROR;
}
if (avfw2 && !avfw2->Init())
{
LOG(VB_GENERAL, LOG_ERR, "avfw2->Init() failed");
SetPlayerContext(NULL);
if (hls)
delete hls;
delete avfw;
delete avfw2;
return REENCODE_ERROR;
}
if (avfw2 && !avfw2->OpenFile())
{
LOG(VB_GENERAL, LOG_ERR, "avfw2->OpenFile() failed");
SetPlayerContext(NULL);
if (hls)
delete hls;
delete avfw;
delete avfw2;
return REENCODE_ERROR;
}
arb->m_audioFrameSize = avfw->GetAudioFrameSize() * arb->m_channels * 2;
GetPlayer()->SetVideoFilters(
gCoreContext->GetSetting("HTTPLiveStreamFilters"));
}
else if (fifodir.isEmpty())
{
if (!GetProfile(profileName, encodingType, video_height,
(int)round(video_frame_rate))) {
LOG(VB_GENERAL, LOG_ERR, "Transcoding aborted, no profile found.");
SetPlayerContext(NULL);
return REENCODE_ERROR;
}
// For overriding settings on the command line
QMap<QString, QString> recorderOptionsMap;
if (!recorderOptions.isEmpty())
{
QStringList options = recorderOptions
.split(",", QString::SkipEmptyParts);
int loop = 0;
while (loop < options.size())
{
QStringList tokens = options[loop].split("=");
recorderOptionsMap[tokens[0]] = tokens[1];
loop++;
}
}
vidsetting = get_str_option(m_recProfile, "videocodec");
audsetting = get_str_option(m_recProfile, "audiocodec");
vidfilters = get_str_option(m_recProfile, "transcodefilters");
if (encodingType == "MPEG-2" &&
get_int_option(m_recProfile, "transcodelossless"))
{
LOG(VB_GENERAL, LOG_NOTICE, "Switching to MPEG-2 transcoder.");
SetPlayerContext(NULL);
return REENCODE_MPEG2TRANS;
}
// Recorder setup
if (get_int_option(m_recProfile, "transcodelossless"))
{
vidsetting = encodingType;
audsetting = "MP3";
}
else if (get_int_option(m_recProfile, "transcoderesize"))
{
int actualHeight = (video_height == 1088 ? 1080 : video_height);
GetPlayer()->SetVideoFilters(vidfilters);
newWidth = get_int_option(m_recProfile, "width");
newHeight = get_int_option(m_recProfile, "height");
// If height or width are 0, then we need to calculate them
if (newHeight == 0 && newWidth > 0)
newHeight = (int)(1.0 * newWidth * actualHeight / video_width);
else if (newWidth == 0 && newHeight > 0)
newWidth = (int)(1.0 * newHeight * video_width / actualHeight);
else if (newWidth == 0 && newHeight == 0)
{
newHeight = 480;
newWidth = (int)(1.0 * 480 * video_width / actualHeight);
if (newWidth > 640)
{
newWidth = 640;
newHeight = (int)(1.0 * 640 * actualHeight / video_width);
}
}
if (encodingType.startsWith("mpeg", Qt::CaseInsensitive))
{
// make sure dimensions are valid for MPEG codecs
newHeight = (newHeight + 15) & ~0xF;
newWidth = (newWidth + 15) & ~0xF;
}
LOG(VB_GENERAL, LOG_INFO, QString("Resizing from %1x%2 to %3x%4")
.arg(video_width).arg(video_height)
.arg(newWidth).arg(newHeight));
}
else // lossy and no resize
GetPlayer()->SetVideoFilters(vidfilters);
// this is ripped from tv_rec SetupRecording. It'd be nice to merge
nvr->SetOption("inpixfmt", FMT_YV12);
nvr->SetOption("width", newWidth);
nvr->SetOption("height", newHeight);
nvr->SetOption("tvformat", gCoreContext->GetSetting("TVFormat"));
nvr->SetOption("vbiformat", gCoreContext->GetSetting("VbiFormat"));
nvr->SetFrameRate(video_frame_rate);
nvr->SetVideoAspect(video_aspect);
nvr->SetTranscoding(true);
if ((vidsetting == "MPEG-4") ||
(recorderOptionsMap["videocodec"] == "mpeg4"))
{
nvr->SetOption("videocodec", "mpeg4");
nvr->SetIntOption(m_recProfile, "mpeg4bitrate");
nvr->SetIntOption(m_recProfile, "scalebitrate");
nvr->SetIntOption(m_recProfile, "mpeg4maxquality");
nvr->SetIntOption(m_recProfile, "mpeg4minquality");
nvr->SetIntOption(m_recProfile, "mpeg4qualdiff");
nvr->SetIntOption(m_recProfile, "mpeg4optionvhq");
nvr->SetIntOption(m_recProfile, "mpeg4option4mv");
#ifdef USING_FFMPEG_THREADS
nvr->SetIntOption(m_recProfile, "encodingthreadcount");
#endif
}
else if ((vidsetting == "MPEG-2") ||
(recorderOptionsMap["videocodec"] == "mpeg2video"))
{
nvr->SetOption("videocodec", "mpeg2video");
nvr->SetIntOption(m_recProfile, "mpeg2bitrate");
nvr->SetIntOption(m_recProfile, "scalebitrate");
#ifdef USING_FFMPEG_THREADS
nvr->SetIntOption(m_recProfile, "encodingthreadcount");
#endif
}
else if ((vidsetting == "RTjpeg") ||
(recorderOptionsMap["videocodec"] == "rtjpeg"))
{
nvr->SetOption("videocodec", "rtjpeg");
nvr->SetIntOption(m_recProfile, "rtjpegquality");
nvr->SetIntOption(m_recProfile, "rtjpegchromafilter");
nvr->SetIntOption(m_recProfile, "rtjpeglumafilter");
}
else if (vidsetting.isEmpty())
{
LOG(VB_GENERAL, LOG_ERR, "No video information found!");
LOG(VB_GENERAL, LOG_ERR, "Please ensure that recording profiles "
"for the transcoder are set");
SetPlayerContext(NULL);
return REENCODE_ERROR;
}
else
{
LOG(VB_GENERAL, LOG_ERR,
QString("Unknown video codec: %1").arg(vidsetting));
SetPlayerContext(NULL);
return REENCODE_ERROR;
}
nvr->SetOption("samplerate", arb->m_eff_audiorate);
if (audsetting == "MP3")
{
nvr->SetOption("audiocompression", 1);
nvr->SetIntOption(m_recProfile, "mp3quality");
copyaudio = true;
}
else if (audsetting == "Uncompressed")
{
nvr->SetOption("audiocompression", 0);
}
else
{
LOG(VB_GENERAL, LOG_ERR,
QString("Unknown audio codec: %1").arg(audsetting));
}
nvr->AudioInit(true);
// For overriding settings on the command line
if (recorderOptionsMap.size() > 0)
{
QMap<QString, QString>::Iterator it;
QString key, value;
for (it = recorderOptionsMap.begin();
it != recorderOptionsMap.end(); ++it)
{
key = it.key();
value = *it;
LOG(VB_GENERAL, LOG_NOTICE,
QString("Forcing Recorder option '%1' to '%2'")
.arg(key).arg(value));
if (value.contains(QRegExp("[^0-9]")))
nvr->SetOption(key, value);
else
nvr->SetOption(key, value.toInt());
if (key == "width")
newWidth = (value.toInt() + 15) & ~0xF;
else if (key == "height")
newHeight = (value.toInt() + 15) & ~0xF;
else if (key == "videocodec")
{
if (value == "mpeg4")
vidsetting = "MPEG-4";
else if (value == "mpeg2video")
vidsetting = "MPEG-2";
else if (value == "rtjpeg")
vidsetting = "RTjpeg";
}
}
}
if ((vidsetting == "MPEG-4") ||
(vidsetting == "MPEG-2"))
nvr->SetupAVCodecVideo();
else if (vidsetting == "RTjpeg")
nvr->SetupRTjpeg();
outRingBuffer = RingBuffer::Create(outputname, true, false);
nvr->SetRingBuffer(outRingBuffer);
nvr->WriteHeader();
nvr->StreamAllocate();
}
if (vidsetting == encodingType && !framecontrol && !avfMode &&
fifodir.isEmpty() && honorCutList &&
video_width == newWidth && video_height == newHeight)
{
copyvideo = true;
LOG(VB_GENERAL, LOG_INFO, "Reencoding video in 'raw' mode");
}
if (honorCutList && deleteMap.size() > 0)
{
if (cleanCut)
{
// Have the player seek only part of the way
// through a cut, and then use the cutter to
// discard the rest
cutter = new Cutter();
cutter->SetCutList(deleteMap, ctx);
GetPlayer()->SetCutList(cutter->AdjustedCutList());
}
else
{
// Have the player apply the cut list
GetPlayer()->SetCutList(deleteMap);
}
}
GetPlayer()->InitForTranscode(copyaudio, copyvideo);
if (GetPlayer()->IsErrored())
{
LOG(VB_GENERAL, LOG_ERR,
"Unable to initialize MythPlayer for Transcode");
SetPlayerContext(NULL);
if (hls)
delete hls;
if (avfw)
delete avfw;
if (avfw2)
delete avfw2;
return REENCODE_ERROR;
}
int vidSize = 0;
// 1920x1080 video is actually 1920x1088 because of the 16x16 blocks so
// we have to fudge the output size here. nuvexport knows how to handle
// this and as of right now it is the only app that uses the fifo ability.
if (video_height == 1080 && video_width == 1920)
vidSize = (1088 * 1920) * 3 / 2;
else
vidSize = (video_height * video_width) * 3 / 2;
VideoFrame frame;
frame.codec = FMT_YV12;
frame.width = newWidth;
frame.height = newHeight;
frame.size = newWidth * newHeight * 3 / 2;
if (!fifodir.isEmpty())
{
AudioPlayer *aplayer = GetPlayer()->GetAudio();
const char *audio_codec_name;
switch(aplayer->GetCodec())
{
case AV_CODEC_ID_AC3:
audio_codec_name = "ac3";
break;
case AV_CODEC_ID_EAC3:
audio_codec_name = "eac3";
break;
case AV_CODEC_ID_DTS:
audio_codec_name = "dts";
break;
case AV_CODEC_ID_TRUEHD:
audio_codec_name = "truehd";
break;
case AV_CODEC_ID_MP3:
audio_codec_name = "mp3";
break;
case AV_CODEC_ID_MP2:
audio_codec_name = "mp2";
break;
case AV_CODEC_ID_AAC:
audio_codec_name = "aac";
break;
case AV_CODEC_ID_AAC_LATM:
audio_codec_name = "aac_latm";
break;
default:
audio_codec_name = "unknown";
}
if (!arb->m_passthru)
audio_codec_name = "raw";
// If cutlist is used then get info on first uncut frame
if (honorCutList && fifo_info)
{
bool is_key;
int did_ff;
frm_dir_map_t::iterator dm_iter;
GetPlayer()->TranscodeGetNextFrame(dm_iter, did_ff, is_key, true);
QSize buf_size = GetPlayer()->GetVideoBufferSize();
video_width = buf_size.width();
video_height = buf_size.height();
video_aspect = GetPlayer()->GetVideoAspect();
video_frame_rate = GetPlayer()->GetFrameRate();
}
// Display details of the format of the fifo data.
LOG(VB_GENERAL, LOG_INFO,
QString("FifoVideoWidth %1").arg(video_width));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoVideoHeight %1").arg(video_height));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoVideoAspectRatio %1").arg(video_aspect));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoVideoFrameRate %1").arg(video_frame_rate));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoAudioFormat %1").arg(audio_codec_name));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoAudioChannels %1").arg(arb->m_channels));
LOG(VB_GENERAL, LOG_INFO,
QString("FifoAudioSampleRate %1").arg(arb->m_eff_audiorate));
if(fifo_info)
{
// Request was for just the format of fifo data, not for
// the actual transcode, so stop here.
unlink(outputname.toLocal8Bit().constData());
SetPlayerContext(NULL);
return REENCODE_OK;
}
QString audfifo = fifodir + QString("/audout");
QString vidfifo = fifodir + QString("/vidout");
int audio_size = arb->m_eff_audiorate * arb->m_bytes_per_frame;
// framecontrol is true if we want to enforce fifo sync.
if (framecontrol)
LOG(VB_GENERAL, LOG_INFO, "Enforcing sync on fifos");
fifow = new FIFOWriter(2, framecontrol);
if (!fifow->FIFOInit(0, QString("video"), vidfifo, vidSize, 50) ||
!fifow->FIFOInit(1, QString("audio"), audfifo, audio_size, 25))
{