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 "modules/audio_processing/aec_dump/write_to_file_task.h"
12 
13 #include <string>
14 
15 namespace webrtc {
16 
WriteToFileTask(webrtc::FileWrapper * debug_file,int64_t * num_bytes_left_for_log)17 WriteToFileTask::WriteToFileTask(webrtc::FileWrapper* debug_file,
18                                  int64_t* num_bytes_left_for_log)
19     : debug_file_(debug_file),
20       num_bytes_left_for_log_(num_bytes_left_for_log) {}
21 
22 WriteToFileTask::~WriteToFileTask() = default;
23 
GetEvent()24 audioproc::Event* WriteToFileTask::GetEvent() {
25   return &event_;
26 }
27 
IsRoomForNextEvent(size_t event_byte_size) const28 bool WriteToFileTask::IsRoomForNextEvent(size_t event_byte_size) const {
29   int64_t next_message_size = event_byte_size + sizeof(int32_t);
30   return (*num_bytes_left_for_log_ < 0) ||
31          (*num_bytes_left_for_log_ >= next_message_size);
32 }
33 
UpdateBytesLeft(size_t event_byte_size)34 void WriteToFileTask::UpdateBytesLeft(size_t event_byte_size) {
35   RTC_DCHECK(IsRoomForNextEvent(event_byte_size));
36   if (*num_bytes_left_for_log_ >= 0) {
37     *num_bytes_left_for_log_ -= (sizeof(int32_t) + event_byte_size);
38   }
39 }
40 
Run()41 bool WriteToFileTask::Run() {
42   std::string event_string;
43   event_.SerializeToString(&event_string);
44 
45   const size_t event_byte_size = event_.ByteSizeLong();
46 
47   if (!IsRoomForNextEvent(event_byte_size)) {
48     // Ensure that no further events are written, even if they're smaller than
49     // the current event.
50     *num_bytes_left_for_log_ = 0;
51     return true;
52   }
53 
54   UpdateBytesLeft(event_byte_size);
55 
56   // Write message preceded by its size.
57   if (!debug_file_->Write(&event_byte_size, sizeof(int32_t))) {
58     RTC_NOTREACHED();
59   }
60   if (!debug_file_->Write(event_string.data(), event_string.length())) {
61     RTC_NOTREACHED();
62   }
63   return true;  // Delete task from queue at once.
64 }
65 
66 }  // namespace webrtc
67