FfmpegStream.cpp 5.67 KB
Newer Older
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
#include "FfmpegStream.h"
#include "FfmpegUtil.h"

using namespace std;

// (TODO) Currently, disable the use of refCount
static int refCount = 0;

FfmpegStream::FfmpegStream(
    AVFormatContext* inputCtx,
    int index,
    enum AVMediaType avMediaType,
    double seekFrameMargin)
    : inputCtx_(inputCtx),
      index_(index),
      avMediaType_(avMediaType),
      seekFrameMargin_(seekFrameMargin) {}

FfmpegStream::~FfmpegStream() {
  if (frame_) {
    av_frame_free(&frame_);
  }
  avcodec_free_context(&codecCtx_);
}

int FfmpegStream::openCodecContext() {
  VLOG(2) << "stream start_time: " << inputCtx_->streams[index_]->start_time;

  auto typeString = av_get_media_type_string(avMediaType_);
  AVStream* st = inputCtx_->streams[index_];
  auto codec_id = st->codecpar->codec_id;
  VLOG(1) << "codec_id: " << codec_id;
  AVCodec* codec = avcodec_find_decoder(codec_id);
  if (!codec) {
    LOG(ERROR) << "avcodec_find_decoder failed for codec_id: " << int(codec_id);
    return AVERROR(EINVAL);
  }
  VLOG(1) << "Succeed to find decoder";

  codecCtx_ = avcodec_alloc_context3(codec);
  if (!codecCtx_) {
    LOG(ERROR) << "avcodec_alloc_context3 fails";
    return AVERROR(ENOMEM);
  }

  int ret;
  /* Copy codec parameters from input stream to output codec context */
  if ((ret = avcodec_parameters_to_context(codecCtx_, st->codecpar)) < 0) {
    LOG(ERROR) << "Failed to copy " << typeString
               << " codec parameters to decoder context";
    return ret;
  }

  AVDictionary* opts = nullptr;
  av_dict_set(&opts, "refcounted_frames", refCount ? "1" : "0", 0);

  // after avcodec_open2, value of codecCtx_->time_base is NOT meaningful
  // But inputCtx_->streams[index_]->time_base has meaningful values
  if ((ret = avcodec_open2(codecCtx_, codec, &opts)) < 0) {
    LOG(ERROR) << "avcodec_open2 failed. " << ffmpeg_util::getErrorDesc(ret);
    return ret;
  }
  VLOG(1) << "Succeed to open codec";

  frame_ = av_frame_alloc();
  return initFormat();
}

unique_ptr<DecodedFrame> FfmpegStream::getFrameData(int getPtsOnly) {
  if (!codecCtx_) {
    LOG(ERROR) << "Codec is not initialized";
    return nullptr;
  }
  if (getPtsOnly) {
    unique_ptr<DecodedFrame> decodedFrame = make_unique<DecodedFrame>();
    decodedFrame->pts_ = frame_->pts;
    return decodedFrame;
  } else {
    unique_ptr<DecodedFrame> decodedFrame = sampleFrameData();
    if (decodedFrame) {
      decodedFrame->pts_ = frame_->pts;
    }
    return decodedFrame;
  }
}

void FfmpegStream::flush(int getPtsOnly, DecoderOutput& decoderOutput) {
  VLOG(1) << "Media Type: " << getMediaType() << ", flush stream.";
  // need to receive frames before entering draining mode
  receiveAvailFrames(getPtsOnly, decoderOutput);

  VLOG(2) << "send nullptr packet";
  sendPacket(nullptr);
  // receive remaining frames after entering draining mode
  receiveAvailFrames(getPtsOnly, decoderOutput);

  avcodec_flush_buffers(codecCtx_);
}

bool FfmpegStream::isFramePtsInRange() {
  CHECK(frame_);
  auto pts = frame_->pts;
  auto startPts = this->getStartPts();
  auto endPts = this->getEndPts();
  VLOG(2) << "isPtsInRange. pts: " << pts << ", startPts: " << startPts
          << ", endPts: " << endPts;
  return (pts == AV_NOPTS_VALUE) ||
      (pts >= startPts && (endPts >= 0 ? pts <= endPts : true));
}

bool FfmpegStream::isFramePtsExceedRange() {
  if (frame_) {
    auto endPts = this->getEndPts();
    VLOG(2) << "isFramePtsExceedRange. last_pts_: " << last_pts_
            << ", endPts: " << endPts;
    return endPts >= 0 ? last_pts_ >= endPts : false;
  } else {
    return true;
  }
}

// seek a frame
int FfmpegStream::seekFrame(int64_t seekPts) {
  // translate margin from second to pts
  int64_t margin = (int64_t)(
      seekFrameMargin_ * (double)inputCtx_->streams[index_]->time_base.den /
      (double)inputCtx_->streams[index_]->time_base.num);
  int64_t real_seekPts = (seekPts - margin) > 0 ? (seekPts - margin) : 0;
  VLOG(2) << "seek margin: " << margin;
  VLOG(2) << "real seekPts: " << real_seekPts;
  int ret = av_seek_frame(
      inputCtx_,
      index_,
      (seekPts - margin) > 0 ? (seekPts - margin) : 0,
      AVSEEK_FLAG_BACKWARD);
  if (ret < 0) {
    LOG(WARNING) << "av_seek_frame fails. Stream index: " << index_;
    return ret;
  }
  return 0;
}

// send/receive encoding and decoding API overview
// https://ffmpeg.org/doxygen/3.4/group__lavc__encdec.html
int FfmpegStream::sendPacket(const AVPacket* packet) {
  return avcodec_send_packet(codecCtx_, packet);
}

int FfmpegStream::receiveFrame() {
  int ret = avcodec_receive_frame(codecCtx_, frame_);
  if (ret >= 0) {
    // succeed
    frame_->pts = av_frame_get_best_effort_timestamp(frame_);
    if (frame_->pts == AV_NOPTS_VALUE) {
      // Trick: if we can not figure out pts, we just set it to be (last_pts +
      // 1)
      frame_->pts = last_pts_ + 1;
    }
    last_pts_ = frame_->pts;

    VLOG(2) << "avcodec_receive_frame succeed";
  } else if (ret == AVERROR(EAGAIN)) {
    VLOG(2) << "avcodec_receive_frame fails and returns AVERROR(EAGAIN). ";
  } else if (ret == AVERROR_EOF) {
    // no more frame to read
    VLOG(2) << "avcodec_receive_frame returns AVERROR_EOF";
  } else {
    LOG(WARNING) << "avcodec_receive_frame failed. Error: "
                 << ffmpeg_util::getErrorDesc(ret);
  }
  return ret;
}

void FfmpegStream::receiveAvailFrames(
    int getPtsOnly,
    DecoderOutput& decoderOutput) {
  int result = 0;
  while ((result = receiveFrame()) >= 0) {
    unique_ptr<DecodedFrame> decodedFrame = getFrameData(getPtsOnly);

    if (decodedFrame &&
        ((!getPtsOnly && decodedFrame->frameSize_ > 0) || getPtsOnly)) {
      if (isFramePtsInRange()) {
        decoderOutput.addMediaFrame(getMediaType(), std::move(decodedFrame));
      }
    } // end-if
  } // end-while
}