Merge branch 'master' of ssh://git.carlh.net/home/carl/git/dcpomatic
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic 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 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic 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 DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.h"
27 #include "dcp_content_type.h"
28 #include "filter.h"
29 #include "cinema_sound_processor.h"
30 #include "config.h"
31 #include "ratio.h"
32 #include "job.h"
33 #include "cross.h"
34 #include "video_content.h"
35 #include "rect.h"
36 #include "digester.h"
37 #include "audio_processor.h"
38 #include "compose.hpp"
39 #include "audio_buffers.h"
40 #include <dcp/locale_convert.h>
41 #include <dcp/util.h>
42 #include <dcp/raw_convert.h>
43 #include <dcp/picture_asset.h>
44 #include <dcp/sound_asset.h>
45 #include <dcp/subtitle_asset.h>
46 extern "C" {
47 #include <libavfilter/avfilter.h>
48 #include <libavformat/avformat.h>
49 #include <libavcodec/avcodec.h>
50 }
51 #include <curl/curl.h>
52 #ifdef DCPOMATIC_GRAPHICS_MAGICK
53 #include <Magick++.h>
54 #endif
55 #include <glib.h>
56 #include <pangomm/init.h>
57 #include <boost/algorithm/string.hpp>
58 #include <boost/range/algorithm/replace_if.hpp>
59 #include <boost/thread.hpp>
60 #include <boost/filesystem.hpp>
61 #ifdef DCPOMATIC_WINDOWS
62 #include <boost/locale.hpp>
63 #include <dbghelp.h>
64 #endif
65 #include <signal.h>
66 #include <iomanip>
67 #include <iostream>
68 #include <fstream>
69 #include <climits>
70 #include <stdexcept>
71 #ifdef DCPOMATIC_POSIX
72 #include <execinfo.h>
73 #include <cxxabi.h>
74 #endif
75
76 #include "i18n.h"
77
78 using std::string;
79 using std::setfill;
80 using std::ostream;
81 using std::endl;
82 using std::vector;
83 using std::min;
84 using std::max;
85 using std::map;
86 using std::list;
87 using std::multimap;
88 using std::istream;
89 using std::pair;
90 using std::cout;
91 using std::bad_alloc;
92 using std::set_terminate;
93 using std::make_pair;
94 using boost::shared_ptr;
95 using boost::thread;
96 using boost::optional;
97 using boost::lexical_cast;
98 using boost::bad_lexical_cast;
99 using dcp::Size;
100 using dcp::raw_convert;
101 using dcp::locale_convert;
102
103 /** Path to our executable, required by the stacktrace stuff and filled
104  *  in during App::onInit().
105  */
106 string program_name;
107 bool is_batch_converter = false;
108 static boost::thread::id ui_thread;
109 static boost::filesystem::path backtrace_file;
110
111 /** Convert some number of seconds to a string representation
112  *  in hours, minutes and seconds.
113  *
114  *  @param s Seconds.
115  *  @return String of the form H:M:S (where H is hours, M
116  *  is minutes and S is seconds).
117  */
118 string
119 seconds_to_hms (int s)
120 {
121         int m = s / 60;
122         s -= (m * 60);
123         int h = m / 60;
124         m -= (h * 60);
125
126         char buffer[64];
127         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
128         return buffer;
129 }
130
131 string
132 time_to_hmsf (DCPTime time, Frame rate)
133 {
134         Frame f = time.frames_round (rate);
135         int s = f / rate;
136         f -= (s * rate);
137         int m = s / 60;
138         s -= m * 60;
139         int h = m / 60;
140         m -= h * 60;
141
142         char buffer[64];
143         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
144         return buffer;
145 }
146
147 /** @param s Number of seconds.
148  *  @return String containing an approximate description of s (e.g. "about 2 hours")
149  */
150 string
151 seconds_to_approximate_hms (int s)
152 {
153         int m = s / 60;
154         s -= (m * 60);
155         int h = m / 60;
156         m -= (h * 60);
157
158         string ap;
159
160         bool hours = h > 0;
161         bool minutes = h < 6 && m > 0;
162         bool seconds = h == 0 && m < 10 && s > 0;
163
164         if (m > 30 && !minutes) {
165                 /* round up the hours */
166                 ++h;
167         }
168         if (s > 30 && !seconds) {
169                 /* round up the minutes */
170                 ++m;
171                 if (m == 60) {
172                         m = 0;
173                         minutes = false;
174                         ++h;
175                 }
176         }
177
178         if (hours) {
179                 /// TRANSLATORS: h here is an abbreviation for hours
180                 ap += locale_convert<string>(h) + _("h");
181
182                 if (minutes || seconds) {
183                         ap += N_(" ");
184                 }
185         }
186
187         if (minutes) {
188                 /// TRANSLATORS: m here is an abbreviation for minutes
189                 ap += locale_convert<string>(m) + _("m");
190
191                 if (seconds) {
192                         ap += N_(" ");
193                 }
194         }
195
196         if (seconds) {
197                 /* Seconds */
198                 /// TRANSLATORS: s here is an abbreviation for seconds
199                 ap += locale_convert<string>(s) + _("s");
200         }
201
202         return ap;
203 }
204
205 double
206 seconds (struct timeval t)
207 {
208         return t.tv_sec + (double (t.tv_usec) / 1e6);
209 }
210
211 #ifdef DCPOMATIC_WINDOWS
212
213 /** Resolve symbol name and source location given the path to the executable */
214 int
215 addr2line (void const * const addr)
216 {
217         char addr2line_cmd[512] = { 0 };
218         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
219         return system(addr2line_cmd);
220 }
221
222 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
223  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
224  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
225  */
226 LONG WINAPI
227 exception_handler(struct _EXCEPTION_POINTERS * info)
228 {
229         FILE* f = fopen_boost (backtrace_file, "w");
230         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
231         fclose(f);
232
233         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
234                 CONTEXT* context = info->ContextRecord;
235                 SymInitialize (GetCurrentProcess (), 0, true);
236
237                 STACKFRAME frame = { 0 };
238
239                 /* setup initial stack frame */
240 #if _WIN64
241                 frame.AddrPC.Offset    = context->Rip;
242                 frame.AddrStack.Offset = context->Rsp;
243                 frame.AddrFrame.Offset = context->Rbp;
244 #else
245                 frame.AddrPC.Offset    = context->Eip;
246                 frame.AddrStack.Offset = context->Esp;
247                 frame.AddrFrame.Offset = context->Ebp;
248 #endif
249                 frame.AddrPC.Mode      = AddrModeFlat;
250                 frame.AddrStack.Mode   = AddrModeFlat;
251                 frame.AddrFrame.Mode   = AddrModeFlat;
252
253                 while (
254                         StackWalk (
255                                 IMAGE_FILE_MACHINE_I386,
256                                 GetCurrentProcess (),
257                                 GetCurrentThread (),
258                                 &frame,
259                                 context,
260                                 0,
261                                 SymFunctionTableAccess,
262                                 SymGetModuleBase,
263                                 0
264                                 )
265                         ) {
266                         addr2line((void *) frame.AddrPC.Offset);
267                 }
268         } else {
269 #ifdef _WIN64
270                 addr2line ((void *) info->ContextRecord->Rip);
271 #else
272                 addr2line ((void *) info->ContextRecord->Eip);
273 #endif
274         }
275
276         return EXCEPTION_CONTINUE_SEARCH;
277 }
278 #endif
279
280 void
281 set_backtrace_file (boost::filesystem::path p)
282 {
283         backtrace_file = p;
284 }
285
286 /** This is called when there is an unhandled exception.  Any
287  *  backtrace in this function is useless on Windows as the stack has
288  *  already been unwound from the throw; we have the gdb wrap hack to
289  *  cope with that.
290  */
291 void
292 terminate ()
293 {
294         try {
295                 static bool tried_throw = false;
296                 // try once to re-throw currently active exception
297                 if (!tried_throw) {
298                         tried_throw = true;
299                         throw;
300                 }
301         }
302         catch (const std::exception &e) {
303                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
304                           << e.what() << std::endl;
305         }
306         catch (...) {
307                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
308                           << std::endl;
309         }
310
311         abort();
312 }
313
314 void
315 dcpomatic_setup_path_encoding ()
316 {
317 #ifdef DCPOMATIC_WINDOWS
318         /* Dark voodoo which, I think, gets boost::filesystem::path to
319            correctly convert UTF-8 strings to paths, and also paths
320            back to UTF-8 strings (on path::string()).
321
322            After this, constructing boost::filesystem::paths from strings
323            converts from UTF-8 to UTF-16 inside the path.  Then
324            path::string().c_str() gives UTF-8 and
325            path::c_str()          gives UTF-16.
326
327            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
328            so things are much simpler.
329         */
330         std::locale::global (boost::locale::generator().generate (""));
331         boost::filesystem::path::imbue (std::locale ());
332 #endif
333 }
334
335 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
336  *  Must be called from the UI thread, if there is one.
337  */
338 void
339 dcpomatic_setup ()
340 {
341 #ifdef DCPOMATIC_WINDOWS
342         boost::filesystem::path p = g_get_user_config_dir ();
343         p /= "backtrace.txt";
344         set_backtrace_file (p);
345         SetUnhandledExceptionFilter(exception_handler);
346 #endif
347
348         av_register_all ();
349         avfilter_register_all ();
350
351 #ifdef DCPOMATIC_OSX
352         /* Add our library directory to the libltdl search path so that
353            xmlsec can find xmlsec1-openssl.
354         */
355         boost::filesystem::path lib = app_contents ();
356         lib /= "Frameworks";
357         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
358 #endif
359
360         set_terminate (terminate);
361
362         Pango::init ();
363         dcp::init ();
364
365         Ratio::setup_ratios ();
366         PresetColourConversion::setup_colour_conversion_presets ();
367         VideoContentScale::setup_scales ();
368         DCPContentType::setup_dcp_content_types ();
369         Filter::setup_filters ();
370         CinemaSoundProcessor::setup_cinema_sound_processors ();
371         AudioProcessor::setup_audio_processors ();
372
373         curl_global_init (CURL_GLOBAL_ALL);
374
375 #ifdef DCPOMATIC_GRAPHICS_MAGICK
376         Magick::InitializeMagick (0);
377 #endif
378
379         ui_thread = boost::this_thread::get_id ();
380 }
381
382 #ifdef DCPOMATIC_WINDOWS
383 boost::filesystem::path
384 mo_path ()
385 {
386         wchar_t buffer[512];
387         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
388         boost::filesystem::path p (buffer);
389         p = p.parent_path ();
390         p = p.parent_path ();
391         p /= "locale";
392         return p;
393 }
394 #endif
395
396 #ifdef DCPOMATIC_OSX
397 boost::filesystem::path
398 mo_path ()
399 {
400         return "DCP-o-matic 2.app/Contents/Resources";
401 }
402 #endif
403
404 void
405 dcpomatic_setup_gettext_i18n (string lang)
406 {
407 #ifdef DCPOMATIC_LINUX
408         lang += ".UTF8";
409 #endif
410
411         if (!lang.empty ()) {
412                 /* Override our environment language.  Note that the caller must not
413                    free the string passed into putenv().
414                 */
415                 string s = String::compose ("LANGUAGE=%1", lang);
416                 putenv (strdup (s.c_str ()));
417                 s = String::compose ("LANG=%1", lang);
418                 putenv (strdup (s.c_str ()));
419                 s = String::compose ("LC_ALL=%1", lang);
420                 putenv (strdup (s.c_str ()));
421         }
422
423         setlocale (LC_ALL, "");
424         textdomain ("libdcpomatic2");
425
426 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
427         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
428         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
429 #endif
430
431 #ifdef DCPOMATIC_LINUX
432         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
433 #endif
434 }
435
436 /** Compute a digest of the first and last `size' bytes of a set of files. */
437 string
438 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
439 {
440         boost::scoped_array<char> buffer (new char[size]);
441         Digester digester;
442
443         /* Head */
444         boost::uintmax_t to_do = size;
445         char* p = buffer.get ();
446         int i = 0;
447         while (i < int64_t (files.size()) && to_do > 0) {
448                 FILE* f = fopen_boost (files[i], "rb");
449                 if (!f) {
450                         throw OpenFileError (files[i].string(), errno, true);
451                 }
452
453                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
454                 fread (p, 1, this_time, f);
455                 p += this_time;
456                 to_do -= this_time;
457                 fclose (f);
458
459                 ++i;
460         }
461         digester.add (buffer.get(), size - to_do);
462
463         /* Tail */
464         to_do = size;
465         p = buffer.get ();
466         i = files.size() - 1;
467         while (i >= 0 && to_do > 0) {
468                 FILE* f = fopen_boost (files[i], "rb");
469                 if (!f) {
470                         throw OpenFileError (files[i].string(), errno, true);
471                 }
472
473                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
474                 dcpomatic_fseek (f, -this_time, SEEK_END);
475                 fread (p, 1, this_time, f);
476                 p += this_time;
477                 to_do -= this_time;
478                 fclose (f);
479
480                 --i;
481         }
482         digester.add (buffer.get(), size - to_do);
483
484         return digester.get ();
485 }
486
487 /** Round a number up to the nearest multiple of another number.
488  *  @param c Index.
489  *  @param stride Array of numbers to round, indexed by c.
490  *  @param t Multiple to round to.
491  *  @return Rounded number.
492  */
493 int
494 stride_round_up (int c, int const * stride, int t)
495 {
496         int const a = stride[c] + (t - 1);
497         return a - (a % t);
498 }
499
500 /** Trip an assert if the caller is not in the UI thread */
501 void
502 ensure_ui_thread ()
503 {
504         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
505 }
506
507 string
508 audio_channel_name (int c)
509 {
510         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
511
512         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
513         /// enhancement channel (sub-woofer).
514         string const channels[] = {
515                 _("Left"),
516                 _("Right"),
517                 _("Centre"),
518                 _("Lfe (sub)"),
519                 _("Left surround"),
520                 _("Right surround"),
521                 _("Hearing impaired"),
522                 _("Visually impaired"),
523                 _("Left centre"),
524                 _("Right centre"),
525                 _("Left rear surround"),
526                 _("Right rear surround"),
527                 _("D-BOX primary"),
528                 _("D-BOX secondary"),
529                 _("Unused"),
530                 _("Unused")
531         };
532
533         return channels[c];
534 }
535
536 string
537 short_audio_channel_name (int c)
538 {
539         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
540
541         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
542         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
543         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
544         /// primary channel and DBS is the D-BOX secondary channel.
545         string const channels[] = {
546                 _("L"),
547                 _("R"),
548                 _("C"),
549                 _("Lfe"),
550                 _("Ls"),
551                 _("Rs"),
552                 _("HI"),
553                 _("VI"),
554                 _("Lc"),
555                 _("Rc"),
556                 _("BsL"),
557                 _("BsR"),
558                 _("DBP"),
559                 _("DBS"),
560                 "",
561                 ""
562         };
563
564         return channels[c];
565 }
566
567
568 bool
569 valid_image_file (boost::filesystem::path f)
570 {
571         if (boost::starts_with (f.leaf().string(), "._")) {
572                 return false;
573         }
574
575         string ext = f.extension().string();
576         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
577         return (
578                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
579                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
580                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr"
581                 );
582 }
583
584 bool
585 valid_sound_file (boost::filesystem::path f)
586 {
587         if (boost::starts_with (f.leaf().string(), "._")) {
588                 return false;
589         }
590
591         string ext = f.extension().string();
592         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
593         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
594 }
595
596 bool
597 valid_j2k_file (boost::filesystem::path f)
598 {
599         string ext = f.extension().string();
600         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
601         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
602 }
603
604 string
605 tidy_for_filename (string f)
606 {
607         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
608         return f;
609 }
610
611 dcp::Size
612 fit_ratio_within (float ratio, dcp::Size full_frame)
613 {
614         if (ratio < full_frame.ratio ()) {
615                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
616         }
617
618         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
619 }
620
621 void *
622 wrapped_av_malloc (size_t s)
623 {
624         void* p = av_malloc (s);
625         if (!p) {
626                 throw bad_alloc ();
627         }
628         return p;
629 }
630
631 map<string, string>
632 split_get_request (string url)
633 {
634         enum {
635                 AWAITING_QUESTION_MARK,
636                 KEY,
637                 VALUE
638         } state = AWAITING_QUESTION_MARK;
639
640         map<string, string> r;
641         string k;
642         string v;
643         for (size_t i = 0; i < url.length(); ++i) {
644                 switch (state) {
645                 case AWAITING_QUESTION_MARK:
646                         if (url[i] == '?') {
647                                 state = KEY;
648                         }
649                         break;
650                 case KEY:
651                         if (url[i] == '=') {
652                                 v.clear ();
653                                 state = VALUE;
654                         } else {
655                                 k += url[i];
656                         }
657                         break;
658                 case VALUE:
659                         if (url[i] == '&') {
660                                 r.insert (make_pair (k, v));
661                                 k.clear ();
662                                 state = KEY;
663                         } else {
664                                 v += url[i];
665                         }
666                         break;
667                 }
668         }
669
670         if (state == VALUE) {
671                 r.insert (make_pair (k, v));
672         }
673
674         return r;
675 }
676
677 string
678 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
679 {
680         dcp::NameFormat::Map values;
681         values['t'] = "j2c";
682         values['r'] = raw_convert<string> (reel_index + 1);
683         values['n'] = raw_convert<string> (reel_count);
684         if (summary) {
685                 values['c'] = careful_string_filter (summary.get());
686         }
687         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
688 }
689
690 string
691 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
692 {
693         dcp::NameFormat::Map values;
694         values['t'] = "pcm";
695         values['r'] = raw_convert<string> (reel_index + 1);
696         values['n'] = raw_convert<string> (reel_count);
697         if (summary) {
698                 values['c'] = careful_string_filter (summary.get());
699         }
700         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
701 }
702
703 float
704 relaxed_string_to_float (string s)
705 {
706         try {
707                 boost::algorithm::replace_all (s, ",", ".");
708                 return lexical_cast<float> (s);
709         } catch (bad_lexical_cast) {
710                 boost::algorithm::replace_all (s, ".", ",");
711                 return lexical_cast<float> (s);
712         }
713 }
714
715 string
716 careful_string_filter (string s)
717 {
718         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
719            There's no apparent list of what really is allowed, so this is a guess.
720            Safety first and all that.
721         */
722
723         string out;
724         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
725         for (size_t i = 0; i < s.size(); ++i) {
726                 if (allowed.find (s[i]) != string::npos) {
727                         out += s[i];
728                 }
729         }
730
731         return out;
732 }
733
734 /** @param mapped List of mapped audio channels from a Film.
735  *  @param channels Total number of channels in the Film.
736  *  @return First: number of non-LFE channels, second: number of LFE channels.
737  */
738 pair<int, int>
739 audio_channel_types (list<int> mapped, int channels)
740 {
741         int non_lfe = 0;
742         int lfe = 0;
743
744         BOOST_FOREACH (int i, mapped) {
745                 if (i >= channels) {
746                         /* This channel is mapped but is not included in the DCP */
747                         continue;
748                 }
749
750                 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
751                         ++lfe;
752                 } else {
753                         ++non_lfe;
754                 }
755         }
756
757         return make_pair (non_lfe, lfe);
758 }
759
760 shared_ptr<AudioBuffers>
761 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
762 {
763         shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
764         mapped->make_silent ();
765
766         for (int i = 0; i < map.input_channels(); ++i) {
767                 for (int j = 0; j < mapped->channels(); ++j) {
768                         if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
769                                 mapped->accumulate_channel (
770                                         input.get(),
771                                         i,
772                                         static_cast<dcp::Channel> (j),
773                                         map.get (i, static_cast<dcp::Channel> (j))
774                                         );
775                         }
776                 }
777         }
778
779         return mapped;
780 }
781
782 Eyes
783 increment_eyes (Eyes e)
784 {
785         if (e == EYES_LEFT) {
786                 return EYES_RIGHT;
787         }
788
789         return EYES_LEFT;
790 }