1/*
2 * Copyright (c) 2024 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#include <cstdio>
17#include <cstring>
18#include <sstream>
19#include <dirent.h>
20#include "common/log.h"
21#include "osal/utils/dump_buffer.h"
22#include "parameter.h"
23#include "osal/filesystem/file_system.h"
24
25namespace {
26constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_FOUNDATION, "DumpBuffer" };
27constexpr size_t DUMP_DATA_UNIT = 1; // data unit is 1 byte
28}
29
30namespace OHOS {
31namespace Media {
32std::map<std::string, FILE*> allDumpFileFds;
33void DumpAVBufferToFile(const std::string& para, const std::string& fileName, const std::shared_ptr<AVBuffer>& buffer)
34{
35    MEDIA_LOG_D("dump avbuffer to %{public}s", fileName.c_str());
36    if (buffer == nullptr || buffer->memory_ == nullptr) {
37        MEDIA_LOG_E("buffer or memory is nullptr.");
38        return;
39    }
40    FALSE_RETURN_MSG((para == "w" || para == "a") && !fileName.empty(), "para or fileName is invalid.");
41    size_t bufferSize = static_cast<size_t>(buffer->memory_->GetSize());
42    FALSE_RETURN((bufferSize != 0) && (buffer->memory_->GetAddr() != nullptr));
43    std::string mode = para + "b+";
44    std::string filePath = DUMP_FILE_DIR + fileName;
45    if (filePath == "") {
46        return;
47    }
48    FILE* dumpFile = std::fopen(filePath.c_str(), mode.c_str());
49    if (dumpFile == nullptr) {
50        MEDIA_LOG_E("dump buffer to file failed.");
51        return;
52    }
53    size_t ret =
54        fwrite(reinterpret_cast<const char*>(buffer->memory_->GetAddr()), DUMP_DATA_UNIT, bufferSize, dumpFile);
55    if (ret < 0) {
56        MEDIA_LOG_I("dump is fail.");
57    }
58    std::fclose(dumpFile);
59}
60} // Media
61} // OHOS