xref: /aosp_15_r20/external/webrtc/test/testsupport/yuv_frame_writer.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <stdio.h>
12 
13 #include <string>
14 
15 #include "rtc_base/checks.h"
16 #include "rtc_base/logging.h"
17 #include "test/testsupport/frame_writer.h"
18 
19 namespace webrtc {
20 namespace test {
21 
YuvFrameWriterImpl(std::string output_filename,int width,int height)22 YuvFrameWriterImpl::YuvFrameWriterImpl(std::string output_filename,
23                                        int width,
24                                        int height)
25     : output_filename_(output_filename),
26       frame_length_in_bytes_(0),
27       width_(width),
28       height_(height),
29       output_file_(nullptr) {}
30 
~YuvFrameWriterImpl()31 YuvFrameWriterImpl::~YuvFrameWriterImpl() {
32   Close();
33 }
34 
Init()35 bool YuvFrameWriterImpl::Init() {
36   if (width_ <= 0 || height_ <= 0) {
37     RTC_LOG(LS_ERROR) << "Frame width and height must be positive.";
38     return false;
39   }
40   frame_length_in_bytes_ =
41       width_ * height_ + 2 * ((width_ + 1) / 2) * ((height_ + 1) / 2);
42 
43   output_file_ = fopen(output_filename_.c_str(), "wb");
44   if (output_file_ == nullptr) {
45     RTC_LOG(LS_ERROR) << "Couldn't open output file: "
46                       << output_filename_.c_str();
47     return false;
48   }
49   return true;
50 }
51 
WriteFrame(const uint8_t * frame_buffer)52 bool YuvFrameWriterImpl::WriteFrame(const uint8_t* frame_buffer) {
53   RTC_DCHECK(frame_buffer);
54   if (output_file_ == nullptr) {
55     RTC_LOG(LS_ERROR) << "YuvFrameWriterImpl is not initialized.";
56     return false;
57   }
58   size_t bytes_written =
59       fwrite(frame_buffer, 1, frame_length_in_bytes_, output_file_);
60   if (bytes_written != frame_length_in_bytes_) {
61     RTC_LOG(LS_ERROR) << "Cound't write frame to file: "
62                       << output_filename_.c_str();
63     return false;
64   }
65   return true;
66 }
67 
Close()68 void YuvFrameWriterImpl::Close() {
69   if (output_file_ != nullptr) {
70     fclose(output_file_);
71     output_file_ = nullptr;
72   }
73 }
74 
FrameLength()75 size_t YuvFrameWriterImpl::FrameLength() {
76   return frame_length_in_bytes_;
77 }
78 
79 }  // namespace test
80 }  // namespace webrtc
81