Debian Codegraph @

heifio/encoder_y4m.cc

raw
1 /*
2 libheif example application.
3
4 MIT License
5
6 Copyright (c) 2019 Dirk Farin <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in all
16 copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 SOFTWARE.
25 */
26 #include "encoder_y4m.h"
27
28 #include <cerrno>
29 #include <cstring>
30 #include <cassert>
31
32
33 Y4MEncoder::Y4MEncoder() = default;
34
35
36 void Y4MEncoder::UpdateDecodingOptions(const struct heif_image_handle* handle,
37 struct heif_decoding_options* options) const
38 {
39 options->convert_hdr_to_8bit = 1;
40 }
41
42
43 bool Y4MEncoder::Encode(const struct heif_image_handle* handle,
44 const struct heif_image* image,
45 const std::string& filename)
46 {
47 FILE* fp = fopen(filename.c_str(), "wb");
48 if (!fp) {
49 fprintf(stderr, "Can't open %s: %s\n", filename.c_str(), strerror(errno));
50 return false;
51 }
52
53 size_t y_stride, cb_stride, cr_stride;
54 const uint8_t* yp = heif_image_get_plane_readonly2(image, heif_channel_Y, &y_stride);
55 const uint8_t* cbp = heif_image_get_plane_readonly2(image, heif_channel_Cb, &cb_stride);
56 const uint8_t* crp = heif_image_get_plane_readonly2(image, heif_channel_Cr, &cr_stride);
57
58 assert(y_stride > 0);
59 assert(cb_stride > 0);
60 assert(cr_stride > 0);
61
62 int yw = heif_image_get_width(image, heif_channel_Y);
63 int yh = heif_image_get_height(image, heif_channel_Y);
64 int cw = heif_image_get_width(image, heif_channel_Cb);
65 int ch = heif_image_get_height(image, heif_channel_Cb);
66
67 if (yw < 0 || cw < 0) {
68 fclose(fp);
69 return false;
70 }
71
72 fprintf(fp, "YUV4MPEG2 W%d H%d F30:1\nFRAME\n", yw, yh);
73
74 for (int y = 0; y < yh; y++) {
75 fwrite(yp + y * y_stride, 1, yw, fp);
76 }
77
78 for (int y = 0; y < ch; y++) {
79 fwrite(cbp + y * cb_stride, 1, cw, fp);
80 }
81
82 for (int y = 0; y < ch; y++) {
83 fwrite(crp + y * cr_stride, 1, cw, fp);
84 }
85
86 fclose(fp);
87
88 return true;
89 }