Support encoding of MPEG2 DCPs.
[dcpomatic.git] / src / lib / mpeg2_encoder.cc
1 /*
2     Copyright (C) 2024 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "mpeg2_encoder.h"
23 #include "writer.h"
24 #include <dcp/ffmpeg_image.h>
25 extern "C" {
26 #include <libavutil/pixfmt.h>
27 }
28
29
30 using std::shared_ptr;
31
32
33 MPEG2Encoder::MPEG2Encoder(shared_ptr<const Film> film, Writer& writer)
34         : VideoEncoder(film, writer)
35         , _transcoder(film->frame_size(), film->video_frame_rate(), film->video_bit_rate())
36 {
37
38 }
39
40
41 void
42 MPEG2Encoder::encode(shared_ptr<PlayerVideo> pv, dcpomatic::DCPTime time)
43 {
44         VideoEncoder::encode(pv, time);
45
46         auto image = pv->image(
47                 [](AVPixelFormat) { return AV_PIX_FMT_YUV420P; },
48                 VideoRange::VIDEO,
49                 false
50                 );
51
52         dcp::FFmpegImage ffmpeg_image(time.get() * _film->video_frame_rate() / dcpomatic::DCPTime::HZ);
53
54         DCPOMATIC_ASSERT(image->size() == ffmpeg_image.size());
55
56         auto height = image->size().height;
57
58         for (int y = 0; y < height; ++y) {
59                 memcpy(ffmpeg_image.y() + ffmpeg_image.y_stride() * y, image->data()[0] + image->stride()[0] * y, ffmpeg_image.y_stride());
60         }
61
62         for (int y = 0; y < height / 2; ++y) {
63                 memcpy(ffmpeg_image.u() + ffmpeg_image.u_stride() * y, image->data()[1] + image->stride()[1] * y, ffmpeg_image.u_stride());
64                 memcpy(ffmpeg_image.v() + ffmpeg_image.v_stride() * y, image->data()[2] + image->stride()[2] * y, ffmpeg_image.v_stride());
65         }
66
67         if (auto compressed = _transcoder.compress_frame(std::move(ffmpeg_image))) {
68                 _writer.write(compressed->first, compressed->second);
69         }
70 }
71
72
73 void
74 MPEG2Encoder::end()
75 {
76         if (auto compressed = _transcoder.flush()) {
77                 _writer.write(compressed->first, compressed->second);
78         }
79 }
80