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