Debian Codegraph @

cvd_src/videofilebuffer2.cc

raw symbols SCIP
1 // IMPORTANT LICENSING NOTE!
2 //
3 // This file is licensed under the BSD license.
4 //
5 // However, if you use it in its current form you MAY be including some
6 // GPL licensed code from FFMPEG. Therefore any binary made using this file
7 // MUST be covered under the GPL.
8
9 //A mix of videofilebuffer.cc and documentation from http://plagatux.es/2011/07/using-libav-library/
10
11 #ifndef __STDC_CONSTANT_MACROS
12 #define __STDC_CONSTANT_MACROS
13 #endif
14
15 extern "C"
16 {
17 #include <libavcodec/avcodec.h>
18 #include <libavdevice/avdevice.h>
19 #include <libavformat/avformat.h>
20 #include <libavutil/imgutils.h>
21 #include <libswscale/swscale.h>
22 }
23
24 #include <algorithm>
25 #include <cvd/exceptions.h>
26 #include <cvd/videofilebuffer.h>
27 #include <map>
28 #include <string>
29 #include <utility>
30
31 #include <cvd/image_io.h>
32 #include <iostream>
33
34 using namespace std;
35 using namespace CVD;
36
37 //#define DEBUG
38
39 #ifdef DEBUG
40 #define DS(X) \
41 do \
42 { \
43 cerr << "VideoFileBuffer2: " << X << endl; \
44 } while(0)
45 #define DV(X, Y) \
46 do \
47 { \
48 cerr << "VideoFileBuffer2: " << X << " = " << Y << endl; \
49 } while(0)
50 #define Dv(X) \
51 do \
52 { \
53 cerr << "VideoFileBuffer2: " << #X << " = " << (X) << endl; \
54 } while(0)
55 #define DR(X) \
56 do \
57 { \
58 cerr << "VideoFileBuffer2: " << #X << " returned " << r << endl; \
59 } while(0)
60 #define DE(X) \
61 do \
62 { \
63 cerr << X; \
64 } while(0)
65 #else
66 #define DS(X) \
67 do \
68 { \
69 } while(0)
70 #define DV(X, Y) \
71 do \
72 { \
73 } while(0)
74 #define Dv(X) \
75 do \
76 { \
77 } while(0)
78 #define DR(X) \
79 do \
80 { \
81 } while(0)
82 #define DR(X) \
83 do \
84 { \
85 } while(0)
86 #define DE(X) \
87 do \
88 { \
89 } while(0)
90 #endif
91
92 #define VS(X) \
93 do \
94 { \
95 if(verbose) \
96 cerr << "VideoFileBuffer2: " << X << endl; \
97 } while(0)
98 #define VV(X, Y) \
99 do \
100 { \
101 if(verbose) \
102 cerr << "VideoFileBuffer2: " << X << " = " << Y << endl; \
103 } while(0)
104 #define Vv(X) \
105 do \
106 { \
107 if(verbose) \
108 cerr << "VideoFileBuffer2: " << #X << " = " << (X) << endl; \
109 } while(0)
110 #define VR(X) \
111 do \
112 { \
113 if(verbose) \
114 cerr << "VideoFileBuffer2: " << #X << " returned " << r << endl; \
115 } while(0)
116 namespace CVD
117 {
118
119 namespace Exceptions
120 {
121 struct VideoFileBuffer2 : CVD::Exceptions::VideoBuffer::All
122 {
123 using CVD::Exceptions::VideoBuffer::All::All;
124 };
125 }
126
127 template <class T>
128 struct PixFmt
129 {
130 };
131
132 template <>
133 struct PixFmt<byte>
134 {
135 static AVPixelFormat get()
136 {
137 return AV_PIX_FMT_GRAY8;
138 }
139 };
140
141 template <>
142 struct PixFmt<Rgb<byte>>
143 {
144 static AVPixelFormat get()
145 {
146 return AV_PIX_FMT_RGB24;
147 }
148 };
149
150 namespace VFB
151 {
152
153 class VFHolderBase
154 {
155 protected:
156 void* frame;
157
158 virtual void remove() = 0;
159
160 public:
161 virtual ~VFHolderBase()
162 {
163 }
164
165 void* release()
166 {
167 void* f = frame;
168 frame = 0;
169 return f;
170 };
171
172 virtual unique_ptr<VFHolderBase> duplicate() = 0;
173 };
174
175 template <class C>
176 class VFHolder : public VFHolderBase
177 {
178 using VFHolderBase::frame;
179
180 void remove()
181 {
182 if(frame)
183 static_cast<VideoFileFrame<C>*>(frame)->delete_self();
184 };
185
186 VFHolder(const VFHolder&);
187 void operator=(const VFHolder&);
188
189 public:
190 ~VFHolder()
191 {
192 remove();
193 }
194
195 VFHolder(VideoFileFrame<C>* f)
196 {
197 frame = f;
198 }
199
200 unique_ptr<VFHolderBase> duplicate();
201 };
202
203 class RawVideoFileBufferPIMPL
204 {
205 bool rgb;
206 AVPixelFormat output_fmt;
207 AVFormatContext* input_format_context;
208
209 int video_stream_index;
210 AVCodecContext* video_codec_context;
211
212 AVFrame* raw_image;
213 AVFrame* converted_image;
214
215 ImageRef size;
216
217 double frame_rate;
218 double stream_time_base;
219 double approx_next_timestamp;
220
221 const AVCodec* video_codec;
222 SwsContext* img_convert_context;
223
224 bool verbose;
225 bool ready;
226
227 VideoBufferFlags::OnEndOfBuffer end_of_buffer_behaviour;
228
229 public:
230 template <class T>
231 static VideoFileFrame<T>* generate_frame(double t, Image<T>&& im)
232 {
233 return new VideoFileFrame<T>(t, move(im));
234 }
235
236 private:
237 unique_ptr<VFHolderBase> next_frame;
238
239 string err(int e)
240 {
241 char buf[1024];
242 av_strerror(e, buf, sizeof(buf) - 1);
243 buf[sizeof(buf) - 1] = 0;
244 return buf;
245 }
246
247 static double to_double(const AVRational& r)
248 {
249 return 1.0 * r.num / r.den;
250 }
251
252 public:
253 RawVideoFileBufferPIMPL(const string& fname, const string& formatname, bool rgb_, bool verbose_, const map<string, string>& options)
254 : rgb(rgb_)
255 , output_fmt(rgb ? PixFmt<Rgb<byte>>::get() : PixFmt<byte>::get())
256 , input_format_context(0)
257 , video_stream_index(-1)
258 , video_codec_context(0)
259 , raw_image(0)
260 , converted_image(0)
261 , video_codec(0)
262 , img_convert_context(0)
263 , verbose(verbose_)
264 , ready(false)
265 , end_of_buffer_behaviour(VideoBufferFlags::RepeatLastFrame)
266 {
267
268 try
269 {
270 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
271 // see https://github.com/FFmpeg/FFmpeg/commit/0694d8702421e7aff1340038559c438b61bb30dd
272 av_register_all();
273 #endif
274 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 10, 100)
275 // see https://github.com/FFmpeg/FFmpeg/commit/3f0a41367eb9180ab6d22d43ad42b9bd85a26df0
276 avcodec_register_all();
277 #endif
278 avdevice_register_all();
279 DS("starting");
280
281 int r;
282
283 input_format_context = avformat_alloc_context();
284 if(input_format_context == NULL)
285 throw Exceptions::VideoFileBuffer2("Out of memory.");
286
287 auto* fmt = (formatname != "") ? av_find_input_format(formatname.c_str()) : nullptr;
288
289 VS("av_find_input_format(" << formatname << ") = " << fmt);
290 if(fmt != nullptr)
291 {
292 Vv(fmt->name);
293 Vv(fmt->long_name);
294 Vv(fmt->flags & AVFMT_NOFILE);
295 Vv(fmt->flags & AVFMT_NEEDNUMBER);
296 }
297
298 AVDictionary* opts = nullptr;
299 for(const auto& o : options)
300 av_dict_set(&opts, o.first.c_str(), o.second.c_str(), 0);
301
302 //avformat_open_input semes to be the latest non-depracated method for this task.
303 //It requires a pre-allocated context.
304 r = avformat_open_input(&input_format_context, fname.c_str(), fmt, &opts);
305 VR(avformat_open_input);
306
307 av_dict_free(&opts);
308
309 if(r < 0)
310 throw Exceptions::VideoFileBuffer::FileOpen(fname, err(r));
311
312 r = avformat_find_stream_info(input_format_context, NULL);
313 VR(av_find_stream_info);
314 if(r < 0)
315 throw Exceptions::VideoFileBuffer::FileOpen(fname, err(r));
316
317 VV("number of streams", input_format_context->nb_streams);
318 VS("Enumerating streams:");
319 video_stream_index = -1;
320 //Trawl through the various streams to get some nice
321 //verbosity and to find the first video stream.
322 for(unsigned int i = 0; i < input_format_context->nb_streams; i++)
323 {
324 AVMediaType t = input_format_context->streams[i]->codecpar->codec_type;
325 AVCodecParameters* vc = input_format_context->streams[i]->codecpar;
326
327 if(t == AVMEDIA_TYPE_UNKNOWN)
328 VS(" " << i << ": "
329 << "unknown");
330 else if(t == AVMEDIA_TYPE_VIDEO)
331 {
332 VS(" " << i << ": "
333 << "video");
334
335 if(video_stream_index != -1)
336 {
337 VS(" warning, multiple video streams.");
338 }
339 else
340 {
341 VS(" selecting this stream.");
342 video_stream_index = i;
343
344 size.x = vc->width;
345 size.y = vc->height;
346 }
347
348 AVStream& s = *(input_format_context->streams[i]);
349
350 VS(" stream");
351 VV(" frame rate (num)", s.r_frame_rate.num);
352 VV(" frame rate (num)", s.r_frame_rate.den);
353 VV(" time base (num) ", s.time_base.num);
354 VV(" time base (den) ", s.time_base.den);
355
356 VS(" codec");
357 VV(" width ", vc->width);
358 VV(" height ", vc->height);
359 VV(" bit rate ", vc->bit_rate);
360
361 //Frame timestamps are represented as integer multiples of
362 //rationals with the obvious definition. The number of
363 //incrementes between frames is not necessarily 1, so this
364 //number cannot be used to compute the frame rate.
365
366 //The number of ticks per frame gives the frame rate.
367 //frame_rate = 1. / ( 1.0 * vc->ticks_per_frame* vc->time_base.num / vc->time_base.den);
368
369 //The frame rate is also recorded in the stream...
370 frame_rate = to_double(s.r_frame_rate);
371 VV(" frame rate (?) ", frame_rate);
372
373 //The ticks is usually 2 for interlaced video and 1 otherwise.
374 //However, some progressive video converted from interlaced also has
375 //ticks=2
376
377 //But the frame rate is also recorded in the
378
379 //Get the stream time base, since this is required to
380 //turn the packet timestamps into seconds.
381 stream_time_base = to_double(s.time_base);
382 }
383 else if(t == AVMEDIA_TYPE_AUDIO)
384 VS(" " << i << ": "
385 << "audio");
386 else if(t == AVMEDIA_TYPE_DATA)
387 VS(" " << i << ": "
388 << "data");
389 else if(t == AVMEDIA_TYPE_SUBTITLE)
390 VS(" " << i << ": "
391 << "subtitle");
392 else if(t == AVMEDIA_TYPE_ATTACHMENT)
393 VS(" " << i << ": "
394 << "attachment");
395 }
396
397 if(video_stream_index == -1)
398 throw Exceptions::VideoFileBuffer2("VideoFileBuffer2: no video stream found.");
399
400 //Get hold of the video decoding mechanism
401 auto* parameters = input_format_context->streams[video_stream_index]->codecpar;
402 video_codec = avcodec_find_decoder(parameters->codec_id);
403 if(video_codec == NULL)
404 throw Exceptions::VideoFileBuffer2("VideoFileBuffer2: no decoder found");
405
406 video_codec_context = avcodec_alloc_context3(video_codec);
407 avcodec_parameters_to_context(video_codec_context, parameters);
408
409 r = avcodec_open2(video_codec_context, video_codec, 0);
410 VR(avcodec_open2);
411 if(r < 0)
412 throw Exceptions::VideoFileBuffer::FileOpen(fname, err(r));
413
414 raw_image = av_frame_alloc();
415
416 //Get hold of the mechanism to convert the video frame into
417 //a useful pixel format. The sws part is GPL, not LGPL.
418 //
419 //In principle, this could be done using libCVD's internal conversion
420 //code in order to break the GPL dependence.
421 converted_image = av_frame_alloc();
422 img_convert_context = sws_getContext(size.x, size.y, video_codec_context->pix_fmt, //Input
423 size.x, size.y, output_fmt, //Output
424 SWS_POINT, //The nastiest scaler should be OK, since we're not scaling. Right? right?
425 NULL, NULL, NULL);
426
427 if(img_convert_context == 0)
428 throw Exceptions::VideoFileBuffer2("Software scaler not found! This is very strange.");
429
430 //FIXME: streams do not always start at 0
431 approx_next_timestamp = 0;
432
433 //Load the first frame...
434 load_next_frame();
435
436 return;
437 }
438 catch(...)
439 {
440 free_all();
441 throw;
442 }
443 }
444
445 void on_end_of_buffer(VideoBufferFlags::OnEndOfBuffer f)
446 {
447 end_of_buffer_behaviour = f;
448 }
449
450 void seek_to(double t)
451 {
452 t = max(0., t);
453
454 uint64_t stamp = static_cast<uint64_t>(floor(t / stream_time_base + 0.5));
455
456 DE(endl);
457 DS("seeking");
458 Dv(stamp);
459
460 int r = av_seek_frame(input_format_context, video_stream_index, stamp, AVSEEK_FLAG_ANY);
461 approx_next_timestamp = t;
462
463 DE(endl);
464
465 if(r < 0)
466 throw Exceptions::VideoFileBuffer::BadSeek(t, err(r));
467 }
468
469 template <typename T>
470 unique_ptr<VFHolderBase> read_frame_from_video()
471 {
472
473 if(PixFmt<T>::get() != output_fmt)
474 throw Exceptions::VideoFileBuffer2("Mismatched format: probably an internal library error.");
475
476 while(true)
477 {
478 int r = avcodec_receive_frame(video_codec_context, raw_image);
479 if(r == AVERROR_EOF)
480 {
481 DS("EOF");
482 return unique_ptr<VFHolderBase>();
483 }
484 else if(r < 0 && r != AVERROR(EAGAIN))
485 {
486 throw Exceptions::VideoFileBuffer::BadDecode(approx_next_timestamp, err(r));
487 }
488 else
489 {
490 break;
491 }
492
493 AVPacket* packet = av_packet_alloc();
494 r = av_read_frame(input_format_context, packet);
495
496 if(r == AVERROR_EOF)
497 {
498 avcodec_send_packet(video_codec_context, nullptr);
499 av_packet_free(&packet);
500 continue;
501 }
502 else if(r < 0)
503 {
504 av_packet_free(&packet);
505 throw Exceptions::VideoFileBuffer::BadDecode(approx_next_timestamp, err(r));
506 }
507
508 Dv(packet.stream_index);
509
510 Dv(packet.pts); //Presentation time stamp (pts) is sometimes junk in keyframes.
511 Dv(packet.dts); //decode time stamp
512 double timestamp = static_cast<double>(packet->dts) * stream_time_base;
513 approx_next_timestamp = timestamp + 1. / frame_rate;
514 Dv(timestamp);
515
516 //The duration can lie and be set to 0
517 Dv(packet.duration);
518 DV("duration", packet.duration * stream_time_base);
519
520 if(packet->stream_index == video_stream_index)
521 {
522 r = avcodec_send_packet(video_codec_context, packet);
523 if(r != AVERROR(EAGAIN) && r != AVERROR(EOF))
524 {
525 av_packet_free(&packet);
526 throw Exceptions::VideoFileBuffer::BadDecode(approx_next_timestamp, err(r));
527 }
528 }
529
530 av_packet_free(&packet);
531 }
532
533 double timestamp = static_cast<double>(raw_image->pkt_dts) * stream_time_base;
534 Dv(timestamp);
535
536 Dv(raw_image->key_frame);
537 Dv(raw_image->pts); //presentation timestamp. Time to present frame. Seems to contain junk. Do not use.
538 Dv(raw_image->interlaced_frame);
539 Dv(raw_image->top_field_first);
540
541 //Allocate memory for the converted image
542 Image<T> ret(size);
543
544 //Set up converted_image so it uses the data in ret as its data buffer.
545 uint8_t* data[4];
546 int linesize[4];
547 av_image_fill_arrays(data,
548 linesize,
549 reinterpret_cast<uint8_t*>(ret.data()),
550 output_fmt,
551 ret.size().x,
552 ret.size().y,
553 1);
554 sws_scale(img_convert_context, raw_image->data, raw_image->linesize, 0, size.y, data, linesize);
555
556 ready = true;
557 return unique_ptr<VFHolderBase>(new VFHolder<T>(new VideoFileFrame<T>(timestamp, std::move(ret))));
558 }
559
560 void load_next_frame()
561 {
562 if(output_fmt == AV_PIX_FMT_GRAY8)
563 next_frame = read_frame_from_video<byte>();
564 else // if(output_fmt == PIX_FMT_RGB24)
565 next_frame = read_frame_from_video<Rgb<byte>>();
566 }
567
568 void put_frame(void* f)
569 {
570 if(output_fmt == AV_PIX_FMT_GRAY8)
571 delete static_cast<VideoFileFrame<byte>*>(f);
572 else
573 delete static_cast<VideoFileFrame<Rgb<byte>>*>(f);
574 };
575
576 void* get_frame()
577 {
578 if(!frame_pending())
579 throw Exceptions::VideoFileBuffer::EndOfFile();
580
581 //Safely grab the frame
582 unique_ptr<VFHolderBase> fr = move(next_frame);
583 load_next_frame();
584
585 if(next_frame.get() == NULL)
586 {
587 switch(end_of_buffer_behaviour)
588 {
589 case VideoBufferFlags::RepeatLastFrame:
590 next_frame = (*fr).duplicate();
591 break;
592
593 case VideoBufferFlags::UnsetPending:
594 ready = false;
595 break;
596
597 case VideoBufferFlags::Loop:
598 seek_to(0.0);
599 load_next_frame();
600 break;
601 }
602 }
603
604 void* f = fr->release();
605 fr.release();
606
607 return f;
608 }
609
610 bool frame_pending()
611 {
612 return ready;
613 }
614
615 ~RawVideoFileBufferPIMPL()
616 {
617 free_all();
618 }
619
620 void free_all()
621 {
622 if(input_format_context != NULL)
623 avformat_free_context(input_format_context);
624
625 if(raw_image != NULL)
626 av_free(raw_image);
627
628 if(converted_image != NULL)
629 av_free(converted_image);
630
631 if(img_convert_context != NULL)
632 sws_freeContext(img_convert_context);
633 }
634
635 double frames_per_second() const
636 {
637 return frame_rate;
638 }
639
640 ImageRef get_size() const
641 {
642 return size;
643 }
644 };
645
646 template <class C>
647 unique_ptr<VFHolderBase> VFHolder<C>::duplicate()
648 {
649 VideoFileFrame<C>* fr = static_cast<VideoFileFrame<C>*>(frame);
650
651 Image<C> copy;
652 copy.copy_from(*fr);
653
654 return unique_ptr<VFHolderBase>(new VFHolder(RawVideoFileBufferPIMPL::generate_frame<C>(fr->timestamp(), move(copy))));
655 }
656
657 ///Public implementation of RawVideoFileBuffer
658 RawVideoFileBuffer::RawVideoFileBuffer(const std::string& file, const std::string& fmt, bool is_rgb, bool verbose, const map<string, string>& opts)
659 : p(new RawVideoFileBufferPIMPL(file, fmt, is_rgb, verbose, opts))
660 {
661 }
662
663 RawVideoFileBuffer::~RawVideoFileBuffer()
664 {
665 }
666
667 ImageRef RawVideoFileBuffer::size()
668 {
669 return p->get_size();
670 }
671
672 bool RawVideoFileBuffer::frame_pending()
673 {
674 return p->frame_pending();
675 }
676
677 void* RawVideoFileBuffer::get_frame()
678 {
679 return p->get_frame();
680 }
681
682 void RawVideoFileBuffer::put_frame(void* f)
683 {
684 p->put_frame(f);
685 }
686
687 void RawVideoFileBuffer::seek_to(double t)
688 {
689 p->seek_to(t);
690 }
691
692 void RawVideoFileBuffer::on_end_of_buffer(VideoBufferFlags::OnEndOfBuffer b)
693 {
694 p->on_end_of_buffer(b);
695 }
696
697 double RawVideoFileBuffer::frames_per_second()
698 {
699 return p->frames_per_second();
700 }
701
702 }
703 }