]> git.sesse.net Git - casparcg/blob - modules/flash/producer/flash_producer.cpp
2.0. flash_producer: Now possible to set static template-host size. Useful for e...
[casparcg] / modules / flash / producer / flash_producer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\r
5 *\r
6 *    CasparCG is free software: you can redistribute it and/or modify\r
7 *    it under the terms of the GNU General Public License as published by\r
8 *    the Free Software Foundation, either version 3 of the License, or\r
9 *    (at your option) any later version.\r
10 *\r
11 *    CasparCG is distributed in the hope that it will be useful,\r
12 *    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 *    GNU General Public License for more details.\r
15 \r
16 *    You should have received a copy of the GNU General Public License\r
17 *    along with CasparCG.  If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 */\r
20  \r
21 #include "../stdafx.h"\r
22 \r
23 #if defined(_MSC_VER)\r
24 #pragma warning (disable : 4146)\r
25 #pragma warning (disable : 4244)\r
26 #endif\r
27 \r
28 #include "flash_producer.h"\r
29 #include "FlashAxContainer.h"\r
30 \r
31 #include <core/video_format.h>\r
32 \r
33 #include <core/producer/frame/basic_frame.h>\r
34 #include <core/producer/frame/frame_factory.h>\r
35 #include <core/mixer/write_frame.h>\r
36 \r
37 #include <common/env.h>\r
38 #include <common/concurrency/com_context.h>\r
39 #include <common/diagnostics/graph.h>\r
40 #include <common/memory/memcpy.h>\r
41 #include <common/memory/memclr.h>\r
42 #include <common/utility/timer.h>\r
43 \r
44 #include <boost/filesystem.hpp>\r
45 #include <boost/thread.hpp>\r
46 #include <boost/timer.hpp>\r
47 \r
48 #include <functional>\r
49 \r
50 namespace caspar {\r
51                 \r
52 class bitmap\r
53 {\r
54 public:\r
55         bitmap(size_t width, size_t height)\r
56                 : bmp_data_(nullptr)\r
57                 , hdc_(CreateCompatibleDC(0), DeleteDC)\r
58         {       \r
59                 BITMAPINFO info;\r
60                 memset(&info, 0, sizeof(BITMAPINFO));\r
61                 info.bmiHeader.biBitCount = 32;\r
62                 info.bmiHeader.biCompression = BI_RGB;\r
63                 info.bmiHeader.biHeight = -height;\r
64                 info.bmiHeader.biPlanes = 1;\r
65                 info.bmiHeader.biSize = sizeof(BITMAPINFO);\r
66                 info.bmiHeader.biWidth = width;\r
67 \r
68                 bmp_.reset(CreateDIBSection(static_cast<HDC>(hdc_.get()), &info, DIB_RGB_COLORS, reinterpret_cast<void**>(&bmp_data_), 0, 0), DeleteObject);\r
69                 SelectObject(static_cast<HDC>(hdc_.get()), bmp_.get()); \r
70 \r
71                 if(!bmp_data_)\r
72                         BOOST_THROW_EXCEPTION(std::bad_alloc());\r
73         }\r
74 \r
75         operator HDC() {return static_cast<HDC>(hdc_.get());}\r
76 \r
77         BYTE* data() { return bmp_data_;}\r
78         const BYTE* data() const { return bmp_data_;}\r
79 \r
80 private:\r
81         BYTE* bmp_data_;        \r
82         std::shared_ptr<void> hdc_;\r
83         std::shared_ptr<void> bmp_;\r
84 };\r
85 \r
86 class flash_renderer\r
87 {       \r
88         const std::wstring filename_;\r
89 \r
90         const std::shared_ptr<core::frame_factory> frame_factory_;\r
91         \r
92         CComObject<caspar::flash::FlashAxContainer>* ax_;\r
93         safe_ptr<core::basic_frame> head_;\r
94         bitmap bmp_;\r
95         \r
96         safe_ptr<diagnostics::graph> graph_;\r
97         boost::timer frame_timer_;\r
98         boost::timer tick_timer_;\r
99 \r
100         high_prec_timer timer_;\r
101 \r
102         const size_t width_;\r
103         const size_t height_;\r
104         \r
105 public:\r
106         flash_renderer(const safe_ptr<diagnostics::graph>& graph, const std::shared_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, int width, int height) \r
107                 : graph_(graph)\r
108                 , filename_(filename)\r
109                 , frame_factory_(frame_factory)\r
110                 , ax_(nullptr)\r
111                 , head_(core::basic_frame::empty())\r
112                 , bmp_(width, height)\r
113                 , width_(width)\r
114                 , height_(height)\r
115         {\r
116                 graph_->add_guide("frame-time", 0.5f);\r
117                 graph_->set_color("frame-time", diagnostics::color(0.8f, 0.3f, 0.4f));  \r
118                 graph_->add_guide("tick-time", 0.5);\r
119                 graph_->set_color("tick-time", diagnostics::color(0.1f, 0.7f, 0.8f));\r
120                 graph_->set_color("param", diagnostics::color(1.0f, 0.5f, 0.0f));       \r
121                 graph_->set_color("underflow", diagnostics::color(0.6f, 0.3f, 0.9f));                   \r
122                 \r
123                 if(FAILED(CComObject<caspar::flash::FlashAxContainer>::CreateInstance(&ax_)))\r
124                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to create FlashAxContainer"));\r
125                 \r
126                 ax_->set_print([this]{return L"flash_renderer";});\r
127 \r
128                 if(FAILED(ax_->CreateAxControl()))\r
129                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Create FlashAxControl"));\r
130                 \r
131                 CComPtr<IShockwaveFlash> spFlash;\r
132                 if(FAILED(ax_->QueryControl(&spFlash)))\r
133                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Query FlashAxControl"));\r
134                                                                                                 \r
135                 if(FAILED(spFlash->put_Playing(true)) )\r
136                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to start playing Flash"));\r
137 \r
138                 if(FAILED(spFlash->put_Movie(CComBSTR(filename.c_str()))))\r
139                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Load Template Host"));\r
140                                                                                 \r
141                 if(FAILED(spFlash->put_ScaleMode(2)))  //Exact fit. Scale without respect to the aspect ratio.\r
142                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(narrow(print()) + " Failed to Set Scale Mode"));\r
143                                                 \r
144                 ax_->SetSize(width_, height_);          \r
145         \r
146                 CASPAR_LOG(info) << print() << L" Thread started.";\r
147                 CASPAR_LOG(info) << print() << L" Successfully initialized to, width: " << width_ << L" height: " << height_ << L".";\r
148         }\r
149 \r
150         ~flash_renderer()\r
151         {               \r
152                 if(ax_)\r
153                 {\r
154                         ax_->DestroyAxControl();\r
155                         ax_->Release();\r
156                 }\r
157                 CASPAR_LOG(info) << print() << L" Thread ended.";\r
158         }\r
159         \r
160         void param(const std::wstring& param)\r
161         {               \r
162                 if(!ax_->FlashCall(param))\r
163                         CASPAR_LOG(warning) << print() << " Flash function call failed. Param: " << param << ".";\r
164                 graph_->add_tag("param");\r
165         }\r
166         \r
167         safe_ptr<core::basic_frame> render_frame(bool has_underflow)\r
168         {\r
169                 //if(format_desc_ != frame_factory_->get_video_format_desc())\r
170                 //{\r
171                 //      format_desc_ = frame_factory_->get_video_format_desc();\r
172                 //      bmp_ = bitmap(format_desc_.width, format_desc_.height);\r
173                 //      ax_->SetFormat(format_desc_);\r
174                 //}\r
175 \r
176                 float frame_time = 1.0f/ax_->GetFPS();\r
177 \r
178                 graph_->update_value("tick-time", static_cast<float>(tick_timer_.elapsed()/frame_time)*0.5f);\r
179                 tick_timer_.restart();\r
180 \r
181                 if(ax_->IsEmpty())\r
182                         return core::basic_frame::empty();              \r
183                 \r
184                 if(!has_underflow)                      \r
185                         timer_.tick(frame_time); // This will block the thread.\r
186                 else\r
187                         graph_->add_tag("underflow");\r
188                         \r
189                 frame_timer_.restart();\r
190 \r
191                 ax_->Tick();\r
192                 if(ax_->InvalidRect())\r
193                 {                       \r
194                         fast_memclr(bmp_.data(), width_*height_*4);\r
195                         ax_->DrawControl(bmp_);\r
196                 \r
197                         auto frame = frame_factory_->create_frame(this, width_, height_);\r
198                         fast_memcpy(frame->image_data().begin(), bmp_.data(), width_*height_*4);\r
199                         frame->commit();\r
200                         head_ = frame;\r
201                 }               \r
202                                 \r
203                 graph_->update_value("frame-time", static_cast<float>(frame_timer_.elapsed()/frame_time)*0.5f);\r
204                 return head_;\r
205         }\r
206 \r
207         double fps() const\r
208         {\r
209                 return ax_->GetFPS();   \r
210         }\r
211         \r
212         std::wstring print()\r
213         {\r
214                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L"]";               \r
215         }\r
216 };\r
217 \r
218 struct flash_producer : public core::frame_producer\r
219 {       \r
220         const std::wstring filename_;   \r
221         const safe_ptr<core::frame_factory> frame_factory_;\r
222 \r
223         tbb::atomic<int> fps_;\r
224 \r
225         std::shared_ptr<diagnostics::graph> graph_;\r
226 \r
227         tbb::concurrent_bounded_queue<safe_ptr<core::basic_frame>> frame_buffer_;\r
228 \r
229         safe_ptr<core::basic_frame>     last_frame_;\r
230                                 \r
231         com_context<flash_renderer> context_;   \r
232 \r
233         int width_;\r
234         int height_;\r
235 public:\r
236         flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::wstring& filename, size_t width, size_t height) \r
237                 : filename_(filename)           \r
238                 , frame_factory_(frame_factory)\r
239                 , context_(L"flash_producer")\r
240                 , last_frame_(core::basic_frame::empty())\r
241                 , width_(width > 0 ? width : frame_factory->get_video_format_desc().width)\r
242                 , height_(height > 0 ? height : frame_factory->get_video_format_desc().height)\r
243         {       \r
244                 if(!boost::filesystem::exists(filename))\r
245                         BOOST_THROW_EXCEPTION(file_not_found() << boost::errinfo_file_name(narrow(filename)));  \r
246                  \r
247                 fps_ = 0;\r
248 \r
249                 graph_ = diagnostics::create_graph([this]{return print();});\r
250                 graph_->set_color("output-buffer", diagnostics::color(0.0f, 1.0f, 0.0f));\r
251                 \r
252                 frame_buffer_.set_capacity(1);\r
253 \r
254                 initialize();                           \r
255         }\r
256 \r
257         ~flash_producer()\r
258         {\r
259                 frame_buffer_.clear();\r
260         }\r
261 \r
262         // frame_producer\r
263                 \r
264         virtual safe_ptr<core::basic_frame> receive(int)\r
265         {                               \r
266                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));\r
267 \r
268                 auto frame = core::basic_frame::late();\r
269                 if(frame_buffer_.try_pop(frame))\r
270                         last_frame_ = frame;\r
271 \r
272                 return frame;\r
273         }\r
274 \r
275         virtual safe_ptr<core::basic_frame> last_frame() const\r
276         {\r
277                 return last_frame_;\r
278         }               \r
279         \r
280         virtual void param(const std::wstring& param) \r
281         {       \r
282                 context_.begin_invoke([=]\r
283                 {\r
284                         if(!context_)\r
285                                 initialize();\r
286 \r
287                         try\r
288                         {\r
289                                 context_->param(param); \r
290 \r
291                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
292                                 if(abs(context_->fps() - format_desc.fps) > 0.01 && abs(context_->fps()/2.0 - format_desc.fps) > 0.01)\r
293                                         CASPAR_LOG(warning) << print() << " Invalid frame-rate: " << context_->fps() << L". Should be either " << format_desc.fps << L" or " << format_desc.fps*2.0 << L".";\r
294                         }\r
295                         catch(...)\r
296                         {\r
297                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
298                                 context_.reset(nullptr);\r
299                                 frame_buffer_.push(core::basic_frame::empty());\r
300                         }\r
301                 });\r
302         }\r
303                 \r
304         virtual std::wstring print() const\r
305         { \r
306                 return L"flash[" + boost::filesystem::wpath(filename_).filename() + L", " + \r
307                                         boost::lexical_cast<std::wstring>(fps_) + L"]";         \r
308         }       \r
309 \r
310         // flash_producer\r
311 \r
312         void initialize()\r
313         {\r
314                 context_.reset([&]{return new flash_renderer(safe_ptr<diagnostics::graph>(graph_), frame_factory_, filename_, width_, height_);});\r
315                 while(frame_buffer_.try_push(core::basic_frame::empty())){}             \r
316                 render(context_.get());\r
317         }\r
318 \r
319         void render(const flash_renderer* renderer)\r
320         {               \r
321                 context_.begin_invoke([=]\r
322                 {\r
323                         if(context_.get() != renderer) // Since initialize will start a new recursive call make sure the recursive calls are only for a specific instance.\r
324                                 return;\r
325 \r
326                         try\r
327                         {               \r
328                                 const auto& format_desc = frame_factory_->get_video_format_desc();\r
329 \r
330                                 if(abs(context_->fps()/2.0 - format_desc.fps) < 2.0) // flash == 2 * format -> interlace\r
331                                 {\r
332                                         auto frame1 = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());\r
333                                         auto frame2 = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());\r
334                                         frame_buffer_.push(core::basic_frame::interlace(frame1, frame2, format_desc.mode));\r
335                                 }\r
336                                 else if(abs(context_->fps()- format_desc.fps/2.0) < 2.0) // format == 2 * flash -> duplicate\r
337                                 {\r
338                                         auto frame = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());\r
339                                         frame_buffer_.push(frame);\r
340                                         frame_buffer_.push(frame);\r
341                                 }\r
342                                 else //if(abs(renderer_->fps() - format_desc_.fps) < 0.1) // format == flash -> simple\r
343                                 {\r
344                                         auto frame = context_->render_frame(frame_buffer_.size() < frame_buffer_.capacity());\r
345                                         frame_buffer_.push(frame);\r
346                                 }\r
347 \r
348                                 graph_->set_value("output-buffer", static_cast<float>(frame_buffer_.size())/static_cast<float>(frame_buffer_.capacity()));      \r
349                                 fps_.fetch_and_store(static_cast<int>(context_->fps()*100.0));\r
350 \r
351                                 render(renderer);\r
352                         }\r
353                         catch(...)\r
354                         {\r
355                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
356                                 context_.reset(nullptr);\r
357                                 frame_buffer_.push(core::basic_frame::empty());\r
358                         }\r
359                 });\r
360         }\r
361 };\r
362 \r
363 safe_ptr<core::frame_producer> create_flash_producer(const safe_ptr<core::frame_factory>& frame_factory, const std::vector<std::wstring>& params)\r
364 {\r
365         std::wstring filename = env::template_folder() + L"\\" + params[0];\r
366 \r
367         size_t width = frame_factory->get_video_format_desc().width;\r
368         size_t height = frame_factory->get_video_format_desc().height;\r
369 \r
370         if(params.size() >= 3)\r
371         {\r
372                 width = boost::lexical_cast<size_t>(params[1]);\r
373                 height = boost::lexical_cast<size_t>(params[2]);\r
374         }\r
375         \r
376         return make_safe<flash_producer>(frame_factory, filename, width, height);\r
377 }\r
378 \r
379 std::wstring find_flash_template(const std::wstring& template_name)\r
380 {\r
381         if(boost::filesystem::exists(template_name + L".ft")) \r
382                 return template_name + L".ft";\r
383         \r
384         if(boost::filesystem::exists(template_name + L".ct"))\r
385                 return template_name + L".ct";\r
386 \r
387         return L"";\r
388 }\r
389 \r
390 }