]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/ffmpeg_producer.cpp
* Upgraded to Visual Studio 2013
[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 std::wstring get_relative_or_original(
68                 const std::wstring& filename,
69                 const boost::filesystem::wpath& relative_to)
70 {
71         boost::filesystem::wpath file(filename);
72         auto result = file.filename().wstring();
73
74         boost::filesystem::wpath current_path = file;
75
76         while (true)
77         {
78                 current_path = current_path.parent_path();
79
80                 if (boost::filesystem::equivalent(current_path, relative_to))
81                         break;
82
83                 if (current_path.empty())
84                         return filename;
85
86                 result = current_path.filename().wstring() + L"/" + result;
87         }
88
89         return result;
90 }
91
92 struct ffmpeg_producer : public core::frame_producer_base
93 {
94         spl::shared_ptr<core::monitor::subject>                 monitor_subject_;
95         const std::wstring                                                              filename_;
96         const std::wstring                                                              path_relative_to_media_;
97         
98         const spl::shared_ptr<diagnostics::graph>               graph_;
99                                         
100         const spl::shared_ptr<core::frame_factory>              frame_factory_;
101         const core::video_format_desc                                   format_desc_;
102
103         input                                                                                   input_; 
104
105         const double                                                                    fps_;
106         const uint32_t                                                                  start_;
107                 
108         std::unique_ptr<video_decoder>                                  video_decoder_;
109         std::unique_ptr<audio_decoder>                                  audio_decoder_; 
110         frame_muxer                                                                             muxer_;
111         core::constraints                                                               constraints_;
112         
113         core::draw_frame                                                                last_frame_;
114
115         boost::optional<uint32_t>                                               seek_target_;
116         
117 public:
118         explicit ffmpeg_producer(const spl::shared_ptr<core::frame_factory>& frame_factory, 
119                                                          const core::video_format_desc& format_desc, 
120                                                          const std::wstring& filename, 
121                                                          const std::wstring& filter, 
122                                                          bool loop, 
123                                                          uint32_t start, 
124                                                          uint32_t length) 
125                 : filename_(filename)
126                 , path_relative_to_media_(get_relative_or_original(filename, env::media_folder()))
127                 , frame_factory_(frame_factory)         
128                 , format_desc_(format_desc)
129                 , input_(graph_, filename_, loop, start, length)
130                 , fps_(read_fps(input_.context(), format_desc_.fps))
131                 , muxer_(fps_, frame_factory, format_desc_, filter)
132                 , start_(start)
133                 , last_frame_(core::draw_frame::empty())
134         {
135                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
136                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));   
137                 diagnostics::register_graph(graph_);
138                 
139
140                 try
141                 {
142                         video_decoder_.reset(new video_decoder(input_));
143                         video_decoder_->monitor_output().attach_parent(monitor_subject_);
144                         constraints_.width.set(video_decoder_->width());
145                         constraints_.height.set(video_decoder_->height());
146                         
147                         CASPAR_LOG(info) << print() << L" " << video_decoder_->print();
148                 }
149                 catch(averror_stream_not_found&)
150                 {
151                         //CASPAR_LOG(warning) << print() << " No video-stream found. Running without video.";   
152                 }
153                 catch(...)
154                 {
155                         CASPAR_LOG_CURRENT_EXCEPTION();
156                         CASPAR_LOG(warning) << print() << "Failed to open video-stream. Running without video.";        
157                 }
158
159                 try
160                 {
161                         audio_decoder_ .reset(new audio_decoder(input_, format_desc_));
162                         audio_decoder_->monitor_output().attach_parent(monitor_subject_);
163                         
164                         CASPAR_LOG(info) << print() << L" " << audio_decoder_->print();
165                 }
166                 catch(averror_stream_not_found&)
167                 {
168                         //CASPAR_LOG(warning) << print() << " No audio-stream found. Running without audio.";   
169                 }
170                 catch(...)
171                 {
172                         CASPAR_LOG_CURRENT_EXCEPTION();
173                         CASPAR_LOG(warning) << print() << " Failed to open audio-stream. Running without audio.";               
174                 }       
175                 
176                 decode_next_frame();
177
178                 CASPAR_LOG(info) << print() << L" Initialized";
179         }
180
181         // frame_producer
182         
183         core::draw_frame receive_impl() override
184         {                               
185                 auto frame = core::draw_frame::late();          
186                 
187                 boost::timer frame_timer;
188                 
189                 end_seek();
190                                 
191                 decode_next_frame();
192                 
193                 if(!muxer_.empty())
194                 {
195                         last_frame_ = frame = std::move(muxer_.front());
196                         muxer_.pop();   
197                 }
198                 else                            
199                         graph_->set_tag("underflow");
200                                                                         
201                 graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);
202                 *monitor_subject_
203                                 << core::monitor::message("/profiler/time")     % frame_timer.elapsed() % (1.0/format_desc_.fps);                       
204                 *monitor_subject_
205                                 << core::monitor::message("/file/time")         % (file_frame_number()/fps_) 
206                                                                                                                         % (file_nb_frames()/fps_)
207                                 << core::monitor::message("/file/frame")        % static_cast<int32_t>(file_frame_number())
208                                                                                                                         % static_cast<int32_t>(file_nb_frames())
209                                 << core::monitor::message("/file/fps")          % fps_
210                                 << core::monitor::message("/file/path")         % path_relative_to_media_
211                                 << core::monitor::message("/loop")                      % input_.loop();
212                                                 
213                 return frame;
214         }
215
216         core::draw_frame last_frame() override
217         {
218                 end_seek();
219                 return core::draw_frame::still(last_frame_);
220         }
221
222         core::constraints& pixel_constraints() override
223         {
224                 return constraints_;
225         }
226
227         uint32_t nb_frames() const override
228         {
229                 if(input_.loop())
230                         return std::numeric_limits<uint32_t>::max();
231
232                 uint32_t nb_frames = file_nb_frames();
233
234                 nb_frames = std::min(input_.length(), nb_frames);
235                 nb_frames = muxer_.calc_nb_frames(nb_frames);
236                 
237                 return nb_frames > start_ ? nb_frames - start_ : 0;
238         }
239
240         uint32_t file_nb_frames() const
241         {
242                 uint32_t file_nb_frames = 0;
243                 file_nb_frames = std::max(file_nb_frames, video_decoder_ ? video_decoder_->nb_frames() : 0);
244                 file_nb_frames = std::max(file_nb_frames, audio_decoder_ ? audio_decoder_->nb_frames() : 0);
245                 return file_nb_frames;
246         }
247
248         uint32_t file_frame_number() const
249         {
250                 return video_decoder_ ? video_decoder_->file_frame_number() : 0;
251         }
252                 
253         std::future<std::wstring> call(const std::vector<std::wstring>& params) override
254         {
255                 static const boost::wregex loop_exp(L"LOOP\\s*(?<VALUE>\\d?)?", boost::regex::icase);
256                 static const boost::wregex seek_exp(L"SEEK\\s+(?<VALUE>\\d+)", boost::regex::icase);
257                 static const boost::wregex length_exp(L"LENGTH\\s+(?<VALUE>\\d+)?", boost::regex::icase);
258                 static const boost::wregex start_exp(L"START\\s+(?<VALUE>\\d+)?", boost::regex::icase);
259
260                 auto param = boost::algorithm::join(params, L" ");
261                 
262                 std::wstring result;
263                         
264                 boost::wsmatch what;
265                 if(boost::regex_match(param, what, loop_exp))
266                 {
267                         auto value = what["VALUE"].str();
268                         if(!value.empty())
269                                 input_.loop(boost::lexical_cast<bool>(value));
270                         result = boost::lexical_cast<std::wstring>(loop());
271                 }
272                 else if(boost::regex_match(param, what, seek_exp))
273                 {
274                         auto value = what["VALUE"].str();
275                         seek(boost::lexical_cast<uint32_t>(value));
276                 }
277                 else if(boost::regex_match(param, what, length_exp))
278                 {
279                         auto value = what["VALUE"].str();
280                         if(!value.empty())
281                                 length(boost::lexical_cast<uint32_t>(value));                   
282                         result = boost::lexical_cast<std::wstring>(length());
283                 }
284                 else if(boost::regex_match(param, what, start_exp))
285                 {
286                         auto value = what["VALUE"].str();
287                         if(!value.empty())
288                                 start(boost::lexical_cast<uint32_t>(value));
289                         result = boost::lexical_cast<std::wstring>(start());
290                 }
291                 else
292                         CASPAR_THROW_EXCEPTION(invalid_argument());
293
294                 return make_ready_future(std::move(result));
295         }
296                                 
297         std::wstring print() const override
298         {
299                 return L"ffmpeg[" + boost::filesystem::path(filename_).filename().wstring() + L"|" 
300                                                   + print_mode() + L"|" 
301                                                   + boost::lexical_cast<std::wstring>(file_frame_number()) + L"/" + boost::lexical_cast<std::wstring>(file_nb_frames()) + L"]";
302         }
303
304         std::wstring name() const override
305         {
306                 return L"ffmpeg";
307         }
308
309         boost::property_tree::wptree info() const override
310         {
311                 boost::property_tree::wptree info;
312                 info.add(L"type",                               L"ffmpeg");
313                 info.add(L"filename",                   filename_);
314                 info.add(L"width",                              video_decoder_ ? video_decoder_->width() : 0);
315                 info.add(L"height",                             video_decoder_ ? video_decoder_->height() : 0);
316                 info.add(L"progressive",                video_decoder_ ? video_decoder_->is_progressive() : 0);
317                 info.add(L"fps",                                fps_);
318                 info.add(L"loop",                               input_.loop());
319                 info.add(L"frame-number",               frame_number());
320                 auto nb_frames2 = nb_frames();
321                 info.add(L"nb-frames",                  nb_frames2 == std::numeric_limits<int64_t>::max() ? -1 : nb_frames2);
322                 info.add(L"file-frame-number",  file_frame_number());
323                 info.add(L"file-nb-frames",             file_nb_frames());
324                 return info;
325         }
326         
327         core::monitor::subject& monitor_output()
328         {
329                 return *monitor_subject_;
330         }
331
332         // ffmpeg_producer
333         
334         void end_seek()
335         {
336                 for(int n = 0; n < 8 && (last_frame_ == core::draw_frame::empty() || (seek_target_ && file_frame_number() != *seek_target_+2)); ++n)
337                 {
338                         decode_next_frame();
339                         if(!muxer_.empty())
340                         {
341                                 last_frame_ = muxer_.front();
342                                 seek_target_.reset();
343                         }
344                 }
345         }
346
347         void loop(bool value)
348         {
349                 input_.loop(value);
350         }
351
352         bool loop() const
353         {
354                 return input_.loop();
355         }
356
357         void length(uint32_t value)
358         {
359                 input_.length(value);
360         }
361
362         uint32_t length()
363         {
364                 return input_.length();
365         }
366         
367         void start(uint32_t value)
368         {
369                 input_.start(value);
370         }
371
372         uint32_t start()
373         {
374                 return input_.start();
375         }
376
377         void seek(uint32_t target)
378         {               
379                 seek_target_ = std::min(target, file_nb_frames());
380
381                 input_.seek(*seek_target_);
382                 muxer_.clear();
383         }
384
385         std::wstring print_mode() const
386         {
387                 return ffmpeg::print_mode(video_decoder_ ? video_decoder_->width() : 0, 
388                         video_decoder_ ? video_decoder_->height() : 0, 
389                         fps_, 
390                         video_decoder_ ? !video_decoder_->is_progressive() : false);
391         }
392                         
393         void decode_next_frame()
394         {
395                 for(int n = 0; n < 8 && muxer_.empty(); ++n)
396                 {                               
397                         if(!muxer_.video_ready())
398                                 muxer_.push_video(video_decoder_ ? (*video_decoder_)() : create_frame());
399                         if(!muxer_.audio_ready())
400                                 muxer_.push_audio(audio_decoder_ ? (*audio_decoder_)() : create_frame());
401                 }
402                 graph_->set_text(print());
403         }
404 };
405
406 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)
407 {               
408         auto filename = probe_stem(env::media_folder() + L"\\" + params.at(0));
409
410         if(filename.empty())
411                 return core::frame_producer::empty();
412         
413         bool loop               = contains_param(L"LOOP", params);
414         auto start              = get_param(L"START", params, get_param(L"SEEK", params, static_cast<uint32_t>(0)));
415         auto length             = get_param(L"LENGTH", params, std::numeric_limits<uint32_t>::max());
416         auto filter_str = get_param(L"FILTER", params, L"");    
417         
418         return create_destroy_proxy(spl::make_shared_ptr(std::make_shared<ffmpeg_producer>(frame_factory, format_desc, filename, filter_str, loop, start, length)));
419 }
420
421 }}