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