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