hunting/utils/MediaBase/src/FfmpegOutputStream.cpp
2024-06-29 20:03:12 +08:00

78 lines
2.5 KiB
C++

/*
* Copyright (c) 2023 Fancy Code.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FfmpegOutputStream.h"
#include "FfmpegDecoder.h"
#include "FfmpegEncoder.h"
#include "ILog.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <libavcodec/codec_id.h>
#include <libavcodec/packet.h>
#include <libavformat/avformat.h>
#include <libavutil/frame.h>
#ifdef __cplusplus
}
#endif
#include <cstddef>
#include <functional>
#include <memory>
FfmpegOutputStream::FfmpegOutputStream(const AVCodecID &encodecId, const AVCodecID &dncodecId)
: mEncodecId(encodecId), mDeccodecId(dncodecId), mTmpPkt(nullptr), mStream(nullptr)
{
}
bool FfmpegOutputStream::Init(AVFormatContext *outputFormat)
{
mDecodeCallback = std::bind(&FfmpegOutputStream::GetDecodeDataCallback, this, std::placeholders::_1);
mTmpPkt = av_packet_alloc();
if (!mTmpPkt) {
LogError("Could not allocate AVPacket\n");
return false;
}
mStream = avformat_new_stream(outputFormat, nullptr);
if (!mStream) {
LogError("Could not allocate stream\n");
return false;
}
mDecoder = std::make_shared<FfmpegDecoder>(mDeccodecId);
mDecoder->Init();
mStream->id = outputFormat->nb_streams - 1;
mEncoder = std::make_shared<FfmpegEncoder>(mEncodecId);
mEncoder->Init(outputFormat->flags);
mStream->time_base = mEncoder->GetTimeBase();
mEncoder->OpenEncoder(nullptr, mStream);
return true;
}
void FfmpegOutputStream::UnInit(void)
{
mEncoder->UnInit();
mDecoder->UnInit();
av_packet_free(&mTmpPkt);
}
void FfmpegOutputStream::WriteSourceData(const void *data, const size_t &size)
{
mDecoder->DecodeData(data, size, mDecodeCallback);
}
void FfmpegOutputStream::SetWriteSourceDataCallback(std::function<void(AVPacket *pkt)> callback)
{
mEncodeCallback = callback;
}
void FfmpegOutputStream::GetDecodeDataCallback(AVFrame *frame)
{
mEncoder->EncodeData(frame, mStream, mEncodeCallback);
}
void FfmpegOutputStream::GetEncodeDataCallback(AVPacket *pkt)
{
}