]> git.sesse.net Git - casparcg/blob - protocol/amcp/AMCPCommandsImpl.cpp
* Fixed CEF compilation error in debug mode.
[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 bool MixerCommand::DoExecute()
389 {       
390         //Perform loading of the clip
391         try
392         {       
393                 bool defer = boost::iequals(parameters().back(), L"DEFER");
394                 if(defer)
395                         parameters().pop_back();
396
397                 std::vector<stage::transform_tuple_t> transforms;
398
399                 if(boost::iequals(parameters()[0], L"KEYER") || boost::iequals(parameters()[0], L"IS_KEY"))
400                 {
401                         bool value = boost::lexical_cast<int>(parameters().at(1));
402                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
403                         {
404                                 transform.image_transform.is_key = value;
405                                 return transform;                                       
406                         }, 0, L"linear"));
407                 }
408                 else if(boost::iequals(parameters()[0], L"OPACITY"))
409                 {
410                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
411                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
412
413                         double value = boost::lexical_cast<double>(parameters().at(1));
414                         
415                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
416                         {
417                                 transform.image_transform.opacity = value;
418                                 return transform;                                       
419                         }, duration, tween));
420                 }
421                 else if(boost::iequals(parameters()[0], L"FILL") || boost::iequals(parameters()[0], L"FILL_RECT"))
422                 {
423                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
424                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
425                         double x        = boost::lexical_cast<double>(parameters().at(1));
426                         double y        = boost::lexical_cast<double>(parameters().at(2));
427                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
428                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
429
430                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) mutable -> frame_transform
431                         {
432                                 transform.image_transform.fill_translation[0]   = x;
433                                 transform.image_transform.fill_translation[1]   = y;
434                                 transform.image_transform.fill_scale[0]                 = x_s;
435                                 transform.image_transform.fill_scale[1]                 = y_s;
436                                 return transform;
437                         }, duration, tween));
438                 }
439                 else if(boost::iequals(parameters()[0], L"CLIP") || boost::iequals(parameters()[0], L"CLIP_RECT"))
440                 {
441                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
442                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
443                         double x        = boost::lexical_cast<double>(parameters().at(1));
444                         double y        = boost::lexical_cast<double>(parameters().at(2));
445                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
446                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
447
448                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
449                         {
450                                 transform.image_transform.clip_translation[0]   = x;
451                                 transform.image_transform.clip_translation[1]   = y;
452                                 transform.image_transform.clip_scale[0]                 = x_s;
453                                 transform.image_transform.clip_scale[1]                 = y_s;
454                                 return transform;
455                         }, duration, tween));
456                 }
457                 else if(boost::iequals(parameters()[0], L"GRID"))
458                 {
459                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
460                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
461                         int n = boost::lexical_cast<int>(parameters().at(1));
462                         double delta = 1.0/static_cast<double>(n);
463                         for(int x = 0; x < n; ++x)
464                         {
465                                 for(int y = 0; y < n; ++y)
466                                 {
467                                         int index = x+y*n+1;
468                                         transforms.push_back(stage::transform_tuple_t(index, [=](frame_transform transform) -> frame_transform
469                                         {               
470                                                 transform.image_transform.fill_translation[0]   = x*delta;
471                                                 transform.image_transform.fill_translation[1]   = y*delta;
472                                                 transform.image_transform.fill_scale[0]                 = delta;
473                                                 transform.image_transform.fill_scale[1]                 = delta;
474                                                 transform.image_transform.clip_translation[0]   = x*delta;
475                                                 transform.image_transform.clip_translation[1]   = y*delta;
476                                                 transform.image_transform.clip_scale[0]                 = delta;
477                                                 transform.image_transform.clip_scale[1]                 = delta;                        
478                                                 return transform;
479                                         }, duration, tween));
480                                 }
481                         }
482                 }
483                 else if(boost::iequals(parameters()[0], L"BLEND"))
484                 {
485                         auto blend_str = parameters().at(1);                                                            
486                         int layer = layer_index();
487                         channel()->mixer().set_blend_mode(layer, get_blend_mode(blend_str));    
488                 }
489                 else if(boost::iequals(parameters()[0], L"MASTERVOLUME"))
490                 {
491                         float master_volume = boost::lexical_cast<float>(parameters().at(1));
492                         channel()->mixer().set_master_volume(master_volume);
493                 }
494                 else if(boost::iequals(parameters()[0], L"BRIGHTNESS"))
495                 {
496                         auto value = boost::lexical_cast<double>(parameters().at(1));
497                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
498                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
499                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
500                         {
501                                 transform.image_transform.brightness = value;
502                                 return transform;
503                         }, duration, tween));
504                 }
505                 else if(boost::iequals(parameters()[0], L"SATURATION"))
506                 {
507                         auto value = boost::lexical_cast<double>(parameters().at(1));
508                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
509                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
510                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
511                         {
512                                 transform.image_transform.saturation = value;
513                                 return transform;
514                         }, duration, tween));   
515                 }
516                 else if(parameters()[0] == L"CONTRAST")
517                 {
518                         auto value = boost::lexical_cast<double>(parameters().at(1));
519                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
520                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
521                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
522                         {
523                                 transform.image_transform.contrast = value;
524                                 return transform;
525                         }, duration, tween));   
526                 }
527                 else if(boost::iequals(parameters()[0], L"LEVELS"))
528                 {
529                         levels value;
530                         value.min_input  = boost::lexical_cast<double>(parameters().at(1));
531                         value.max_input  = boost::lexical_cast<double>(parameters().at(2));
532                         value.gamma              = boost::lexical_cast<double>(parameters().at(3));
533                         value.min_output = boost::lexical_cast<double>(parameters().at(4));
534                         value.max_output = boost::lexical_cast<double>(parameters().at(5));
535                         int duration = parameters().size() > 6 ? boost::lexical_cast<int>(parameters()[6]) : 0;
536                         std::wstring tween = parameters().size() > 7 ? parameters()[7] : L"linear";
537
538                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
539                         {
540                                 transform.image_transform.levels = value;
541                                 return transform;
542                         }, duration, tween));
543                 }
544                 else if(boost::iequals(parameters()[0], L"VOLUME"))
545                 {
546                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
547                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
548                         double value = boost::lexical_cast<double>(parameters()[1]);
549
550                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
551                         {
552                                 transform.audio_transform.volume = value;
553                                 return transform;
554                         }, duration, tween));
555                 }
556                 else if(boost::iequals(parameters()[0], L"CLEAR"))
557                 {
558                         int layer = layer_index(std::numeric_limits<int>::max());
559
560                         if (layer == std::numeric_limits<int>::max())
561                         {
562                                 channel()->stage().clear_transforms();
563                                 channel()->mixer().clear_blend_modes();
564                         }
565                         else
566                         {
567                                 channel()->stage().clear_transforms(layer);
568                                 channel()->mixer().clear_blend_mode(layer);
569                         }
570                 }
571                 else if(boost::iequals(parameters()[0], L"COMMIT"))
572                 {
573                         transforms = std::move(deferred_transforms[channel_index()]);
574                 }
575                 else
576                 {
577                         SetReplyString(L"404 MIXER ERROR\r\n");
578                         return false;
579                 }
580
581                 if(defer)
582                 {
583                         auto& defer_tranforms = deferred_transforms[channel_index()];
584                         defer_tranforms.insert(defer_tranforms.end(), transforms.begin(), transforms.end());
585                 }
586                 else
587                         channel()->stage().apply_transforms(transforms);
588         
589                 SetReplyString(L"202 MIXER OK\r\n");
590
591                 return true;
592         }
593         catch(file_not_found&)
594         {
595                 CASPAR_LOG_CURRENT_EXCEPTION();
596                 SetReplyString(L"404 MIXER ERROR\r\n");
597                 return false;
598         }
599         catch(...)
600         {
601                 CASPAR_LOG_CURRENT_EXCEPTION();
602                 SetReplyString(L"502 MIXER FAILED\r\n");
603                 return false;
604         }
605 }
606
607 bool SwapCommand::DoExecute()
608 {       
609         //Perform loading of the clip
610         try
611         {
612                 if(layer_index(-1) != -1)
613                 {
614                         std::vector<std::string> strs;
615                         boost::split(strs, parameters()[0], boost::is_any_of("-"));
616                         
617                         auto ch1 = channel();
618                         auto ch2 = channels().at(boost::lexical_cast<int>(strs.at(0))-1);
619
620                         int l1 = layer_index();
621                         int l2 = boost::lexical_cast<int>(strs.at(1));
622
623                         ch1->stage().swap_layer(l1, l2, ch2.channel->stage());
624                 }
625                 else
626                 {
627                         auto ch1 = channel();
628                         auto ch2 = channels().at(boost::lexical_cast<int>(parameters()[0])-1);
629                         ch1->stage().swap_layers(ch2.channel->stage());
630                 }
631                 
632                 SetReplyString(L"202 SWAP OK\r\n");
633
634                 return true;
635         }
636         catch(file_not_found&)
637         {
638                 CASPAR_LOG_CURRENT_EXCEPTION();
639                 SetReplyString(L"404 SWAP ERROR\r\n");
640                 return false;
641         }
642         catch(...)
643         {
644                 CASPAR_LOG_CURRENT_EXCEPTION();
645                 SetReplyString(L"502 SWAP FAILED\r\n");
646                 return false;
647         }
648 }
649
650 bool AddCommand::DoExecute()
651 {       
652         //Perform loading of the clip
653         try
654         {
655                 //create_consumer still expects all parameters to be uppercase
656                 for (auto& str : parameters())
657                 {
658                         boost::to_upper(str);
659                 }
660
661                 core::diagnostics::scoped_call_context save;
662                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
663
664                 auto consumer = create_consumer(parameters(), &channel()->stage());
665                 channel()->output().add(layer_index(consumer->index()), consumer);
666         
667                 SetReplyString(L"202 ADD OK\r\n");
668
669                 return true;
670         }
671         catch(file_not_found&)
672         {
673                 CASPAR_LOG_CURRENT_EXCEPTION();
674                 SetReplyString(L"404 ADD ERROR\r\n");
675                 return false;
676         }
677         catch(...)
678         {
679                 CASPAR_LOG_CURRENT_EXCEPTION();
680                 SetReplyString(L"502 ADD FAILED\r\n");
681                 return false;
682         }
683 }
684
685 bool RemoveCommand::DoExecute()
686 {       
687         //Perform loading of the clip
688         try
689         {
690                 auto index = layer_index(std::numeric_limits<int>::min());
691                 if(index == std::numeric_limits<int>::min())
692                 {
693                         //create_consumer still expects all parameters to be uppercase
694                         for (auto& str : parameters())
695                         {
696                                 boost::to_upper(str);
697                         }
698
699                         index = create_consumer(parameters(), &channel()->stage())->index();
700                 }
701
702                 channel()->output().remove(index);
703
704                 SetReplyString(L"202 REMOVE OK\r\n");
705
706                 return true;
707         }
708         catch(file_not_found&)
709         {
710                 CASPAR_LOG_CURRENT_EXCEPTION();
711                 SetReplyString(L"404 REMOVE ERROR\r\n");
712                 return false;
713         }
714         catch(...)
715         {
716                 CASPAR_LOG_CURRENT_EXCEPTION();
717                 SetReplyString(L"502 REMOVE FAILED\r\n");
718                 return false;
719         }
720 }
721
722 bool LoadCommand::DoExecute()
723 {       
724         //Perform loading of the clip
725         try
726         {
727                 core::diagnostics::scoped_call_context save;
728                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
729                 core::diagnostics::call_context::for_thread().layer = layer_index();
730                 auto pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
731                 channel()->stage().load(layer_index(), pFP, true);
732         
733                 SetReplyString(L"202 LOAD OK\r\n");
734
735                 return true;
736         }
737         catch(file_not_found&)
738         {
739                 CASPAR_LOG_CURRENT_EXCEPTION();
740                 SetReplyString(L"404 LOAD ERROR\r\n");
741                 return false;
742         }
743         catch(...)
744         {
745                 CASPAR_LOG_CURRENT_EXCEPTION();
746                 SetReplyString(L"502 LOAD FAILED\r\n");
747                 return false;
748         }
749 }
750
751 bool LoadbgCommand::DoExecute()
752 {
753         transition_info transitionInfo;
754         
755         // TRANSITION
756
757         std::wstring message;
758         for(size_t n = 0; n < parameters().size(); ++n)
759                 message += boost::to_upper_copy(parameters()[n]) + L" ";
760                 
761         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)?.*)");
762         boost::wsmatch what;
763         if(boost::regex_match(message, what, expr))
764         {
765                 auto transition = what["TRANSITION"].str();
766                 transitionInfo.duration = boost::lexical_cast<size_t>(what["DURATION"].str());
767                 auto direction = what["DIRECTION"].matched ? what["DIRECTION"].str() : L"";
768                 auto tween = what["TWEEN"].matched ? what["TWEEN"].str() : L"";
769                 transitionInfo.tweener = tween;         
770
771                 if(transition == L"CUT")
772                         transitionInfo.type = transition_type::cut;
773                 else if(transition == L"MIX")
774                         transitionInfo.type = transition_type::mix;
775                 else if(transition == L"PUSH")
776                         transitionInfo.type = transition_type::push;
777                 else if(transition == L"SLIDE")
778                         transitionInfo.type = transition_type::slide;
779                 else if(transition == L"WIPE")
780                         transitionInfo.type = transition_type::wipe;
781                 
782                 if(direction == L"FROMLEFT")
783                         transitionInfo.direction = transition_direction::from_left;
784                 else if(direction == L"FROMRIGHT")
785                         transitionInfo.direction = transition_direction::from_right;
786                 else if(direction == L"LEFT")
787                         transitionInfo.direction = transition_direction::from_right;
788                 else if(direction == L"RIGHT")
789                         transitionInfo.direction = transition_direction::from_left;
790         }
791         
792         //Perform loading of the clip
793         try
794         {
795                 std::shared_ptr<core::frame_producer> pFP;
796                 
797                 static boost::wregex expr(LR"(\[(?<CHANNEL>\d+)\])", boost::regex::icase);
798                         
799                 core::diagnostics::scoped_call_context save;
800                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
801                 core::diagnostics::call_context::for_thread().layer = layer_index();
802
803                 boost::wsmatch what;
804                 if(boost::regex_match(parameters().at(0), what, expr))
805                 {
806                         auto channel_index = boost::lexical_cast<int>(what["CHANNEL"].str());
807                         pFP = reroute::create_producer(*channels().at(channel_index-1).channel); 
808                 }
809                 else
810                 {
811                         pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
812                 }
813                 
814                 if(pFP == frame_producer::empty())
815                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(parameters().size() > 0 ? parameters()[0] : L""));
816
817                 bool auto_play = contains_param(L"AUTO", parameters());
818
819                 auto pFP2 = create_transition_producer(channel()->video_format_desc().field_mode, spl::make_shared_ptr(pFP), transitionInfo);
820                 if(auto_play)
821                         channel()->stage().load(layer_index(), pFP2, false, transitionInfo.duration); // TODO: LOOP
822                 else
823                         channel()->stage().load(layer_index(), pFP2, false); // TODO: LOOP
824         
825                 
826                 SetReplyString(L"202 LOADBG OK\r\n");
827
828                 return true;
829         }
830         catch(file_not_found&)
831         {               
832                 CASPAR_LOG(error) << L"File not found. No match found for parameters. Check syntax.";
833                 SetReplyString(L"404 LOADBG ERROR\r\n");
834                 return false;
835         }
836         catch(...)
837         {
838                 CASPAR_LOG_CURRENT_EXCEPTION();
839                 SetReplyString(L"502 LOADBG FAILED\r\n");
840                 return false;
841         }
842 }
843
844 bool PauseCommand::DoExecute()
845 {
846         try
847         {
848                 channel()->stage().pause(layer_index());
849                 SetReplyString(L"202 PAUSE OK\r\n");
850                 return true;
851         }
852         catch(...)
853         {
854                 SetReplyString(L"501 PAUSE FAILED\r\n");
855         }
856
857         return false;
858 }
859
860 bool PlayCommand::DoExecute()
861 {
862         try
863         {
864                 if(!parameters().empty())
865                 {
866                         LoadbgCommand lbg(*this);
867
868                         if(!lbg.Execute())
869                                 throw std::exception();
870                 }
871
872                 channel()->stage().play(layer_index());
873                 
874                 SetReplyString(L"202 PLAY OK\r\n");
875                 return true;
876         }
877         catch(...)
878         {
879                 SetReplyString(L"501 PLAY FAILED\r\n");
880         }
881
882         return false;
883 }
884
885 bool StopCommand::DoExecute()
886 {
887         try
888         {
889                 channel()->stage().stop(layer_index());
890                 SetReplyString(L"202 STOP OK\r\n");
891                 return true;
892         }
893         catch(...)
894         {
895                 SetReplyString(L"501 STOP FAILED\r\n");
896         }
897
898         return false;
899 }
900
901 bool ClearCommand::DoExecute()
902 {
903         int index = layer_index(std::numeric_limits<int>::min());
904         if(index != std::numeric_limits<int>::min())
905                 channel()->stage().clear(index);
906         else
907                 channel()->stage().clear();
908                 
909         SetReplyString(L"202 CLEAR OK\r\n");
910
911         return true;
912 }
913
914 bool PrintCommand::DoExecute()
915 {
916         channel()->output().add(create_consumer({ L"IMAGE" }, &channel()->stage()));
917                 
918         SetReplyString(L"202 PRINT OK\r\n");
919
920         return true;
921 }
922
923 bool LogCommand::DoExecute()
924 {
925         if(boost::iequals(parameters().at(0), L"LEVEL"))
926                 log::set_log_level(parameters().at(1));
927
928         SetReplyString(L"202 LOG OK\r\n");
929
930         return true;
931 }
932
933 bool CGCommand::DoExecute()
934 {
935         try
936         {
937                 std::wstring command = boost::to_upper_copy(parameters()[0]);
938                 if(command == L"ADD")
939                         return DoExecuteAdd();
940                 else if(command == L"PLAY")
941                         return DoExecutePlay();
942                 else if(command == L"STOP")
943                         return DoExecuteStop();
944                 else if(command == L"NEXT")
945                         return DoExecuteNext();
946                 else if(command == L"REMOVE")
947                         return DoExecuteRemove();
948                 else if(command == L"CLEAR")
949                         return DoExecuteClear();
950                 else if(command == L"UPDATE")
951                         return DoExecuteUpdate();
952                 else if(command == L"INVOKE")
953                         return DoExecuteInvoke();
954                 else if(command == L"INFO")
955                         return DoExecuteInfo();
956         }
957         catch(...)
958         {
959                 CASPAR_LOG_CURRENT_EXCEPTION();
960         }
961
962         SetReplyString(L"403 CG ERROR\r\n");
963         return false;
964 }
965
966 bool CGCommand::ValidateLayer(const std::wstring& layerstring) {
967         int length = layerstring.length();
968         for(int i = 0; i < length; ++i) {
969                 if(!std::isdigit(layerstring[i])) {
970                         return false;
971                 }
972         }
973
974         return true;
975 }
976
977 bool CGCommand::DoExecuteAdd() {
978         //CG 1 ADD 0 "template_folder/templatename" [STARTLABEL] 0/1 [DATA]
979
980         int layer = 0;                          //_parameters[1]
981 //      std::wstring templateName;      //_parameters[2]
982         std::wstring label;             //_parameters[3]
983         bool bDoStart = false;          //_parameters[3] alt. _parameters[4]
984 //      std::wstring data;                      //_parameters[4] alt. _parameters[5]
985
986         if(parameters().size() < 4) 
987         {
988                 SetReplyString(L"402 CG ERROR\r\n");
989                 return false;
990         }
991         unsigned int dataIndex = 4;
992
993         if(!ValidateLayer(parameters()[1])) 
994         {
995                 SetReplyString(L"403 CG ERROR\r\n");
996                 return false;
997         }
998
999         layer = boost::lexical_cast<int>(parameters()[1]);
1000
1001         if(parameters()[3].length() > 1) 
1002         {       //read label
1003                 label = parameters()[3];
1004                 ++dataIndex;
1005
1006                 if(parameters().size() > 4 && parameters()[4].length() > 0)     //read play-on-load-flag
1007                         bDoStart = (parameters()[4][0]==L'1') ? true : false;
1008                 else 
1009                 {
1010                         SetReplyString(L"402 CG ERROR\r\n");
1011                         return false;
1012                 }
1013         }
1014         else if(parameters()[3].length() > 0) { //read play-on-load-flag
1015                 bDoStart = (parameters()[3][0]==L'1') ? true : false;
1016         }
1017         else 
1018         {
1019                 SetReplyString(L"403 CG ERROR\r\n");
1020                 return false;
1021         }
1022
1023         const wchar_t* pDataString = 0;
1024         std::wstring dataFromFile;
1025         if(parameters().size() > dataIndex) 
1026         {       //read data
1027                 const std::wstring& dataString = parameters()[dataIndex];
1028
1029                 if(dataString[0] == L'<') //the data is an XML-string
1030                         pDataString = dataString.c_str();
1031                 else 
1032                 {
1033                         //The data is not an XML-string, it must be a filename
1034                         std::wstring filename = env::data_folder();
1035                         filename.append(dataString);
1036                         filename.append(L".ftd");
1037
1038                         auto found_file = find_case_insensitive(filename);
1039
1040                         if (found_file)
1041                         {
1042                                 dataFromFile = read_file(boost::filesystem::path(*found_file));
1043                                 pDataString = dataFromFile.c_str();
1044                         }
1045                 }
1046         }
1047
1048         auto filename = parameters()[2];
1049         auto proxy = cg_registry_->get_or_create_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER), filename);
1050
1051         if (proxy == core::cg_proxy::empty())
1052         {
1053                 CASPAR_LOG(warning) << "Could not find template " << parameters()[2];
1054                 SetReplyString(L"404 CG ERROR\r\n");
1055         }
1056         else
1057         {
1058                 proxy->add(layer, filename, bDoStart, label, (pDataString != 0) ? pDataString : L"");
1059         }
1060
1061         return true;
1062 }
1063
1064 bool CGCommand::DoExecutePlay()
1065 {
1066         if(parameters().size() > 1)
1067         {
1068                 if(!ValidateLayer(parameters()[1])) 
1069                 {
1070                         SetReplyString(L"403 CG ERROR\r\n");
1071                         return false;
1072                 }
1073                 int layer = boost::lexical_cast<int>(parameters()[1]);
1074                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->play(layer);
1075         }
1076         else
1077         {
1078                 SetReplyString(L"402 CG ERROR\r\n");
1079                 return true;
1080         }
1081
1082         SetReplyString(L"202 CG OK\r\n");
1083         return true;
1084 }
1085
1086 bool CGCommand::DoExecuteStop() 
1087 {
1088         if(parameters().size() > 1)
1089         {
1090                 if(!ValidateLayer(parameters()[1])) 
1091                 {
1092                         SetReplyString(L"403 CG ERROR\r\n");
1093                         return false;
1094                 }
1095                 int layer = boost::lexical_cast<int>(parameters()[1]);
1096                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->stop(layer, 0);
1097         }
1098         else 
1099         {
1100                 SetReplyString(L"402 CG ERROR\r\n");
1101                 return true;
1102         }
1103
1104         SetReplyString(L"202 CG OK\r\n");
1105         return true;
1106 }
1107
1108 bool CGCommand::DoExecuteNext()
1109 {
1110         if(parameters().size() > 1) 
1111         {
1112                 if(!ValidateLayer(parameters()[1])) 
1113                 {
1114                         SetReplyString(L"403 CG ERROR\r\n");
1115                         return false;
1116                 }
1117
1118                 int layer = boost::lexical_cast<int>(parameters()[1]);
1119                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->next(layer);
1120         }
1121         else 
1122         {
1123                 SetReplyString(L"402 CG ERROR\r\n");
1124                 return true;
1125         }
1126
1127         SetReplyString(L"202 CG OK\r\n");
1128         return true;
1129 }
1130
1131 bool CGCommand::DoExecuteRemove() 
1132 {
1133         if(parameters().size() > 1) 
1134         {
1135                 if(!ValidateLayer(parameters()[1])) 
1136                 {
1137                         SetReplyString(L"403 CG ERROR\r\n");
1138                         return false;
1139                 }
1140
1141                 int layer = boost::lexical_cast<int>(parameters()[1]);
1142                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->remove(layer);
1143         }
1144         else 
1145         {
1146                 SetReplyString(L"402 CG ERROR\r\n");
1147                 return true;
1148         }
1149
1150         SetReplyString(L"202 CG OK\r\n");
1151         return true;
1152 }
1153
1154 bool CGCommand::DoExecuteClear() 
1155 {
1156         channel()->stage().clear(layer_index(core::cg_proxy::DEFAULT_LAYER));
1157         SetReplyString(L"202 CG OK\r\n");
1158         return true;
1159 }
1160
1161 bool CGCommand::DoExecuteUpdate() 
1162 {
1163         try
1164         {
1165                 if(!ValidateLayer(parameters().at(1)))
1166                 {
1167                         SetReplyString(L"403 CG ERROR\r\n");
1168                         return false;
1169                 }
1170                                                 
1171                 std::wstring dataString = parameters().at(2);                           
1172                 if(dataString.at(0) != L'<')
1173                 {
1174                         //The data is not an XML-string, it must be a filename
1175                         std::wstring filename = env::data_folder();
1176                         filename.append(dataString);
1177                         filename.append(L".ftd");
1178
1179                         dataString = read_file(boost::filesystem::path(filename));
1180                 }               
1181
1182                 int layer = boost::lexical_cast<int>(parameters()[1]);
1183                 cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->update(layer, dataString);
1184         }
1185         catch(...)
1186         {
1187                 SetReplyString(L"402 CG ERROR\r\n");
1188                 return true;
1189         }
1190
1191         SetReplyString(L"202 CG OK\r\n");
1192         return true;
1193 }
1194
1195 bool CGCommand::DoExecuteInvoke() 
1196 {
1197         std::wstringstream replyString;
1198         replyString << L"201 CG OK\r\n";
1199
1200         if(parameters().size() > 2)
1201         {
1202                 if(!ValidateLayer(parameters()[1]))
1203                 {
1204                         SetReplyString(L"403 CG ERROR\r\n");
1205                         return false;
1206                 }
1207                 int layer = boost::lexical_cast<int>(parameters()[1]);
1208                 auto result = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->invoke(layer, parameters()[2]);
1209                 replyString << result << L"\r\n";
1210         }
1211         else 
1212         {
1213                 SetReplyString(L"402 CG ERROR\r\n");
1214                 return true;
1215         }
1216         
1217         SetReplyString(replyString.str());
1218         return true;
1219 }
1220
1221 bool CGCommand::DoExecuteInfo() 
1222 {
1223         std::wstringstream replyString;
1224         replyString << L"201 CG OK\r\n";
1225
1226         if(parameters().size() > 1)
1227         {
1228                 if(!ValidateLayer(parameters()[1]))
1229                 {
1230                         SetReplyString(L"403 CG ERROR\r\n");
1231                         return false;
1232                 }
1233
1234                 int layer = boost::lexical_cast<int>(parameters()[1]);
1235                 auto desc = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->description(layer);
1236                 
1237                 replyString << desc << L"\r\n";
1238         }
1239         else 
1240         {
1241                 auto info = cg_registry_->get_proxy(channel(), layer_index(core::cg_proxy::DEFAULT_LAYER))->template_host_info();
1242                 replyString << info << L"\r\n";
1243         }       
1244
1245         SetReplyString(replyString.str());
1246         return true;
1247 }
1248
1249 bool DataCommand::DoExecute()
1250 {
1251         std::wstring command = boost::to_upper_copy(parameters()[0]);
1252         if(command == L"STORE")
1253                 return DoExecuteStore();
1254         else if(command == L"RETRIEVE")
1255                 return DoExecuteRetrieve();
1256         else if(command == L"REMOVE")
1257                 return DoExecuteRemove();
1258         else if(command == L"LIST")
1259                 return DoExecuteList();
1260
1261         SetReplyString(L"403 DATA ERROR\r\n");
1262         return false;
1263 }
1264
1265 bool DataCommand::DoExecuteStore() 
1266 {
1267         if(parameters().size() < 3) 
1268         {
1269                 SetReplyString(L"402 DATA STORE ERROR\r\n");
1270                 return false;
1271         }
1272
1273         std::wstring filename = env::data_folder();
1274         filename.append(parameters()[1]);
1275         filename.append(L".ftd");
1276
1277         auto data_path = boost::filesystem::path(filename).parent_path().wstring();
1278         auto found_data_path = find_case_insensitive(data_path);
1279
1280         if (found_data_path)
1281                 data_path = *found_data_path;
1282
1283         if(!boost::filesystem::exists(data_path))
1284                 boost::filesystem::create_directories(data_path);
1285
1286         auto found_filename = find_case_insensitive(filename);
1287
1288         if (found_filename)
1289                 filename = *found_filename; // Overwrite case insensitive.
1290
1291         boost::filesystem::wofstream datafile(filename);
1292         if(!datafile) 
1293         {
1294                 SetReplyString(L"501 DATA STORE FAILED\r\n");
1295                 return false;
1296         }
1297
1298         datafile << static_cast<wchar_t>(65279); // UTF-8 BOM character
1299         datafile << parameters()[2] << std::flush;
1300         datafile.close();
1301
1302         std::wstring replyString = L"202 DATA STORE OK\r\n";
1303         SetReplyString(replyString);
1304         return true;
1305 }
1306
1307 bool DataCommand::DoExecuteRetrieve() 
1308 {
1309         if(parameters().size() < 2) 
1310         {
1311                 SetReplyString(L"402 DATA RETRIEVE ERROR\r\n");
1312                 return false;
1313         }
1314
1315         std::wstring filename = env::data_folder();
1316         filename.append(parameters()[1]);
1317         filename.append(L".ftd");
1318
1319         std::wstring file_contents;
1320
1321         auto found_file = find_case_insensitive(filename);
1322
1323         if (found_file)
1324                 file_contents = read_file(boost::filesystem::path(*found_file));
1325
1326         if (file_contents.empty()) 
1327         {
1328                 SetReplyString(L"404 DATA RETRIEVE ERROR\r\n");
1329                 return false;
1330         }
1331
1332         std::wstringstream reply(L"201 DATA RETRIEVE OK\r\n");
1333
1334         std::wstringstream file_contents_stream(file_contents);
1335         std::wstring line;
1336         
1337         bool firstLine = true;
1338         while(std::getline(file_contents_stream, line))
1339         {
1340                 if(firstLine)
1341                         firstLine = false;
1342                 else
1343                         reply << "\n";
1344
1345                 reply << line;
1346         }
1347
1348         reply << "\r\n";
1349         SetReplyString(reply.str());
1350         return true;
1351 }
1352
1353 bool DataCommand::DoExecuteRemove()
1354
1355         if (parameters().size() < 2)
1356         {
1357                 SetReplyString(L"402 DATA REMOVE ERROR\r\n");
1358                 return false;
1359         }
1360
1361         std::wstring filename = env::data_folder();
1362         filename.append(parameters()[1]);
1363         filename.append(L".ftd");
1364
1365         if (!boost::filesystem::exists(filename))
1366         {
1367                 SetReplyString(L"404 DATA REMOVE ERROR\r\n");
1368                 return false;
1369         }
1370
1371         if (!boost::filesystem::remove(filename))
1372         {
1373                 SetReplyString(L"403 DATA REMOVE ERROR\r\n");
1374                 return false;
1375         }
1376
1377         SetReplyString(L"201 DATA REMOVE OK\r\n");
1378
1379         return true;
1380 }
1381
1382 bool DataCommand::DoExecuteList() 
1383 {
1384         std::wstringstream replyString;
1385         replyString << L"200 DATA LIST OK\r\n";
1386
1387         for (boost::filesystem::recursive_directory_iterator itr(env::data_folder()), end; itr != end; ++itr)
1388         {                       
1389                 if(boost::filesystem::is_regular_file(itr->path()))
1390                 {
1391                         if(!boost::iequals(itr->path().extension().wstring(), L".ftd"))
1392                                 continue;
1393                         
1394                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::data_folder().size()-1, itr->path().wstring().size()));
1395                         
1396                         auto str = relativePath.replace_extension(L"").generic_wstring();
1397                         if(str[0] == L'\\' || str[0] == L'/')
1398                                 str = std::wstring(str.begin() + 1, str.end());
1399
1400                         replyString << str << L"\r\n";
1401                 }
1402         }
1403         
1404         replyString << L"\r\n";
1405
1406         SetReplyString(boost::to_upper_copy(replyString.str()));
1407         return true;
1408 }
1409
1410 bool CinfCommand::DoExecute()
1411 {
1412         std::wstringstream replyString;
1413         
1414         try
1415         {
1416                 std::wstring info;
1417                 for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end && info.empty(); ++itr)
1418                 {
1419                         auto path = itr->path();
1420                         auto file = path.replace_extension(L"").filename().wstring();
1421                         if(boost::iequals(file, parameters().at(0)))
1422                                 info += MediaInfo(itr->path(), system_info_repo_) + L"\r\n";
1423                 }
1424
1425                 if(info.empty())
1426                 {
1427                         SetReplyString(L"404 CINF ERROR\r\n");
1428                         return false;
1429                 }
1430                 replyString << L"200 CINF OK\r\n";
1431                 replyString << info << "\r\n";
1432         }
1433         catch(...)
1434         {
1435                 CASPAR_LOG_CURRENT_EXCEPTION();
1436                 SetReplyString(L"404 CINF ERROR\r\n");
1437                 return false;
1438         }
1439         
1440         SetReplyString(replyString.str());
1441         return true;
1442 }
1443
1444 void GenerateChannelInfo(int index, const spl::shared_ptr<core::video_channel>& pChannel, std::wstringstream& replyString)
1445 {
1446         replyString << index+1 << L" " << pChannel->video_format_desc().name << L" PLAYING\r\n";
1447 }
1448
1449 bool InfoCommand::DoExecute()
1450 {
1451         std::wstringstream replyString;
1452         
1453         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
1454
1455         try
1456         {
1457                 if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"TEMPLATE"))
1458                 {               
1459                         replyString << L"201 INFO TEMPLATE OK\r\n";
1460
1461                         auto filename = parameters().at(1);
1462                                                 
1463                         std::wstringstream str;
1464                         str << u16(cg_registry_->read_meta_info(filename));
1465                         boost::property_tree::wptree info;
1466                         boost::property_tree::xml_parser::read_xml(str, info, boost::property_tree::xml_parser::trim_whitespace | boost::property_tree::xml_parser::no_comments);
1467
1468                         boost::property_tree::xml_parser::write_xml(replyString, info, w);
1469                 }
1470                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"CONFIG"))
1471                 {               
1472                         replyString << L"201 INFO CONFIG OK\r\n";
1473
1474                         boost::property_tree::write_xml(replyString, caspar::env::properties(), w);
1475                 }
1476                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"PATHS"))
1477                 {
1478                         replyString << L"201 INFO PATHS OK\r\n";
1479
1480                         boost::property_tree::wptree info;
1481                         info.add_child(L"paths", caspar::env::properties().get_child(L"configuration.paths"));
1482                         info.add(L"paths.initial-path", boost::filesystem::initial_path().wstring() + L"/");
1483
1484                         boost::property_tree::write_xml(replyString, info, w);
1485                 }
1486                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SYSTEM"))
1487                 {
1488                         replyString << L"201 INFO SYSTEM OK\r\n";
1489                         
1490                         boost::property_tree::wptree info;
1491                         
1492                         info.add(L"system.name",                                        caspar::system_product_name());
1493                         info.add(L"system.os.description",                      caspar::os_description());
1494                         info.add(L"system.cpu",                                         caspar::cpu_info());
1495
1496                         system_info_repo_->fill_information(info);
1497                                                 
1498                         boost::property_tree::write_xml(replyString, info, w);
1499                 }
1500                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SERVER"))
1501                 {
1502                         replyString << L"201 INFO SERVER OK\r\n";
1503                         
1504                         boost::property_tree::wptree info;
1505
1506                         int index = 0;
1507                         for (auto& channel : channels())
1508                                 info.add_child(L"channels.channel", channel.channel->info())
1509                                         .add(L"index", ++index);
1510                         
1511                         boost::property_tree::write_xml(replyString, info, w);
1512                 }
1513                 else // channel
1514                 {                       
1515                         if(parameters().size() >= 1)
1516                         {
1517                                 replyString << L"201 INFO OK\r\n";
1518                                 boost::property_tree::wptree info;
1519
1520                                 std::vector<std::wstring> split;
1521                                 boost::split(split, parameters()[0], boost::is_any_of("-"));
1522                                         
1523                                 int layer = std::numeric_limits<int>::min();
1524                                 int channel = boost::lexical_cast<int>(split[0]) - 1;
1525
1526                                 if(split.size() > 1)
1527                                         layer = boost::lexical_cast<int>(split[1]);
1528                                 
1529                                 if(layer == std::numeric_limits<int>::min())
1530                                 {       
1531                                         info.add_child(L"channel", channels().at(channel).channel->info())
1532                                                         .add(L"index", channel);
1533                                 }
1534                                 else
1535                                 {
1536                                         if(parameters().size() >= 2)
1537                                         {
1538                                                 if(boost::iequals(parameters()[1], L"B"))
1539                                                         info.add_child(L"producer", channels().at(channel).channel->stage().background(layer).get()->info());
1540                                                 else
1541                                                         info.add_child(L"producer", channels().at(channel).channel->stage().foreground(layer).get()->info());
1542                                         }
1543                                         else
1544                                         {
1545                                                 info.add_child(L"layer", channels().at(channel).channel->stage().info(layer).get())
1546                                                         .add(L"index", layer);
1547                                         }
1548                                 }
1549                                 boost::property_tree::xml_parser::write_xml(replyString, info, w);
1550                         }
1551                         else
1552                         {
1553                                 // This is needed for backwards compatibility with old clients
1554                                 replyString << L"200 INFO OK\r\n";
1555                                 for(size_t n = 0; n < channels().size(); ++n)
1556                                         GenerateChannelInfo(n, channels()[n].channel, replyString);
1557                         }
1558
1559                 }
1560         }
1561         catch(...)
1562         {
1563                 CASPAR_LOG_CURRENT_EXCEPTION();
1564                 SetReplyString(L"403 INFO ERROR\r\n");
1565                 return false;
1566         }
1567
1568         replyString << L"\r\n";
1569         SetReplyString(replyString.str());
1570         return true;
1571 }
1572
1573 bool ClsCommand::DoExecute()
1574 {
1575         try
1576         {
1577                 std::wstringstream replyString;
1578                 replyString << L"200 CLS OK\r\n";
1579                 replyString << ListMedia(system_info_repo_);
1580                 replyString << L"\r\n";
1581                 SetReplyString(boost::to_upper_copy(replyString.str()));
1582         }
1583         catch(...)
1584         {
1585                 CASPAR_LOG_CURRENT_EXCEPTION();
1586                 SetReplyString(L"501 CLS FAILED\r\n");
1587                 return false;
1588         }
1589
1590         return true;
1591 }
1592
1593 bool TlsCommand::DoExecute()
1594 {
1595         try
1596         {
1597                 std::wstringstream replyString;
1598                 replyString << L"200 TLS OK\r\n";
1599
1600                 replyString << ListTemplates(cg_registry_);
1601                 replyString << L"\r\n";
1602
1603                 SetReplyString(replyString.str());
1604         }
1605         catch(...)
1606         {
1607                 CASPAR_LOG_CURRENT_EXCEPTION();
1608                 SetReplyString(L"501 TLS FAILED\r\n");
1609                 return false;
1610         }
1611         return true;
1612 }
1613
1614 bool VersionCommand::DoExecute()
1615 {
1616         std::wstring replyString = L"201 VERSION OK\r\n" + env::version() + L"\r\n";
1617
1618         if (parameters().size() > 0 && !boost::iequals(parameters()[0], L"SERVER"))
1619         {
1620                 auto version = system_info_repo_->get_version(parameters().at(0));
1621
1622                 if (version.empty())
1623                         replyString = L"403 VERSION ERROR\r\n";
1624                 else
1625                         replyString = L"201 VERSION OK\r\n" + version + L"\r\n";
1626         }
1627
1628         SetReplyString(replyString);
1629         return true;
1630 }
1631
1632 bool ByeCommand::DoExecute()
1633 {
1634         client()->disconnect();
1635         return true;
1636 }
1637
1638 bool SetCommand::DoExecute()
1639 {
1640         try
1641         {
1642                 std::wstring name = boost::to_upper_copy(parameters()[0]);
1643                 std::wstring value = boost::to_upper_copy(parameters()[1]);
1644
1645                 if(name == L"MODE")
1646                 {
1647                         auto format_desc = core::video_format_desc(value);
1648                         if(format_desc.format != core::video_format::invalid)
1649                         {
1650                                 channel()->video_format_desc(format_desc);
1651                                 SetReplyString(L"202 SET MODE OK\r\n");
1652                         }
1653                         else
1654                                 SetReplyString(L"501 SET MODE FAILED\r\n");
1655                 }
1656                 else
1657                 {
1658                         this->SetReplyString(L"403 SET ERROR\r\n");
1659                 }
1660         }
1661         catch(...)
1662         {
1663                 CASPAR_LOG_CURRENT_EXCEPTION();
1664                 SetReplyString(L"501 SET FAILED\r\n");
1665                 return false;
1666         }
1667
1668         return true;
1669 }
1670
1671 bool LockCommand::DoExecute()
1672 {
1673         try
1674         {
1675                 auto it = parameters().begin();
1676
1677                 std::shared_ptr<caspar::IO::lock_container> lock;
1678                 try
1679                 {
1680                         int channel_index = boost::lexical_cast<int>(*it) - 1;
1681                         lock = channels().at(channel_index).lock;
1682                 }
1683                 catch(const boost::bad_lexical_cast&) {}
1684                 catch(...)
1685                 {
1686                         SetReplyString(L"401 LOCK ERROR\r\n");
1687                         return false;
1688                 }
1689
1690                 if(lock)
1691                         ++it;
1692
1693                 if(it == parameters().end())    //too few parameters
1694                 {
1695                         SetReplyString(L"402 LOCK ERROR\r\n");
1696                         return false;
1697                 }
1698
1699                 std::wstring command = boost::to_upper_copy(*it);
1700                 if(command == L"ACQUIRE")
1701                 {
1702                         ++it;
1703                         if(it == parameters().end())    //too few parameters
1704                         {
1705                                 SetReplyString(L"402 LOCK ACQUIRE ERROR\r\n");
1706                                 return false;
1707                         }
1708                         std::wstring lock_phrase = (*it);
1709
1710                         //TODO: read options
1711
1712                         if(lock)
1713                         {
1714                                 //just lock one channel
1715                                 if(!lock->try_lock(lock_phrase, client()))
1716                                 {
1717                                         SetReplyString(L"503 LOCK ACQUIRE FAILED\r\n");
1718                                         return false;
1719                                 }
1720                         }
1721                         else
1722                         {
1723                                 //TODO: lock all channels
1724                                 CASPAR_THROW_EXCEPTION(not_implemented());
1725                         }
1726                         SetReplyString(L"202 LOCK ACQUIRE OK\r\n");
1727
1728                 }
1729                 else if(command == L"RELEASE")
1730                 {
1731                         if(lock)
1732                         {
1733                                 lock->release_lock(client());
1734                         }
1735                         else
1736                         {
1737                                 //TODO: release all channels
1738                                 CASPAR_THROW_EXCEPTION(not_implemented());
1739                         }
1740                         SetReplyString(L"202 LOCK RELEASE OK\r\n");
1741                 }
1742                 else if(command == L"CLEAR")
1743                 {
1744                         std::wstring override_phrase = env::properties().get(L"configuration.lock-clear-phrase", L"");
1745                         std::wstring client_override_phrase;
1746                         if(!override_phrase.empty())
1747                         {
1748                                 ++it;
1749                                 if(it == parameters().end())
1750                                 {
1751                                         SetReplyString(L"402 LOCK CLEAR ERROR\r\n");
1752                                         return false;
1753                                 }
1754                                 client_override_phrase = (*it);
1755                         }
1756
1757                         if(lock)
1758                         {
1759                                 //just clear one channel
1760                                 if(client_override_phrase != override_phrase)
1761                                 {
1762                                         SetReplyString(L"503 LOCK CLEAR FAILED\r\n");
1763                                         return false;
1764                                 }
1765                                 
1766                                 lock->clear_locks();
1767                         }
1768                         else
1769                         {
1770                                 //TODO: clear all channels
1771                                 CASPAR_THROW_EXCEPTION(not_implemented());
1772                         }
1773
1774                         SetReplyString(L"202 LOCK CLEAR OK\r\n");
1775                 }
1776                 else
1777                 {
1778                         SetReplyString(L"403 LOCK ERROR\r\n");
1779                         return false;
1780                 }
1781         }
1782         catch(not_implemented&)
1783         {
1784                 SetReplyString(L"600 LOCK FAILED\r\n");
1785                 return false;
1786         }
1787         catch(...)
1788         {
1789                 CASPAR_LOG_CURRENT_EXCEPTION();
1790                 SetReplyString(L"501 LOCK FAILED\r\n");
1791                 return false;
1792         }
1793
1794         return true;
1795 }
1796
1797 bool ThumbnailCommand::DoExecute()
1798 {
1799         std::wstring command = boost::to_upper_copy(parameters()[0]);
1800
1801         if (command == L"RETRIEVE")
1802                 return DoExecuteRetrieve();
1803         else if (command == L"LIST")
1804                 return DoExecuteList();
1805         else if (command == L"GENERATE")
1806                 return DoExecuteGenerate();
1807         else if (command == L"GENERATE_ALL")
1808                 return DoExecuteGenerateAll();
1809
1810         SetReplyString(L"403 THUMBNAIL ERROR\r\n");
1811         return false;
1812 }
1813
1814 bool ThumbnailCommand::DoExecuteRetrieve() 
1815 {
1816         if(parameters().size() < 2) 
1817         {
1818                 SetReplyString(L"402 THUMBNAIL RETRIEVE ERROR\r\n");
1819                 return false;
1820         }
1821
1822         std::wstring filename = env::thumbnails_folder();
1823         filename.append(parameters()[1]);
1824         filename.append(L".png");
1825
1826         std::wstring file_contents;
1827
1828         auto found_file = find_case_insensitive(filename);
1829
1830         if (found_file)
1831                 file_contents = read_file_base64(boost::filesystem::path(*found_file));
1832
1833         if (file_contents.empty())
1834         {
1835                 SetReplyString(L"404 THUMBNAIL RETRIEVE ERROR\r\n");
1836                 return false;
1837         }
1838
1839         std::wstringstream reply;
1840
1841         reply << L"201 THUMBNAIL RETRIEVE OK\r\n";
1842         reply << file_contents;
1843         reply << L"\r\n";
1844         SetReplyString(reply.str());
1845         return true;
1846 }
1847
1848 bool ThumbnailCommand::DoExecuteList()
1849 {
1850         std::wstringstream replyString;
1851         replyString << L"200 THUMBNAIL LIST OK\r\n";
1852
1853         for (boost::filesystem::recursive_directory_iterator itr(env::thumbnails_folder()), end; itr != end; ++itr)
1854         {      
1855                 if(boost::filesystem::is_regular_file(itr->path()))
1856                 {
1857                         if(!boost::iequals(itr->path().extension().wstring(), L".png"))
1858                                 continue;
1859
1860                         auto relativePath = boost::filesystem::path(itr->path().wstring().substr(env::thumbnails_folder().size()-1, itr->path().wstring().size()));
1861
1862                         auto str = relativePath.replace_extension(L"").generic_wstring();
1863                         if(str[0] == '\\' || str[0] == '/')
1864                                 str = std::wstring(str.begin() + 1, str.end());
1865
1866                         auto mtime = boost::filesystem::last_write_time(itr->path());
1867                         auto mtime_readable = boost::posix_time::to_iso_wstring(boost::posix_time::from_time_t(mtime));
1868                         auto file_size = boost::filesystem::file_size(itr->path());
1869
1870                         replyString << L"\"" << str << L"\" " << mtime_readable << L" " << file_size << L"\r\n";
1871                 }
1872         }
1873
1874         replyString << L"\r\n";
1875
1876         SetReplyString(boost::to_upper_copy(replyString.str()));
1877         return true;
1878 }
1879
1880 bool ThumbnailCommand::DoExecuteGenerate()
1881 {
1882         if (parameters().size() < 2) 
1883         {
1884                 SetReplyString(L"402 THUMBNAIL GENERATE ERROR\r\n");
1885                 return false;
1886         }
1887
1888         if (thumb_gen_)
1889         {
1890                 thumb_gen_->generate(parameters()[1]);
1891                 SetReplyString(L"202 THUMBNAIL GENERATE OK\r\n");
1892                 return true;
1893         }
1894         else
1895         {
1896                 SetReplyString(L"500 THUMBNAIL GENERATE ERROR\r\n");
1897                 return false;
1898         }
1899 }
1900
1901 bool ThumbnailCommand::DoExecuteGenerateAll()
1902 {
1903         if (thumb_gen_)
1904         {
1905                 thumb_gen_->generate_all();
1906                 SetReplyString(L"202 THUMBNAIL GENERATE_ALL OK\r\n");
1907                 return true;
1908         }
1909         else
1910         {
1911                 SetReplyString(L"500 THUMBNAIL GENERATE_ALL ERROR\r\n");
1912                 return false;
1913         }
1914 }
1915
1916 bool KillCommand::DoExecute()
1917 {
1918         shutdown_server_now_->set_value(false); //false for not attempting to restart
1919         SetReplyString(L"202 KILL OK\r\n");
1920         return true;
1921 }
1922
1923 bool RestartCommand::DoExecute()
1924 {
1925         shutdown_server_now_->set_value(true);  //true for attempting to restart
1926         SetReplyString(L"202 RESTART OK\r\n");
1927         return true;
1928 }
1929
1930 }       //namespace amcp
1931 }}      //namespace caspar