root/OpenSceneGraph/trunk/src/osgPlugins/ffmpeg/FFmpegDecoderVideo.cpp @ 9861

Revision 9861, 9.1 kB (checked in by robert, 6 years ago)

Removed boost reference and cleaned up debug output

RevLine 
[9816]1#include "FFmpegDecoderVideo.hpp"
2
3#include <osg/Notify>
[9860]4#include <osg/Timer>
[9816]5
6#include <stdexcept>
7#include <string.h>
8
9namespace osgFFmpeg {
10
11FFmpegDecoderVideo::FFmpegDecoderVideo(PacketQueue & packets, FFmpegClocks & clocks) :
12    m_packets(packets),
13    m_clocks(clocks),
14    m_stream(0),
15    m_context(0),
16    m_codec(0),
17    m_packet_data(0),
18    m_bytes_remaining(0),
19    m_packet_pts(AV_NOPTS_VALUE),
[9860]20    m_writeBuffer(0),
[9816]21    m_user_data(0),
22    m_publish_func(0),
[9857]23    m_exit(false)
24#ifdef USE_SWSCALE
25    ,m_swscale_ctx(0)
26#endif
[9816]27{
28
29}
30
31
32
33FFmpegDecoderVideo::~FFmpegDecoderVideo()
34{
[9861]35    osg::notify(osg::NOTICE)<<"Destructing FFmpegDecoderVideo..."<<std::endl;
36
[9816]37    if (isRunning())
38    {
39        m_exit = true;
40        join();
41    }
[9854]42   
[9857]43#ifdef USE_SWSCALE
[9854]44    if (m_swscale_ctx)
45    {
46        sws_freeContext(m_swscale_ctx);
47        m_swscale_ctx = 0;
48    }
[9857]49#endif
[9861]50
51    osg::notify(osg::NOTICE)<<"Destructed FFmpegDecoderVideo"<<std::endl;
[9816]52}
53
54
55
56void FFmpegDecoderVideo::open(AVStream * const stream)
57{
58    m_stream = stream;
59    m_context = stream->codec;
60
61    // Trust the video size given at this point
62    // (avcodec_open seems to sometimes return a 0x0 size)
63    m_width = m_context->width;
64    m_height = m_context->height;
65    findAspectRatio();
66
67    // Find out whether we support Alpha channel
68    m_alpha_channel = (m_context->pix_fmt == PIX_FMT_YUVA420P);
69
70    // Find out the framerate
71    m_frame_rate = av_q2d(stream->r_frame_rate);
72
73    // Find the decoder for the video stream
74    m_codec = avcodec_find_decoder(m_context->codec_id);
75
76    if (m_codec == 0)
77        throw std::runtime_error("avcodec_find_decoder() failed");
78
79    // Inform the codec that we can handle truncated bitstreams
80    //if (p_codec->capabilities & CODEC_CAP_TRUNCATED)
81    //    m_context->flags |= CODEC_FLAG_TRUNCATED;
82
83    // Open codec
84    if (avcodec_open(m_context, m_codec) < 0)
85        throw std::runtime_error("avcodec_open() failed");
86
87    // Allocate video frame
[9826]88    m_frame.reset(avcodec_alloc_frame());
[9816]89
90    // Allocate converted RGB frame
[9826]91    m_frame_rgba.reset(avcodec_alloc_frame());
[9860]92    m_buffer_rgba[0].resize(avpicture_get_size(PIX_FMT_RGB32, width(), height()));
93    m_buffer_rgba[1].resize(m_buffer_rgba[0].size());
[9816]94
95    // Assign appropriate parts of the buffer to image planes in m_frame_rgba
[9860]96    avpicture_fill((AVPicture *) (m_frame_rgba).get(), &(m_buffer_rgba[0])[0], PIX_FMT_RGB32, width(), height());
[9816]97
98    // Override get_buffer()/release_buffer() from codec context in order to retrieve the PTS of each frame.
99    m_context->opaque = this;
100    m_context->get_buffer = getBuffer;
101    m_context->release_buffer = releaseBuffer;
102}
103
104
105
106void FFmpegDecoderVideo::run()
107{
108    try
109    {
110        decodeLoop();
111    }
112
113    catch (const std::exception & error)
114    {
115        osg::notify(osg::WARN) << "FFmpegDecoderVideo::run : " << error.what() << std::endl;
116    }
117
118    catch (...)
119    {
120        osg::notify(osg::WARN) << "FFmpegDecoderVideo::run : unhandled exception" << std::endl;
121    }
122}
123
124
125
126void FFmpegDecoderVideo::decodeLoop()
127{
128    FFmpegPacket packet;
129    double pts;
130
131    while (! m_exit)
132    {
133        // Work on the current packet until we have decoded all of it
134
135        while (m_bytes_remaining > 0)
136        {
137            // Save global PTS to be stored in m_frame via getBuffer()
138
139            m_packet_pts = packet.packet.pts;
140
141            // Decode video frame
142
143            int frame_finished = 0;
144
145            const int bytes_decoded = avcodec_decode_video(m_context, m_frame.get(), &frame_finished, m_packet_data, m_bytes_remaining);
146
147            if (bytes_decoded < 0)
148                throw std::runtime_error("avcodec_decode_video failed()");
149
150            m_bytes_remaining -= bytes_decoded;
151            m_packet_data += bytes_decoded;
152
153            // Find out the frame pts
154
155            if (packet.packet.dts == AV_NOPTS_VALUE && m_frame->opaque != 0 && *reinterpret_cast<const int64_t*>(m_frame->opaque) != AV_NOPTS_VALUE)
156            {
157                pts = *reinterpret_cast<const int64_t*>(m_frame->opaque);
158            }
159            else if (packet.packet.dts != AV_NOPTS_VALUE)
160            {
161                pts = packet.packet.dts;
162            }
163            else
164            {
165                pts = 0;
166            }
167
168            pts *= av_q2d(m_stream->time_base);
169
170            // Publish the frame if we have decoded a complete frame
171            if (frame_finished)
172            {
173                const double synched_pts = m_clocks.videoSynchClock(m_frame.get(), av_q2d(m_stream->time_base), pts);
174                const double frame_delay = m_clocks.videoRefreshSchedule(synched_pts);
175
176                publishFrame(frame_delay);
177            }
178        }
179
180        // Get the next packet
181
182        pts = 0;
183
184        if (packet.valid())
185            packet.clear();
186
187        bool is_empty = true;
188        packet = m_packets.timedPop(is_empty, 10);
189
190        if (! is_empty)
191        {
192            if (packet.type == FFmpegPacket::PACKET_DATA)
193            {
194                m_bytes_remaining = packet.packet.size;
195                m_packet_data = packet.packet.data;
196            }
197            else if (packet.type == FFmpegPacket::PACKET_FLUSH)
198            {
199                avcodec_flush_buffers(m_context);
200                m_clocks.rewindVideo();
201            }
202        }
203    }
204}
205
206
207
208void FFmpegDecoderVideo::findAspectRatio()
209{
210    double ratio = 0.0;
211
212    if (m_context->sample_aspect_ratio.num != 0)
213        ratio = (av_q2d(m_context->sample_aspect_ratio) * m_width) / m_height;
214
215    if (ratio <= 0.0)
216        ratio = double(m_width) / double(m_height);
217
218    m_aspect_ratio = ratio;
219}
220
[9854]221int FFmpegDecoderVideo::convert(AVPicture *dst, int dst_pix_fmt, const AVPicture *src,
222            int src_pix_fmt, int src_width, int src_height)
223{
[9860]224    osg::Timer_t startTick = osg::Timer::instance()->tick();
[9854]225#ifdef USE_SWSCALE
226    if (m_swscale_ctx==0)
227    {
228        m_swscale_ctx = sws_getContext(src_width, src_height, src_pix_fmt,
229                                      src_width, src_height, dst_pix_fmt,                                   
[9860]230                                      /*SWS_BILINEAR*/ SWS_BICUBIC, NULL, NULL, NULL);
[9854]231    }
232   
[9857]233
[9860]234    osg::notify(osg::NOTICE)<<"Using sws_scale ";
235
236    int result =  sws_scale(m_swscale_ctx,
237                            src->data, src->linesize, 0, src_height,
238                            dst->data, dst->linesize);
[9854]239#else
[9857]240
[9860]241    osg::notify(osg::NOTICE)<<"Using img_convert ";
242
243    int result = img_convert(dst, dst_pix_fmt, src,
244                             src_pix_fmt, src_width, src_height);
245
[9854]246#endif
[9860]247    osg::Timer_t endTick = osg::Timer::instance()->tick();
248    osg::notify(osg::NOTICE)<<" time = "<<osg::Timer::instance()->delta_m(startTick,endTick)<<"ms"<<std::endl;
249
250    return result;
[9854]251}
[9816]252
253
254void FFmpegDecoderVideo::publishFrame(const double delay)
255{
256    // If no publishing function, just ignore the frame
257    if (m_publish_func == 0)
258        return;
259
260    // If the display delay is too small, we better skip the frame.
261    if (delay < -0.010)
262        return;
[9860]263       
[9816]264    const AVPicture * const src = (const AVPicture *) m_frame.get();
265    AVPicture * const dst = (AVPicture *) m_frame_rgba.get();
266
[9860]267    // Assign appropriate parts of the buffer to image planes in m_frame_rgba
268    avpicture_fill((AVPicture *) (m_frame_rgba).get(), &(m_buffer_rgba[m_writeBuffer])[0], PIX_FMT_RGB32, width(), height());
269
[9816]270    // Convert YUVA420p (i.e. YUV420p plus alpha channel) using our own routine
271
272    if (m_context->pix_fmt == PIX_FMT_YUVA420P)
273        yuva420pToRgba(dst, src, width(), height());
274    else
[9854]275        convert(dst, PIX_FMT_RGB32, src, m_context->pix_fmt, width(), height());
[9816]276
277    // Wait 'delay' seconds before publishing the picture.
278    int i_delay = static_cast<int>(delay * 1000000 + 0.5);
279
280    while (i_delay > 1000)
281    {
282        // Avoid infinite/very long loops
283        if (m_exit)
284            return;
285
286        const int micro_delay = (std::min)(1000000, i_delay);
287
288        OpenThreads::Thread::microSleep(micro_delay);
289
290        i_delay -= micro_delay;
291    }
292
[9860]293    m_writeBuffer = 1-m_writeBuffer;
294
[9816]295    m_publish_func(* this, m_user_data);
296}
297
298
299
300void FFmpegDecoderVideo::yuva420pToRgba(AVPicture * const dst, const AVPicture * const src, int width, int height)
301{
[9854]302    convert(dst, PIX_FMT_RGB32, src, m_context->pix_fmt, width, height);
[9816]303
304    const size_t bpp = 4;
305
306    uint8_t * a_dst = dst->data[0] + 3;
307
308    for (int h = 0; h < height; ++h) {
309
310        const uint8_t * a_src = src->data[3] + h * src->linesize[3];
311
312        for (int w = 0; w < width; ++w) {
313            *a_dst = *a_src;
314            a_dst += bpp;
315            a_src += 1;
316        }
317    }
318}
319
320
321
322int FFmpegDecoderVideo::getBuffer(AVCodecContext * const context, AVFrame * const picture)
323{
324    const FFmpegDecoderVideo * const this_ = reinterpret_cast<const FFmpegDecoderVideo*>(context->opaque);
325
326    const int result = avcodec_default_get_buffer(context, picture);
327    int64_t * p_pts = reinterpret_cast<int64_t*>( av_malloc(sizeof(int64_t)) );
328
329    *p_pts = this_->m_packet_pts;
330    picture->opaque = p_pts;
331
332    return result;
333}
334
335
336
337void FFmpegDecoderVideo::releaseBuffer(AVCodecContext * const context, AVFrame * const picture)
338{
339    if (picture != 0)
340        av_freep(&picture->opaque);
341
342    avcodec_default_release_buffer(context, picture);
343}
344
345
346
347} // namespace osgFFmpeg
Note: See TracBrowser for help on using the browser.