-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathTranscoder.cpp
More file actions
586 lines (510 loc) · 21 KB
/
Copy pathTranscoder.cpp
File metadata and controls
586 lines (510 loc) · 21 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
#include "Transcoder.hpp"
#include <AvTranscoder/file/util.hpp>
#include <AvTranscoder/progress/NoDisplayProgress.hpp>
#include <AvTranscoder/stat/VideoStat.hpp>
#include <cassert>
#include <limits>
#include <algorithm>
namespace avtranscoder
{
Transcoder::Transcoder(IOutputFile& outputFile)
: _outputFile(outputFile)
, _inputFiles()
, _streamTranscoders()
, _streamTranscodersAllocated()
, _profileLoader(true)
, _eProcessMethod(eProcessMethodLongest)
, _mainStreamIndex(0)
, _outputDuration(0)
{
}
Transcoder::~Transcoder()
{
for(std::vector<StreamTranscoder*>::iterator it = _streamTranscodersAllocated.begin();
it != _streamTranscodersAllocated.end(); ++it)
{
delete(*it);
}
for(std::vector<InputFile*>::iterator it = _inputFiles.begin(); it != _inputFiles.end(); ++it)
{
delete(*it);
}
}
void Transcoder::addStream(const InputStreamDesc& inputStreamDesc, const std::string& profileName, const float offset)
{
// Check filename
if(inputStreamDesc._filename.empty())
throw std::runtime_error("Can't process a stream without a filename indicated.");
if(profileName.empty())
{
// Re-wrap
if(!inputStreamDesc.demultiplexing())
addRewrapStream(inputStreamDesc, offset);
// Transcode (transparent for the user)
else
{
const ProfileLoader::Profile profile = getProfileFromInput(inputStreamDesc);
addStream(inputStreamDesc, profile, offset);
}
}
// Transcode
else
{
const ProfileLoader::Profile& encodingProfile = _profileLoader.getProfile(profileName);
addStream(inputStreamDesc, encodingProfile, offset);
}
}
void Transcoder::addStream(const InputStreamDesc& inputStreamDesc, const ProfileLoader::Profile& profile, const float offset)
{
// Check filename
if(!inputStreamDesc._filename.length())
throw std::runtime_error("Can't transcode a stream without a filename indicated.");
std::vector<InputStreamDesc> inputStreamDescArray;
inputStreamDescArray.push_back(inputStreamDesc);
addStream(inputStreamDescArray, profile, offset);
}
void Transcoder::addStream(const std::vector<InputStreamDesc>& inputStreamDescArray, const std::string& profileName, const float offset)
{
// Check number of inputs
if(inputStreamDescArray.empty())
throw std::runtime_error("Need a description of at least one input stream to start the process.");
// If there is one input, switch to an easier case
if(inputStreamDescArray.size() == 1)
{
addStream(inputStreamDescArray.at(0), profileName, offset);
return;
}
// Get encoding profile
ProfileLoader::Profile encodingProfile;
if(profileName.empty())
encodingProfile = getProfileFromInputs(inputStreamDescArray);
else
encodingProfile = _profileLoader.getProfile(profileName);
addStream(inputStreamDescArray, encodingProfile, offset);
}
void Transcoder::addStream(const std::vector<InputStreamDesc>& inputStreamDescArray, const ProfileLoader::Profile& profile, const float offset)
{
// Check number of inputs
if(inputStreamDescArray.empty())
throw std::runtime_error("Need a description of at least one input stream to start the process.");
addTranscodeStream(inputStreamDescArray, profile, offset);
}
void Transcoder::addGenerateStream(const std::string& encodingProfileName)
{
const ProfileLoader::Profile& encodingProfile = _profileLoader.getProfile(encodingProfileName);
addGenerateStream(encodingProfile);
}
void Transcoder::addGenerateStream(const ProfileLoader::Profile& encodingProfile)
{
// Add profile
if(!_profileLoader.hasProfile(encodingProfile))
_profileLoader.addProfile(encodingProfile);
LOG_INFO("Add generated stream with encodingProfile=" << encodingProfile.at(constants::avProfileIdentificatorHuman))
_streamTranscodersAllocated.push_back(new StreamTranscoder(_outputFile, encodingProfile));
_streamTranscoders.push_back(_streamTranscodersAllocated.back());
}
void Transcoder::addStream(StreamTranscoder& stream)
{
_streamTranscoders.push_back(&stream);
}
void Transcoder::preProcessCodecLatency()
{
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
LOG_DEBUG("Init stream " << streamIndex)
_streamTranscoders.at(streamIndex)->preProcessCodecLatency();
}
}
bool Transcoder::processFrame()
{
if(_streamTranscoders.size() == 0)
return false;
// For each stream, process a frame
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
LOG_DEBUG("Process stream " << streamIndex + 1 << "/" << _streamTranscoders.size())
// if a stream failed to process
if(!_streamTranscoders.at(streamIndex)->processFrame())
{
LOG_WARN("Failed to process the stream transcoder at index " << streamIndex)
// if this is the end of the main stream
if(streamIndex == _mainStreamIndex) {
LOG_INFO("End of process because the main stream at index " << _mainStreamIndex << " failed to process a new frame.")
return false;
}
}
}
return true;
}
ProcessStat Transcoder::process()
{
NoDisplayProgress progress;
return process(progress);
}
ProcessStat Transcoder::process(IProgress& progress)
{
if(_streamTranscoders.size() == 0)
throw std::runtime_error("Missing input streams in transcoder");
manageSwitchToGenerator();
LOG_INFO("Start process")
_outputFile.beginWrap();
preProcessCodecLatency();
const float expectedOutputDuration = getExpectedOutputDuration();
LOG_INFO("The expected output duration of the program will be " << expectedOutputDuration << "s.")
size_t frame = 0;
bool frameProcessed = true;
while(frameProcessed)
{
LOG_DEBUG("Process frame " << frame)
frameProcessed = processFrame();
++frame;
const float progressDuration = getCurrentOutputDuration();
// check if JobStatusCancel
if(progress.progress((progressDuration > expectedOutputDuration) ? expectedOutputDuration : progressDuration,
expectedOutputDuration) == eJobStatusCancel)
{
LOG_INFO("End of process because the job was canceled.")
break;
}
// check progressDuration
if(_eProcessMethod == eProcessMethodBasedOnDuration && progressDuration >= expectedOutputDuration)
{
LOG_INFO("End of process because the output program duration ("
<< progressDuration << "s) is equal or upper than " << expectedOutputDuration << "s.")
break;
}
}
_outputFile.endWrap();
LOG_INFO("End of process: " << ++frame << " frames processed")
LOG_INFO("Get process statistics")
ProcessStat processStat;
fillProcessStat(processStat);
return processStat;
}
void Transcoder::setProcessMethod(const EProcessMethod eProcessMethod, const size_t indexBasedStream,
const double outputDuration)
{
_eProcessMethod = eProcessMethod;
_mainStreamIndex = indexBasedStream;
_outputDuration = outputDuration;
}
void Transcoder::addRewrapStream(const InputStreamDesc& inputStreamDesc, const float offset)
{
LOG_INFO("Add rewrap stream from " << inputStreamDesc << " with offset=" << offset << "s")
InputFile* referenceFile = addInputFile(inputStreamDesc._filename, inputStreamDesc._streamIndex, offset);
_streamTranscodersAllocated.push_back(
new StreamTranscoder(referenceFile->getStream(inputStreamDesc._streamIndex), _outputFile, offset));
_streamTranscoders.push_back(_streamTranscodersAllocated.back());
}
void Transcoder::addTranscodeStream(const std::vector<InputStreamDesc>& inputStreamDescArray, const ProfileLoader::Profile& profile,
const float offset)
{
// Add profile
if(!_profileLoader.hasProfile(profile))
_profileLoader.addProfile(profile);
std::stringstream sources;
for(size_t index = 0; index < inputStreamDescArray.size(); ++index)
sources << inputStreamDescArray.at(index);
LOG_INFO("Add transcode stream from the following inputs:" << std::endl << sources.str()
<< "with encodingProfile=" << profile.at(constants::avProfileIdentificatorHuman) << std::endl
<< "and offset=" << offset << "s")
// Create all streams from the given inputs
std::vector<IInputStream*> inputStreams;
AVMediaType commonStreamType = AVMEDIA_TYPE_UNKNOWN;
for(std::vector<InputStreamDesc>::const_iterator it = inputStreamDescArray.begin(); it != inputStreamDescArray.end(); ++it)
{
if(it->_filename.empty())
{
inputStreams.push_back(NULL);
continue;
}
InputFile* referenceFile = addInputFile(it->_filename, it->_streamIndex, offset);
inputStreams.push_back(&referenceFile->getStream(it->_streamIndex));
// Check stream type
const AVMediaType currentStreamType = referenceFile->getProperties().getStreamPropertiesWithIndex(it->_streamIndex).getStreamType();
if(commonStreamType == AVMEDIA_TYPE_UNKNOWN)
commonStreamType = currentStreamType;
else if(currentStreamType != commonStreamType)
throw std::runtime_error("All the given inputs should be of the same type (video, audio...).");
}
_streamTranscodersAllocated.push_back(
new StreamTranscoder(inputStreamDescArray, inputStreams, _outputFile, profile, offset));
_streamTranscoders.push_back(_streamTranscodersAllocated.back());
}
InputFile* Transcoder::addInputFile(const std::string& filename, const int streamIndex, const float offset)
{
InputFile* referenceFile = NULL;
if(streamIndex >= 0)
{
for(std::vector<InputFile*>::iterator it = _inputFiles.begin(); it != _inputFiles.end(); ++it)
{
if(((*it)->getFilename() == filename) && !(*it)->getStream(streamIndex).isActivated())
{
referenceFile = (*it);
LOG_DEBUG("Get instance of InputFile from '" << filename << "'")
break;
}
}
}
if(!referenceFile)
{
LOG_DEBUG("New instance of InputFile from '" << filename << "'")
_inputFiles.push_back(new InputFile(filename));
referenceFile = _inputFiles.back();
}
if(streamIndex >= 0)
referenceFile->activateStream(streamIndex);
else
{
for(size_t index = 0; index < referenceFile->getProperties().getNbStreams(); ++index)
referenceFile->activateStream(index);
}
// If negative offset, move forward in the input stream
if(offset < 0)
referenceFile->seekAtTime(-offset);
return referenceFile;
}
ProfileLoader::Profile Transcoder::getProfileFromInput(const InputStreamDesc& inputStreamDesc)
{
std::vector<InputStreamDesc> inputStreamDescArray;
inputStreamDescArray.push_back(inputStreamDesc);
return getProfileFromInputs(inputStreamDescArray);
}
ProfileLoader::Profile Transcoder::getProfileFromInputs(const std::vector<InputStreamDesc>& inputStreamDescArray)
{
assert(inputStreamDescArray.size() >= 1);
// Get properties from the first input
size_t nonEmptyFileName = std::numeric_limits<size_t>::max();
for(size_t i = 0; i < inputStreamDescArray.size(); ++i)
{
if(!inputStreamDescArray.at(i)._filename.empty())
{
nonEmptyFileName = i;
break;
}
}
if(nonEmptyFileName == std::numeric_limits<size_t>::max())
throw std::runtime_error("Cannot get profile from empty input streams");
const InputStreamDesc& inputStreamDesc = inputStreamDescArray.at(nonEmptyFileName);
InputFile inputFile(inputStreamDesc._filename);
const StreamProperties* streamProperties = &inputFile.getProperties().getStreamPropertiesWithIndex(inputStreamDesc._streamIndex);
const VideoProperties* videoProperties = NULL;
const AudioProperties* audioProperties = NULL;
switch(inputFile.getStream(inputStreamDesc._streamIndex).getProperties().getStreamType())
{
case AVMEDIA_TYPE_VIDEO:
{
videoProperties = dynamic_cast<const VideoProperties*>(streamProperties);
break;
}
case AVMEDIA_TYPE_AUDIO:
{
audioProperties = dynamic_cast<const AudioProperties*>(streamProperties);
break;
}
default:
break;
}
// common fileds in profile types
ProfileLoader::Profile profile;
profile[constants::avProfileIdentificator] = "profileFromInput";
profile[constants::avProfileIdentificatorHuman] = "profile from input";
// video
if(videoProperties != NULL)
{
profile[constants::avProfileType] = avtranscoder::constants::avProfileTypeVideo;
profile[constants::avProfileCodec] = videoProperties->getCodecName();
profile[constants::avProfilePixelFormat] = videoProperties->getPixelProperties().getPixelFormatName();
std::stringstream ss;
ss << videoProperties->getFps();
profile[constants::avProfileFrameRate] = ss.str();
ss.str(""); ss << videoProperties->getWidth();
profile[constants::avProfileWidth] = ss.str();
ss.str(""); ss << videoProperties->getHeight();
profile[constants::avProfileHeight] = ss.str();
}
// audio
else if(audioProperties != NULL)
{
profile[constants::avProfileType] = avtranscoder::constants::avProfileTypeAudio;
profile[constants::avProfileCodec] = audioProperties->getCodecName();
profile[constants::avProfileSampleFormat] = audioProperties->getSampleFormatName();
std::stringstream ss;
ss << audioProperties->getSampleRate();
profile[constants::avProfileSampleRate] = ss.str();
ss.str("");
// override number of channels parameters to manage demultiplexing
size_t nbChannels = 0;
for(std::vector<InputStreamDesc>::const_iterator it = inputStreamDescArray.begin(); it != inputStreamDescArray.end(); ++it)
{
if(inputStreamDesc.demultiplexing())
nbChannels += it->_channelIndexArray.size();
else
{
InputFile inputFile(it->_filename);
const StreamProperties& currentStream = inputFile.getProperties().getStreamPropertiesWithIndex(inputStreamDesc._streamIndex);
if(currentStream.getStreamType() != AVMEDIA_TYPE_AUDIO)
throw std::runtime_error("All the given inputs should be audio streams.");
nbChannels += dynamic_cast<const AudioProperties&>(currentStream).getNbChannels();
}
}
ss << nbChannels;
profile[constants::avProfileChannel] = ss.str();
}
return profile;
}
float Transcoder::getStreamDuration(const size_t indexStream) const
{
return _streamTranscoders.at(indexStream)->getDuration();
}
float Transcoder::getMinTotalDuration()
{
float minTotalDuration = std::numeric_limits<float>::max();
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
const float streamDuration = getStreamDuration(streamIndex);
if(std::min(streamDuration, minTotalDuration) == streamDuration)
{
minTotalDuration = streamDuration;
_mainStreamIndex = streamIndex;
}
}
return minTotalDuration;
}
float Transcoder::getMaxTotalDuration()
{
float maxTotalDuration = 0;
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
const float streamDuration = getStreamDuration(streamIndex);
if(std::max(streamDuration, maxTotalDuration) == streamDuration)
{
maxTotalDuration = streamDuration;
_mainStreamIndex = streamIndex;
}
}
return maxTotalDuration;
}
float Transcoder::getExpectedOutputDuration()
{
switch(_eProcessMethod)
{
case eProcessMethodShortest:
return getMinTotalDuration();
case eProcessMethodLongest:
return getMaxTotalDuration();
case eProcessMethodBasedOnStream:
return getStreamDuration(_mainStreamIndex);
case eProcessMethodBasedOnDuration:
return _outputDuration;
case eProcessMethodInfinity:
return std::numeric_limits<float>::max();
default:
return getMaxTotalDuration();
}
}
float Transcoder::getCurrentOutputDuration() const
{
float currentOutputDuration = -1;
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
const float currentStreamDuration = _outputFile.getStream(streamIndex).getStreamDuration();
if(currentOutputDuration == -1)
currentOutputDuration = currentStreamDuration;
else if(currentStreamDuration < currentOutputDuration)
currentOutputDuration = currentStreamDuration;
}
return currentOutputDuration;
}
void Transcoder::manageSwitchToGenerator()
{
for(size_t i = 0; i < _streamTranscoders.size(); ++i)
{
const float currentDuration = _streamTranscoders.at(i)->getDuration();
switch(_eProcessMethod)
{
case eProcessMethodShortest:
if(_streamTranscoders.at(i)->getDuration() >= getMinTotalDuration())
_streamTranscoders.at(i)->needToSwitchToGenerator(false);
else
_streamTranscoders.at(i)->needToSwitchToGenerator();
break;
case eProcessMethodLongest:
if(_streamTranscoders.at(i)->getDuration() == getMaxTotalDuration())
_streamTranscoders.at(i)->needToSwitchToGenerator(false);
else
_streamTranscoders.at(i)->needToSwitchToGenerator();
break;
case eProcessMethodBasedOnStream:
if(i != _mainStreamIndex && currentDuration < _streamTranscoders.at(_mainStreamIndex)->getDuration())
_streamTranscoders.at(i)->needToSwitchToGenerator();
else
_streamTranscoders.at(i)->needToSwitchToGenerator(false);
break;
case eProcessMethodBasedOnDuration:
if(_streamTranscoders.at(i)->getDuration() >= _outputDuration)
_streamTranscoders.at(i)->needToSwitchToGenerator(false);
else
_streamTranscoders.at(i)->needToSwitchToGenerator();
break;
case eProcessMethodInfinity:
_streamTranscoders.at(i)->needToSwitchToGenerator();
break;
}
}
}
void Transcoder::fillProcessStat(ProcessStat& processStat)
{
for(size_t streamIndex = 0; streamIndex < _streamTranscoders.size(); ++streamIndex)
{
IOutputStream& stream = _streamTranscoders.at(streamIndex)->getOutputStream();
if(_streamTranscoders.at(streamIndex)->getInputStreams().empty())
{
LOG_WARN("Cannot process statistics of generated stream.")
continue;
}
size_t nonNullInputStreamIndex = 0;
std::vector<IInputStream*> inputStreams = _streamTranscoders.at(streamIndex)->getInputStreams();
for(size_t i = 0; i < inputStreams.size(); ++i)
{
if(inputStreams.at(i) != NULL)
{
nonNullInputStreamIndex = i;
break;
}
}
const IInputStream* inputStream = inputStreams.at(nonNullInputStreamIndex);
const AVMediaType mediaType = inputStream->getProperties().getStreamType();
switch(mediaType)
{
case AVMEDIA_TYPE_VIDEO:
{
VideoStat videoStat(stream.getStreamDuration(), stream.getNbFrames());
IEncoder* encoder = _streamTranscoders.at(streamIndex)->getEncoder();
if(encoder)
{
const AVCodecContext& encoderContext = encoder->getCodec().getAVCodecContext();
if(encoderContext.coded_frame && (encoderContext.flags & CODEC_FLAG_PSNR))
{
videoStat.setQuality(encoderContext.coded_frame->quality);
videoStat.setPSNR(encoderContext.coded_frame->error[0] /
(encoderContext.width * encoderContext.height * 255.0 * 255.0));
}
}
processStat.addVideoStat(streamIndex, videoStat);
break;
}
case AVMEDIA_TYPE_AUDIO:
{
AudioStat audioStat(stream.getStreamDuration(), stream.getNbFrames());
processStat.addAudioStat(streamIndex, audioStat);
break;
}
default:
LOG_WARN("No process statistics for stream at index: " << streamIndex << " (AVMediaType = " << mediaType
<< ")")
break;
}
}
}
}