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
|
#include "stream.h"
#include <c10/util/Logging.h>
#include <stdio.h>
#include <string.h>
#include "util.h"
namespace ffmpeg {
const AVRational timeBaseQ = AVRational{1, AV_TIME_BASE};
Stream::Stream(
AVFormatContext* inputCtx,
MediaFormat format,
bool convertPtsToWallTime,
int64_t loggingUuid)
: inputCtx_(inputCtx),
format_(format),
convertPtsToWallTime_(convertPtsToWallTime),
loggingUuid_(loggingUuid) {}
Stream::~Stream() {
if (frame_) {
av_free(frame_);
}
if (codecCtx_) {
avcodec_free_context(&codecCtx_);
}
}
// look up the proper CODEC querying the function
AVCodec* Stream::findCodec(AVCodecParameters* params) {
return (AVCodec*)avcodec_find_decoder(params->codec_id);
}
// Allocate memory for the AVCodecContext, which will hold the context for
// decode/encode process. Then fill this codec context with CODEC parameters
// defined in stream parameters. Open the codec, and allocate the global frame
// defined in the header file
int Stream::openCodec(std::vector<DecoderMetadata>* metadata, int num_threads) {
AVStream* steam = inputCtx_->streams[format_.stream];
AVCodec* codec = findCodec(steam->codecpar);
if (!codec) {
LOG(ERROR) << "LoggingUuid #" << loggingUuid_
<< ", avcodec_find_decoder failed for codec_id: "
<< int(steam->codecpar->codec_id);
return AVERROR(EINVAL);
}
if (!(codecCtx_ = avcodec_alloc_context3(codec))) {
LOG(ERROR) << "LoggingUuid #" << loggingUuid_
<< ", avcodec_alloc_context3 failed";
return AVERROR(ENOMEM);
}
// multithreading heuristics
// if user defined,
if (num_threads > max_threads) {
num_threads = max_threads;
}
if (num_threads > 0) {
// if user defined, respect that
// note that default thread_type will be used
codecCtx_->thread_count = num_threads;
} else {
// otherwise set sensible defaults
codecCtx_->thread_count = 8;
codecCtx_->thread_type = FF_THREAD_SLICE;
}
int ret;
// Copy codec parameters from input stream to output codec context
if ((ret = avcodec_parameters_to_context(codecCtx_, steam->codecpar)) < 0) {
LOG(ERROR) << "LoggingUuid #" << loggingUuid_
<< ", avcodec_parameters_to_context failed";
return ret;
}
// after avcodec_open2, value of codecCtx_->time_base is NOT meaningful
if ((ret = avcodec_open2(codecCtx_, codec, nullptr)) < 0) {
LOG(ERROR) << "LoggingUuid #" << loggingUuid_
<< ", avcodec_open2 failed: " << Util::generateErrorDesc(ret);
avcodec_free_context(&codecCtx_);
codecCtx_ = nullptr;
return ret;
}
frame_ = av_frame_alloc();
switch (format_.type) {
case TYPE_VIDEO:
fps_ = av_q2d(av_guess_frame_rate(inputCtx_, steam, nullptr));
break;
case TYPE_AUDIO:
fps_ = codecCtx_->sample_rate;
break;
default:
fps_ = 30.0;
}
if ((ret = initFormat())) {
LOG(ERROR) << "initFormat failed, type: " << format_.type;
}
if (metadata) {
DecoderMetadata header;
header.format = format_;
header.fps = fps_;
header.num = steam->time_base.num;
header.den = steam->time_base.den;
header.duration =
av_rescale_q(steam->duration, steam->time_base, timeBaseQ);
metadata->push_back(header);
}
return ret;
}
// send the raw data packet (compressed frame) to the decoder, through the codec
// context and receive the raw data frame (uncompressed frame) from the
// decoder, through the same codec context
int Stream::analyzePacket(const AVPacket* packet, bool* gotFrame) {
int consumed = 0;
int result = avcodec_send_packet(codecCtx_, packet);
if (result == AVERROR(EAGAIN)) {
*gotFrame = false; // no bytes get consumed, fetch frame
} else if (result == AVERROR_EOF) {
*gotFrame = false; // more than one flush packet
if (packet) {
// got packet after flush, this is an error
return result;
}
} else if (result < 0) {
LOG(ERROR) << "avcodec_send_packet failed, err: "
<< Util::generateErrorDesc(result);
return result; // error
} else {
consumed = packet ? packet->size : 0; // all bytes get consumed
}
result = avcodec_receive_frame(codecCtx_, frame_);
if (result >= 0) {
*gotFrame = true; // frame is available
} else if (result == AVERROR(EAGAIN)) {
*gotFrame = false; // no frames at this time, needs more packets
if (!consumed) {
// precaution, if no packages got consumed and no frames are available
return result;
}
} else if (result == AVERROR_EOF) {
*gotFrame = false; // the last frame has been flushed
// precaution, if no more frames are available assume we consume all bytes
consumed = 0;
} else { // error
LOG(ERROR) << "avcodec_receive_frame failed, err: "
<< Util::generateErrorDesc(result);
return result;
}
return consumed;
}
// General decoding function:
// given the packet, analyse the metadata, and write the
// metadata and the buffer to the DecoderOutputImage.
int Stream::decodePacket(
const AVPacket* packet,
DecoderOutputMessage* out,
bool headerOnly,
bool* hasMsg) {
int consumed;
bool gotFrame = false;
*hasMsg = false;
if ((consumed = analyzePacket(packet, &gotFrame)) >= 0 &&
(packet == nullptr || gotFrame)) {
int result;
if ((result = getMessage(out, !gotFrame, headerOnly)) < 0) {
return result; // report error
}
*hasMsg = result > 0;
}
return consumed;
}
int Stream::flush(DecoderOutputMessage* out, bool headerOnly) {
bool hasMsg = false;
int result = decodePacket(nullptr, out, headerOnly, &hasMsg);
if (result < 0) {
avcodec_flush_buffers(codecCtx_);
return result;
}
if (!hasMsg) {
avcodec_flush_buffers(codecCtx_);
return 0;
}
return 1;
}
// Sets the header and payload via stream::setHeader and copyFrameBytes
// functions that are defined in type stream subclass (VideoStream, AudioStream,
// ...)
int Stream::getMessage(DecoderOutputMessage* out, bool flush, bool headerOnly) {
if (flush) {
// only flush of audio frames makes sense
if (format_.type == TYPE_AUDIO) {
int processed = 0;
size_t total = 0;
// grab all audio bytes by chunks
do {
if ((processed = copyFrameBytes(out->payload.get(), flush)) < 0) {
return processed;
}
total += processed;
} while (processed);
if (total) {
// set header if message bytes are available
setHeader(&out->header, flush);
return 1;
}
}
return 0;
} else {
if (format_.type == TYPE_AUDIO) {
int processed = 0;
if ((processed = copyFrameBytes(out->payload.get(), flush)) < 0) {
return processed;
}
if (processed) {
// set header if message bytes are available
setHeader(&out->header, flush);
return 1;
}
return 0;
} else {
// set header
setHeader(&out->header, flush);
if (headerOnly) {
// Only header is requisted
return 1;
}
return copyFrameBytes(out->payload.get(), flush);
}
}
}
void Stream::setHeader(DecoderHeader* header, bool flush) {
header->seqno = numGenerator_++;
setFramePts(header, flush);
if (convertPtsToWallTime_) {
keeper_.adjust(header->pts);
}
header->format = format_;
header->keyFrame = 0;
header->fps = std::numeric_limits<double>::quiet_NaN();
}
void Stream::setFramePts(DecoderHeader* header, bool flush) {
if (flush) {
header->pts = nextPts_; // already in us
} else {
header->pts = frame_->best_effort_timestamp;
if (header->pts == AV_NOPTS_VALUE) {
header->pts = nextPts_;
} else {
header->pts = av_rescale_q(
header->pts,
inputCtx_->streams[format_.stream]->time_base,
timeBaseQ);
}
switch (format_.type) {
case TYPE_AUDIO:
nextPts_ = header->pts + frame_->nb_samples * AV_TIME_BASE / fps_;
break;
case TYPE_VIDEO:
nextPts_ = header->pts + AV_TIME_BASE / fps_;
break;
default:
nextPts_ = header->pts;
}
}
}
} // namespace ffmpeg
|