]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/muxer/frame_muxer.cpp
* Fixed bug where a new audio stream was created in the audio mixer for each frame...
[casparcg] / modules / ffmpeg / producer / muxer / frame_muxer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../../StdAfx.h"
23
24 #include "frame_muxer.h"
25
26 #include "../filter/filter.h"
27 #include "../util/util.h"
28
29 #include <core/producer/frame_producer.h>
30 #include <core/frame/draw_frame.h>
31 #include <core/frame/frame_transform.h>
32 #include <core/frame/pixel_format.h>
33 #include <core/frame/frame_factory.h>
34 #include <core/frame/frame.h>
35 #include <core/frame/audio_channel_layout.h>
36
37 #include <common/env.h>
38 #include <common/except.h>
39 #include <common/log.h>
40
41 #if defined(_MSC_VER)
42 #pragma warning (push)
43 #pragma warning (disable : 4244)
44 #endif
45 extern "C" 
46 {
47         #define __STDC_CONSTANT_MACROS
48         #define __STDC_LIMIT_MACROS
49         #include <libavcodec/avcodec.h>
50         #include <libavformat/avformat.h>
51 }
52 #if defined(_MSC_VER)
53 #pragma warning (pop)
54 #endif
55
56 #include <common/assert.h>
57 #include <boost/range/algorithm_ext/push_back.hpp>
58 #include <boost/algorithm/string/predicate.hpp>
59
60 #include <deque>
61 #include <queue>
62 #include <vector>
63
64 using namespace caspar::core;
65
66 namespace caspar { namespace ffmpeg {
67
68 bool is_frame_format_changed(const AVFrame& lhs, const AVFrame& rhs)
69 {
70         if (lhs.format != rhs.format)
71                 return true;
72
73         for (int i = 0; i < AV_NUM_DATA_POINTERS; ++i)
74         {
75                 if (lhs.linesize[i] != rhs.linesize[i])
76                         return true;
77         }
78
79         return false;
80 }
81         
82 struct frame_muxer::impl : boost::noncopyable
83 {       
84         std::queue<core::mutable_frame>                                 video_stream_;
85         core::mutable_audio_buffer                                              audio_stream_;
86         std::queue<draw_frame>                                                  frame_buffer_;
87         display_mode                                                                    display_mode_                   = display_mode::invalid;
88         const double                                                                    in_fps_;
89         const video_format_desc                                                 format_desc_;
90         audio_channel_layout                                                    channel_layout_;
91         
92         std::vector<int>                                                                audio_cadence_                  = format_desc_.audio_cadence;
93                         
94         spl::shared_ptr<core::frame_factory>                    frame_factory_;
95         std::shared_ptr<AVFrame>                                                previous_frame_;
96
97         std::unique_ptr<filter>                                                 filter_;
98         const std::wstring                                                              filter_str_;
99         bool                                                                                    force_deinterlacing_    = env::properties().get(L"configuration.force-deinterlace", true);
100                 
101         impl(
102                         double in_fps,
103                         const spl::shared_ptr<core::frame_factory>& frame_factory,
104                         const core::video_format_desc& format_desc,
105                         const core::audio_channel_layout& channel_layout,
106                         const std::wstring& filter_str)
107                 : in_fps_(in_fps)
108                 , format_desc_(format_desc)
109                 , channel_layout_(channel_layout)
110                 , frame_factory_(frame_factory)
111                 , filter_str_(filter_str)
112         {               
113                 // Note: Uses 1 step rotated cadence for 1001 modes (1602, 1602, 1601, 1602, 1601)
114                 // This cadence fills the audio mixer most optimally.
115                 boost::range::rotate(audio_cadence_, std::end(audio_cadence_)-1);
116         }
117         
118         void push_video(const std::shared_ptr<AVFrame>& video)
119         {               
120                 if(!video)
121                         return;
122
123                 if (previous_frame_ && video->data[0] && is_frame_format_changed(*previous_frame_, *video))
124                 {
125                         // Fixes bug where avfilter crashes server on some DV files (starts in YUV420p but changes to YUV411p after the first frame).
126                         CASPAR_LOG(info) << L"[frame_muxer] Frame format has changed. Resetting display mode.";
127                         display_mode_ = display_mode::invalid;
128                 }
129
130                 if(!video->data[0])
131                 {
132                         auto empty_frame = frame_factory_->create_frame(this, core::pixel_format_desc(core::pixel_format::invalid), channel_layout_);
133                         video_stream_.push(std::move(empty_frame));
134                         display_mode_ = display_mode::simple;
135                 }
136                 else
137                 {
138                         if(!filter_ || display_mode_ == display_mode::invalid)
139                                 update_display_mode(video);
140                                 
141                         filter_->push(video);
142                         previous_frame_ = video;
143                         for (auto& av_frame : filter_->poll_all())
144                                 video_stream_.push(make_frame(this, av_frame, format_desc_.fps, *frame_factory_, channel_layout_));
145                 }
146
147                 merge();
148         }
149
150         void push_audio(const std::shared_ptr<AVFrame>& audio)
151         {
152                 if(!audio)
153                         return;
154
155                 if(!audio->data[0])             
156                 {
157                         if (channel_layout_ == core::audio_channel_layout::invalid())
158                                 channel_layout_ = *core::audio_channel_layout_repository::get_default()->get_layout(L"stereo");
159
160                         boost::range::push_back(audio_stream_, core::mutable_audio_buffer(audio_cadence_.front() * channel_layout_.num_channels, 0));
161                 }
162                 else
163                 {
164                         auto ptr = reinterpret_cast<int32_t*>(audio->data[0]);
165                         audio_stream_.insert(audio_stream_.end(), ptr, ptr + audio->linesize[0]/sizeof(int32_t));
166                 }
167
168                 merge();
169         }
170         
171         bool video_ready() const
172         {
173                 switch(display_mode_)
174                 {
175                 case display_mode::deinterlace_bob_reinterlace:                                 
176                 case display_mode::interlace:   
177                 case display_mode::half:
178                         return video_stream_.size() >= 2;
179                 default:                                                                                
180                         return video_stream_.size() >= 1;
181                 }
182         }
183         
184         bool audio_ready() const
185         {
186                 switch(display_mode_)
187                 {
188                 case display_mode::duplicate:                                   
189                         return audio_stream_.size() >= static_cast<size_t>(audio_cadence_[0] + audio_cadence_[1 % audio_cadence_.size()]) * channel_layout_.num_channels;
190                 default:                                                                                
191                         return audio_stream_.size() >= static_cast<size_t>(audio_cadence_.front()) * channel_layout_.num_channels;
192                 }
193         }
194
195         bool empty() const
196         {
197                 return frame_buffer_.empty();
198         }
199
200         core::draw_frame front() const
201         {
202                 return frame_buffer_.front();
203         }
204
205         void pop()
206         {
207                 frame_buffer_.pop();
208         }
209                 
210         void merge()
211         {
212                 while(video_ready() && audio_ready() && display_mode_ != display_mode::invalid)
213                 {                               
214                         auto frame1                     = pop_video();
215                         frame1.audio_data()     = pop_audio();
216
217                         switch(display_mode_)
218                         {
219                         case display_mode::simple:                                              
220                         case display_mode::deinterlace_bob:                             
221                         case display_mode::deinterlace: 
222                                 {
223                                         frame_buffer_.push(core::draw_frame(std::move(frame1)));
224                                         break;
225                                 }
226                         case display_mode::interlace:                                   
227                         case display_mode::deinterlace_bob_reinterlace: 
228                                 {                               
229                                         auto frame2 = pop_video();
230
231                                         frame_buffer_.push(core::draw_frame::interlace(
232                                                 core::draw_frame(std::move(frame1)),
233                                                 core::draw_frame(std::move(frame2)),
234                                                 format_desc_.field_mode));      
235                                         break;
236                                 }
237                         case display_mode::duplicate:   
238                                 {
239                                         //boost::range::push_back(frame1.audio_data(), pop_audio());
240
241                                         auto second_audio_frame = core::mutable_frame(
242                                                         std::vector<array<std::uint8_t>>(),
243                                                         pop_audio(),
244                                                         frame1.stream_tag(),
245                                                         core::pixel_format_desc(),
246                                                         channel_layout_);
247                                         auto first_frame = core::draw_frame(std::move(frame1));
248                                         auto muted_first_frame = core::draw_frame(first_frame);
249                                         muted_first_frame.transform().audio_transform.volume = 0;
250                                         auto second_frame = core::draw_frame({ core::draw_frame(std::move(second_audio_frame)), muted_first_frame });
251
252                                         // Same video but different audio.
253                                         frame_buffer_.push(first_frame);
254                                         frame_buffer_.push(second_frame);
255                                         break;
256                                 }
257                         case display_mode::half:        
258                                 {                               
259                                         pop_video(); // Throw away
260
261                                         frame_buffer_.push(core::draw_frame(std::move(frame1)));
262                                         break;
263                                 }
264                         default:
265                                 CASPAR_THROW_EXCEPTION(invalid_operation());
266                         }
267                 }
268         }
269         
270         core::mutable_frame pop_video()
271         {
272                 auto frame = std::move(video_stream_.front());
273                 video_stream_.pop();            
274                 return std::move(frame);
275         }
276
277         core::mutable_audio_buffer pop_audio()
278         {
279                 if (audio_stream_.size() < audio_cadence_.front() * channel_layout_.num_channels)
280                         CASPAR_THROW_EXCEPTION(out_of_range());
281
282                 auto begin = audio_stream_.begin();
283                 auto end   = begin + audio_cadence_.front() * channel_layout_.num_channels;
284
285                 core::mutable_audio_buffer samples(begin, end);
286                 audio_stream_.erase(begin, end);
287                 
288                 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
289
290                 return samples;
291         }
292                                 
293         void update_display_mode(const std::shared_ptr<AVFrame>& frame)
294         {
295                 std::wstring filter_str = filter_str_;
296
297                 display_mode_ = display_mode::simple;
298
299                 auto mode = get_mode(*frame);
300                 if(mode == core::field_mode::progressive && frame->height < 720 && in_fps_ < 50.0) // SD frames are interlaced. Probably incorrect meta-data. Fix it.
301                         mode = core::field_mode::upper;
302
303                 auto fps  = in_fps_;
304
305                 if(filter::is_deinterlacing(filter_str_))
306                         mode = core::field_mode::progressive;
307
308                 if(filter::is_double_rate(filter_str_))
309                         fps *= 2;
310                         
311                 display_mode_ = get_display_mode(mode, fps, format_desc_.field_mode, format_desc_.fps);
312                         
313                 if((frame->height != 480 || format_desc_.height != 486) && // don't deinterlace for NTSC DV
314                                 display_mode_ == display_mode::simple && mode != core::field_mode::progressive && format_desc_.field_mode != core::field_mode::progressive && 
315                                 frame->height != format_desc_.height)
316                 {
317                         display_mode_ = display_mode::deinterlace_bob_reinterlace; // The frame will most likely be scaled, we need to deinterlace->reinterlace 
318                 }
319
320                 // ALWAYS de-interlace, until we have GPU de-interlacing.
321                 if(force_deinterlacing_ && frame->interlaced_frame && display_mode_ != display_mode::deinterlace_bob && display_mode_ != display_mode::deinterlace)
322                         display_mode_ = display_mode::deinterlace_bob_reinterlace;
323                 
324                 if(display_mode_ == display_mode::deinterlace)
325                         filter_str = append_filter(filter_str, L"YADIF=0:-1");
326                 else if(display_mode_ == display_mode::deinterlace_bob || display_mode_ == display_mode::deinterlace_bob_reinterlace)
327                         filter_str = append_filter(filter_str, L"YADIF=1:-1");
328
329                 if(display_mode_ == display_mode::invalid)
330                 {
331                         CASPAR_LOG(warning) << L"[frame_muxer] Auto-transcode: Failed to detect display-mode.";
332                         display_mode_ = display_mode::simple;
333                 }
334
335                 if(frame->height == 480) // NTSC DV
336                 {
337                         auto pad_str = L"PAD=" + boost::lexical_cast<std::wstring>(frame->width) + L":486:0:2:black";
338                         filter_str = append_filter(filter_str, pad_str);
339                 }
340
341                 filter_.reset (new filter(
342                         frame->width,
343                         frame->height,
344                         boost::rational<int>(1000000, static_cast<int>(in_fps_ * 1000000)),
345                         boost::rational<int>(static_cast<int>(in_fps_ * 1000000), 1000000),
346                         boost::rational<int>(frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den),
347                         static_cast<AVPixelFormat>(frame->format),
348                         std::vector<AVPixelFormat>(),
349                         u8(filter_str)));
350
351                 CASPAR_LOG(info) << L"[frame_muxer] " << display_mode_ << L" " << print_mode(frame->width, frame->height, in_fps_, frame->interlaced_frame > 0);
352         }
353         
354         uint32_t calc_nb_frames(uint32_t nb_frames) const
355         {
356                 uint64_t nb_frames2 = nb_frames;
357                 
358                 if(filter_ && filter_->is_double_rate()) // Take into account transformations in filter.
359                         nb_frames2 *= 2;
360
361                 switch(display_mode_) // Take into account transformation in run.
362                 {
363                 case display_mode::deinterlace_bob_reinterlace:
364                 case display_mode::interlace:   
365                 case display_mode::half:
366                         nb_frames2 /= 2;
367                         break;
368                 case display_mode::duplicate:
369                         nb_frames2 *= 2;
370                         break;
371                 }
372
373                 return static_cast<uint32_t>(nb_frames2);
374         }
375
376         void clear()
377         {
378                 while(!video_stream_.empty())
379                         video_stream_.pop();    
380
381                 audio_stream_.clear();
382
383                 while(!frame_buffer_.empty())
384                         frame_buffer_.pop();
385                 
386                 filter_.reset();
387         }
388 };
389
390 frame_muxer::frame_muxer(
391                 double in_fps,
392                 const spl::shared_ptr<core::frame_factory>& frame_factory,
393                 const core::video_format_desc& format_desc,
394                 const core::audio_channel_layout& channel_layout,
395                 const std::wstring& filter)
396         : impl_(new impl(in_fps, frame_factory, format_desc, channel_layout, filter)){}
397 void frame_muxer::push_video(const std::shared_ptr<AVFrame>& frame){impl_->push_video(frame);}
398 void frame_muxer::push_audio(const std::shared_ptr<AVFrame>& frame){impl_->push_audio(frame);}
399 bool frame_muxer::empty() const{return impl_->empty();}
400 core::draw_frame frame_muxer::front() const{return impl_->front();}
401 void frame_muxer::pop(){return impl_->pop();}
402 void frame_muxer::clear(){impl_->clear();}
403 uint32_t frame_muxer::calc_nb_frames(uint32_t nb_frames) const {return impl_->calc_nb_frames(nb_frames);}
404 bool frame_muxer::video_ready() const{return impl_->video_ready();}
405 bool frame_muxer::audio_ready() const{return impl_->audio_ready();}
406
407 }}