video_decoder.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "video_decoder.h"
  2. #include "ffmpeg.h"
  3. VideoDecoder::VideoDecoder(AVCodecParameters* codec_parameters) {
  4. avcodec_register_all();
  5. const auto codec = avcodec_find_decoder(codec_parameters->codec_id);
  6. if (!codec) {
  7. throw ffmpeg::Error{"Unsupported video codec"};
  8. }
  9. codec_context_ = avcodec_alloc_context3(codec);
  10. if (!codec_context_) {
  11. throw ffmpeg::Error{"Couldn't allocate video codec context"};
  12. }
  13. ffmpeg::check(avcodec_parameters_to_context(
  14. codec_context_, codec_parameters));
  15. ffmpeg::check(avcodec_open2(codec_context_, codec, nullptr));
  16. }
  17. VideoDecoder::~VideoDecoder() {
  18. avcodec_free_context(&codec_context_);
  19. }
  20. bool VideoDecoder::send(AVPacket* packet) {
  21. auto ret = avcodec_send_packet(codec_context_, packet);
  22. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  23. return false;
  24. } else {
  25. ffmpeg::check(ret);
  26. return true;
  27. }
  28. }
  29. bool VideoDecoder::receive(AVFrame* frame) {
  30. auto ret = avcodec_receive_frame(codec_context_, frame);
  31. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  32. return false;
  33. } else {
  34. ffmpeg::check(ret);
  35. return true;
  36. }
  37. }
  38. unsigned VideoDecoder::width() const {
  39. return codec_context_->width;
  40. }
  41. unsigned VideoDecoder::height() const {
  42. return codec_context_->height;
  43. }
  44. AVPixelFormat VideoDecoder::pixel_format() const {
  45. return codec_context_->pix_fmt;
  46. }
  47. AVRational VideoDecoder::time_base() const {
  48. return codec_context_->time_base;
  49. }