Debian Codegraph @

cvd_src/videoffmpeg.cc

raw symbols SCIP
1 #include "cvd/videoffmpeg.h"
2
3 extern "C"
4 {
5 #include <libavcodec/avcodec.h>
6 #include <libavformat/avformat.h>
7 #include <libavutil/imgutils.h>
8 #include <libswscale/swscale.h>
9 }
10
11 #include <memory>
12 #include <stdexcept>
13 #include <string>
14
15 namespace CVD
16 {
17 namespace internal
18 {
19 namespace
20 {
21 using namespace std::string_literals;
22 }
23
24 void AVCodecContextCloser::operator()(AVCodecContext* context) const
25 {
26 if(context)
27 {
28 av_freep(&context->extradata);
29 avcodec_close(context);
30 av_free(context);
31 }
32 }
33
34 void AVFormatContextCloser::operator()(AVFormatContext* context) const
35 {
36 if(context)
37 {
38 avformat_close_input(&context);
39 avformat_free_context(context);
40 }
41 }
42
43 void AVFrameDeleter::operator()(AVFrame* p) const
44 {
45 if(p)
46 {
47 av_frame_free(&p);
48 }
49 }
50
51 void AVPacketDeleter::operator()(AVPacket* p) const
52 {
53 if(p)
54 {
55 av_packet_free(&p);
56 }
57 }
58
59 void SwsContextCloser::operator()(SwsContext* context) const
60 {
61 if(context)
62 {
63 sws_freeContext(context);
64 }
65 }
66
67 void CheckAVError(int result)
68 {
69 if(result != 0)
70 {
71 char error[1024];
72 av_strerror(result, error, sizeof(error));
73 throw std::runtime_error("Video encoding/decoding error: "s + error);
74 }
75 }
76
77 void SendFrame(AVFormatContext* format, AVCodecContext* codec, const AVFrame* frame)
78 {
79 bool sent = false;
80 while(!sent)
81 {
82 int r = avcodec_send_frame(codec, frame);
83 if(r != AVERROR(EAGAIN))
84 {
85 CheckAVError(r);
86 sent = true;
87 }
88
89 for(;;)
90 {
91 std::unique_ptr<AVPacket, AVPacketDeleter> packet(av_packet_alloc());
92 int r = avcodec_receive_packet(codec, packet.get());
93 if(r == AVERROR(EAGAIN) || r == AVERROR_EOF)
94 {
95 break;
96 }
97 CheckAVError(r);
98 packet->duration = format->streams[packet->stream_index]->r_frame_rate.den;
99 CheckAVError(av_interleaved_write_frame(format, packet.get()));
100 }
101 }
102 }
103
104 void SetColorSpace(SwsContext* scalerContext, int colorspace)
105 {
106 // Newer VideoRecorder videos are encoded with Rec. 709 color conversion, so set the appropriate scaler
107 // color space.
108 int* invTable;
109 int* table;
110 int inFull, outFull, brightness, contrast, saturation;
111 sws_getColorspaceDetails(scalerContext, &invTable, &inFull, &table, &outFull, &brightness, &contrast, &saturation);
112 auto coefficients = sws_getCoefficients(colorspace);
113 sws_setColorspaceDetails(
114 scalerContext, coefficients, inFull, coefficients, outFull, brightness, contrast, saturation);
115 }
116
117 }
118 }