1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #define HST_LOG_TAG "DataSinkFile"
17
18 #include "data_sink_file.h"
19 #include <fcntl.h>
20 #include "common/log.h"
21
22 namespace OHOS {
23 namespace Media {
DataSinkFile(FILE * file)24 DataSinkFile::DataSinkFile(FILE *file) : file_(file), pos_(0), end_(-1), isCanRead_(true)
25 {
26 end_ = fseek(file_, 0L, SEEK_END);
27 if (fseek(file_, 0L, SEEK_SET) < 0) {
28 MEDIA_LOG_E("failed to construct, file is %{public}p, error is %{public}s", file_, strerror(errno));
29 }
30 }
31
~DataSinkFile()32 DataSinkFile::~DataSinkFile()
33 {
34 if (file_ != nullptr) {
35 }
36 }
37
Read(uint8_t * buf,int32_t bufSize)38 int32_t DataSinkFile::Read(uint8_t *buf, int32_t bufSize)
39 {
40 FALSE_RETURN_V_MSG_E(file_ != nullptr, -1, "failed to read, file is %{public}p", file_);
41 if (pos_ >= end_) {
42 return 0;
43 }
44
45 FALSE_RETURN_V_MSG_E(fseek(file_, pos_, SEEK_SET) >= 0, -1, "failed to seek, %{public}s", strerror(errno));
46 int32_t size = fread(buf, 1, bufSize, file_);
47 FALSE_RETURN_V_MSG_E(size >= 0, -1, "failed to read, %{public}s", strerror(errno));
48
49 pos_ = pos_ + size;
50 return size;
51 }
52
Write(const uint8_t * buf,int32_t bufSize)53 int32_t DataSinkFile::Write(const uint8_t *buf, int32_t bufSize)
54 {
55 FALSE_RETURN_V_MSG_E(file_ != nullptr, -1, "failed to read, file is %{public}p", file_);
56
57 FALSE_RETURN_V_MSG_E(fseek(file_, pos_, SEEK_SET) >= 0, -1, "failed to seek, %{public}s", strerror(errno));
58 int32_t size = fwrite(buf, 1, bufSize, file_);
59 FALSE_RETURN_V_MSG_E(size == bufSize, -1, "failed to write, %{public}s", strerror(errno));
60
61 pos_ = pos_ + size;
62 end_ = pos_ > end_ ? pos_ : end_;
63 return size;
64 }
65
Seek(int64_t offset,int whence)66 int64_t DataSinkFile::Seek(int64_t offset, int whence)
67 {
68 switch (whence) {
69 case SEEK_SET:
70 pos_ = offset;
71 break;
72 case SEEK_CUR:
73 pos_ = pos_ + offset;
74 break;
75 case SEEK_END:
76 pos_ = end_ + offset;
77 break;
78 default:
79 pos_ = offset;
80 break;
81 }
82 return pos_;
83 }
84
GetCurrentPosition() const85 int64_t DataSinkFile::GetCurrentPosition() const
86 {
87 return pos_;
88 }
89
CanRead()90 bool DataSinkFile::CanRead()
91 {
92 return isCanRead_;
93 }
94 } // namespace Media
95 } // namespace OHOS