]> git.sesse.net Git - casparcg/blob - protocol/amcp/AMCPCommandsImpl.cpp
* Refactored blend_mode to be part of frame_transform instead of a global parameter...
[casparcg] / protocol / amcp / AMCPCommandsImpl.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: Nicklas P Andersson
20 */
21
22 #include "../StdAfx.h"
23
24 #if defined(_MSC_VER)
25 #pragma warning (push, 1) // TODO: Legacy code, just disable warnings
26 #endif
27
28 #include "AMCPCommandsImpl.h"
29 #include "AMCPProtocolStrategy.h"
30
31 #include <common/env.h>
32
33 #include <common/log.h>
34 #include <common/param.h>
35 #include <common/os/system_info.h>
36 #include <common/os/filesystem.h>
37 #include <common/base64.h>
38
39 #include <core/producer/frame_producer.h>
40 #include <core/video_format.h>
41 #include <core/producer/transition/transition_producer.h>
42 #include <core/frame/frame_transform.h>
43 #include <core/producer/stage.h>
44 #include <core/producer/layer.h>
45 #include <core/mixer/mixer.h>
46 #include <core/consumer/output.h>
47 #include <core/thumbnail_generator.h>
48 #include <core/producer/media_info/media_info.h>
49 #include <core/producer/media_info/media_info_repository.h>
50 #include <core/diagnostics/call_context.h>
51 #include <core/diagnostics/osd_graph.h>
52 #include <core/system_info_provider.h>
53
54 #include <modules/reroute/producer/reroute_producer.h>
55
56 #include <algorithm>
57 #include <locale>
58 #include <fstream>
59 #include <memory>
60 #include <cctype>
61 #include <future>
62
63 #include <boost/date_time/posix_time/posix_time.hpp>
64 #include <boost/lexical_cast.hpp>
65 #include <boost/algorithm/string.hpp>
66 #include <boost/filesystem.hpp>
67 #include <boost/filesystem/fstream.hpp>
68 #include <boost/regex.hpp>
69 #include <boost/property_tree/xml_parser.hpp>
70 #include <boost/locale.hpp>
71 #include <boost/range/adaptor/transformed.hpp>
72 #include <boost/range/algorithm/copy.hpp>
73 #include <boost/archive/iterators/base64_from_binary.hpp>
74 #include <boost/archive/iterators/insert_linebreaks.hpp>
75 #include <boost/archive/iterators/transform_width.hpp>
76
77 #include <tbb/concurrent_unordered_map.h>
78
79 /* Return codes
80
81 102 [action]                    Information that [action] has happened
82 101 [action]                    Information that [action] has happened plus one row of data  
83
84 202 [command] OK                [command] has been executed
85 201 [command] OK                [command] has been executed, plus one row of data  
86 200 [command] OK                [command] has been executed, plus multiple lines of data. ends with an empty line
87
88 400 ERROR                               the command could not be understood
89 401 [command] ERROR             invalid/missing channel
90 402 [command] ERROR             parameter missing
91 403 [command] ERROR             invalid parameter  
92 404 [command] ERROR             file not found
93
94 500 FAILED                              internal error
95 501 [command] FAILED    internal error
96 502 [command] FAILED    could not read file
97 503 [command] FAILED    access denied
98
99 600 [command] FAILED    [command] not implemented
100 */
101
102 namespace caspar { namespace protocol {
103
104 using namespace core;
105
106 std::wstring read_file_base64(const boost::filesystem::path& file)
107 {
108         using namespace boost::archive::iterators;
109
110         boost::filesystem::ifstream filestream(file, std::ios::binary);
111
112         if (!filestream)
113                 return L"";
114
115         auto length = boost::filesystem::file_size(file);
116         std::vector<char> bytes;
117         bytes.resize(length);
118         filestream.read(bytes.data(), length);
119
120         std::string result(to_base64(bytes.data(), length));
121         return std::wstring(result.begin(), result.end());
122 }
123
124 std::wstring read_utf8_file(const boost::filesystem::path& file)
125 {
126         std::wstringstream result;
127         boost::filesystem::wifstream filestream(file);
128
129         if (filestream) 
130         {
131                 // Consume BOM first
132                 filestream.get();
133                 // read all data
134                 result << filestream.rdbuf();
135         }
136
137         return result.str();
138 }
139
140 std::wstring read_latin1_file(const boost::filesystem::path& file)
141 {
142         boost::locale::generator gen;
143         gen.locale_cache_enabled(true);
144         gen.categories(boost::locale::codepage_facet);
145
146         std::stringstream result_stream;
147         boost::filesystem::ifstream filestream(file);
148         filestream.imbue(gen("en_US.ISO8859-1"));
149
150         if (filestream)
151         {
152                 // read all data
153                 result_stream << filestream.rdbuf();
154         }
155
156         std::string result = result_stream.str();
157         std::wstring widened_result;
158
159         // The first 255 codepoints in unicode is the same as in latin1
160         boost::copy(
161                 result | boost::adaptors::transformed(
162                                 [](char c) { return static_cast<unsigned char>(c); }),
163                 std::back_inserter(widened_result));
164
165         return widened_result;
166 }
167
168 std::wstring read_file(const boost::filesystem::path& file)
169 {
170         static const uint8_t BOM[] = {0xef, 0xbb, 0xbf};
171
172         if (!boost::filesystem::exists(file))
173         {
174                 return L"";
175         }
176
177         if (boost::filesystem::file_size(file) >= 3)
178         {
179                 boost::filesystem::ifstream bom_stream(file);
180
181                 char header[3];
182                 bom_stream.read(header, 3);
183                 bom_stream.close();
184
185                 if (std::memcmp(BOM, header, 3) == 0)
186                         return read_utf8_file(file);
187         }
188
189         return read_latin1_file(file);
190 }
191
192 std::wstring MediaInfo(const boost::filesystem::path& path, const spl::shared_ptr<media_info_repository>& media_info_repo)
193 {
194         if (!boost::filesystem::is_regular_file(path))
195                 return L"";
196
197         auto media_info = media_info_repo->get(path.wstring());
198
199         if (!media_info)
200                 return L"";
201
202         auto is_not_digit = [](char c){ return std::isdigit(c) == 0; };
203
204         auto relativePath = boost::filesystem::path(path.wstring().substr(env::media_folder().size() - 1, path.wstring().size()));
205
206         auto writeTimeStr = boost::posix_time::to_iso_string(boost::posix_time::from_time_t(boost::filesystem::last_write_time(path)));
207         writeTimeStr.erase(std::remove_if(writeTimeStr.begin(), writeTimeStr.end(), is_not_digit), writeTimeStr.end());
208         auto writeTimeWStr = std::wstring(writeTimeStr.begin(), writeTimeStr.end());
209
210         auto sizeStr = boost::lexical_cast<std::wstring>(boost::filesystem::file_size(path));
211         sizeStr.erase(std::remove_if(sizeStr.begin(), sizeStr.end(), is_not_digit), sizeStr.end());
212         auto sizeWStr = std::wstring(sizeStr.begin(), sizeStr.end());
213
214         auto str = relativePath.replace_extension(L"").generic_wstring();
215         if (str[0] == '\\' || str[0] == '/')
216                 str = std::wstring(str.begin() + 1, str.end());
217
218         return std::wstring()
219                 + L"\"" + str +
220                 + L"\" " + media_info->clip_type +
221                 + L" " + sizeStr +
222                 + L" " + writeTimeWStr +
223                 + L" " + boost::lexical_cast<std::wstring>(media_info->duration) +
224                 + L" " + boost::lexical_cast<std::wstring>(media_info->time_base.numerator()) + L"/" + boost::lexical_cast<std::wstring>(media_info->time_base.denominator())
225                 + L"\r\n";
226 }
227
228 std::wstring ListMedia(const spl::shared_ptr<media_info_repository>& media_info_repo)
229 {       
230         std::wstringstream replyString;
231         for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end; ++itr)
232                 replyString << MediaInfo(itr->path(), media_info_repo);
233         
234         return boost::to_upper_copy(replyString.str());
235 }
236
237 std::wstring ListTemplates(const spl::shared_ptr<core::cg_producer_registry>& cg_registry)
238 {
239         std::wstringstream replyString;
240
241         for (boost::filesystem::recursive_directory_iterator itr(env::template_folder()), end; itr != end; ++itr)
242         {               
243                 if(boost::filesystem::is_regular_file(itr->path()) && cg_registry->is_cg_extension(itr->path().extension().wstring()))
244                 {
245                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::template_folder().size()-1, itr->path().wstring().size()));
246
247                         auto writeTimeStr = boost::posix_time::to_iso_string(boost::posix_time::from_time_t(boost::filesystem::last_write_time(itr->path())));
248                         writeTimeStr.erase(std::remove_if(writeTimeStr.begin(), writeTimeStr.end(), [](char c){ return std::isdigit(c) == 0;}), writeTimeStr.end());
249                         auto writeTimeWStr = std::wstring(writeTimeStr.begin(), writeTimeStr.end());
250
251                         auto sizeStr = boost::lexical_cast<std::string>(boost::filesystem::file_size(itr->path()));
252                         sizeStr.erase(std::remove_if(sizeStr.begin(), sizeStr.end(), [](char c){ return std::isdigit(c) == 0;}), sizeStr.end());
253
254                         auto sizeWStr = std::wstring(sizeStr.begin(), sizeStr.end());
255
256                         auto dir = relativePath.parent_path();
257                         auto file = boost::to_upper_copy(relativePath.filename().wstring());
258                         relativePath = dir / file;
259                                                 
260                         auto str = relativePath.replace_extension(L"").generic_wstring();
261                         boost::trim_if(str, boost::is_any_of("\\/"));
262
263                         replyString << L"\"" << str
264                                                 << L"\" " << sizeWStr
265                                                 << L" " << writeTimeWStr
266                                                 << L"\r\n";
267                 }
268         }
269         return replyString.str();
270 }
271
272 namespace amcp {
273         
274 void AMCPCommand::SendReply()
275 {
276         if(replyString_.empty())
277                 return;
278
279         client_->send(std::move(replyString_));
280 }
281
282 bool DiagnosticsCommand::DoExecute()
283 {       
284         try
285         {
286                 core::diagnostics::osd::show_graphs(true);
287
288                 SetReplyString(L"202 DIAG OK\r\n");
289
290                 return true;
291         }
292         catch(...)
293         {
294                 CASPAR_LOG_CURRENT_EXCEPTION();
295                 SetReplyString(L"502 DIAG FAILED\r\n");
296                 return false;
297         }
298 }
299
300 bool ChannelGridCommand::DoExecute()
301 {
302         int index = 1;
303         auto self = channels().back().channel;
304         
305         core::diagnostics::scoped_call_context save;
306         core::diagnostics::call_context::for_thread().video_channel = channels().size();
307
308         std::vector<std::wstring> params;
309         params.push_back(L"SCREEN");
310         params.push_back(L"0");
311         params.push_back(L"NAME");
312         params.push_back(L"Channel Grid Window");
313         auto screen = create_consumer(params, &self->stage());
314
315         self->output().add(screen);
316
317         for (auto& channel : channels())
318         {
319                 if(channel.channel != self)
320                 {
321                         core::diagnostics::call_context::for_thread().layer = index;
322                         auto producer = reroute::create_producer(*channel.channel);
323                         self->stage().load(index, producer, false);
324                         self->stage().play(index);
325                         index++;
326                 }
327         }
328
329         int n = channels().size()-1;
330         double delta = 1.0/static_cast<double>(n);
331         for(int x = 0; x < n; ++x)
332         {
333                 for(int y = 0; y < n; ++y)
334                 {
335                         int index = x+y*n+1;
336                         auto transform = [=](frame_transform transform) -> frame_transform
337                         {               
338                                 transform.image_transform.fill_translation[0]   = x*delta;
339                                 transform.image_transform.fill_translation[1]   = y*delta;
340                                 transform.image_transform.fill_scale[0]                 = delta;
341                                 transform.image_transform.fill_scale[1]                 = delta;
342                                 transform.image_transform.clip_translation[0]   = x*delta;
343                                 transform.image_transform.clip_translation[1]   = y*delta;
344                                 transform.image_transform.clip_scale[0]                 = delta;
345                                 transform.image_transform.clip_scale[1]                 = delta;                        
346                                 return transform;
347                         };
348                         self->stage().apply_transform(index, transform);
349                 }
350         }
351
352         return true;
353 }
354
355 bool CallCommand::DoExecute()
356 {       
357         //Perform loading of the clip
358         try
359         {
360                 auto result = channel()->stage().call(layer_index(), parameters());
361                 
362                 // TODO: because of std::async deferred timed waiting does not work
363
364                 /*auto wait_res = result.wait_for(std::chrono::seconds(2));
365                 if (wait_res == std::future_status::timeout)
366                         CASPAR_THROW_EXCEPTION(timed_out());*/
367                                 
368                 std::wstringstream replyString;
369                 if(result.get().empty())
370                         replyString << L"202 CALL OK\r\n";
371                 else
372                         replyString << L"201 CALL OK\r\n" << result.get() << L"\r\n";
373                 
374                 SetReplyString(replyString.str());
375
376                 return true;
377         }
378         catch(...)
379         {
380                 CASPAR_LOG_CURRENT_EXCEPTION();
381                 SetReplyString(L"502 CALL FAILED\r\n");
382                 return false;
383         }
384 }
385
386 tbb::concurrent_unordered_map<int, std::vector<stage::transform_tuple_t>> deferred_transforms;
387
388 core::frame_transform MixerCommand::get_current_transform()
389 {
390         return channel()->stage().get_current_transform(layer_index()).get();
391 }
392
393 bool MixerCommand::DoExecute()
394 {       
395         //Perform loading of the clip
396         try
397         {       
398                 bool defer = boost::iequals(parameters().back(), L"DEFER");
399                 if(defer)
400                         parameters().pop_back();
401
402                 std::vector<stage::transform_tuple_t> transforms;
403
404                 if(boost::iequals(parameters()[0], L"KEYER") || boost::iequals(parameters()[0], L"IS_KEY"))
405                 {
406                         if (parameters().size() == 1)
407                                 return reply_value([](const frame_transform& t) { return t.image_transform.is_key ? 1 : 0; });
408
409                         bool value = boost::lexical_cast<int>(parameters().at(1));
410                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
411                         {
412                                 transform.image_transform.is_key = value;
413                                 return transform;                                       
414                         }, 0, L"linear"));
415                 }
416                 else if(boost::iequals(parameters()[0], L"OPACITY"))
417                 {
418                         if (parameters().size() == 1)
419                                 return reply_value([](const frame_transform& t) { return t.image_transform.opacity; });
420
421                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
422                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
423
424                         double value = boost::lexical_cast<double>(parameters().at(1));
425                         
426                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
427                         {
428                                 transform.image_transform.opacity = value;
429                                 return transform;                                       
430                         }, duration, tween));
431                 }
432                 else if (boost::iequals(parameters()[0], L"ANCHOR"))
433                 {
434                         if (parameters().size() == 1)
435                         {
436                                 auto transform = get_current_transform().image_transform;
437                                 auto anchor = transform.anchor;
438                                 SetReplyString(
439                                                 L"201 MIXER OK\r\n"
440                                                 + boost::lexical_cast<std::wstring>(anchor[0]) + L" "
441                                                 + boost::lexical_cast<std::wstring>(anchor[1]) + L"\r\n");
442                                 return true;
443                         }
444
445                         int duration = parameters().size() > 3 ? boost::lexical_cast<int>(parameters()[3]) : 0;
446                         std::wstring tween = parameters().size() > 4 ? parameters()[4] : L"linear";
447                         double x = boost::lexical_cast<double>(parameters().at(1));
448                         double y = boost::lexical_cast<double>(parameters().at(2));
449
450                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) mutable -> frame_transform
451                         {
452                                 transform.image_transform.anchor[0] = x;
453                                 transform.image_transform.anchor[1] = y;
454                                 return transform;
455                         }, duration, tween));
456                 }
457                 else if (boost::iequals(parameters()[0], L"FILL") || boost::iequals(parameters()[0], L"FILL_RECT"))
458                 {
459                         if (parameters().size() == 1)
460                         {
461                                 auto transform = get_current_transform().image_transform;
462                                 auto translation = transform.fill_translation;
463                                 auto scale = transform.fill_scale;
464                                 SetReplyString(
465                                                 L"201 MIXER OK\r\n"
466                                                 + boost::lexical_cast<std::wstring>(translation[0]) + L" "
467                                                 + boost::lexical_cast<std::wstring>(translation[1]) + L" "
468                                                 + boost::lexical_cast<std::wstring>(scale[0]) + L" "
469                                                 + boost::lexical_cast<std::wstring>(scale[1]) + L"\r\n");
470                                 return true;
471                         }
472
473                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
474                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
475                         double x        = boost::lexical_cast<double>(parameters().at(1));
476                         double y        = boost::lexical_cast<double>(parameters().at(2));
477                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
478                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
479
480                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) mutable -> frame_transform
481                         {
482                                 transform.image_transform.fill_translation[0]   = x;
483                                 transform.image_transform.fill_translation[1]   = y;
484                                 transform.image_transform.fill_scale[0]                 = x_s;
485                                 transform.image_transform.fill_scale[1]                 = y_s;
486                                 return transform;
487                         }, duration, tween));
488                 }
489                 else if(boost::iequals(parameters()[0], L"CLIP") || boost::iequals(parameters()[0], L"CLIP_RECT"))
490                 {
491                         if (parameters().size() == 1)
492                         {
493                                 auto transform = get_current_transform().image_transform;
494                                 auto translation = transform.clip_translation;
495                                 auto scale = transform.clip_scale;
496                                 SetReplyString(
497                                                 L"201 MIXER OK\r\n"
498                                                 + boost::lexical_cast<std::wstring>(translation[0]) + L" "
499                                                 + boost::lexical_cast<std::wstring>(translation[1]) + L" "
500                                                 + boost::lexical_cast<std::wstring>(scale[0]) + L" "
501                                                 + boost::lexical_cast<std::wstring>(scale[1]) + L"\r\n");
502                                 return true;
503                         }
504
505                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
506                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
507                         double x        = boost::lexical_cast<double>(parameters().at(1));
508                         double y        = boost::lexical_cast<double>(parameters().at(2));
509                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
510                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
511
512                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
513                         {
514                                 transform.image_transform.clip_translation[0]   = x;
515                                 transform.image_transform.clip_translation[1]   = y;
516                                 transform.image_transform.clip_scale[0]                 = x_s;
517                                 transform.image_transform.clip_scale[1]                 = y_s;
518                                 return transform;
519                         }, duration, tween));
520                 }
521                 else if (boost::iequals(parameters()[0], L"CROP"))
522                 {
523                         if (parameters().size() == 1)
524                         {
525                                 auto crop = get_current_transform().image_transform.crop;
526                                 SetReplyString(
527                                         L"201 MIXER OK\r\n"
528                                         + boost::lexical_cast<std::wstring>(crop.ul[0]) + L" "
529                                         + boost::lexical_cast<std::wstring>(crop.ul[1]) + L" "
530                                         + boost::lexical_cast<std::wstring>(crop.lr[0]) + L" "
531                                         + boost::lexical_cast<std::wstring>(crop.lr[1]) + L"\r\n");
532                                 return true;
533                         }
534
535                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
536                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
537                         double ul_x = boost::lexical_cast<double>(parameters().at(1));
538                         double ul_y = boost::lexical_cast<double>(parameters().at(2));
539                         double lr_x = boost::lexical_cast<double>(parameters().at(3));
540                         double lr_y = boost::lexical_cast<double>(parameters().at(4));
541
542                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
543                         {
544                                 transform.image_transform.crop.ul[0] = ul_x;
545                                 transform.image_transform.crop.ul[1] = ul_y;
546                                 transform.image_transform.crop.lr[0] = lr_x;
547                                 transform.image_transform.crop.lr[1] = lr_y;
548                                 return transform;
549                         }, duration, tween));
550                 }
551                 else if (boost::iequals(parameters()[0], L"PERSPECTIVE"))
552                 {
553                         if (parameters().size() == 1)
554                         {
555                                 auto perspective = get_current_transform().image_transform.perspective;
556                                 SetReplyString(
557                                                 L"201 MIXER OK\r\n"
558                                                 + boost::lexical_cast<std::wstring>(perspective.ul[0]) + L" "
559                                                 + boost::lexical_cast<std::wstring>(perspective.ul[1]) + L" "
560                                                 + boost::lexical_cast<std::wstring>(perspective.ur[0]) + L" "
561                                                 + boost::lexical_cast<std::wstring>(perspective.ur[1]) + L" "
562                                                 + boost::lexical_cast<std::wstring>(perspective.lr[0]) + L" "
563                                                 + boost::lexical_cast<std::wstring>(perspective.lr[1]) + L" "
564                                                 + boost::lexical_cast<std::wstring>(perspective.ll[0]) + L" "
565                                                 + boost::lexical_cast<std::wstring>(perspective.ll[1]) + L"\r\n");
566                                 return true;
567                         }
568
569                         int duration = parameters().size() > 9 ? boost::lexical_cast<int>(parameters()[9]) : 0;
570                         std::wstring tween = parameters().size() > 10 ? parameters()[10] : L"linear";
571                         double ul_x = boost::lexical_cast<double>(parameters().at(1));
572                         double ul_y = boost::lexical_cast<double>(parameters().at(2));
573                         double ur_x = boost::lexical_cast<double>(parameters().at(3));
574                         double ur_y = boost::lexical_cast<double>(parameters().at(4));
575                         double lr_x = boost::lexical_cast<double>(parameters().at(5));
576                         double lr_y = boost::lexical_cast<double>(parameters().at(6));
577                         double ll_x = boost::lexical_cast<double>(parameters().at(7));
578                         double ll_y = boost::lexical_cast<double>(parameters().at(8));
579
580                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
581                         {
582                                 transform.image_transform.perspective.ul[0] = ul_x;
583                                 transform.image_transform.perspective.ul[1] = ul_y;
584                                 transform.image_transform.perspective.ur[0] = ur_x;
585                                 transform.image_transform.perspective.ur[1] = ur_y;
586                                 transform.image_transform.perspective.lr[0] = lr_x;
587                                 transform.image_transform.perspective.lr[1] = lr_y;
588                                 transform.image_transform.perspective.ll[0] = ll_x;
589                                 transform.image_transform.perspective.ll[1] = ll_y;
590                                 return transform;
591                         }, duration, tween));
592                 }
593                 else if (boost::iequals(parameters()[0], L"GRID"))
594                 {
595                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
596                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
597                         int n = boost::lexical_cast<int>(parameters().at(1));
598                         double delta = 1.0/static_cast<double>(n);
599                         for(int x = 0; x < n; ++x)
600                         {
601                                 for(int y = 0; y < n; ++y)
602                                 {
603                                         int index = x+y*n+1;
604                                         transforms.push_back(stage::transform_tuple_t(index, [=](frame_transform transform) -> frame_transform
605                                         {               
606                                                 transform.image_transform.fill_translation[0]   = x*delta;
607                                                 transform.image_transform.fill_translation[1]   = y*delta;
608                                                 transform.image_transform.fill_scale[0]                 = delta;
609                                                 transform.image_transform.fill_scale[1]                 = delta;
610                                                 transform.image_transform.clip_translation[0]   = x*delta;
611                                                 transform.image_transform.clip_translation[1]   = y*delta;
612                                                 transform.image_transform.clip_scale[0]                 = delta;
613                                                 transform.image_transform.clip_scale[1]                 = delta;                        
614                                                 return transform;
615                                         }, duration, tween));
616                                 }
617                         }
618                 }
619                 else if (boost::iequals(parameters()[0], L"MIPMAP"))
620                 {
621                         if (parameters().size() == 1)
622                                 return reply_value([](const frame_transform& t) { return t.image_transform.use_mipmap ? 1 : 0; });
623
624                         bool value = boost::lexical_cast<int>(parameters().at(1));
625                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
626                         {
627                                 transform.image_transform.use_mipmap = value;
628                                 return transform;
629                         }, 0, L"linear"));
630                 }
631                 else if(boost::iequals(parameters()[0], L"BLEND"))
632                 {
633                         if (parameters().size() == 1)
634                                 return reply_value([](const frame_transform& t) { return get_blend_mode(t.image_transform.blend_mode); });
635
636                         auto value = get_blend_mode(parameters().at(1));
637                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
638                         {
639                                 transform.image_transform.blend_mode = value;
640                                 return transform;
641                         }, 0, L"linear"));
642                 }
643                 else if(boost::iequals(parameters()[0], L"MASTERVOLUME"))
644                 {
645                         if (parameters().size() == 1)
646                         {
647                                 auto volume = channel()->mixer().get_master_volume();
648                                 SetReplyString(L"201 MIXER OK\r\n"
649                                                 + boost::lexical_cast<std::wstring>(volume)+L"\r\n");
650                                 return true;
651                         }
652
653                         float master_volume = boost::lexical_cast<float>(parameters().at(1));
654                         channel()->mixer().set_master_volume(master_volume);
655                 }
656                 else if(boost::iequals(parameters()[0], L"BRIGHTNESS"))
657                 {
658                         if (parameters().size() == 1)
659                                 return reply_value([](const frame_transform& t) { return t.image_transform.brightness; });
660
661                         auto value = boost::lexical_cast<double>(parameters().at(1));
662                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
663                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
664                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
665                         {
666                                 transform.image_transform.brightness = value;
667                                 return transform;
668                         }, duration, tween));
669                 }
670                 else if(boost::iequals(parameters()[0], L"SATURATION"))
671                 {
672                         if (parameters().size() == 1)
673                                 return reply_value([](const frame_transform& t) { return t.image_transform.saturation; });
674
675                         auto value = boost::lexical_cast<double>(parameters().at(1));
676                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
677                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
678                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
679                         {
680                                 transform.image_transform.saturation = value;
681                                 return transform;
682                         }, duration, tween));   
683                 }
684                 else if (boost::iequals(parameters()[0], L"CONTRAST"))
685                 {
686                         if (parameters().size() == 1)
687                                 return reply_value([](const frame_transform& t) { return t.image_transform.contrast; });
688
689                         auto value = boost::lexical_cast<double>(parameters().at(1));
690                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
691                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
692                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
693                         {
694                                 transform.image_transform.contrast = value;
695                                 return transform;
696                         }, duration, tween));   
697                 }
698                 else if (boost::iequals(parameters()[0], L"ROTATION"))
699                 {
700                         static const double PI = 3.141592653589793;
701
702                         if (parameters().size() == 1)
703                                 return reply_value([](const frame_transform& t) { return t.image_transform.angle / PI * 180.0; });
704
705                         auto value = boost::lexical_cast<double>(parameters().at(1)) * PI / 180.0;
706                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
707                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
708                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
709                         {
710                                 transform.image_transform.angle = value;
711                                 return transform;
712                         }, duration, tween));
713                 }
714                 else if (boost::iequals(parameters()[0], L"LEVELS"))
715                 {
716                         if (parameters().size() == 1)
717                         {
718                                 auto levels = get_current_transform().image_transform.levels;
719                                 SetReplyString(L"201 MIXER OK\r\n"
720                                                 + boost::lexical_cast<std::wstring>(levels.min_input) + L" "
721                                                 + boost::lexical_cast<std::wstring>(levels.max_input) + L" "
722                                                 + boost::lexical_cast<std::wstring>(levels.gamma) + L" "
723                                                 + boost::lexical_cast<std::wstring>(levels.min_output) + L" "
724                                                 + boost::lexical_cast<std::wstring>(levels.max_output) + L"\r\n");
725                                 return true;
726                         }
727
728                         levels value;
729                         value.min_input  = boost::lexical_cast<double>(parameters().at(1));
730                         value.max_input  = boost::lexical_cast<double>(parameters().at(2));
731                         value.gamma              = boost::lexical_cast<double>(parameters().at(3));
732                         value.min_output = boost::lexical_cast<double>(parameters().at(4));
733                         value.max_output = boost::lexical_cast<double>(parameters().at(5));
734                         int duration = parameters().size() > 6 ? boost::lexical_cast<int>(parameters()[6]) : 0;
735                         std::wstring tween = parameters().size() > 7 ? parameters()[7] : L"linear";
736
737                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
738                         {
739                                 transform.image_transform.levels = value;
740                                 return transform;
741                         }, duration, tween));
742                 }
743                 else if(boost::iequals(parameters()[0], L"VOLUME"))
744                 {
745                         if (parameters().size() == 1)
746                                 return reply_value([](const frame_transform& t) { return t.audio_transform.volume; });
747
748                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
749                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
750                         double value = boost::lexical_cast<double>(parameters()[1]);
751
752                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
753                         {
754                                 transform.audio_transform.volume = value;
755                                 return transform;
756                         }, duration, tween));
757                 }
758                 else if(boost::iequals(parameters()[0], L"CLEAR"))
759                 {
760                         int layer = layer_index(std::numeric_limits<int>::max());
761
762                         if (layer == std::numeric_limits<int>::max())
763                         {
764                                 channel()->stage().clear_transforms();
765                         }
766                         else
767                         {
768                                 channel()->stage().clear_transforms(layer);
769                         }
770                 }
771                 else if(boost::iequals(parameters()[0], L"COMMIT"))
772                 {
773                         transforms = std::move(deferred_transforms[channel_index()]);
774                 }
775                 else
776                 {
777                         SetReplyString(L"404 MIXER ERROR\r\n");
778                         return false;
779                 }
780
781                 if(defer)
782                 {
783                         auto& defer_tranforms = deferred_transforms[channel_index()];
784                         defer_tranforms.insert(defer_tranforms.end(), transforms.begin(), transforms.end());
785                 }
786                 else
787                         channel()->stage().apply_transforms(transforms);
788         
789                 SetReplyString(L"202 MIXER OK\r\n");
790
791                 return true;
792         }
793         catch(file_not_found&)
794         {
795                 CASPAR_LOG_CURRENT_EXCEPTION();
796                 SetReplyString(L"404 MIXER ERROR\r\n");
797                 return false;
798         }
799         catch(...)
800         {
801                 CASPAR_LOG_CURRENT_EXCEPTION();
802                 SetReplyString(L"502 MIXER FAILED\r\n");
803                 return false;
804         }
805 }
806
807 bool SwapCommand::DoExecute()
808 {       
809         //Perform loading of the clip
810         try
811         {
812                 if(layer_index(-1) != -1)
813                 {
814                         std::vector<std::string> strs;
815                         boost::split(strs, parameters()[0], boost::is_any_of("-"));
816                         
817                         auto ch1 = channel();
818                         auto ch2 = channels().at(boost::lexical_cast<int>(strs.at(0))-1);
819
820                         int l1 = layer_index();
821                         int l2 = boost::lexical_cast<int>(strs.at(1));
822
823                         ch1->stage().swap_layer(l1, l2, ch2.channel->stage());
824                 }
825                 else
826                 {
827                         auto ch1 = channel();
828                         auto ch2 = channels().at(boost::lexical_cast<int>(parameters()[0])-1);
829                         ch1->stage().swap_layers(ch2.channel->stage());
830                 }
831                 
832                 SetReplyString(L"202 SWAP OK\r\n");
833
834                 return true;
835         }
836         catch(file_not_found&)
837         {
838                 CASPAR_LOG_CURRENT_EXCEPTION();
839                 SetReplyString(L"404 SWAP ERROR\r\n");
840                 return false;
841         }
842         catch(...)
843         {
844                 CASPAR_LOG_CURRENT_EXCEPTION();
845                 SetReplyString(L"502 SWAP FAILED\r\n");
846                 return false;
847         }
848 }
849
850 bool AddCommand::DoExecute()
851 {       
852         //Perform loading of the clip
853         try
854         {
855                 //create_consumer still expects all parameters to be uppercase
856                 for (auto& str : parameters())
857                 {
858                         boost::to_upper(str);
859                 }
860
861                 core::diagnostics::scoped_call_context save;
862                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
863
864                 auto consumer = create_consumer(parameters(), &channel()->stage());
865                 channel()->output().add(layer_index(consumer->index()), consumer);
866         
867                 SetReplyString(L"202 ADD OK\r\n");
868
869                 return true;
870         }
871         catch(file_not_found&)
872         {
873                 CASPAR_LOG_CURRENT_EXCEPTION();
874                 SetReplyString(L"404 ADD ERROR\r\n");
875                 return false;
876         }
877         catch(...)
878         {
879                 CASPAR_LOG_CURRENT_EXCEPTION();
880                 SetReplyString(L"502 ADD FAILED\r\n");
881                 return false;
882         }
883 }
884
885 bool RemoveCommand::DoExecute()
886 {       
887         //Perform loading of the clip
888         try
889         {
890                 auto index = layer_index(std::numeric_limits<int>::min());
891                 if(index == std::numeric_limits<int>::min())
892                 {
893                         //create_consumer still expects all parameters to be uppercase
894                         for (auto& str : parameters())
895                         {
896                                 boost::to_upper(str);
897                         }
898
899                         index = create_consumer(parameters(), &channel()->stage())->index();
900                 }
901
902                 channel()->output().remove(index);
903
904                 SetReplyString(L"202 REMOVE OK\r\n");
905
906                 return true;
907         }
908         catch(file_not_found&)
909         {
910                 CASPAR_LOG_CURRENT_EXCEPTION();
911                 SetReplyString(L"404 REMOVE ERROR\r\n");
912                 return false;
913         }
914         catch(...)
915         {
916                 CASPAR_LOG_CURRENT_EXCEPTION();
917                 SetReplyString(L"502 REMOVE FAILED\r\n");
918                 return false;
919         }
920 }
921
922 bool LoadCommand::DoExecute()
923 {       
924         //Perform loading of the clip
925         try
926         {
927                 core::diagnostics::scoped_call_context save;
928                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
929                 core::diagnostics::call_context::for_thread().layer = layer_index();
930                 auto pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
931                 channel()->stage().load(layer_index(), pFP, true);
932         
933                 SetReplyString(L"202 LOAD OK\r\n");
934
935                 return true;
936         }
937         catch(file_not_found&)
938         {
939                 CASPAR_LOG_CURRENT_EXCEPTION();
940                 SetReplyString(L"404 LOAD ERROR\r\n");
941                 return false;
942         }
943         catch(...)
944         {
945                 CASPAR_LOG_CURRENT_EXCEPTION();
946                 SetReplyString(L"502 LOAD FAILED\r\n");
947                 return false;
948         }
949 }
950
951 bool LoadbgCommand::DoExecute()
952 {
953         transition_info transitionInfo;
954         
955         // TRANSITION
956
957         std::wstring message;
958         for(size_t n = 0; n < parameters().size(); ++n)
959                 message += boost::to_upper_copy(parameters()[n]) + L" ";
960                 
961         static const boost::wregex expr(LR"(.*(?<TRANSITION>CUT|PUSH|SLIDE|WIPE|MIX)\s*(?<DURATION>\d+)\s*(?<TWEEN>(LINEAR)|(EASE[^\s]*))?\s*(?<DIRECTION>FROMLEFT|FROMRIGHT|LEFT|RIGHT)?.*)");
962         boost::wsmatch what;
963         if(boost::regex_match(message, what, expr))
964         {
965                 auto transition = what["TRANSITION"].str();
966                 transitionInfo.duration = boost::lexical_cast<size_t>(what["DURATION"].str());
967                 auto direction = what["DIRECTION"].matched ? what["DIRECTION"].str() : L"";
968                 auto tween = what["TWEEN"].matched ? what["TWEEN"].str() : L"";
969                 transitionInfo.tweener = tween;         
970
971                 if(transition == L"CUT")
972                         transitionInfo.type = transition_type::cut;
973                 else if(transition == L"MIX")
974                         transitionInfo.type = transition_type::mix;
975                 else if(transition == L"PUSH")
976                         transitionInfo.type = transition_type::push;
977                 else if(transition == L"SLIDE")
978                         transitionInfo.type = transition_type::slide;
979                 else if(transition == L"WIPE")
980                         transitionInfo.type = transition_type::wipe;
981                 
982                 if(direction == L"FROMLEFT")
983                         transitionInfo.direction = transition_direction::from_left;
984                 else if(direction == L"FROMRIGHT")
985                         transitionInfo.direction = transition_direction::from_right;
986                 else if(direction == L"LEFT")
987                         transitionInfo.direction = transition_direction::from_right;
988                 else if(direction == L"RIGHT")
989                         transitionInfo.direction = transition_direction::from_left;
990         }
991         
992         //Perform loading of the clip
993         try
994         {
995                 std::shared_ptr<core::frame_producer> pFP;
996                 
997                 static boost::wregex expr(LR"(\[(?<CHANNEL>\d+)\])", boost::regex::icase);
998                         
999                 core::diagnostics::scoped_call_context save;
1000                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
1001                 core::diagnostics::call_context::for_thread().layer = layer_index();
1002
1003                 boost::wsmatch what;
1004                 if(boost::regex_match(parameters().at(0), what, expr))
1005                 {
1006                         auto channel_index = boost::lexical_cast<int>(what["CHANNEL"].str());
1007                         pFP = reroute::create_producer(*channels().at(channel_index-1).channel); 
1008                 }
1009                 else
1010                 {
1011                         pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
1012                 }
1013                 
1014                 if(pFP == frame_producer::empty())
1015                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(parameters().size() > 0 ? parameters()[0] : L""));
1016
1017                 bool auto_play = contains_param(L"AUTO", parameters());
1018
1019                 auto pFP2 = create_transition_producer(channel()->video_format_desc().field_mode, spl::make_shared_ptr(pFP), transitionInfo);
1020                 if(auto_play)
1021                         channel()->stage().load(layer_index(), pFP2, false, transitionInfo.duration); // TODO: LOOP
1022                 else
1023                         channel()->stage().load(layer_index(), pFP2, false); // TODO: LOOP
1024         
1025                 
1026                 SetReplyString(L"202 LOADBG OK\r\n");
1027
1028                 return true;
1029         }
1030         catch(file_not_found&)
1031         {               
1032                 CASPAR_LOG(error) << L"File not found. No match found for parameters. Check syntax.";
1033                 SetReplyString(L"404 LOADBG ERROR\r\n");
1034                 return false;
1035         }
1036         catch(...)
1037         {
1038                 CASPAR_LOG_CURRENT_EXCEPTION();
1039                 SetReplyString(L"502 LOADBG FAILED\r\n");
1040                 return false;
1041         }
1042 }
1043
1044 bool PauseCommand::DoExecute()
1045 {
1046         try
1047         {
1048                 channel()->stage().pause(layer_index());
1049                 SetReplyString(L"202 PAUSE OK\r\n");
1050                 return true;
1051         }
1052         catch(...)
1053         {
1054                 SetReplyString(L"501 PAUSE FAILED\r\n");
1055         }
1056
1057         return false;
1058 }
1059
1060 bool PlayCommand::DoExecute()
1061 {
1062         try
1063         {
1064                 if(!parameters().empty())
1065                 {
1066                         LoadbgCommand lbg(*this);
1067
1068                         if(!lbg.Execute())
1069                                 throw std::exception();
1070                 }
1071
1072                 channel()->stage().play(layer_index());
1073                 
1074                 SetReplyString(L"202 PLAY OK\r\n");
1075                 return true;
1076         }
1077         catch(...)
1078         {
1079                 SetReplyString(L"501 PLAY FAILED\r\n");
1080         }
1081
1082         return false;
1083 }
1084
1085 bool StopCommand::DoExecute()
1086 {
1087         try
1088         {
1089                 channel()->stage().stop(layer_index());
1090                 SetReplyString(L"202 STOP OK\r\n");
1091                 return true;
1092         }
1093         catch(...)
1094         {
1095                 SetReplyString(L"501 STOP FAILED\r\n");
1096         }
1097
1098         return false;
1099 }
1100
1101 bool ClearCommand::DoExecute()
1102 {
1103         int index = layer_index(std::numeric_limits<int>::min());
1104         if(index != std::numeric_limits<int>::min())
1105                 channel()->stage().clear(index);
1106         else
1107                 channel()->stage().clear();
1108                 
1109         SetReplyString(L"202 CLEAR OK\r\n");
1110
1111         return true;
1112 }
1113
1114 bool PrintCommand::DoExecute()
1115 {
1116         channel()->output().add(create_consumer({ L"IMAGE" }, &channel()->stage()));
1117                 
1118         SetReplyString(L"202 PRINT OK\r\n");
1119
1120         return true;
1121 }
1122
1123 bool LogCommand::DoExecute()
1124 {
1125         if(boost::iequals(parameters().at(0), L"LEVEL"))
1126                 log::set_log_level(parameters().at(1));
1127
1128         SetReplyString(L"202 LOG OK\r\n");
1129
1130         return true;
1131 }
1132
1133 bool CGCommand::DoExecute()
1134 {
1135         try
1136         {
1137                 std::wstring command = boost::to_upper_copy(parameters()[0]);
1138                 if(command == L"ADD")
1139                         return DoExecuteAdd();
1140                 else if(command == L"PLAY")
1141                         return DoExecutePlay();
1142                 else if(command == L"STOP")
1143                         return DoExecuteStop();
1144                 else if(command == L"NEXT")
1145                         return DoExecuteNext();
1146                 else if(command == L"REMOVE")
1147                         return DoExecuteRemove();
1148                 else if(command == L"CLEAR")
1149                         return DoExecuteClear();
1150                 else if(command == L"UPDATE")
1151                         return DoExecuteUpdate();
1152                 else if(command == L"INVOKE")
1153                         return DoExecuteInvoke();
1154                 else if(command == L"INFO")
1155                         return DoExecuteInfo();
1156         }
1157         catch(...)
1158         {
1159                 CASPAR_LOG_CURRENT_EXCEPTION();
1160         }
1161
1162         SetReplyString(L"403 CG ERROR\r\n");
1163         return false;
1164 }
1165
1166 bool CGCommand::ValidateLayer(const std::wstring& layerstring) {
1167         int length = layerstring.length();
1168         for(int i = 0; i < length; ++i) {
1169                 if(!std::isdigit(layerstring[i])) {
1170                         return false;
1171                 }
1172         }
1173
1174         return true;
1175 }
1176
1177 bool CGCommand::DoExecuteAdd() {
1178         //CG 1 ADD 0 "template_folder/templatename" [STARTLABEL] 0/1 [DATA]
1179
1180         int layer = 0;                          //_parameters[1]
1181 //      std::wstring templateName;      //_parameters[2]
1182         std::wstring label;             //_parameters[3]
1183         bool bDoStart = false;          //_parameters[3] alt. _parameters[4]
1184 //      std::wstring data;                      //_parameters[4] alt. _parameters[5]
1185
1186         if(parameters().size() < 4) 
1187         {
1188                 SetReplyString(L"402 CG ERROR\r\n");
1189                 return false;
1190         }
1191         unsigned int dataIndex = 4;
1192
1193         if(!ValidateLayer(parameters()[1])) 
1194         {
1195                 SetReplyString(L"403 CG ERROR\r\n");
1196                 return false;
1197         }
1198
1199         layer = boost::lexical_cast<int>(parameters()[1]);
1200
1201         if(parameters()[3].length() > 1) 
1202         {       //read label
1203                 label = parameters()[3];
1204                 ++dataIndex;
1205
1206                 if(parameters().size() > 4 && parameters()[4].length() > 0)     //read play-on-load-flag
1207                         bDoStart = (parameters()[4][0]==L'1') ? true : false;
1208                 else 
1209                 {
1210                         SetReplyString(L"402 CG ERROR\r\n");
1211                         return false;
1212                 }
1213         }
1214         else if(parameters()[3].length() > 0) { //read play-on-load-flag
1215                 bDoStart = (parameters()[3][0]==L'1') ? true : false;
1216         }
1217         else 
1218         {
1219                 SetReplyString(L"403 CG ERROR\r\n");
1220                 return false;
1221         }
1222
1223         const wchar_t* pDataString = 0;
1224         std::wstring dataFromFile;
1225         if(parameters().size() > dataIndex) 
1226         {       //read data
1227                 const std::wstring& dataString = parameters()[dataIndex];
1228
1229                 if (dataString.at(0) == L'<' || dataString.at(0) == L'{') //the data is XML or Json
1230                         pDataString = dataString.c_str();
1231                 else 
1232                 {
1233                         //The data is not an XML-string, it must be a filename
1234                         std::wstring filename = env::data_folder();
1235                         filename.append(dataString);
1236                         filename.append(L".ftd");
1237
1238                         auto found_file = find_case_insensitive(filename);
1239
1240                         if (found_file)
1241                         {
1242                                 dataFromFile = read_file(boost::filesystem::path(*found_file));
1243                                 pDataString = dataFromFile.c_str();
1244                         }
1245                 }
1246         }
1247
1248         auto filename = parameters()[2];
1249         auto proxy = cg_registry_->get_or_create_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER), filename);
1250
1251         if (proxy == core::cg_proxy::empty())
1252         {
1253                 CASPAR_LOG(warning) << "Could not find template " << parameters()[2];
1254                 SetReplyString(L"404 CG ERROR\r\n");
1255         }
1256         else
1257         {
1258                 proxy->add(layer, filename, bDoStart, label, (pDataString != 0) ? pDataString : L"");
1259         }
1260
1261         return true;
1262 }
1263
1264 bool CGCommand::DoExecutePlay()
1265 {
1266         if(parameters().size() > 1)
1267         {
1268                 if(!ValidateLayer(parameters()[1])) 
1269                 {
1270                         SetReplyString(L"403 CG ERROR\r\n");
1271                         return false;
1272                 }
1273                 int layer = boost::lexical_cast<int>(parameters()[1]);
1274                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->play(layer);
1275         }
1276         else
1277         {
1278                 SetReplyString(L"402 CG ERROR\r\n");
1279                 return true;
1280         }
1281
1282         SetReplyString(L"202 CG OK\r\n");
1283         return true;
1284 }
1285
1286 bool CGCommand::DoExecuteStop() 
1287 {
1288         if(parameters().size() > 1)
1289         {
1290                 if(!ValidateLayer(parameters()[1])) 
1291                 {
1292                         SetReplyString(L"403 CG ERROR\r\n");
1293                         return false;
1294                 }
1295                 int layer = boost::lexical_cast<int>(parameters()[1]);
1296                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->stop(layer, 0);
1297         }
1298         else 
1299         {
1300                 SetReplyString(L"402 CG ERROR\r\n");
1301                 return true;
1302         }
1303
1304         SetReplyString(L"202 CG OK\r\n");
1305         return true;
1306 }
1307
1308 bool CGCommand::DoExecuteNext()
1309 {
1310         if(parameters().size() > 1) 
1311         {
1312                 if(!ValidateLayer(parameters()[1])) 
1313                 {
1314                         SetReplyString(L"403 CG ERROR\r\n");
1315                         return false;
1316                 }
1317
1318                 int layer = boost::lexical_cast<int>(parameters()[1]);
1319                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->next(layer);
1320         }
1321         else 
1322         {
1323                 SetReplyString(L"402 CG ERROR\r\n");
1324                 return true;
1325         }
1326
1327         SetReplyString(L"202 CG OK\r\n");
1328         return true;
1329 }
1330
1331 bool CGCommand::DoExecuteRemove() 
1332 {
1333         if(parameters().size() > 1) 
1334         {
1335                 if(!ValidateLayer(parameters()[1])) 
1336                 {
1337                         SetReplyString(L"403 CG ERROR\r\n");
1338                         return false;
1339                 }
1340
1341                 int layer = boost::lexical_cast<int>(parameters()[1]);
1342                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->remove(layer);
1343         }
1344         else 
1345         {
1346                 SetReplyString(L"402 CG ERROR\r\n");
1347                 return true;
1348         }
1349
1350         SetReplyString(L"202 CG OK\r\n");
1351         return true;
1352 }
1353
1354 bool CGCommand::DoExecuteClear() 
1355 {
1356         channel()->stage().clear(layer_index(core::cg_proxy::DEFAULT_LAYER));
1357         SetReplyString(L"202 CG OK\r\n");
1358         return true;
1359 }
1360
1361 bool CGCommand::DoExecuteUpdate() 
1362 {
1363         try
1364         {
1365                 if(!ValidateLayer(parameters().at(1)))
1366                 {
1367                         SetReplyString(L"403 CG ERROR\r\n");
1368                         return false;
1369                 }
1370                                                 
1371                 std::wstring dataString = parameters().at(2);                           
1372                 if (dataString.at(0) != L'<' && dataString.at(0) != L'{')
1373                 {
1374                         //The data is not XML or Json, it must be a filename
1375                         std::wstring filename = env::data_folder();
1376                         filename.append(dataString);
1377                         filename.append(L".ftd");
1378
1379                         dataString = read_file(boost::filesystem::path(filename));
1380                 }               
1381
1382                 int layer = boost::lexical_cast<int>(parameters()[1]);
1383                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->update(layer, dataString);
1384         }
1385         catch(...)
1386         {
1387                 SetReplyString(L"402 CG ERROR\r\n");
1388                 return true;
1389         }
1390
1391         SetReplyString(L"202 CG OK\r\n");
1392         return true;
1393 }
1394
1395 bool CGCommand::DoExecuteInvoke() 
1396 {
1397         std::wstringstream replyString;
1398         replyString << L"201 CG OK\r\n";
1399
1400         if(parameters().size() > 2)
1401         {
1402                 if(!ValidateLayer(parameters()[1]))
1403                 {
1404                         SetReplyString(L"403 CG ERROR\r\n");
1405                         return false;
1406                 }
1407                 int layer = boost::lexical_cast<int>(parameters()[1]);
1408                 auto result = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->invoke(layer, parameters()[2]);
1409                 replyString << result << L"\r\n";
1410         }
1411         else 
1412         {
1413                 SetReplyString(L"402 CG ERROR\r\n");
1414                 return true;
1415         }
1416         
1417         SetReplyString(replyString.str());
1418         return true;
1419 }
1420
1421 bool CGCommand::DoExecuteInfo() 
1422 {
1423         std::wstringstream replyString;
1424         replyString << L"201 CG OK\r\n";
1425
1426         if(parameters().size() > 1)
1427         {
1428                 if(!ValidateLayer(parameters()[1]))
1429                 {
1430                         SetReplyString(L"403 CG ERROR\r\n");
1431                         return false;
1432                 }
1433
1434                 int layer = boost::lexical_cast<int>(parameters()[1]);
1435                 auto desc = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->description(layer);
1436                 
1437                 replyString << desc << L"\r\n";
1438         }
1439         else 
1440         {
1441                 auto info = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->template_host_info();
1442                 replyString << info << L"\r\n";
1443         }       
1444
1445         SetReplyString(replyString.str());
1446         return true;
1447 }
1448
1449 bool DataCommand::DoExecute()
1450 {
1451         std::wstring command = boost::to_upper_copy(parameters()[0]);
1452         if(command == L"STORE")
1453                 return DoExecuteStore();
1454         else if(command == L"RETRIEVE")
1455                 return DoExecuteRetrieve();
1456         else if(command == L"REMOVE")
1457                 return DoExecuteRemove();
1458         else if(command == L"LIST")
1459                 return DoExecuteList();
1460
1461         SetReplyString(L"403 DATA ERROR\r\n");
1462         return false;
1463 }
1464
1465 bool DataCommand::DoExecuteStore() 
1466 {
1467         if(parameters().size() < 3) 
1468         {
1469                 SetReplyString(L"402 DATA STORE ERROR\r\n");
1470                 return false;
1471         }
1472
1473         std::wstring filename = env::data_folder();
1474         filename.append(parameters()[1]);
1475         filename.append(L".ftd");
1476
1477         auto data_path = boost::filesystem::path(filename).parent_path().wstring();
1478         auto found_data_path = find_case_insensitive(data_path);
1479
1480         if (found_data_path)
1481                 data_path = *found_data_path;
1482
1483         if(!boost::filesystem::exists(data_path))
1484                 boost::filesystem::create_directories(data_path);
1485
1486         auto found_filename = find_case_insensitive(filename);
1487
1488         if (found_filename)
1489                 filename = *found_filename; // Overwrite case insensitive.
1490
1491         boost::filesystem::wofstream datafile(filename);
1492         if(!datafile) 
1493         {
1494                 SetReplyString(L"501 DATA STORE FAILED\r\n");
1495                 return false;
1496         }
1497
1498         datafile << static_cast<wchar_t>(65279); // UTF-8 BOM character
1499         datafile << parameters()[2] << std::flush;
1500         datafile.close();
1501
1502         std::wstring replyString = L"202 DATA STORE OK\r\n";
1503         SetReplyString(replyString);
1504         return true;
1505 }
1506
1507 bool DataCommand::DoExecuteRetrieve() 
1508 {
1509         if(parameters().size() < 2) 
1510         {
1511                 SetReplyString(L"402 DATA RETRIEVE ERROR\r\n");
1512                 return false;
1513         }
1514
1515         std::wstring filename = env::data_folder();
1516         filename.append(parameters()[1]);
1517         filename.append(L".ftd");
1518
1519         std::wstring file_contents;
1520
1521         auto found_file = find_case_insensitive(filename);
1522
1523         if (found_file)
1524                 file_contents = read_file(boost::filesystem::path(*found_file));
1525
1526         if (file_contents.empty()) 
1527         {
1528                 SetReplyString(L"404 DATA RETRIEVE ERROR\r\n");
1529                 return false;
1530         }
1531
1532         std::wstringstream reply(L"201 DATA RETRIEVE OK\r\n");
1533
1534         std::wstringstream file_contents_stream(file_contents);
1535         std::wstring line;
1536         
1537         bool firstLine = true;
1538         while(std::getline(file_contents_stream, line))
1539         {
1540                 if(firstLine)
1541                         firstLine = false;
1542                 else
1543                         reply << "\n";
1544
1545                 reply << line;
1546         }
1547
1548         reply << "\r\n";
1549         SetReplyString(reply.str());
1550         return true;
1551 }
1552
1553 bool DataCommand::DoExecuteRemove()
1554
1555         if (parameters().size() < 2)
1556         {
1557                 SetReplyString(L"402 DATA REMOVE ERROR\r\n");
1558                 return false;
1559         }
1560
1561         std::wstring filename = env::data_folder();
1562         filename.append(parameters()[1]);
1563         filename.append(L".ftd");
1564
1565         if (!boost::filesystem::exists(filename))
1566         {
1567                 SetReplyString(L"404 DATA REMOVE ERROR\r\n");
1568                 return false;
1569         }
1570
1571         if (!boost::filesystem::remove(filename))
1572         {
1573                 SetReplyString(L"403 DATA REMOVE ERROR\r\n");
1574                 return false;
1575         }
1576
1577         SetReplyString(L"201 DATA REMOVE OK\r\n");
1578
1579         return true;
1580 }
1581
1582 bool DataCommand::DoExecuteList() 
1583 {
1584         std::wstringstream replyString;
1585         replyString << L"200 DATA LIST OK\r\n";
1586
1587         for (boost::filesystem::recursive_directory_iterator itr(env::data_folder()), end; itr != end; ++itr)
1588         {                       
1589                 if(boost::filesystem::is_regular_file(itr->path()))
1590                 {
1591                         if(!boost::iequals(itr->path().extension().wstring(), L".ftd"))
1592                                 continue;
1593                         
1594                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::data_folder().size()-1, itr->path().wstring().size()));
1595                         
1596                         auto str = relativePath.replace_extension(L"").generic_wstring();
1597                         if(str[0] == L'\\' || str[0] == L'/')
1598                                 str = std::wstring(str.begin() + 1, str.end());
1599
1600                         replyString << str << L"\r\n";
1601                 }
1602         }
1603         
1604         replyString << L"\r\n";
1605
1606         SetReplyString(boost::to_upper_copy(replyString.str()));
1607         return true;
1608 }
1609
1610 bool CinfCommand::DoExecute()
1611 {
1612         std::wstringstream replyString;
1613         
1614         try
1615         {
1616                 std::wstring info;
1617                 for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end && info.empty(); ++itr)
1618                 {
1619                         auto path = itr->path();
1620                         auto file = path.replace_extension(L"").filename().wstring();
1621                         if(boost::iequals(file, parameters().at(0)))
1622                                 info += MediaInfo(itr->path(), system_info_repo_) + L"\r\n";
1623                 }
1624
1625                 if(info.empty())
1626                 {
1627                         SetReplyString(L"404 CINF ERROR\r\n");
1628                         return false;
1629                 }
1630                 replyString << L"200 CINF OK\r\n";
1631                 replyString << info << "\r\n";
1632         }
1633         catch(...)
1634         {
1635                 CASPAR_LOG_CURRENT_EXCEPTION();
1636                 SetReplyString(L"404 CINF ERROR\r\n");
1637                 return false;
1638         }
1639         
1640         SetReplyString(replyString.str());
1641         return true;
1642 }
1643
1644 void GenerateChannelInfo(int index, const spl::shared_ptr<core::video_channel>& pChannel, std::wstringstream& replyString)
1645 {
1646         replyString << index+1 << L" " << pChannel->video_format_desc().name << L" PLAYING\r\n";
1647 }
1648
1649 bool InfoCommand::DoExecute()
1650 {
1651         std::wstringstream replyString;
1652         
1653         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
1654
1655         try
1656         {
1657                 if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"TEMPLATE"))
1658                 {               
1659                         replyString << L"201 INFO TEMPLATE OK\r\n";
1660
1661                         auto filename = parameters().at(1);
1662                                                 
1663                         std::wstringstream str;
1664                         str << u16(cg_registry_->read_meta_info(filename));
1665                         boost::property_tree::wptree info;
1666                         boost::property_tree::xml_parser::read_xml(str, info, boost::property_tree::xml_parser::trim_whitespace | boost::property_tree::xml_parser::no_comments);
1667
1668                         boost::property_tree::xml_parser::write_xml(replyString, info, w);
1669                 }
1670                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"CONFIG"))
1671                 {               
1672                         replyString << L"201 INFO CONFIG OK\r\n";
1673
1674                         boost::property_tree::write_xml(replyString, caspar::env::properties(), w);
1675                 }
1676                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"PATHS"))
1677                 {
1678                         replyString << L"201 INFO PATHS OK\r\n";
1679
1680                         boost::property_tree::wptree info;
1681                         info.add_child(L"paths", caspar::env::properties().get_child(L"configuration.paths"));
1682                         info.add(L"paths.initial-path", boost::filesystem::initial_path().wstring() + L"/");
1683
1684                         boost::property_tree::write_xml(replyString, info, w);
1685                 }
1686                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SYSTEM"))
1687                 {
1688                         replyString << L"201 INFO SYSTEM OK\r\n";
1689                         
1690                         boost::property_tree::wptree info;
1691                         
1692                         info.add(L"system.name",                                        caspar::system_product_name());
1693                         info.add(L"system.os.description",                      caspar::os_description());
1694                         info.add(L"system.cpu",                                         caspar::cpu_info());
1695
1696                         system_info_repo_->fill_information(info);
1697                                                 
1698                         boost::property_tree::write_xml(replyString, info, w);
1699                 }
1700                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SERVER"))
1701                 {
1702                         replyString << L"201 INFO SERVER OK\r\n";
1703                         
1704                         boost::property_tree::wptree info;
1705
1706                         int index = 0;
1707                         for (auto& channel : channels())
1708                                 info.add_child(L"channels.channel", channel.channel->info())
1709                                         .add(L"index", ++index);
1710                         
1711                         boost::property_tree::write_xml(replyString, info, w);
1712                 }
1713                 else // channel
1714                 {                       
1715                         if(parameters().size() >= 1)
1716                         {
1717                                 replyString << L"201 INFO OK\r\n";
1718                                 boost::property_tree::wptree info;
1719
1720                                 std::vector<std::wstring> split;
1721                                 boost::split(split, parameters()[0], boost::is_any_of("-"));
1722                                         
1723                                 int layer = std::numeric_limits<int>::min();
1724                                 int channel = boost::lexical_cast<int>(split[0]) - 1;
1725
1726                                 if(split.size() > 1)
1727                                         layer = boost::lexical_cast<int>(split[1]);
1728                                 
1729                                 if(layer == std::numeric_limits<int>::min())
1730                                 {       
1731                                         info.add_child(L"channel", channels().at(channel).channel->info())
1732                                                         .add(L"index", channel);
1733                                 }
1734                                 else
1735                                 {
1736                                         if(parameters().size() >= 2)
1737                                         {
1738                                                 if(boost::iequals(parameters()[1], L"B"))
1739                                                         info.add_child(L"producer", channels().at(channel).channel->stage().background(layer).get()->info());
1740                                                 else
1741                                                         info.add_child(L"producer", channels().at(channel).channel->stage().foreground(layer).get()->info());
1742                                         }
1743                                         else
1744                                         {
1745                                                 info.add_child(L"layer", channels().at(channel).channel->stage().info(layer).get())
1746                                                         .add(L"index", layer);
1747                                         }
1748                                 }
1749                                 boost::property_tree::xml_parser::write_xml(replyString, info, w);
1750                         }
1751                         else
1752                         {
1753                                 // This is needed for backwards compatibility with old clients
1754                                 replyString << L"200 INFO OK\r\n";
1755                                 for(size_t n = 0; n < channels().size(); ++n)
1756                                         GenerateChannelInfo(n, channels()[n].channel, replyString);
1757                         }
1758
1759                 }
1760         }
1761         catch(...)
1762         {
1763                 CASPAR_LOG_CURRENT_EXCEPTION();
1764                 SetReplyString(L"403 INFO ERROR\r\n");
1765                 return false;
1766         }
1767
1768         replyString << L"\r\n";
1769         SetReplyString(replyString.str());
1770         return true;
1771 }
1772
1773 bool ClsCommand::DoExecute()
1774 {
1775         try
1776         {
1777                 std::wstringstream replyString;
1778                 replyString << L"200 CLS OK\r\n";
1779                 replyString << ListMedia(system_info_repo_);
1780                 replyString << L"\r\n";
1781                 SetReplyString(boost::to_upper_copy(replyString.str()));
1782         }
1783         catch(...)
1784         {
1785                 CASPAR_LOG_CURRENT_EXCEPTION();
1786                 SetReplyString(L"501 CLS FAILED\r\n");
1787                 return false;
1788         }
1789
1790         return true;
1791 }
1792
1793 bool TlsCommand::DoExecute()
1794 {
1795         try
1796         {
1797                 std::wstringstream replyString;
1798                 replyString << L"200 TLS OK\r\n";
1799
1800                 replyString << ListTemplates(cg_registry_);
1801                 replyString << L"\r\n";
1802
1803                 SetReplyString(replyString.str());
1804         }
1805         catch(...)
1806         {
1807                 CASPAR_LOG_CURRENT_EXCEPTION();
1808                 SetReplyString(L"501 TLS FAILED\r\n");
1809                 return false;
1810         }
1811         return true;
1812 }
1813
1814 bool VersionCommand::DoExecute()
1815 {
1816         std::wstring replyString = L"201 VERSION OK\r\n" + env::version() + L"\r\n";
1817
1818         if (parameters().size() > 0 && !boost::iequals(parameters()[0], L"SERVER"))
1819         {
1820                 auto version = system_info_repo_->get_version(parameters().at(0));
1821
1822                 if (version.empty())
1823                         replyString = L"403 VERSION ERROR\r\n";
1824                 else
1825                         replyString = L"201 VERSION OK\r\n" + version + L"\r\n";
1826         }
1827
1828         SetReplyString(replyString);
1829         return true;
1830 }
1831
1832 bool ByeCommand::DoExecute()
1833 {
1834         client()->disconnect();
1835         return true;
1836 }
1837
1838 bool SetCommand::DoExecute()
1839 {
1840         try
1841         {
1842                 std::wstring name = boost::to_upper_copy(parameters()[0]);
1843                 std::wstring value = boost::to_upper_copy(parameters()[1]);
1844
1845                 if(name == L"MODE")
1846                 {
1847                         auto format_desc = core::video_format_desc(value);
1848                         if(format_desc.format != core::video_format::invalid)
1849                         {
1850                                 channel()->video_format_desc(format_desc);
1851                                 SetReplyString(L"202 SET MODE OK\r\n");
1852                         }
1853                         else
1854                                 SetReplyString(L"501 SET MODE FAILED\r\n");
1855                 }
1856                 else
1857                 {
1858                         this->SetReplyString(L"403 SET ERROR\r\n");
1859                 }
1860         }
1861         catch(...)
1862         {
1863                 CASPAR_LOG_CURRENT_EXCEPTION();
1864                 SetReplyString(L"501 SET FAILED\r\n");
1865                 return false;
1866         }
1867
1868         return true;
1869 }
1870
1871 bool LockCommand::DoExecute()
1872 {
1873         try
1874         {
1875                 auto it = parameters().begin();
1876
1877                 std::shared_ptr<caspar::IO::lock_container> lock;
1878                 try
1879                 {
1880                         int channel_index = boost::lexical_cast<int>(*it) - 1;
1881                         lock = channels().at(channel_index).lock;
1882                 }
1883                 catch(const boost::bad_lexical_cast&) {}
1884                 catch(...)
1885                 {
1886                         SetReplyString(L"401 LOCK ERROR\r\n");
1887                         return false;
1888                 }
1889
1890                 if(lock)
1891                         ++it;
1892
1893                 if(it == parameters().end())    //too few parameters
1894                 {
1895                         SetReplyString(L"402 LOCK ERROR\r\n");
1896                         return false;
1897                 }
1898
1899                 std::wstring command = boost::to_upper_copy(*it);
1900                 if(command == L"ACQUIRE")
1901                 {
1902                         ++it;
1903                         if(it == parameters().end())    //too few parameters
1904                         {
1905                                 SetReplyString(L"402 LOCK ACQUIRE ERROR\r\n");
1906                                 return false;
1907                         }
1908                         std::wstring lock_phrase = (*it);
1909
1910                         //TODO: read options
1911
1912                         if(lock)
1913                         {
1914                                 //just lock one channel
1915                                 if(!lock->try_lock(lock_phrase, client()))
1916                                 {
1917                                         SetReplyString(L"503 LOCK ACQUIRE FAILED\r\n");
1918                                         return false;
1919                                 }
1920                         }
1921                         else
1922                         {
1923                                 //TODO: lock all channels
1924                                 CASPAR_THROW_EXCEPTION(not_implemented());
1925                         }
1926                         SetReplyString(L"202 LOCK ACQUIRE OK\r\n");
1927
1928                 }
1929                 else if(command == L"RELEASE")
1930                 {
1931                         if(lock)
1932                         {
1933                                 lock->release_lock(client());
1934                         }
1935                         else
1936                         {
1937                                 //TODO: release all channels
1938                                 CASPAR_THROW_EXCEPTION(not_implemented());
1939                         }
1940                         SetReplyString(L"202 LOCK RELEASE OK\r\n");
1941                 }
1942                 else if(command == L"CLEAR")
1943                 {
1944                         std::wstring override_phrase = env::properties().get(L"configuration.lock-clear-phrase", L"");
1945                         std::wstring client_override_phrase;
1946                         if(!override_phrase.empty())
1947                         {
1948                                 ++it;
1949                                 if(it == parameters().end())
1950                                 {
1951                                         SetReplyString(L"402 LOCK CLEAR ERROR\r\n");
1952                                         return false;
1953                                 }
1954                                 client_override_phrase = (*it);
1955                         }
1956
1957                         if(lock)
1958                         {
1959                                 //just clear one channel
1960                                 if(client_override_phrase != override_phrase)
1961                                 {
1962                                         SetReplyString(L"503 LOCK CLEAR FAILED\r\n");
1963                                         return false;
1964                                 }
1965                                 
1966                                 lock->clear_locks();
1967                         }
1968                         else
1969                         {
1970                                 //TODO: clear all channels
1971                                 CASPAR_THROW_EXCEPTION(not_implemented());
1972                         }
1973
1974                         SetReplyString(L"202 LOCK CLEAR OK\r\n");
1975                 }
1976                 else
1977                 {
1978                         SetReplyString(L"403 LOCK ERROR\r\n");
1979                         return false;
1980                 }
1981         }
1982         catch(not_implemented&)
1983         {
1984                 SetReplyString(L"600 LOCK FAILED\r\n");
1985                 return false;
1986         }
1987         catch(...)
1988         {
1989                 CASPAR_LOG_CURRENT_EXCEPTION();
1990                 SetReplyString(L"501 LOCK FAILED\r\n");
1991                 return false;
1992         }
1993
1994         return true;
1995 }
1996
1997 bool ThumbnailCommand::DoExecute()
1998 {
1999         std::wstring command = boost::to_upper_copy(parameters()[0]);
2000
2001         if (command == L"RETRIEVE")
2002                 return DoExecuteRetrieve();
2003         else if (command == L"LIST")
2004                 return DoExecuteList();
2005         else if (command == L"GENERATE")
2006                 return DoExecuteGenerate();
2007         else if (command == L"GENERATE_ALL")
2008                 return DoExecuteGenerateAll();
2009
2010         SetReplyString(L"403 THUMBNAIL ERROR\r\n");
2011         return false;
2012 }
2013
2014 bool ThumbnailCommand::DoExecuteRetrieve() 
2015 {
2016         if(parameters().size() < 2) 
2017         {
2018                 SetReplyString(L"402 THUMBNAIL RETRIEVE ERROR\r\n");
2019                 return false;
2020         }
2021
2022         std::wstring filename = env::thumbnails_folder();
2023         filename.append(parameters()[1]);
2024         filename.append(L".png");
2025
2026         std::wstring file_contents;
2027
2028         auto found_file = find_case_insensitive(filename);
2029
2030         if (found_file)
2031                 file_contents = read_file_base64(boost::filesystem::path(*found_file));
2032
2033         if (file_contents.empty())
2034         {
2035                 SetReplyString(L"404 THUMBNAIL RETRIEVE ERROR\r\n");
2036                 return false;
2037         }
2038
2039         std::wstringstream reply;
2040
2041         reply << L"201 THUMBNAIL RETRIEVE OK\r\n";
2042         reply << file_contents;
2043         reply << L"\r\n";
2044         SetReplyString(reply.str());
2045         return true;
2046 }
2047
2048 bool ThumbnailCommand::DoExecuteList()
2049 {
2050         std::wstringstream replyString;
2051         replyString << L"200 THUMBNAIL LIST OK\r\n";
2052
2053         for (boost::filesystem::recursive_directory_iterator itr(env::thumbnails_folder()), end; itr != end; ++itr)
2054         {      
2055                 if(boost::filesystem::is_regular_file(itr->path()))
2056                 {
2057                         if(!boost::iequals(itr->path().extension().wstring(), L".png"))
2058                                 continue;
2059
2060                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::thumbnails_folder().size()-1, itr->path().wstring().size()));
2061
2062                         auto str = relativePath.replace_extension(L"").generic_wstring();
2063                         if(str[0] == '\\' || str[0] == '/')
2064                                 str = std::wstring(str.begin() + 1, str.end());
2065
2066                         auto mtime = boost::filesystem::last_write_time(itr->path());
2067                         auto mtime_readable = boost::posix_time::to_iso_wstring(boost::posix_time::from_time_t(mtime));
2068                         auto file_size = boost::filesystem::file_size(itr->path());
2069
2070                         replyString << L"\"" << str << L"\" " << mtime_readable << L" " << file_size << L"\r\n";
2071                 }
2072         }
2073
2074         replyString << L"\r\n";
2075
2076         SetReplyString(boost::to_upper_copy(replyString.str()));
2077         return true;
2078 }
2079
2080 bool ThumbnailCommand::DoExecuteGenerate()
2081 {
2082         if (parameters().size() < 2) 
2083         {
2084                 SetReplyString(L"402 THUMBNAIL GENERATE ERROR\r\n");
2085                 return false;
2086         }
2087
2088         if (thumb_gen_)
2089         {
2090                 thumb_gen_->generate(parameters()[1]);
2091                 SetReplyString(L"202 THUMBNAIL GENERATE OK\r\n");
2092                 return true;
2093         }
2094         else
2095         {
2096                 SetReplyString(L"500 THUMBNAIL GENERATE ERROR\r\n");
2097                 return false;
2098         }
2099 }
2100
2101 bool ThumbnailCommand::DoExecuteGenerateAll()
2102 {
2103         if (thumb_gen_)
2104         {
2105                 thumb_gen_->generate_all();
2106                 SetReplyString(L"202 THUMBNAIL GENERATE_ALL OK\r\n");
2107                 return true;
2108         }
2109         else
2110         {
2111                 SetReplyString(L"500 THUMBNAIL GENERATE_ALL ERROR\r\n");
2112                 return false;
2113         }
2114 }
2115
2116 bool KillCommand::DoExecute()
2117 {
2118         shutdown_server_now_->set_value(false); //false for not attempting to restart
2119         SetReplyString(L"202 KILL OK\r\n");
2120         return true;
2121 }
2122
2123 bool RestartCommand::DoExecute()
2124 {
2125         shutdown_server_now_->set_value(true);  //true for attempting to restart
2126         SetReplyString(L"202 RESTART OK\r\n");
2127         return true;
2128 }
2129
2130 }       //namespace amcp
2131 }}      //namespace caspar