File size: 7,013 Bytes
ea55f45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*

 * This copyright notice applies to this header file only:

 *

 * Copyright (c) 2010-2024 NVIDIA Corporation

 *

 * Permission is hereby granted, free of charge, to any person

 * obtaining a copy of this software and associated documentation

 * files (the "Software"), to deal in the Software without

 * restriction, includi ng without limitation the rights to use,

 * copy, modify, merge, publish, distribute, sublicense, and/or sell

 * copies of the software, and to permit persons to whom the

 * software is furnished to do so, subject to the following

 * conditions:

 *

 * The above copyright notice and this permission notice shall be

 * included in all copies or substantial portions of the Software.

 *

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES

 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND

 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT

 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,

 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING

 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

 * OTHER DEALINGS IN THE SOFTWARE.

 */
#pragma once

#include "NvCodecUtils.h"
#include "FFmpegDemuxer.h"
//---------------------------------------------------------------------------
//! \file FFmpegMuxer.h 
//! \brief Provides functionality for stream demuxing
//!
//! This header file is used by Transcode apps to demux input video clips before decoding frames from it. 
//---------------------------------------------------------------------------

/**

* @brief libavformat wrapper class. Puts the elementary encoded stream into container format.

*/

typedef enum {
    MEDIA_FORMAT_ELEMENTARY = 0,
    MEDIA_FORMAT_MOV = 1,
    MEDIA_FORMAT_MP4 = 2,
} MEDIA_FORMAT;

MEDIA_FORMAT GetMediaFormat (char* szOutputFileName)
{
    char* extension = strrchr(szOutputFileName, '.');
    if (_stricmp(extension, ".mov") == 0)
    {
        return MEDIA_FORMAT_MOV;
    }
    else if (_stricmp(extension, ".mp4") == 0)
    {
        return MEDIA_FORMAT_MP4;
    }
    else
        return MEDIA_FORMAT_ELEMENTARY;
}

class FFmpegMuxer {
private:
    AVFormatContext* inFmtc = NULL;
    AVFormatContext* fmtc = NULL;
    AVIOContext* avioc = NULL;
    AVPacket* packet = NULL;
    AVStream* videoStream = NULL;
    AVStream* stream = NULL;

    int iVideoStream;
    int nWidth, nHeight;
    double timeBase = 0.0;
    int64_t userTimeScale = 0;

public:
    FFmpegMuxer(const char* szFilePath, MEDIA_FORMAT mediaFormat, AVFormatContext *inFmtc, AVCodecID codecID, int width, int height) {

        if (mediaFormat == MEDIA_FORMAT_MOV)
        {
            ck(avformat_alloc_output_context2(&fmtc, NULL, "mov", szFilePath));
        }
        else if (mediaFormat == MEDIA_FORMAT_MP4)
        {
            ck(avformat_alloc_output_context2(&fmtc, NULL, "mp4", szFilePath));
        }

        this->inFmtc = inFmtc;
        for (int i = 0; i < (int)inFmtc->nb_streams; i++)
        {
            if (inFmtc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
            {
                stream = avformat_new_stream(fmtc, NULL);
                if (!stream) {
                    LOG(ERROR) << "Stream creation failed";
                    return;
                }

                stream->codecpar->codec_id = codecID;
                stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
                stream->codecpar->width = width;
                stream->codecpar->height = height;
            }
            else
            {
                stream = avformat_new_stream(fmtc, NULL);
                if (!stream) {
                    LOG(ERROR) << "Stream creation failed";
                    return;
                }

                if (avcodec_parameters_copy(stream->codecpar, inFmtc->streams[i]->codecpar) < 0) {
                    LOG(ERROR) << "Error copying codec parameters";
                    return;
                }
            }

            stream->time_base = inFmtc->streams[i]->time_base;

            if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
            {
                iVideoStream = i;
                videoStream = stream;
            }
        }

        //fix the default time resolution
        if (!(fmtc->oformat->flags & AVFMT_NOFILE)) {
            if (avio_open(&fmtc->pb, szFilePath, AVIO_FLAG_WRITE) < 0) {
                LOG(ERROR) << "Error opening output file" << szFilePath;
                return;
            }
        }

        if (avformat_write_header(fmtc, NULL) < 0) {
            LOG(ERROR) << "Error writing header";
            return;
        }

        packet = av_packet_alloc();
        if (!packet) {
            LOG(ERROR) << "Error allocating packet";
            return;
        }
    }

    ~FFmpegMuxer() {

        if (!fmtc) {
            return;
        }

        av_write_trailer(fmtc);

        if (!(fmtc->oformat->flags & AVFMT_NOFILE)) {
            avio_closep(&fmtc->pb);
        }

        av_packet_unref(packet);
        av_packet_free(&packet);

        avformat_free_context(fmtc);

        if (avioc) {
            av_freep(&avioc->buffer);
            av_freep(&avioc);
        }
    }

    bool Mux(uint8_t* data, unsigned int size, int64_t pts, int64_t dts, int stream_index, int is_key_frame = 0, int numb = 0) {
        if (!fmtc) {
            return false;
        }

        packet->data = data;
        packet->size = size;
        packet->stream_index = stream_index;
        if (is_key_frame)
            packet->flags |= AV_PKT_FLAG_KEY;

        int offset = 0;
        if (inFmtc->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            AVRational r = { 1, inFmtc->streams[stream_index]->avg_frame_rate.num };
            if (inFmtc->streams[stream_index]->avg_frame_rate.num > 0) {
                packet->duration = av_rescale_q(1, r, fmtc->streams[stream_index]->time_base);
                offset = (int)(numb * inFmtc->streams[stream_index]->time_base.den * inFmtc->streams[stream_index]->avg_frame_rate.den / inFmtc->streams[stream_index]->avg_frame_rate.num);
            }
            else {
                packet->duration = 0;
            }
        }

        packet->pts = av_rescale_q(pts, inFmtc->streams[stream_index]->time_base, fmtc->streams[stream_index]->time_base) + offset;
        packet->dts = av_rescale_q(dts, inFmtc->streams[stream_index]->time_base, fmtc->streams[stream_index]->time_base);

        if (packet->pts < packet->dts) {
            packet->pts = packet->dts;
        }

        if (av_interleaved_write_frame(fmtc, packet) < 0) {
            LOG(ERROR) << "Error writing frame\n";
            return false;
        }

        return true;
    }
};