]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/ffmpeg_producer.cpp
set svn:eol-style native on .h and .cpp files
[casparcg] / modules / ffmpeg / producer / ffmpeg_producer.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 "ffmpeg_producer.h"
25
26 #include "../ffmpeg_error.h"
27
28 #include "muxer/frame_muxer.h"
29 #include "input/input.h"
30 #include "util/util.h"
31 #include "audio/audio_decoder.h"
32 #include "video/video_decoder.h"
33
34 #include <common/env.h>
35 #include <common/log.h>
36 #include <common/param.h>
37 #include <common/diagnostics/graph.h>
38 #include <common/future.h>
39
40 #include <core/video_format.h>
41 #include <core/producer/frame_producer.h>
42 #include <core/frame/frame_factory.h>
43 #include <core/frame/draw_frame.h>
44 #include <core/frame/frame_transform.h>
45 #include <core/monitor/monitor.h>
46
47 #include <boost/algorithm/string.hpp>
48 #include <common/assert.h>
49 #include <boost/assign.hpp>
50 #include <boost/timer.hpp>
51 #include <boost/foreach.hpp>
52 #include <boost/filesystem.hpp>
53 #include <boost/range/algorithm/find_if.hpp>
54 #include <boost/range/algorithm/find.hpp>
55 #include <boost/property_tree/ptree.hpp>
56 #include <boost/regex.hpp>
57 #include <boost/thread/future.hpp>
58
59 #include <tbb/parallel_invoke.h>
60
61 #include <limits>
62 #include <memory>
63 #include <queue>
64
65 namespace caspar { namespace ffmpeg {
66                                 
67 struct ffmpeg_producer : public core::frame_producer_base
68 {
69         monitor::basic_subject                                                  event_subject_;
70         const std::wstring                                                              filename_;
71         
72         const spl::shared_ptr<diagnostics::graph>               graph_;
73                                         
74         const spl::shared_ptr<core::frame_factory>              frame_factory_;
75         const core::video_format_desc                                   format_desc_;
76
77         input                                                                                   input_; 
78
79         const double                                                                    fps_;
80         const uint32_t                                                                  start_;
81                 
82         std::unique_ptr<video_decoder>                                  video_decoder_;
83         std::unique_ptr<audio_decoder>                                  audio_decoder_; 
84         frame_muxer                                                                             muxer_;
85         
86         core::draw_frame                                                                last_frame_;
87
88         boost::optional<uint32_t>                                               seek_target_;
89         
90 public:
91         explicit ffmpeg_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, 
92                                                          const core::video_format_desc& format_desc, 
93                                                          const std::wstring& filename, 
94                                                          const std::wstring& filter, 
95                                                          bool loop, 
96                                                          uint32_t start, 
97                                                          uint32_t length) 
98                 : filename_(filename)
99                 , frame_factory_(frame_factory)         
100                 , format_desc_(format_desc)
101                 , input_(graph_, filename_, loop, start, length)
102                 , fps_(read_fps(input_.context(), format_desc_.fps))
103                 , muxer_(fps_, frame_factory, format_desc_, filter)
104                 , start_(start)
105                 , last_frame_(core::draw_frame::empty())
106         {
107                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
108                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   
109                 diagnostics::register_graph(graph_);
110                 
111
112                 try
113                 {
114                         video_decoder_.reset(new video_decoder(input_));
115                         video_decoder_->subscribe(event_subject_);
116                         
117                         CASPAR_LOG(info) << print() << L" " << video_decoder_->print();
118                 }
119                 catch(averror_stream_not_found&)
120                 {
121                         //CASPAR_LOG(warning) << print() << " No video-stream found. Running without video.";   
122                 }
123                 catch(...)
124                 {
125                         CASPAR_LOG_CURRENT_EXCEPTION();
126                         CASPAR_LOG(warning) << print() << "Failed to open video-stream. Running without video.";        
127                 }
128
129                 try
130                 {
131                         audio_decoder_ .reset(new audio_decoder(input_, format_desc_));
132                         audio_decoder_->subscribe(event_subject_);
133                         
134                         CASPAR_LOG(info) << print() << L" " << audio_decoder_->print();
135                 }
136                 catch(averror_stream_not_found&)
137                 {
138                         //CASPAR_LOG(warning) << print() << " No audio-stream found. Running without audio.";   
139                 }
140                 catch(...)
141                 {
142                         CASPAR_LOG_CURRENT_EXCEPTION();
143                         CASPAR_LOG(warning) << print() << " Failed to open audio-stream. Running without audio.";               
144                 }       
145                 
146                 decode_next_frame();
147
148                 CASPAR_LOG(info) << print() << L" Initialized";
149         }
150
151         // frame_producer
152         
153         core::draw_frame receive_impl() override
154         {                               
155                 auto frame = core::draw_frame::late();          
156                 
157                 boost::timer frame_timer;
158                 
159                 end_seek();
160                                 
161                 decode_next_frame();
162                 
163                 if(!muxer_.empty())
164                 {
165                         last_frame_ = frame = std::move(muxer_.front());
166                         muxer_.pop();   
167                 }
168                 else                            
169                         graph_->set_tag("underflow");
170                                                                         
171                 graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);
172                 event_subject_  << monitor::event("profiler/time") % frame_timer.elapsed() % (1.0/format_desc_.fps);                    
173                                                                 
174                 event_subject_  << monitor::event("file/time")                  % monitor::duration(file_frame_number()/fps_) 
175                                                                                                                                 % monitor::duration(file_nb_frames()/fps_)
176                                                 << monitor::event("file/frame")                 % static_cast<int32_t>(file_frame_number())
177                                                                                                                                 % static_cast<int32_t>(file_nb_frames())
178                                                 << monitor::event("file/fps")                   % fps_
179                                                 << monitor::event("file/path")                  % filename_
180                                                 << monitor::event("loop")                               % input_.loop();
181                                                 
182                 return frame;
183         }
184
185         core::draw_frame last_frame() override
186         {
187                 end_seek();
188                 return core::draw_frame::still(last_frame_);
189         }
190                 
191         uint32_t nb_frames() const override
192         {
193                 if(input_.loop())
194                         return std::numeric_limits<uint32_t>::max();
195
196                 uint32_t nb_frames = file_nb_frames();
197
198                 nb_frames = std::min(input_.length(), nb_frames);
199                 nb_frames = muxer_.calc_nb_frames(nb_frames);
200                 
201                 return nb_frames > start_ ? nb_frames - start_ : 0;
202         }
203
204         uint32_t file_nb_frames() const
205         {
206                 uint32_t file_nb_frames = 0;
207                 file_nb_frames = std::max(file_nb_frames, video_decoder_ ? video_decoder_->nb_frames() : 0);
208                 file_nb_frames = std::max(file_nb_frames, audio_decoder_ ? audio_decoder_->nb_frames() : 0);
209                 return file_nb_frames;
210         }
211
212         uint32_t file_frame_number() const
213         {
214                 return video_decoder_ ? video_decoder_->file_frame_number() : 0;
215         }
216                 
217         boost::unique_future<std::wstring> call(const std::wstring& param) override
218         {
219                 static const boost::wregex loop_exp(L"LOOP\\s*(?<VALUE>\\d?)?", boost::regex::icase);
220                 static const boost::wregex seek_exp(L"SEEK\\s+(?<VALUE>\\d+)", boost::regex::icase);
221                 static const boost::wregex length_exp(L"LENGTH\\s+(?<VALUE>\\d+)?", boost::regex::icase);
222                 static const boost::wregex start_exp(L"START\\s+(?<VALUE>\\d+)?", boost::regex::icase);
223                 
224                 std::wstring result;
225                         
226                 boost::wsmatch what;
227                 if(boost::regex_match(param, what, loop_exp))
228                 {
229                         auto value = what["VALUE"].str();
230                         if(!value.empty())
231                                 input_.loop(boost::lexical_cast<bool>(value));
232                         result = boost::lexical_cast<std::wstring>(loop());
233                 }
234                 else if(boost::regex_match(param, what, seek_exp))
235                 {
236                         auto value = what["VALUE"].str();
237                         seek(boost::lexical_cast<uint32_t>(value));
238                 }
239                 else if(boost::regex_match(param, what, length_exp))
240                 {
241                         auto value = what["VALUE"].str();
242                         if(!value.empty())
243                                 length(boost::lexical_cast<uint32_t>(value));                   
244                         result = boost::lexical_cast<std::wstring>(length());
245                 }
246                 else if(boost::regex_match(param, what, start_exp))
247                 {
248                         auto value = what["VALUE"].str();
249                         if(!value.empty())
250                                 start(boost::lexical_cast<uint32_t>(value));
251                         result = boost::lexical_cast<std::wstring>(start());
252                 }
253                 else
254                         CASPAR_THROW_EXCEPTION(invalid_argument());
255
256                 return async(launch::deferred, [=]{return result;});
257         }
258                                 
259         std::wstring print() const override
260         {
261                 return L"ffmpeg[" + boost::filesystem::path(filename_).filename().wstring() + L"|" 
262                                                   + print_mode() + L"|" 
263                                                   + boost::lexical_cast<std::wstring>(file_frame_number()) + L"/" + boost::lexical_cast<std::wstring>(file_nb_frames()) + L"]";
264         }
265
266         std::wstring name() const override
267         {
268                 return L"ffmpeg";
269         }
270
271         boost::property_tree::wptree info() const override
272         {
273                 boost::property_tree::wptree info;
274                 info.add(L"type",                               L"ffmpeg");
275                 info.add(L"filename",                   filename_);
276                 info.add(L"width",                              video_decoder_ ? video_decoder_->width() : 0);
277                 info.add(L"height",                             video_decoder_ ? video_decoder_->height() : 0);
278                 info.add(L"progressive",                video_decoder_ ? video_decoder_->is_progressive() : 0);
279                 info.add(L"fps",                                fps_);
280                 info.add(L"loop",                               input_.loop());
281                 info.add(L"frame-number",               frame_number());
282                 auto nb_frames2 = nb_frames();
283                 info.add(L"nb-frames",                  nb_frames2 == std::numeric_limits<int64_t>::max() ? -1 : nb_frames2);
284                 info.add(L"file-frame-number",  file_frame_number());
285                 info.add(L"file-nb-frames",             file_nb_frames());
286                 return info;
287         }
288         
289         void subscribe(const monitor::observable::observer_ptr& o) override
290         {
291                 event_subject_.subscribe(o);
292         }
293
294         void unsubscribe(const monitor::observable::observer_ptr& o) override
295         {
296                 event_subject_.unsubscribe(o);
297         }
298
299         // ffmpeg_producer
300         
301         void end_seek()
302         {
303                 for(int n = 0; n < 8 && (last_frame_ == core::draw_frame::empty() || (seek_target_ && file_frame_number() != *seek_target_+2)); ++n)
304                 {
305                         decode_next_frame();
306                         if(!muxer_.empty())
307                         {
308                                 last_frame_ = muxer_.front();
309                                 seek_target_.reset();
310                         }
311                 }
312         }
313
314         void loop(bool value)
315         {
316                 input_.loop(value);
317         }
318
319         bool loop() const
320         {
321                 return input_.loop();
322         }
323
324         void length(uint32_t value)
325         {
326                 input_.length(value);
327         }
328
329         uint32_t length()
330         {
331                 return input_.length();
332         }
333         
334         void start(uint32_t value)
335         {
336                 input_.start(value);
337         }
338
339         uint32_t start()
340         {
341                 return input_.start();
342         }
343
344         void seek(uint32_t target)
345         {               
346                 seek_target_ = std::min(target, file_nb_frames());
347
348                 input_.seek(*seek_target_);
349                 muxer_.clear();
350         }
351
352         std::wstring print_mode() const
353         {
354                 return ffmpeg::print_mode(video_decoder_ ? video_decoder_->width() : 0, 
355                         video_decoder_ ? video_decoder_->height() : 0, 
356                         fps_, 
357                         video_decoder_ ? !video_decoder_->is_progressive() : false);
358         }
359                         
360         void decode_next_frame()
361         {
362                 for(int n = 0; n < 8 && muxer_.empty(); ++n)
363                 {                               
364                         if(!muxer_.video_ready())
365                                 muxer_.push_video(video_decoder_ ? (*video_decoder_)() : create_frame());
366                         if(!muxer_.audio_ready())
367                                 muxer_.push_audio(audio_decoder_ ? (*audio_decoder_)() : create_frame());
368                 }
369                 graph_->set_text(print());
370         }
371 };
372
373 spl::shared_ptr<core::frame_producer> create_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, const core::video_format_desc& format_desc, const std::vector<std::wstring>& params)
374 {               
375         auto filename = probe_stem(env::media_folder() + L"\\" + params.at(0));
376
377         if(filename.empty())
378                 return core::frame_producer::empty();
379         
380         auto loop               = boost::range::find(params, L"LOOP") != params.end();
381         auto start              = get_param(L"START", params, get_param(L"SEEK", params, static_cast<uint32_t>(0)));
382         auto length             = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
383         auto filter_str = get_param(L"FILTER", params, L"");    
384         
385         return create_destroy_proxy(spl::make_shared_ptr(std::make_shared<ffmpeg_producer>(frame_factory, format_desc, filename, filter_str, loop, start, length)));
386 }
387
388 }}