]> git.sesse.net Git - casparcg/blob - protocol/amcp/AMCPCommandsImpl.cpp
* Merged streaming_consumer from 2.0
[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"CHROMA"))
644                 {
645                         if (parameters().size() == 1)
646                         {
647                                 auto chroma = get_current_transform().image_transform.chroma;
648                                 SetReplyString(
649                                         L"201 MIXER OK\r\n"
650                                         + core::get_chroma_mode(chroma.key) + L" "
651                                         + boost::lexical_cast<std::wstring>(chroma.threshold) + L" "
652                                         + boost::lexical_cast<std::wstring>(chroma.softness) + L" "
653                                         + boost::lexical_cast<std::wstring>(chroma.spill) + L"\r\n");
654                                 return true;
655                         }
656
657                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters().at(5)) : 0;
658                         std::wstring tween = parameters().size() > 6 ? parameters().at(6) : L"linear";
659
660                         core::chroma chroma;
661                         chroma.key                      = get_chroma_mode(parameters().at(1));
662                         chroma.threshold        = boost::lexical_cast<double>(parameters().at(2));
663                         chroma.softness         = boost::lexical_cast<double>(parameters().at(3));
664                         chroma.spill            = parameters().size() > 4 ? boost::lexical_cast<double>(parameters().at(4)) : 0.0;
665                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
666                         {
667                                 transform.image_transform.chroma = chroma;
668                                 return transform;
669                         }, duration, tween));
670                 }
671                 else if (boost::iequals(parameters()[0], L"MASTERVOLUME"))
672                 {
673                         if (parameters().size() == 1)
674                         {
675                                 auto volume = channel()->mixer().get_master_volume();
676                                 SetReplyString(L"201 MIXER OK\r\n"
677                                                 + boost::lexical_cast<std::wstring>(volume)+L"\r\n");
678                                 return true;
679                         }
680
681                         float master_volume = boost::lexical_cast<float>(parameters().at(1));
682                         channel()->mixer().set_master_volume(master_volume);
683                 }
684                 else if(boost::iequals(parameters()[0], L"BRIGHTNESS"))
685                 {
686                         if (parameters().size() == 1)
687                                 return reply_value([](const frame_transform& t) { return t.image_transform.brightness; });
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.brightness = value;
695                                 return transform;
696                         }, duration, tween));
697                 }
698                 else if(boost::iequals(parameters()[0], L"SATURATION"))
699                 {
700                         if (parameters().size() == 1)
701                                 return reply_value([](const frame_transform& t) { return t.image_transform.saturation; });
702
703                         auto value = boost::lexical_cast<double>(parameters().at(1));
704                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
705                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
706                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
707                         {
708                                 transform.image_transform.saturation = value;
709                                 return transform;
710                         }, duration, tween));   
711                 }
712                 else if (boost::iequals(parameters()[0], L"CONTRAST"))
713                 {
714                         if (parameters().size() == 1)
715                                 return reply_value([](const frame_transform& t) { return t.image_transform.contrast; });
716
717                         auto value = boost::lexical_cast<double>(parameters().at(1));
718                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
719                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
720                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
721                         {
722                                 transform.image_transform.contrast = value;
723                                 return transform;
724                         }, duration, tween));   
725                 }
726                 else if (boost::iequals(parameters()[0], L"ROTATION"))
727                 {
728                         static const double PI = 3.141592653589793;
729
730                         if (parameters().size() == 1)
731                                 return reply_value([](const frame_transform& t) { return t.image_transform.angle / PI * 180.0; });
732
733                         auto value = boost::lexical_cast<double>(parameters().at(1)) * PI / 180.0;
734                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
735                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
736                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
737                         {
738                                 transform.image_transform.angle = value;
739                                 return transform;
740                         }, duration, tween));
741                 }
742                 else if (boost::iequals(parameters()[0], L"LEVELS"))
743                 {
744                         if (parameters().size() == 1)
745                         {
746                                 auto levels = get_current_transform().image_transform.levels;
747                                 SetReplyString(L"201 MIXER OK\r\n"
748                                                 + boost::lexical_cast<std::wstring>(levels.min_input) + L" "
749                                                 + boost::lexical_cast<std::wstring>(levels.max_input) + L" "
750                                                 + boost::lexical_cast<std::wstring>(levels.gamma) + L" "
751                                                 + boost::lexical_cast<std::wstring>(levels.min_output) + L" "
752                                                 + boost::lexical_cast<std::wstring>(levels.max_output) + L"\r\n");
753                                 return true;
754                         }
755
756                         levels value;
757                         value.min_input  = boost::lexical_cast<double>(parameters().at(1));
758                         value.max_input  = boost::lexical_cast<double>(parameters().at(2));
759                         value.gamma              = boost::lexical_cast<double>(parameters().at(3));
760                         value.min_output = boost::lexical_cast<double>(parameters().at(4));
761                         value.max_output = boost::lexical_cast<double>(parameters().at(5));
762                         int duration = parameters().size() > 6 ? boost::lexical_cast<int>(parameters()[6]) : 0;
763                         std::wstring tween = parameters().size() > 7 ? parameters()[7] : L"linear";
764
765                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
766                         {
767                                 transform.image_transform.levels = value;
768                                 return transform;
769                         }, duration, tween));
770                 }
771                 else if(boost::iequals(parameters()[0], L"VOLUME"))
772                 {
773                         if (parameters().size() == 1)
774                                 return reply_value([](const frame_transform& t) { return t.audio_transform.volume; });
775
776                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
777                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
778                         double value = boost::lexical_cast<double>(parameters()[1]);
779
780                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
781                         {
782                                 transform.audio_transform.volume = value;
783                                 return transform;
784                         }, duration, tween));
785                 }
786                 else if(boost::iequals(parameters()[0], L"CLEAR"))
787                 {
788                         int layer = layer_index(std::numeric_limits<int>::max());
789
790                         if (layer == std::numeric_limits<int>::max())
791                         {
792                                 channel()->stage().clear_transforms();
793                         }
794                         else
795                         {
796                                 channel()->stage().clear_transforms(layer);
797                         }
798                 }
799                 else if(boost::iequals(parameters()[0], L"COMMIT"))
800                 {
801                         transforms = std::move(deferred_transforms[channel_index()]);
802                 }
803                 else
804                 {
805                         SetReplyString(L"404 MIXER ERROR\r\n");
806                         return false;
807                 }
808
809                 if(defer)
810                 {
811                         auto& defer_tranforms = deferred_transforms[channel_index()];
812                         defer_tranforms.insert(defer_tranforms.end(), transforms.begin(), transforms.end());
813                 }
814                 else
815                         channel()->stage().apply_transforms(transforms);
816         
817                 SetReplyString(L"202 MIXER OK\r\n");
818
819                 return true;
820         }
821         catch(file_not_found&)
822         {
823                 CASPAR_LOG_CURRENT_EXCEPTION();
824                 SetReplyString(L"404 MIXER ERROR\r\n");
825                 return false;
826         }
827         catch(...)
828         {
829                 CASPAR_LOG_CURRENT_EXCEPTION();
830                 SetReplyString(L"502 MIXER FAILED\r\n");
831                 return false;
832         }
833 }
834
835 bool SwapCommand::DoExecute()
836 {       
837         //Perform loading of the clip
838         try
839         {
840                 if(layer_index(-1) != -1)
841                 {
842                         std::vector<std::string> strs;
843                         boost::split(strs, parameters()[0], boost::is_any_of("-"));
844                         
845                         auto ch1 = channel();
846                         auto ch2 = channels().at(boost::lexical_cast<int>(strs.at(0))-1);
847
848                         int l1 = layer_index();
849                         int l2 = boost::lexical_cast<int>(strs.at(1));
850
851                         ch1->stage().swap_layer(l1, l2, ch2.channel->stage());
852                 }
853                 else
854                 {
855                         auto ch1 = channel();
856                         auto ch2 = channels().at(boost::lexical_cast<int>(parameters()[0])-1);
857                         ch1->stage().swap_layers(ch2.channel->stage());
858                 }
859                 
860                 SetReplyString(L"202 SWAP OK\r\n");
861
862                 return true;
863         }
864         catch(file_not_found&)
865         {
866                 CASPAR_LOG_CURRENT_EXCEPTION();
867                 SetReplyString(L"404 SWAP ERROR\r\n");
868                 return false;
869         }
870         catch(...)
871         {
872                 CASPAR_LOG_CURRENT_EXCEPTION();
873                 SetReplyString(L"502 SWAP FAILED\r\n");
874                 return false;
875         }
876 }
877
878 bool AddCommand::DoExecute()
879 {       
880         //Perform loading of the clip
881         try
882         {
883                 replace_placeholders(
884                                 L"<CLIENT_IP_ADDRESS>",
885                                 this->client()->address(),
886                                 parameters());
887
888                 core::diagnostics::scoped_call_context save;
889                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
890
891                 auto consumer = create_consumer(parameters(), &channel()->stage());
892                 channel()->output().add(layer_index(consumer->index()), consumer);
893         
894                 SetReplyString(L"202 ADD OK\r\n");
895
896                 return true;
897         }
898         catch(file_not_found&)
899         {
900                 CASPAR_LOG_CURRENT_EXCEPTION();
901                 SetReplyString(L"404 ADD ERROR\r\n");
902                 return false;
903         }
904         catch(...)
905         {
906                 CASPAR_LOG_CURRENT_EXCEPTION();
907                 SetReplyString(L"502 ADD FAILED\r\n");
908                 return false;
909         }
910 }
911
912 bool RemoveCommand::DoExecute()
913 {       
914         //Perform loading of the clip
915         try
916         {
917                 auto index = layer_index(std::numeric_limits<int>::min());
918                 if(index == std::numeric_limits<int>::min())
919                 {
920                         replace_placeholders(
921                                         L"<CLIENT_IP_ADDRESS>",
922                                         this->client()->address(),
923                                         parameters());
924
925                         index = create_consumer(parameters(), &channel()->stage())->index();
926                 }
927
928                 channel()->output().remove(index);
929
930                 SetReplyString(L"202 REMOVE OK\r\n");
931
932                 return true;
933         }
934         catch(file_not_found&)
935         {
936                 CASPAR_LOG_CURRENT_EXCEPTION();
937                 SetReplyString(L"404 REMOVE ERROR\r\n");
938                 return false;
939         }
940         catch(...)
941         {
942                 CASPAR_LOG_CURRENT_EXCEPTION();
943                 SetReplyString(L"502 REMOVE FAILED\r\n");
944                 return false;
945         }
946 }
947
948 bool LoadCommand::DoExecute()
949 {       
950         //Perform loading of the clip
951         try
952         {
953                 core::diagnostics::scoped_call_context save;
954                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
955                 core::diagnostics::call_context::for_thread().layer = layer_index();
956                 auto pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
957                 channel()->stage().load(layer_index(), pFP, true);
958         
959                 SetReplyString(L"202 LOAD OK\r\n");
960
961                 return true;
962         }
963         catch(file_not_found&)
964         {
965                 CASPAR_LOG_CURRENT_EXCEPTION();
966                 SetReplyString(L"404 LOAD ERROR\r\n");
967                 return false;
968         }
969         catch(...)
970         {
971                 CASPAR_LOG_CURRENT_EXCEPTION();
972                 SetReplyString(L"502 LOAD FAILED\r\n");
973                 return false;
974         }
975 }
976
977 bool LoadbgCommand::DoExecute()
978 {
979         transition_info transitionInfo;
980         
981         // TRANSITION
982
983         std::wstring message;
984         for(size_t n = 0; n < parameters().size(); ++n)
985                 message += boost::to_upper_copy(parameters()[n]) + L" ";
986                 
987         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)?.*)");
988         boost::wsmatch what;
989         if(boost::regex_match(message, what, expr))
990         {
991                 auto transition = what["TRANSITION"].str();
992                 transitionInfo.duration = boost::lexical_cast<size_t>(what["DURATION"].str());
993                 auto direction = what["DIRECTION"].matched ? what["DIRECTION"].str() : L"";
994                 auto tween = what["TWEEN"].matched ? what["TWEEN"].str() : L"";
995                 transitionInfo.tweener = tween;         
996
997                 if(transition == L"CUT")
998                         transitionInfo.type = transition_type::cut;
999                 else if(transition == L"MIX")
1000                         transitionInfo.type = transition_type::mix;
1001                 else if(transition == L"PUSH")
1002                         transitionInfo.type = transition_type::push;
1003                 else if(transition == L"SLIDE")
1004                         transitionInfo.type = transition_type::slide;
1005                 else if(transition == L"WIPE")
1006                         transitionInfo.type = transition_type::wipe;
1007                 
1008                 if(direction == L"FROMLEFT")
1009                         transitionInfo.direction = transition_direction::from_left;
1010                 else if(direction == L"FROMRIGHT")
1011                         transitionInfo.direction = transition_direction::from_right;
1012                 else if(direction == L"LEFT")
1013                         transitionInfo.direction = transition_direction::from_right;
1014                 else if(direction == L"RIGHT")
1015                         transitionInfo.direction = transition_direction::from_left;
1016         }
1017         
1018         //Perform loading of the clip
1019         try
1020         {
1021                 std::shared_ptr<core::frame_producer> pFP;
1022                 
1023                 static boost::wregex expr(LR"(\[(?<CHANNEL>\d+)\])", boost::regex::icase);
1024                         
1025                 core::diagnostics::scoped_call_context save;
1026                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
1027                 core::diagnostics::call_context::for_thread().layer = layer_index();
1028
1029                 boost::wsmatch what;
1030                 if(boost::regex_match(parameters().at(0), what, expr))
1031                 {
1032                         auto channel_index = boost::lexical_cast<int>(what["CHANNEL"].str());
1033                         pFP = reroute::create_producer(*channels().at(channel_index-1).channel); 
1034                 }
1035                 else
1036                 {
1037                         pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
1038                 }
1039                 
1040                 if(pFP == frame_producer::empty())
1041                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(parameters().size() > 0 ? parameters()[0] : L""));
1042
1043                 bool auto_play = contains_param(L"AUTO", parameters());
1044
1045                 auto pFP2 = create_transition_producer(channel()->video_format_desc().field_mode, spl::make_shared_ptr(pFP), transitionInfo);
1046                 if(auto_play)
1047                         channel()->stage().load(layer_index(), pFP2, false, transitionInfo.duration); // TODO: LOOP
1048                 else
1049                         channel()->stage().load(layer_index(), pFP2, false); // TODO: LOOP
1050         
1051                 
1052                 SetReplyString(L"202 LOADBG OK\r\n");
1053
1054                 return true;
1055         }
1056         catch(file_not_found&)
1057         {               
1058                 CASPAR_LOG(error) << L"File not found. No match found for parameters. Check syntax.";
1059                 SetReplyString(L"404 LOADBG ERROR\r\n");
1060                 return false;
1061         }
1062         catch(...)
1063         {
1064                 CASPAR_LOG_CURRENT_EXCEPTION();
1065                 SetReplyString(L"502 LOADBG FAILED\r\n");
1066                 return false;
1067         }
1068 }
1069
1070 bool PauseCommand::DoExecute()
1071 {
1072         try
1073         {
1074                 channel()->stage().pause(layer_index());
1075                 SetReplyString(L"202 PAUSE OK\r\n");
1076                 return true;
1077         }
1078         catch(...)
1079         {
1080                 SetReplyString(L"501 PAUSE FAILED\r\n");
1081         }
1082
1083         return false;
1084 }
1085
1086 bool PlayCommand::DoExecute()
1087 {
1088         try
1089         {
1090                 if(!parameters().empty())
1091                 {
1092                         LoadbgCommand lbg(*this);
1093
1094                         if(!lbg.Execute())
1095                                 throw std::exception();
1096                 }
1097
1098                 channel()->stage().play(layer_index());
1099                 
1100                 SetReplyString(L"202 PLAY OK\r\n");
1101                 return true;
1102         }
1103         catch(...)
1104         {
1105                 SetReplyString(L"501 PLAY FAILED\r\n");
1106         }
1107
1108         return false;
1109 }
1110
1111 bool StopCommand::DoExecute()
1112 {
1113         try
1114         {
1115                 channel()->stage().stop(layer_index());
1116                 SetReplyString(L"202 STOP OK\r\n");
1117                 return true;
1118         }
1119         catch(...)
1120         {
1121                 SetReplyString(L"501 STOP FAILED\r\n");
1122         }
1123
1124         return false;
1125 }
1126
1127 bool ClearCommand::DoExecute()
1128 {
1129         int index = layer_index(std::numeric_limits<int>::min());
1130         if(index != std::numeric_limits<int>::min())
1131                 channel()->stage().clear(index);
1132         else
1133                 channel()->stage().clear();
1134                 
1135         SetReplyString(L"202 CLEAR OK\r\n");
1136
1137         return true;
1138 }
1139
1140 bool PrintCommand::DoExecute()
1141 {
1142         channel()->output().add(create_consumer({ L"IMAGE" }, &channel()->stage()));
1143                 
1144         SetReplyString(L"202 PRINT OK\r\n");
1145
1146         return true;
1147 }
1148
1149 bool LogCommand::DoExecute()
1150 {
1151         if(boost::iequals(parameters().at(0), L"LEVEL"))
1152                 log::set_log_level(parameters().at(1));
1153
1154         SetReplyString(L"202 LOG OK\r\n");
1155
1156         return true;
1157 }
1158
1159 bool CGCommand::DoExecute()
1160 {
1161         try
1162         {
1163                 std::wstring command = boost::to_upper_copy(parameters()[0]);
1164                 if(command == L"ADD")
1165                         return DoExecuteAdd();
1166                 else if(command == L"PLAY")
1167                         return DoExecutePlay();
1168                 else if(command == L"STOP")
1169                         return DoExecuteStop();
1170                 else if(command == L"NEXT")
1171                         return DoExecuteNext();
1172                 else if(command == L"REMOVE")
1173                         return DoExecuteRemove();
1174                 else if(command == L"CLEAR")
1175                         return DoExecuteClear();
1176                 else if(command == L"UPDATE")
1177                         return DoExecuteUpdate();
1178                 else if(command == L"INVOKE")
1179                         return DoExecuteInvoke();
1180                 else if(command == L"INFO")
1181                         return DoExecuteInfo();
1182         }
1183         catch(...)
1184         {
1185                 CASPAR_LOG_CURRENT_EXCEPTION();
1186         }
1187
1188         SetReplyString(L"403 CG ERROR\r\n");
1189         return false;
1190 }
1191
1192 bool CGCommand::ValidateLayer(const std::wstring& layerstring) {
1193         int length = layerstring.length();
1194         for(int i = 0; i < length; ++i) {
1195                 if(!std::isdigit(layerstring[i])) {
1196                         return false;
1197                 }
1198         }
1199
1200         return true;
1201 }
1202
1203 bool CGCommand::DoExecuteAdd() {
1204         //CG 1 ADD 0 "template_folder/templatename" [STARTLABEL] 0/1 [DATA]
1205
1206         int layer = 0;                          //_parameters[1]
1207 //      std::wstring templateName;      //_parameters[2]
1208         std::wstring label;             //_parameters[3]
1209         bool bDoStart = false;          //_parameters[3] alt. _parameters[4]
1210 //      std::wstring data;                      //_parameters[4] alt. _parameters[5]
1211
1212         if(parameters().size() < 4) 
1213         {
1214                 SetReplyString(L"402 CG ERROR\r\n");
1215                 return false;
1216         }
1217         unsigned int dataIndex = 4;
1218
1219         if(!ValidateLayer(parameters()[1])) 
1220         {
1221                 SetReplyString(L"403 CG ERROR\r\n");
1222                 return false;
1223         }
1224
1225         layer = boost::lexical_cast<int>(parameters()[1]);
1226
1227         if(parameters()[3].length() > 1) 
1228         {       //read label
1229                 label = parameters()[3];
1230                 ++dataIndex;
1231
1232                 if(parameters().size() > 4 && parameters()[4].length() > 0)     //read play-on-load-flag
1233                         bDoStart = (parameters()[4][0]==L'1') ? true : false;
1234                 else 
1235                 {
1236                         SetReplyString(L"402 CG ERROR\r\n");
1237                         return false;
1238                 }
1239         }
1240         else if(parameters()[3].length() > 0) { //read play-on-load-flag
1241                 bDoStart = (parameters()[3][0]==L'1') ? true : false;
1242         }
1243         else 
1244         {
1245                 SetReplyString(L"403 CG ERROR\r\n");
1246                 return false;
1247         }
1248
1249         const wchar_t* pDataString = 0;
1250         std::wstring dataFromFile;
1251         if(parameters().size() > dataIndex) 
1252         {       //read data
1253                 const std::wstring& dataString = parameters()[dataIndex];
1254
1255                 if (dataString.at(0) == L'<' || dataString.at(0) == L'{') //the data is XML or Json
1256                         pDataString = dataString.c_str();
1257                 else 
1258                 {
1259                         //The data is not an XML-string, it must be a filename
1260                         std::wstring filename = env::data_folder();
1261                         filename.append(dataString);
1262                         filename.append(L".ftd");
1263
1264                         auto found_file = find_case_insensitive(filename);
1265
1266                         if (found_file)
1267                         {
1268                                 dataFromFile = read_file(boost::filesystem::path(*found_file));
1269                                 pDataString = dataFromFile.c_str();
1270                         }
1271                 }
1272         }
1273
1274         auto filename = parameters()[2];
1275         auto proxy = cg_registry_->get_or_create_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER), filename);
1276
1277         if (proxy == core::cg_proxy::empty())
1278         {
1279                 CASPAR_LOG(warning) << "Could not find template " << parameters()[2];
1280                 SetReplyString(L"404 CG ERROR\r\n");
1281         }
1282         else
1283         {
1284                 proxy->add(layer, filename, bDoStart, label, (pDataString != 0) ? pDataString : L"");
1285         }
1286
1287         return true;
1288 }
1289
1290 bool CGCommand::DoExecutePlay()
1291 {
1292         if(parameters().size() > 1)
1293         {
1294                 if(!ValidateLayer(parameters()[1])) 
1295                 {
1296                         SetReplyString(L"403 CG ERROR\r\n");
1297                         return false;
1298                 }
1299                 int layer = boost::lexical_cast<int>(parameters()[1]);
1300                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->play(layer);
1301         }
1302         else
1303         {
1304                 SetReplyString(L"402 CG ERROR\r\n");
1305                 return true;
1306         }
1307
1308         SetReplyString(L"202 CG OK\r\n");
1309         return true;
1310 }
1311
1312 bool CGCommand::DoExecuteStop() 
1313 {
1314         if(parameters().size() > 1)
1315         {
1316                 if(!ValidateLayer(parameters()[1])) 
1317                 {
1318                         SetReplyString(L"403 CG ERROR\r\n");
1319                         return false;
1320                 }
1321                 int layer = boost::lexical_cast<int>(parameters()[1]);
1322                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->stop(layer, 0);
1323         }
1324         else 
1325         {
1326                 SetReplyString(L"402 CG ERROR\r\n");
1327                 return true;
1328         }
1329
1330         SetReplyString(L"202 CG OK\r\n");
1331         return true;
1332 }
1333
1334 bool CGCommand::DoExecuteNext()
1335 {
1336         if(parameters().size() > 1) 
1337         {
1338                 if(!ValidateLayer(parameters()[1])) 
1339                 {
1340                         SetReplyString(L"403 CG ERROR\r\n");
1341                         return false;
1342                 }
1343
1344                 int layer = boost::lexical_cast<int>(parameters()[1]);
1345                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->next(layer);
1346         }
1347         else 
1348         {
1349                 SetReplyString(L"402 CG ERROR\r\n");
1350                 return true;
1351         }
1352
1353         SetReplyString(L"202 CG OK\r\n");
1354         return true;
1355 }
1356
1357 bool CGCommand::DoExecuteRemove() 
1358 {
1359         if(parameters().size() > 1) 
1360         {
1361                 if(!ValidateLayer(parameters()[1])) 
1362                 {
1363                         SetReplyString(L"403 CG ERROR\r\n");
1364                         return false;
1365                 }
1366
1367                 int layer = boost::lexical_cast<int>(parameters()[1]);
1368                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->remove(layer);
1369         }
1370         else 
1371         {
1372                 SetReplyString(L"402 CG ERROR\r\n");
1373                 return true;
1374         }
1375
1376         SetReplyString(L"202 CG OK\r\n");
1377         return true;
1378 }
1379
1380 bool CGCommand::DoExecuteClear() 
1381 {
1382         channel()->stage().clear(layer_index(core::cg_proxy::DEFAULT_LAYER));
1383         SetReplyString(L"202 CG OK\r\n");
1384         return true;
1385 }
1386
1387 bool CGCommand::DoExecuteUpdate() 
1388 {
1389         try
1390         {
1391                 if(!ValidateLayer(parameters().at(1)))
1392                 {
1393                         SetReplyString(L"403 CG ERROR\r\n");
1394                         return false;
1395                 }
1396                                                 
1397                 std::wstring dataString = parameters().at(2);                           
1398                 if (dataString.at(0) != L'<' && dataString.at(0) != L'{')
1399                 {
1400                         //The data is not XML or Json, it must be a filename
1401                         std::wstring filename = env::data_folder();
1402                         filename.append(dataString);
1403                         filename.append(L".ftd");
1404
1405                         dataString = read_file(boost::filesystem::path(filename));
1406                 }               
1407
1408                 int layer = boost::lexical_cast<int>(parameters()[1]);
1409                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->update(layer, dataString);
1410         }
1411         catch(...)
1412         {
1413                 SetReplyString(L"402 CG ERROR\r\n");
1414                 return true;
1415         }
1416
1417         SetReplyString(L"202 CG OK\r\n");
1418         return true;
1419 }
1420
1421 bool CGCommand::DoExecuteInvoke() 
1422 {
1423         std::wstringstream replyString;
1424         replyString << L"201 CG OK\r\n";
1425
1426         if(parameters().size() > 2)
1427         {
1428                 if(!ValidateLayer(parameters()[1]))
1429                 {
1430                         SetReplyString(L"403 CG ERROR\r\n");
1431                         return false;
1432                 }
1433                 int layer = boost::lexical_cast<int>(parameters()[1]);
1434                 auto result = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->invoke(layer, parameters()[2]);
1435                 replyString << result << L"\r\n";
1436         }
1437         else 
1438         {
1439                 SetReplyString(L"402 CG ERROR\r\n");
1440                 return true;
1441         }
1442         
1443         SetReplyString(replyString.str());
1444         return true;
1445 }
1446
1447 bool CGCommand::DoExecuteInfo() 
1448 {
1449         std::wstringstream replyString;
1450         replyString << L"201 CG OK\r\n";
1451
1452         if(parameters().size() > 1)
1453         {
1454                 if(!ValidateLayer(parameters()[1]))
1455                 {
1456                         SetReplyString(L"403 CG ERROR\r\n");
1457                         return false;
1458                 }
1459
1460                 int layer = boost::lexical_cast<int>(parameters()[1]);
1461                 auto desc = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->description(layer);
1462                 
1463                 replyString << desc << L"\r\n";
1464         }
1465         else 
1466         {
1467                 auto info = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->template_host_info();
1468                 replyString << info << L"\r\n";
1469         }       
1470
1471         SetReplyString(replyString.str());
1472         return true;
1473 }
1474
1475 bool DataCommand::DoExecute()
1476 {
1477         std::wstring command = boost::to_upper_copy(parameters()[0]);
1478         if(command == L"STORE")
1479                 return DoExecuteStore();
1480         else if(command == L"RETRIEVE")
1481                 return DoExecuteRetrieve();
1482         else if(command == L"REMOVE")
1483                 return DoExecuteRemove();
1484         else if(command == L"LIST")
1485                 return DoExecuteList();
1486
1487         SetReplyString(L"403 DATA ERROR\r\n");
1488         return false;
1489 }
1490
1491 bool DataCommand::DoExecuteStore() 
1492 {
1493         if(parameters().size() < 3) 
1494         {
1495                 SetReplyString(L"402 DATA STORE ERROR\r\n");
1496                 return false;
1497         }
1498
1499         std::wstring filename = env::data_folder();
1500         filename.append(parameters()[1]);
1501         filename.append(L".ftd");
1502
1503         auto data_path = boost::filesystem::path(filename).parent_path().wstring();
1504         auto found_data_path = find_case_insensitive(data_path);
1505
1506         if (found_data_path)
1507                 data_path = *found_data_path;
1508
1509         if(!boost::filesystem::exists(data_path))
1510                 boost::filesystem::create_directories(data_path);
1511
1512         auto found_filename = find_case_insensitive(filename);
1513
1514         if (found_filename)
1515                 filename = *found_filename; // Overwrite case insensitive.
1516
1517         boost::filesystem::wofstream datafile(filename);
1518         if(!datafile) 
1519         {
1520                 SetReplyString(L"501 DATA STORE FAILED\r\n");
1521                 return false;
1522         }
1523
1524         datafile << static_cast<wchar_t>(65279); // UTF-8 BOM character
1525         datafile << parameters()[2] << std::flush;
1526         datafile.close();
1527
1528         std::wstring replyString = L"202 DATA STORE OK\r\n";
1529         SetReplyString(replyString);
1530         return true;
1531 }
1532
1533 bool DataCommand::DoExecuteRetrieve() 
1534 {
1535         if(parameters().size() < 2) 
1536         {
1537                 SetReplyString(L"402 DATA RETRIEVE ERROR\r\n");
1538                 return false;
1539         }
1540
1541         std::wstring filename = env::data_folder();
1542         filename.append(parameters()[1]);
1543         filename.append(L".ftd");
1544
1545         std::wstring file_contents;
1546
1547         auto found_file = find_case_insensitive(filename);
1548
1549         if (found_file)
1550                 file_contents = read_file(boost::filesystem::path(*found_file));
1551
1552         if (file_contents.empty()) 
1553         {
1554                 SetReplyString(L"404 DATA RETRIEVE ERROR\r\n");
1555                 return false;
1556         }
1557
1558         std::wstringstream reply(L"201 DATA RETRIEVE OK\r\n");
1559
1560         std::wstringstream file_contents_stream(file_contents);
1561         std::wstring line;
1562         
1563         bool firstLine = true;
1564         while(std::getline(file_contents_stream, line))
1565         {
1566                 if(firstLine)
1567                         firstLine = false;
1568                 else
1569                         reply << "\n";
1570
1571                 reply << line;
1572         }
1573
1574         reply << "\r\n";
1575         SetReplyString(reply.str());
1576         return true;
1577 }
1578
1579 bool DataCommand::DoExecuteRemove()
1580
1581         if (parameters().size() < 2)
1582         {
1583                 SetReplyString(L"402 DATA REMOVE ERROR\r\n");
1584                 return false;
1585         }
1586
1587         std::wstring filename = env::data_folder();
1588         filename.append(parameters()[1]);
1589         filename.append(L".ftd");
1590
1591         if (!boost::filesystem::exists(filename))
1592         {
1593                 SetReplyString(L"404 DATA REMOVE ERROR\r\n");
1594                 return false;
1595         }
1596
1597         if (!boost::filesystem::remove(filename))
1598         {
1599                 SetReplyString(L"403 DATA REMOVE ERROR\r\n");
1600                 return false;
1601         }
1602
1603         SetReplyString(L"201 DATA REMOVE OK\r\n");
1604
1605         return true;
1606 }
1607
1608 bool DataCommand::DoExecuteList() 
1609 {
1610         std::wstringstream replyString;
1611         replyString << L"200 DATA LIST OK\r\n";
1612
1613         for (boost::filesystem::recursive_directory_iterator itr(env::data_folder()), end; itr != end; ++itr)
1614         {                       
1615                 if(boost::filesystem::is_regular_file(itr->path()))
1616                 {
1617                         if(!boost::iequals(itr->path().extension().wstring(), L".ftd"))
1618                                 continue;
1619                         
1620                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::data_folder().size()-1, itr->path().wstring().size()));
1621                         
1622                         auto str = relativePath.replace_extension(L"").generic_wstring();
1623                         if(str[0] == L'\\' || str[0] == L'/')
1624                                 str = std::wstring(str.begin() + 1, str.end());
1625
1626                         replyString << str << L"\r\n";
1627                 }
1628         }
1629         
1630         replyString << L"\r\n";
1631
1632         SetReplyString(boost::to_upper_copy(replyString.str()));
1633         return true;
1634 }
1635
1636 bool CinfCommand::DoExecute()
1637 {
1638         std::wstringstream replyString;
1639         
1640         try
1641         {
1642                 std::wstring info;
1643                 for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end && info.empty(); ++itr)
1644                 {
1645                         auto path = itr->path();
1646                         auto file = path.replace_extension(L"").filename().wstring();
1647                         if(boost::iequals(file, parameters().at(0)))
1648                                 info += MediaInfo(itr->path(), system_info_repo_) + L"\r\n";
1649                 }
1650
1651                 if(info.empty())
1652                 {
1653                         SetReplyString(L"404 CINF ERROR\r\n");
1654                         return false;
1655                 }
1656                 replyString << L"200 CINF OK\r\n";
1657                 replyString << info << "\r\n";
1658         }
1659         catch(...)
1660         {
1661                 CASPAR_LOG_CURRENT_EXCEPTION();
1662                 SetReplyString(L"404 CINF ERROR\r\n");
1663                 return false;
1664         }
1665         
1666         SetReplyString(replyString.str());
1667         return true;
1668 }
1669
1670 void GenerateChannelInfo(int index, const spl::shared_ptr<core::video_channel>& pChannel, std::wstringstream& replyString)
1671 {
1672         replyString << index+1 << L" " << pChannel->video_format_desc().name << L" PLAYING\r\n";
1673 }
1674
1675 bool InfoCommand::DoExecute()
1676 {
1677         std::wstringstream replyString;
1678         
1679         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
1680
1681         try
1682         {
1683                 if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"TEMPLATE"))
1684                 {               
1685                         replyString << L"201 INFO TEMPLATE OK\r\n";
1686
1687                         auto filename = parameters().at(1);
1688                                                 
1689                         std::wstringstream str;
1690                         str << u16(cg_registry_->read_meta_info(filename));
1691                         boost::property_tree::wptree info;
1692                         boost::property_tree::xml_parser::read_xml(str, info, boost::property_tree::xml_parser::trim_whitespace | boost::property_tree::xml_parser::no_comments);
1693
1694                         boost::property_tree::xml_parser::write_xml(replyString, info, w);
1695                 }
1696                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"CONFIG"))
1697                 {               
1698                         replyString << L"201 INFO CONFIG OK\r\n";
1699
1700                         boost::property_tree::write_xml(replyString, caspar::env::properties(), w);
1701                 }
1702                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"PATHS"))
1703                 {
1704                         replyString << L"201 INFO PATHS OK\r\n";
1705
1706                         boost::property_tree::wptree info;
1707                         info.add_child(L"paths", caspar::env::properties().get_child(L"configuration.paths"));
1708                         info.add(L"paths.initial-path", boost::filesystem::initial_path().wstring() + L"/");
1709
1710                         boost::property_tree::write_xml(replyString, info, w);
1711                 }
1712                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SYSTEM"))
1713                 {
1714                         replyString << L"201 INFO SYSTEM OK\r\n";
1715                         
1716                         boost::property_tree::wptree info;
1717                         
1718                         info.add(L"system.name",                                        caspar::system_product_name());
1719                         info.add(L"system.os.description",                      caspar::os_description());
1720                         info.add(L"system.cpu",                                         caspar::cpu_info());
1721
1722                         system_info_repo_->fill_information(info);
1723                                                 
1724                         boost::property_tree::write_xml(replyString, info, w);
1725                 }
1726                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SERVER"))
1727                 {
1728                         replyString << L"201 INFO SERVER OK\r\n";
1729                         
1730                         boost::property_tree::wptree info;
1731
1732                         int index = 0;
1733                         for (auto& channel : channels())
1734                                 info.add_child(L"channels.channel", channel.channel->info())
1735                                         .add(L"index", ++index);
1736                         
1737                         boost::property_tree::write_xml(replyString, info, w);
1738                 }
1739                 else // channel
1740                 {                       
1741                         if(parameters().size() >= 1)
1742                         {
1743                                 replyString << L"201 INFO OK\r\n";
1744                                 boost::property_tree::wptree info;
1745
1746                                 std::vector<std::wstring> split;
1747                                 boost::split(split, parameters()[0], boost::is_any_of("-"));
1748                                         
1749                                 int layer = std::numeric_limits<int>::min();
1750                                 int channel = boost::lexical_cast<int>(split[0]) - 1;
1751
1752                                 if(split.size() > 1)
1753                                         layer = boost::lexical_cast<int>(split[1]);
1754                                 
1755                                 if(layer == std::numeric_limits<int>::min())
1756                                 {       
1757                                         info.add_child(L"channel", channels().at(channel).channel->info())
1758                                                         .add(L"index", channel);
1759                                 }
1760                                 else
1761                                 {
1762                                         if(parameters().size() >= 2)
1763                                         {
1764                                                 if(boost::iequals(parameters()[1], L"B"))
1765                                                         info.add_child(L"producer", channels().at(channel).channel->stage().background(layer).get()->info());
1766                                                 else
1767                                                         info.add_child(L"producer", channels().at(channel).channel->stage().foreground(layer).get()->info());
1768                                         }
1769                                         else
1770                                         {
1771                                                 info.add_child(L"layer", channels().at(channel).channel->stage().info(layer).get())
1772                                                         .add(L"index", layer);
1773                                         }
1774                                 }
1775                                 boost::property_tree::xml_parser::write_xml(replyString, info, w);
1776                         }
1777                         else
1778                         {
1779                                 // This is needed for backwards compatibility with old clients
1780                                 replyString << L"200 INFO OK\r\n";
1781                                 for(size_t n = 0; n < channels().size(); ++n)
1782                                         GenerateChannelInfo(n, channels()[n].channel, replyString);
1783                         }
1784
1785                 }
1786         }
1787         catch(...)
1788         {
1789                 CASPAR_LOG_CURRENT_EXCEPTION();
1790                 SetReplyString(L"403 INFO ERROR\r\n");
1791                 return false;
1792         }
1793
1794         replyString << L"\r\n";
1795         SetReplyString(replyString.str());
1796         return true;
1797 }
1798
1799 bool ClsCommand::DoExecute()
1800 {
1801         try
1802         {
1803                 std::wstringstream replyString;
1804                 replyString << L"200 CLS OK\r\n";
1805                 replyString << ListMedia(system_info_repo_);
1806                 replyString << L"\r\n";
1807                 SetReplyString(boost::to_upper_copy(replyString.str()));
1808         }
1809         catch(...)
1810         {
1811                 CASPAR_LOG_CURRENT_EXCEPTION();
1812                 SetReplyString(L"501 CLS FAILED\r\n");
1813                 return false;
1814         }
1815
1816         return true;
1817 }
1818
1819 bool TlsCommand::DoExecute()
1820 {
1821         try
1822         {
1823                 std::wstringstream replyString;
1824                 replyString << L"200 TLS OK\r\n";
1825
1826                 replyString << ListTemplates(cg_registry_);
1827                 replyString << L"\r\n";
1828
1829                 SetReplyString(replyString.str());
1830         }
1831         catch(...)
1832         {
1833                 CASPAR_LOG_CURRENT_EXCEPTION();
1834                 SetReplyString(L"501 TLS FAILED\r\n");
1835                 return false;
1836         }
1837         return true;
1838 }
1839
1840 bool VersionCommand::DoExecute()
1841 {
1842         std::wstring replyString = L"201 VERSION OK\r\n" + env::version() + L"\r\n";
1843
1844         if (parameters().size() > 0 && !boost::iequals(parameters()[0], L"SERVER"))
1845         {
1846                 auto version = system_info_repo_->get_version(parameters().at(0));
1847
1848                 if (version.empty())
1849                         replyString = L"403 VERSION ERROR\r\n";
1850                 else
1851                         replyString = L"201 VERSION OK\r\n" + version + L"\r\n";
1852         }
1853
1854         SetReplyString(replyString);
1855         return true;
1856 }
1857
1858 bool ByeCommand::DoExecute()
1859 {
1860         client()->disconnect();
1861         return true;
1862 }
1863
1864 bool SetCommand::DoExecute()
1865 {
1866         try
1867         {
1868                 std::wstring name = boost::to_upper_copy(parameters()[0]);
1869                 std::wstring value = boost::to_upper_copy(parameters()[1]);
1870
1871                 if(name == L"MODE")
1872                 {
1873                         auto format_desc = core::video_format_desc(value);
1874                         if(format_desc.format != core::video_format::invalid)
1875                         {
1876                                 channel()->video_format_desc(format_desc);
1877                                 SetReplyString(L"202 SET MODE OK\r\n");
1878                         }
1879                         else
1880                                 SetReplyString(L"501 SET MODE FAILED\r\n");
1881                 }
1882                 else
1883                 {
1884                         this->SetReplyString(L"403 SET ERROR\r\n");
1885                 }
1886         }
1887         catch(...)
1888         {
1889                 CASPAR_LOG_CURRENT_EXCEPTION();
1890                 SetReplyString(L"501 SET FAILED\r\n");
1891                 return false;
1892         }
1893
1894         return true;
1895 }
1896
1897 bool LockCommand::DoExecute()
1898 {
1899         try
1900         {
1901                 auto it = parameters().begin();
1902
1903                 std::shared_ptr<caspar::IO::lock_container> lock;
1904                 try
1905                 {
1906                         int channel_index = boost::lexical_cast<int>(*it) - 1;
1907                         lock = channels().at(channel_index).lock;
1908                 }
1909                 catch(const boost::bad_lexical_cast&) {}
1910                 catch(...)
1911                 {
1912                         SetReplyString(L"401 LOCK ERROR\r\n");
1913                         return false;
1914                 }
1915
1916                 if(lock)
1917                         ++it;
1918
1919                 if(it == parameters().end())    //too few parameters
1920                 {
1921                         SetReplyString(L"402 LOCK ERROR\r\n");
1922                         return false;
1923                 }
1924
1925                 std::wstring command = boost::to_upper_copy(*it);
1926                 if(command == L"ACQUIRE")
1927                 {
1928                         ++it;
1929                         if(it == parameters().end())    //too few parameters
1930                         {
1931                                 SetReplyString(L"402 LOCK ACQUIRE ERROR\r\n");
1932                                 return false;
1933                         }
1934                         std::wstring lock_phrase = (*it);
1935
1936                         //TODO: read options
1937
1938                         if(lock)
1939                         {
1940                                 //just lock one channel
1941                                 if(!lock->try_lock(lock_phrase, client()))
1942                                 {
1943                                         SetReplyString(L"503 LOCK ACQUIRE FAILED\r\n");
1944                                         return false;
1945                                 }
1946                         }
1947                         else
1948                         {
1949                                 //TODO: lock all channels
1950                                 CASPAR_THROW_EXCEPTION(not_implemented());
1951                         }
1952                         SetReplyString(L"202 LOCK ACQUIRE OK\r\n");
1953
1954                 }
1955                 else if(command == L"RELEASE")
1956                 {
1957                         if(lock)
1958                         {
1959                                 lock->release_lock(client());
1960                         }
1961                         else
1962                         {
1963                                 //TODO: release all channels
1964                                 CASPAR_THROW_EXCEPTION(not_implemented());
1965                         }
1966                         SetReplyString(L"202 LOCK RELEASE OK\r\n");
1967                 }
1968                 else if(command == L"CLEAR")
1969                 {
1970                         std::wstring override_phrase = env::properties().get(L"configuration.lock-clear-phrase", L"");
1971                         std::wstring client_override_phrase;
1972                         if(!override_phrase.empty())
1973                         {
1974                                 ++it;
1975                                 if(it == parameters().end())
1976                                 {
1977                                         SetReplyString(L"402 LOCK CLEAR ERROR\r\n");
1978                                         return false;
1979                                 }
1980                                 client_override_phrase = (*it);
1981                         }
1982
1983                         if(lock)
1984                         {
1985                                 //just clear one channel
1986                                 if(client_override_phrase != override_phrase)
1987                                 {
1988                                         SetReplyString(L"503 LOCK CLEAR FAILED\r\n");
1989                                         return false;
1990                                 }
1991                                 
1992                                 lock->clear_locks();
1993                         }
1994                         else
1995                         {
1996                                 //TODO: clear all channels
1997                                 CASPAR_THROW_EXCEPTION(not_implemented());
1998                         }
1999
2000                         SetReplyString(L"202 LOCK CLEAR OK\r\n");
2001                 }
2002                 else
2003                 {
2004                         SetReplyString(L"403 LOCK ERROR\r\n");
2005                         return false;
2006                 }
2007         }
2008         catch(not_implemented&)
2009         {
2010                 SetReplyString(L"600 LOCK FAILED\r\n");
2011                 return false;
2012         }
2013         catch(...)
2014         {
2015                 CASPAR_LOG_CURRENT_EXCEPTION();
2016                 SetReplyString(L"501 LOCK FAILED\r\n");
2017                 return false;
2018         }
2019
2020         return true;
2021 }
2022
2023 bool ThumbnailCommand::DoExecute()
2024 {
2025         std::wstring command = boost::to_upper_copy(parameters()[0]);
2026
2027         if (command == L"RETRIEVE")
2028                 return DoExecuteRetrieve();
2029         else if (command == L"LIST")
2030                 return DoExecuteList();
2031         else if (command == L"GENERATE")
2032                 return DoExecuteGenerate();
2033         else if (command == L"GENERATE_ALL")
2034                 return DoExecuteGenerateAll();
2035
2036         SetReplyString(L"403 THUMBNAIL ERROR\r\n");
2037         return false;
2038 }
2039
2040 bool ThumbnailCommand::DoExecuteRetrieve() 
2041 {
2042         if(parameters().size() < 2) 
2043         {
2044                 SetReplyString(L"402 THUMBNAIL RETRIEVE ERROR\r\n");
2045                 return false;
2046         }
2047
2048         std::wstring filename = env::thumbnails_folder();
2049         filename.append(parameters()[1]);
2050         filename.append(L".png");
2051
2052         std::wstring file_contents;
2053
2054         auto found_file = find_case_insensitive(filename);
2055
2056         if (found_file)
2057                 file_contents = read_file_base64(boost::filesystem::path(*found_file));
2058
2059         if (file_contents.empty())
2060         {
2061                 SetReplyString(L"404 THUMBNAIL RETRIEVE ERROR\r\n");
2062                 return false;
2063         }
2064
2065         std::wstringstream reply;
2066
2067         reply << L"201 THUMBNAIL RETRIEVE OK\r\n";
2068         reply << file_contents;
2069         reply << L"\r\n";
2070         SetReplyString(reply.str());
2071         return true;
2072 }
2073
2074 bool ThumbnailCommand::DoExecuteList()
2075 {
2076         std::wstringstream replyString;
2077         replyString << L"200 THUMBNAIL LIST OK\r\n";
2078
2079         for (boost::filesystem::recursive_directory_iterator itr(env::thumbnails_folder()), end; itr != end; ++itr)
2080         {      
2081                 if(boost::filesystem::is_regular_file(itr->path()))
2082                 {
2083                         if(!boost::iequals(itr->path().extension().wstring(), L".png"))
2084                                 continue;
2085
2086                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::thumbnails_folder().size()-1, itr->path().wstring().size()));
2087
2088                         auto str = relativePath.replace_extension(L"").generic_wstring();
2089                         if(str[0] == '\\' || str[0] == '/')
2090                                 str = std::wstring(str.begin() + 1, str.end());
2091
2092                         auto mtime = boost::filesystem::last_write_time(itr->path());
2093                         auto mtime_readable = boost::posix_time::to_iso_wstring(boost::posix_time::from_time_t(mtime));
2094                         auto file_size = boost::filesystem::file_size(itr->path());
2095
2096                         replyString << L"\"" << str << L"\" " << mtime_readable << L" " << file_size << L"\r\n";
2097                 }
2098         }
2099
2100         replyString << L"\r\n";
2101
2102         SetReplyString(boost::to_upper_copy(replyString.str()));
2103         return true;
2104 }
2105
2106 bool ThumbnailCommand::DoExecuteGenerate()
2107 {
2108         if (parameters().size() < 2) 
2109         {
2110                 SetReplyString(L"402 THUMBNAIL GENERATE ERROR\r\n");
2111                 return false;
2112         }
2113
2114         if (thumb_gen_)
2115         {
2116                 thumb_gen_->generate(parameters()[1]);
2117                 SetReplyString(L"202 THUMBNAIL GENERATE OK\r\n");
2118                 return true;
2119         }
2120         else
2121         {
2122                 SetReplyString(L"500 THUMBNAIL GENERATE ERROR\r\n");
2123                 return false;
2124         }
2125 }
2126
2127 bool ThumbnailCommand::DoExecuteGenerateAll()
2128 {
2129         if (thumb_gen_)
2130         {
2131                 thumb_gen_->generate_all();
2132                 SetReplyString(L"202 THUMBNAIL GENERATE_ALL OK\r\n");
2133                 return true;
2134         }
2135         else
2136         {
2137                 SetReplyString(L"500 THUMBNAIL GENERATE_ALL ERROR\r\n");
2138                 return false;
2139         }
2140 }
2141
2142 bool KillCommand::DoExecute()
2143 {
2144         shutdown_server_now_->set_value(false); //false for not attempting to restart
2145         SetReplyString(L"202 KILL OK\r\n");
2146         return true;
2147 }
2148
2149 bool RestartCommand::DoExecute()
2150 {
2151         shutdown_server_now_->set_value(true);  //true for attempting to restart
2152         SetReplyString(L"202 RESTART OK\r\n");
2153         return true;
2154 }
2155
2156 }       //namespace amcp
2157 }}      //namespace caspar