]> git.sesse.net Git - casparcg/blob - accelerator/cpu/image/image_mixer.cpp
set svn:eol-style native on .h and .cpp files
[casparcg] / accelerator / cpu / image / image_mixer.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 "image_mixer.h"
25
26 #include "../util/xmm.h"
27
28 #include <common/assert.h>
29 #include <common/gl/gl_check.h>
30 #include <common/future.h>
31 #include <common/array.h>
32
33 #include <core/frame/frame.h>
34 #include <core/frame/frame_transform.h>
35 #include <core/frame/pixel_format.h>
36 #include <core/video_format.h>
37
38 #include <modules/ffmpeg/producer/util/util.h>
39
40 #include <asmlib.h>
41
42 #include <gl/glew.h>
43
44 #include <tbb/cache_aligned_allocator.h>
45 #include <tbb/parallel_for.h>
46 #include <tbb/parallel_for_each.h>
47 #include <tbb/concurrent_queue.h>
48
49 #include <boost/assign.hpp>
50 #include <boost/foreach.hpp>
51 #include <boost/range.hpp>
52 #include <boost/range/algorithm_ext/erase.hpp>
53 #include <boost/thread/future.hpp>
54
55 #include <algorithm>
56 #include <cstdint>
57 #include <vector>
58
59 #if defined(_MSC_VER)
60 #pragma warning (push)
61 #pragma warning (disable : 4244)
62 #endif
63 extern "C" 
64 {
65         #include <libswscale/swscale.h>
66         #include <libavcodec/avcodec.h>
67         #include <libavformat/avformat.h>
68 }
69 #if defined(_MSC_VER)
70 #pragma warning (pop)
71 #endif
72
73 namespace caspar { namespace accelerator { namespace cpu {
74                 
75 struct item
76 {
77         core::pixel_format_desc                 pix_desc;
78         std::array<const uint8_t*, 4>   data;
79         core::image_transform                   transform;
80
81         item()
82                 : pix_desc(core::pixel_format::invalid)
83         {
84                 data.fill(0);
85         }
86 };
87
88 bool operator==(const item& lhs, const item& rhs)
89 {
90         return lhs.data == rhs.data && lhs.transform == rhs.transform;
91 }
92
93 bool operator!=(const item& lhs, const item& rhs)
94 {
95         return !(lhs == rhs);
96 }
97         
98 // 100% accurate blending with correct rounding.
99 inline xmm::s8_x blend(xmm::s8_x d, xmm::s8_x s)
100 {       
101         using namespace xmm;
102                 
103         // C(S, D) = S + D - (((T >> 8) + T) >> 8);
104         // T(S, D) = S * D[A] + 0x80
105
106         auto aaaa   = s8_x::shuffle(d, s8_x(15, 15, 15, 15, 11, 11, 11, 11, 7, 7, 7, 7, 3, 3, 3, 3));
107         d                       = s8_x(u8_x::min(u8_x(d), u8_x(aaaa))); // Overflow guard. Some source files have color values which incorrectly exceed pre-multiplied alpha values, e.g. red(255) > alpha(254).
108
109         auto xaxa       = s16_x(aaaa) >> 8;             
110                               
111         auto t1         = s16_x::multiply_low(s16_x(s) & 0x00FF, xaxa) + 0x80;    
112         auto t2         = s16_x::multiply_low(s16_x(s) >> 8    , xaxa) + 0x80;
113                 
114         auto xyxy       = s8_x(((t1 >> 8) + t1) >> 8);      
115         auto yxyx       = s8_x((t2 >> 8) + t2);    
116         auto argb   = s8_x::blend(xyxy, yxyx, s8_x(-1, 0, -1, 0));
117
118         return s8_x(s) + (d - argb);
119 }
120         
121 template<typename temporal, typename alignment>
122 static void kernel(uint8_t* dest, const uint8_t* source, size_t count)
123 {                       
124         using namespace xmm;
125
126         for(auto n = 0; n < count; n += 32)    
127         {
128                 auto s0 = s8_x::load<temporal_tag, alignment>(dest+n+0);
129                 auto s1 = s8_x::load<temporal_tag, alignment>(dest+n+16);
130
131                 auto d0 = s8_x::load<temporal_tag, alignment>(source+n+0);
132                 auto d1 = s8_x::load<temporal_tag, alignment>(source+n+16);
133                 
134                 auto argb0 = blend(d0, s0);
135                 auto argb1 = blend(d1, s1);
136
137                 s8_x::store<temporal, alignment>(argb0, dest+n+0 );
138                 s8_x::store<temporal, alignment>(argb1, dest+n+16);
139         } 
140 }
141
142 template<typename temporal>
143 static void kernel(uint8_t* dest, const uint8_t* source, size_t count)
144 {                       
145         using namespace xmm;
146
147         if(reinterpret_cast<int>(dest) % 16 != 0 || reinterpret_cast<int>(source) % 16 != 0)
148                 kernel<temporal_tag, unaligned_tag>(dest, source, count);
149         else
150                 kernel<temporal_tag, aligned_tag>(dest, source, count);
151 }
152
153 class image_renderer
154 {
155         tbb::concurrent_unordered_map<int64_t, tbb::concurrent_bounded_queue<std::shared_ptr<SwsContext>>>      sws_devices_;
156         tbb::concurrent_bounded_queue<spl::shared_ptr<buffer>>                                                                                          temp_buffers_;
157 public: 
158         boost::unique_future<array<const std::uint8_t>> operator()(std::vector<item> items, const core::video_format_desc& format_desc)
159         {       
160                 convert(items, format_desc.width, format_desc.height);          
161                                 
162                 // Remove first field stills.
163                 boost::range::remove_erase_if(items, [&](const item& item)
164                 {
165                         return item.transform.is_still && item.transform.field_mode == format_desc.field_mode; // only us last field for stills.
166                 });
167                 
168                 // Stills are progressive
169                 BOOST_FOREACH(auto item, items)
170                 {
171                         if(item.transform.is_still)
172                                 item.transform.field_mode = core::field_mode::progressive;
173                 }
174
175                 auto result = spl::make_shared<buffer>(format_desc.size, 0);
176                 if(format_desc.field_mode != core::field_mode::progressive)
177                 {                       
178                         draw(items, result->data(), format_desc.width, format_desc.height, core::field_mode::upper);
179                         draw(items, result->data(), format_desc.width, format_desc.height, core::field_mode::lower);
180                 }
181                 else
182                 {
183                         draw(items, result->data(), format_desc.width, format_desc.height,  core::field_mode::progressive);
184                 }
185
186                 temp_buffers_.clear();
187                 
188                 return async(launch::deferred, [=]
189                 {
190                         return array<const std::uint8_t>(result->data(), format_desc.size, true, result);
191                 });     
192         }
193
194 private:
195
196         void draw(std::vector<item> items, uint8_t* dest, std::size_t width, std::size_t height, core::field_mode field_mode)
197         {               
198                 BOOST_FOREACH(auto& item, items)
199                         item.transform.field_mode &= field_mode;
200                 
201                 // Remove empty items.
202                 boost::range::remove_erase_if(items, [&](const item& item)
203                 {
204                         return item.transform.field_mode == core::field_mode::empty;
205                 });
206
207                 if(items.empty())
208                         return;
209                 
210                 auto start = field_mode == core::field_mode::lower ? 1 : 0;
211                 auto step  = field_mode == core::field_mode::progressive ? 1 : 2;
212                 
213                 // TODO: Add support for fill translations.
214                 // TODO: Add support for mask rect.
215                 // TODO: Add support for opacity.
216                 // TODO: Add support for mix transition.
217                 // TODO: Add support for push transition.
218                 // TODO: Add support for wipe transition.
219                 // TODO: Add support for slide transition.
220                 tbb::parallel_for(tbb::blocked_range<std::size_t>(0, height/step), [&](const tbb::blocked_range<std::size_t>& r)
221                 {
222                         for(auto i = r.begin(); i != r.end(); ++i)
223                         {
224                                 auto y = i*step+start;
225
226                                 for(std::size_t n = 0; n < items.size()-1; ++n)
227                                         kernel<xmm::temporal_tag>(dest + y*width*4, items[n].data.at(0) + y*width*4, width*4);
228                                 
229                                 std::size_t n = items.size()-1;                         
230                                 kernel<xmm::nontemporal_tag>(dest + y*width*4, items[n].data.at(0) + y*width*4, width*4);
231                         }
232
233                         _mm_mfence();
234                 });
235         }
236                 
237         void convert(std::vector<item>& source_items, int width, int height)
238         {
239                 std::set<std::array<const uint8_t*, 4>> buffers;
240
241                 BOOST_FOREACH(auto& item, source_items)
242                         buffers.insert(item.data);
243                 
244                 auto dest_items = source_items;
245
246                 tbb::parallel_for_each(buffers.begin(), buffers.end(), [&](const std::array<const uint8_t*, 4>& data)
247                 {                       
248                         auto pix_desc = std::find_if(source_items.begin(), source_items.end(), [&](const item& item){return item.data == data;})->pix_desc;
249
250                         if(pix_desc.format == core::pixel_format::bgra && 
251                                 pix_desc.planes.at(0).width == width &&
252                                 pix_desc.planes.at(0).height == height)
253                                 return;
254
255                         std::array<uint8_t*, 4> data2 = {};
256                         for(std::size_t n = 0; n < data.size(); ++n)
257                                 data2.at(n) = const_cast<uint8_t*>(data[n]);
258
259                         auto input_av_frame = ffmpeg::make_av_frame(data2, pix_desc);
260
261                 
262                         int64_t key = ((static_cast<int64_t>(input_av_frame->width)      << 32) & 0xFFFF00000000) | 
263                                                   ((static_cast<int64_t>(input_av_frame->height) << 16) & 0xFFFF0000) | 
264                                                   ((static_cast<int64_t>(input_av_frame->format) <<  8) & 0xFF00);
265
266                         auto& pool = sws_devices_[key];
267
268                         std::shared_ptr<SwsContext> sws_device;
269                         if(!pool.try_pop(sws_device))
270                         {
271                                 double param;
272                                 sws_device.reset(sws_getContext(input_av_frame->width, input_av_frame->height, static_cast<PixelFormat>(input_av_frame->format), width, height, PIX_FMT_BGRA, SWS_BILINEAR, nullptr, nullptr, &param), sws_freeContext);
273                         }
274                         
275                         if(!sws_device)                         
276                                 CASPAR_THROW_EXCEPTION(operation_failed() << msg_info("Could not create software scaling device.") << boost::errinfo_api_function("sws_getContext"));                           
277                 
278                         auto dest_frame = spl::make_shared<buffer>(width*height*4);
279                         temp_buffers_.push(dest_frame);
280
281                         {
282                                 spl::shared_ptr<AVFrame> dest_av_frame(avcodec_alloc_frame(), av_free); 
283                                 avcodec_get_frame_defaults(dest_av_frame.get());                        
284                                 avpicture_fill(reinterpret_cast<AVPicture*>(dest_av_frame.get()), dest_frame->data(), PIX_FMT_BGRA, width, height);
285                                 
286                                 sws_scale(sws_device.get(), input_av_frame->data, input_av_frame->linesize, 0, input_av_frame->height, dest_av_frame->data, dest_av_frame->linesize);                           
287                                 pool.push(sws_device);
288                         }
289                                         
290                         for(std::size_t n = 0; n < source_items.size(); ++n)
291                         {
292                                 if(source_items[n].data == data)
293                                 {
294                                         dest_items[n].data.assign(0);
295                                         dest_items[n].data[0]                   = dest_frame->data();
296                                         dest_items[n].pix_desc                  = core::pixel_format_desc(core::pixel_format::bgra);
297                                         dest_items[n].pix_desc.planes   = boost::assign::list_of(core::pixel_format_desc::plane(width, height, 4));
298                                         dest_items[n].transform                 = source_items[n].transform;
299                                 }
300                         }
301                 });     
302
303                 source_items = std::move(dest_items);
304         }
305 };
306                 
307 struct image_mixer::impl : boost::noncopyable
308 {       
309         image_renderer                                          renderer_;
310         std::vector<core::image_transform>      transform_stack_;
311         std::vector<item>                                       items_; // layer/stream/items
312 public:
313         impl() 
314                 : transform_stack_(1)   
315         {
316                 CASPAR_LOG(info) << L"Initialized Streaming SIMD Extensions Accelerated CPU Image Mixer";
317         }
318
319         void begin_layer(core::blend_mode blend_mode)
320         {
321         }
322                 
323         void push(const core::frame_transform& transform)
324         {
325                 transform_stack_.push_back(transform_stack_.back()*transform.image_transform);
326         }
327                 
328         void visit(const core::const_frame& frame)
329         {                       
330                 if(frame.pixel_format_desc().format == core::pixel_format::invalid)
331                         return;
332
333                 if(frame.pixel_format_desc().planes.empty())
334                         return;
335                 
336                 if(frame.pixel_format_desc().planes.at(0).size < 16)
337                         return;
338
339                 if(transform_stack_.back().field_mode == core::field_mode::empty)
340                         return;
341
342                 item item;
343                 item.pix_desc   = frame.pixel_format_desc();
344                 item.transform  = transform_stack_.back();
345                 for(int n = 0; n < item.pix_desc.planes.size(); ++n)
346                         item.data.at(n) = frame.image_data(n).begin();          
347
348                 items_.push_back(item);
349         }
350
351         void pop()
352         {
353                 transform_stack_.pop_back();
354         }
355
356         void end_layer()
357         {               
358         }
359         
360         boost::unique_future<array<const std::uint8_t>> render(const core::video_format_desc& format_desc)
361         {
362                 return renderer_(std::move(items_), format_desc);
363         }
364         
365         virtual core::mutable_frame create_frame(const void* tag, const core::pixel_format_desc& desc)
366         {
367                 std::vector<array<std::uint8_t>> buffers;
368                 BOOST_FOREACH(auto& plane, desc.planes)
369                 {
370                         auto buf = spl::make_shared<buffer>(plane.size);
371                         buffers.push_back(array<std::uint8_t>(buf->data(), plane.size, true, buf));
372                 }
373                 return core::mutable_frame(std::move(buffers), core::audio_buffer(), tag, desc);
374         }
375 };
376
377 image_mixer::image_mixer() : impl_(new impl()){}
378 image_mixer::~image_mixer(){}
379 void image_mixer::push(const core::frame_transform& transform){impl_->push(transform);}
380 void image_mixer::visit(const core::const_frame& frame){impl_->visit(frame);}
381 void image_mixer::pop(){impl_->pop();}
382 boost::unique_future<array<const std::uint8_t>> image_mixer::operator()(const core::video_format_desc& format_desc){return impl_->render(format_desc);}
383 void image_mixer::begin_layer(core::blend_mode blend_mode){impl_->begin_layer(blend_mode);}
384 void image_mixer::end_layer(){impl_->end_layer();}
385 core::mutable_frame image_mixer::create_frame(const void* tag, const core::pixel_format_desc& desc) {return impl_->create_frame(tag, desc);}
386
387 }}}