]> git.decadent.org.uk Git - videolink.git/blob - videolink.cpp
Changed informational, warning and error messages to use standard prefixes.
[videolink.git] / videolink.cpp
1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cassert>
5 #include <cstring>
6 #include <exception>
7 #include <fstream>
8 #include <iomanip>
9 #include <iostream>
10 #include <memory>
11 #include <queue>
12 #include <set>
13 #include <sstream>
14 #include <string>
15
16 #include <stdlib.h>
17
18 #include <gdk/gdkkeysyms.h>
19 #include <gdkmm/pixbuf.h>
20 #include <glibmm/convert.h>
21 #include <glibmm/spawn.h>
22 #include <gtkmm/main.h>
23 #include <gtkmm/window.h>
24
25 #include <imglib2/ImageErrors.h>
26 #include <nsGUIEvent.h>
27 #include <nsIBoxObject.h>
28 #include <nsIContent.h>
29 #include <nsIDocShell.h>
30 #include <nsIDOMAbstractView.h>
31 #include <nsIDOMBarProp.h>
32 #include <nsIDOMDocumentEvent.h>
33 #include <nsIDOMDocumentView.h>
34 #include <nsIDOMElement.h>
35 #include <nsIDOMEventTarget.h>
36 #include <nsIDOMHTMLDocument.h>
37 #include <nsIDOMMouseEvent.h>
38 #include <nsIDOMNSDocument.h>
39 #include <nsIDOMWindow.h>
40 #include <nsIEventStateManager.h>
41 #include <nsIInterfaceRequestorUtils.h>
42 #include <nsIURI.h> // required before nsILink.h
43 #include <nsILink.h>
44 #include <nsIPrefBranch.h>
45 #include <nsPresContext.h>
46 #include <nsIPrefService.h>
47 #include <nsIPresShell.h>
48 #include <nsServiceManagerUtils.h>
49 #include <nsIWebBrowser.h>
50 #include <nsString.h>
51
52 #include "browser_widget.hpp"
53 #include "child_iterator.hpp"
54 #include "dvd.hpp"
55 #include "generate_dvd.hpp"
56 #include "geometry.hpp"
57 #include "link_iterator.hpp"
58 #include "null_prompt_service.hpp"
59 #include "pixbufs.hpp"
60 #include "style_sheets.hpp"
61 #include "temp_file.hpp"
62 #include "video.hpp"
63 #include "warp_pointer.hpp"
64 #include "x_frame_buffer.hpp"
65 #include "xml_utils.hpp"
66 #include "xpcom_support.hpp"
67
68 using xpcom_support::check;
69
70 namespace
71 {
72     rectangle get_elem_rect(nsIDOMNSDocument * ns_doc,
73                             nsIDOMElement * elem)
74     {
75         rectangle result;
76
77         // Start with this element's bounding box
78         nsCOMPtr<nsIBoxObject> box;
79         check(ns_doc->GetBoxObjectFor(elem, getter_AddRefs(box)));
80         int width, height;
81         check(box->GetScreenX(&result.left));
82         check(box->GetScreenY(&result.top));
83         check(box->GetWidth(&width));
84         check(box->GetHeight(&height));
85         result.right = result.left + width;
86         result.bottom = result.top + height;
87
88         // Merge bounding boxes of all child elements
89         for (child_iterator it = child_iterator(elem), end; it != end; ++it)
90         {
91             nsCOMPtr<nsIDOMNode> child_node(*it);
92             PRUint16 child_type;
93             if (check(child_node->GetNodeType(&child_type)),
94                 child_type == nsIDOMNode::ELEMENT_NODE)
95             {
96                 nsCOMPtr<nsIDOMElement> child_elem(
97                     do_QueryInterface(child_node));
98                 result |= get_elem_rect(ns_doc, child_elem);
99             }
100         }
101
102         return result;
103     }
104
105
106     enum video_format
107     {
108         video_format_none,
109         video_format_mpeg2_ps,
110         video_format_vob_list
111     };
112
113     video_format video_format_from_uri(const std::string & uri)
114     {
115         // FIXME: This is a bit of a hack.  Perhaps we could decide
116         // later based on the MIME type determined by Mozilla?
117         static struct {
118             const char * extension;
119             video_format format;
120         } const mapping[] = {
121             {".vob",     video_format_mpeg2_ps},
122             {".mpeg",    video_format_mpeg2_ps},
123             {".mpeg2",   video_format_mpeg2_ps},
124             {".mpg",     video_format_mpeg2_ps},
125             {".voblist", video_format_vob_list}
126         };
127         for (std::size_t i = 0;
128              i != sizeof(mapping) / sizeof(mapping[0]);
129              ++i)
130         {
131             std::size_t ext_len = std::strlen(mapping[i].extension);
132             if (uri.size() > ext_len
133                 && uri.compare(uri.size() - ext_len, ext_len,
134                                mapping[i].extension) == 0)
135                 return mapping[i].format;
136         }
137         return video_format_none;
138     }
139
140
141     class base_window : public Gtk::Window
142     {
143     public:
144         base_window(const video::frame_params & frame_params);
145
146     protected:
147         video::frame_params frame_params_;
148         browser_widget browser_widget_;
149
150     private:
151         bool on_idle();
152         virtual void do_late_initialisation() = 0;
153     };
154
155     base_window::base_window(const video::frame_params & frame_params)
156         : frame_params_(frame_params)
157     {
158         set_size_request(frame_params_.width, frame_params_.height);
159         set_resizable(false);
160
161         add(browser_widget_);
162         browser_widget_.show();
163
164         Glib::signal_idle().connect(
165             sigc::mem_fun(this, &base_window::on_idle));
166     }
167
168     bool base_window::on_idle()
169     {
170         do_late_initialisation();
171         return false; // don't call again thankyou
172     }
173
174     class preview_window : public base_window
175     {
176     public:
177         preview_window(const video::frame_params & frame_params,
178                        const std::string & main_page_uri);
179
180     private:
181         virtual void do_late_initialisation();
182         bool on_key_press(GdkEventKey *);
183
184         std::string main_page_uri_;
185     };
186
187     preview_window::preview_window(const video::frame_params & frame_params,
188                                    const std::string & main_page_uri)
189         : base_window(frame_params),
190           main_page_uri_(main_page_uri)
191     {
192         signal_key_press_event().connect(
193             sigc::mem_fun(this, &preview_window::on_key_press));
194     }
195
196     void preview_window::do_late_initialisation()
197     {
198         browser_widget_.load_uri(main_page_uri_);
199     }
200
201     bool preview_window::on_key_press(GdkEventKey * event)
202     {
203         switch (event->keyval)
204         {
205         case GDK_t: // = top menu
206             browser_widget_.load_uri(main_page_uri_);
207             return true;
208         case GDK_q: // = quit
209             Gtk::Main::quit();
210             return true;
211         default:
212             return false;
213         }
214     }
215
216     class conversion_window : public base_window
217     {
218     public:
219         conversion_window(const video::frame_params & frame_params,
220                           const std::string & main_page_uri,
221                           const std::string & output_dir,
222                           dvd_generator::mpeg_encoder encoder);
223
224         bool is_finished() const;
225
226     private:
227         struct page_state;
228
229         dvd_generator::pgc_ref add_menu(const std::string & uri);
230         dvd_generator::pgc_ref add_title(const std::string & uri,
231                                          video_format format);
232         void load_next_page();
233         void do_late_initialisation();
234         void on_net_state_change(const char * uri, gint flags, guint status);
235         bool browser_is_busy() const
236             {
237                 return pending_window_update_ || pending_req_count_;
238             }
239         // Do as much processing as possible.  Return a flag indicating
240         // whether to call again once the browser is idle.
241         bool process();
242         // Return a Pixbuf containing a copy of the window contents.
243         Glib::RefPtr<Gdk::Pixbuf> get_screenshot();
244         // Do as much processing as possible on the page links.  Return
245         // a flag indicating whether to call again once the browser is
246         // idle.
247         bool process_links(
248             page_state * state,
249             nsIDOMDocument * basic_doc,
250             nsIPresShell * pres_shell,
251             nsPresContext * pres_context,
252             nsIDOMWindow * dom_window);
253
254         std::string output_dir_;
255
256         dvd_generator generator_;
257         typedef std::map<std::string, dvd_generator::pgc_ref>
258             resource_map_type;
259         resource_map_type resource_map_;
260
261         std::queue<std::string> page_queue_;
262         bool pending_window_update_;
263         int pending_req_count_;
264         std::auto_ptr<page_state> page_state_;
265
266         bool finished_;
267     };
268
269     conversion_window::conversion_window(
270         const video::frame_params & frame_params,
271         const std::string & main_page_uri,
272         const std::string & output_dir,
273         dvd_generator::mpeg_encoder encoder)
274         : base_window(frame_params),
275           output_dir_(output_dir),
276           generator_(frame_params, encoder),
277           pending_window_update_(false),
278           pending_req_count_(0),
279           finished_(false)
280     {
281         browser_widget_.signal_net_state().connect(
282             sigc::mem_fun(this, &conversion_window::on_net_state_change));
283
284         add_menu(main_page_uri);
285     }
286
287     bool conversion_window::is_finished() const
288     {
289         return finished_;
290     }
291
292     dvd_generator::pgc_ref conversion_window::add_menu(const std::string & uri)
293     {
294         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
295         if (pgc_ref.type == dvd_generator::unknown_pgc)
296         {
297             pgc_ref = generator_.add_menu();
298             page_queue_.push(uri);
299         }
300         return pgc_ref;
301     }
302
303     dvd_generator::pgc_ref conversion_window::add_title(const std::string & uri,
304                                                       video_format format)
305     {
306         dvd_generator::pgc_ref & pgc_ref = resource_map_[uri];
307
308         if (pgc_ref.type == dvd_generator::unknown_pgc)
309         {
310             Glib::ustring hostname;
311             std::string path(Glib::filename_from_uri(uri, hostname));
312             // FIXME: Should check the hostname
313
314             vob_list list;
315
316             // Store a reference to a linked VOB file, or the contents
317             // of a linked VOB list file.
318             if (format == video_format_mpeg2_ps)
319             {
320                 if (!Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
321                     throw std::runtime_error(
322                         path + " is missing or not a regular file");
323                 vob_ref ref;
324                 ref.file = path;
325                 list.push_back(ref);
326             }
327             else if (format == video_format_vob_list)
328             {
329                 read_vob_list(path).swap(list);
330             }
331             else
332             {
333                 assert(!"unrecognised format in add_title");
334             }
335
336             pgc_ref = generator_.add_title(list);
337         }
338
339         return pgc_ref;
340     }
341
342     void conversion_window::load_next_page()
343     {
344         assert(!page_queue_.empty());
345         const std::string & uri = page_queue_.front();
346         std::cout << "INFO: Loading " << uri << std::endl;
347
348         browser_widget_.load_uri(uri);
349     }
350
351     void conversion_window::do_late_initialisation()
352     {
353         // Put pointer in the top-left so that no links appear in
354         // the hover state when we take a screenshot.
355         warp_pointer(get_window(),
356                      -frame_params_.width, -frame_params_.height);
357         
358         load_next_page();
359     }
360
361     void conversion_window::on_net_state_change(const char * uri,
362                                                 gint flags, guint status)
363     {
364 #       ifdef DEBUG_ON_NET_STATE_CHANGE
365         std::cout << "conversion_window::on_net_state_change(";
366         if (uri)
367             std::cout << '"' << uri << '"';
368         else
369             std::cout << "NULL";
370         std::cout << ", ";
371         {
372             gint flags_left = flags;
373             static const struct {
374                 gint value;
375                 const char * name;
376             } flag_names[] = {
377                 { GTK_MOZ_EMBED_FLAG_START, "STATE_START" },
378                 { GTK_MOZ_EMBED_FLAG_REDIRECTING, "STATE_REDIRECTING" },
379                 { GTK_MOZ_EMBED_FLAG_TRANSFERRING, "STATE_TRANSFERRING" },
380                 { GTK_MOZ_EMBED_FLAG_NEGOTIATING, "STATE_NEGOTIATING" },
381                 { GTK_MOZ_EMBED_FLAG_STOP, "STATE_STOP" },
382                 { GTK_MOZ_EMBED_FLAG_IS_REQUEST, "STATE_IS_REQUEST" },
383                 { GTK_MOZ_EMBED_FLAG_IS_DOCUMENT, "STATE_IS_DOCUMENT" },
384                 { GTK_MOZ_EMBED_FLAG_IS_NETWORK, "STATE_IS_NETWORK" },
385                 { GTK_MOZ_EMBED_FLAG_IS_WINDOW, "STATE_IS_WINDOW" }
386             };
387             for (int i = 0; i != sizeof(flag_names)/sizeof(flag_names[0]); ++i)
388             {
389                 if (flags & flag_names[i].value)
390                 {
391                     std::cout << flag_names[i].name;
392                     flags_left -= flag_names[i].value;
393                     if (flags_left)
394                         std::cout << " | ";
395                 }
396             }
397             if (flags_left)
398                 std::cout << "0x" << std::setbase(16) << flags_left;
399         }
400         std::cout << ", " << "0x" << std::setbase(16) << status << ")\n";
401 #       endif // DEBUG_ON_NET_STATE_CHANGE
402
403         if (flags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
404         {
405             if (flags & GTK_MOZ_EMBED_FLAG_START)
406                 ++pending_req_count_;
407
408             if (flags & GTK_MOZ_EMBED_FLAG_STOP)
409             {
410                 assert(pending_req_count_ != 0);
411                 --pending_req_count_;
412             }
413         }
414             
415         if (flags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT
416             && flags & GTK_MOZ_EMBED_FLAG_START)
417         {
418             pending_window_update_ = true;
419         }
420
421         if (flags & GTK_MOZ_EMBED_FLAG_IS_WINDOW
422             && flags & GTK_MOZ_EMBED_FLAG_STOP)
423         {
424             // Check whether the load was successful, ignoring this
425             // pseudo-error.
426             if (status != NS_IMAGELIB_ERROR_LOAD_ABORTED)
427                 check(status);
428
429             pending_window_update_ = false;
430         }
431
432         if (!browser_is_busy())
433         {
434             try
435             {
436                 if (!process())
437                 {
438                     finished_ = true;
439                     Gtk::Main::quit();
440                 }
441             }
442             catch (std::exception & e)
443             {
444                 if (!page_queue_.empty())
445                     std::cerr << "ERROR: While processing <"
446                               << page_queue_.front() << ">:\n";
447                 std::cerr << "ERROR: " << e.what() << "\n";
448                 Gtk::Main::quit();
449             }
450             catch (Glib::Exception & e)
451             {
452                 if (!page_queue_.empty())
453                     std::cerr << "ERROR: While processing <"
454                               << page_queue_.front() << ">:\n";
455                 std::cerr << "ERROR: " << e.what() << "\n";
456                 Gtk::Main::quit();
457             }
458         }
459     }
460
461     struct conversion_window::page_state
462     {
463         page_state(Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf,
464                    nsIDOMDocument * doc, int width, int height)
465                 : norm_pixbuf(norm_pixbuf),
466                   diff_pixbuf(Gdk::Pixbuf::create(
467                                   Gdk::COLORSPACE_RGB,
468                                   true, 8, // has_alpha, bits_per_sample
469                                   width, height)),
470                   links_it(doc),
471                   link_changing(false)
472             {
473             }
474
475         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
476         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
477
478         link_iterator links_it, links_end;
479
480         rectangle link_rect;
481         bool link_changing;
482     };
483
484     bool conversion_window::process()
485     {
486         assert(!page_queue_.empty());
487
488         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
489         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
490         assert(doc_shell);
491         nsCOMPtr<nsIPresShell> pres_shell;
492         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
493         nsCOMPtr<nsPresContext> pres_context;
494         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
495         nsCOMPtr<nsIDOMWindow> dom_window;
496         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
497
498         nsCOMPtr<nsIDOMDocument> basic_doc;
499         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
500
501         // Start or continue processing links.
502         std::auto_ptr<page_state> state(page_state_);
503         if (!state.get())
504             state.reset(
505                 new page_state(
506                     get_screenshot(),
507                     basic_doc, frame_params_.width, frame_params_.height));
508         if (process_links(
509                 state.get(),
510                 basic_doc, pres_shell, pres_context, dom_window))
511         {
512             // Save iteration state for later.
513             page_state_ = state;
514         }
515         else
516         {
517             // We've finished work on the links so generate the
518             // menu VOB.
519             quantise_rgba_pixbuf(state->diff_pixbuf,
520                                  dvd::button_n_colours);
521             generator_.generate_menu_vob(
522                 resource_map_[page_queue_.front()].index,
523                 state->norm_pixbuf, state->diff_pixbuf);
524
525             // Move on to the next page, if any, or else generate
526             // the DVD filesystem.
527             page_queue_.pop();
528             if (!page_queue_.empty())
529             {
530                 load_next_page();
531             }
532             else
533             {
534                 generator_.generate(output_dir_);
535                 return false;
536             }
537         }
538
539         return true;
540     }
541
542     Glib::RefPtr<Gdk::Pixbuf> conversion_window::get_screenshot()
543     {
544         Glib::RefPtr<Gdk::Window> window(get_window());
545         assert(window);
546         window->process_updates(true);
547
548         return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
549                                    window->get_colormap(),
550                                    0, 0, 0, 0,
551                                    frame_params_.width, frame_params_.height);
552     }
553
554     bool conversion_window::process_links(
555         page_state * state,
556         nsIDOMDocument * basic_doc,
557         nsIPresShell * pres_shell,
558         nsPresContext * pres_context,
559         nsIDOMWindow * dom_window)
560     {
561         Glib::RefPtr<Gdk::Window> window(get_window());
562         assert(window);
563
564         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
565         assert(ns_doc);
566         nsCOMPtr<nsIEventStateManager> event_state_man(
567             pres_context->EventStateManager()); // does not AddRef
568         assert(event_state_man);
569         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
570             do_QueryInterface(basic_doc));
571         assert(event_factory);
572         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
573         assert(doc_view);
574         nsCOMPtr<nsIDOMAbstractView> view;
575         check(doc_view->GetDefaultView(getter_AddRefs(view)));
576
577         rectangle window_rect = {
578             0, 0, frame_params_.width, frame_params_.height
579         };
580
581         unsigned menu_index = resource_map_[page_queue_.front()].index;
582
583         for (/* no initialisation */;
584              state->links_it != state->links_end;
585              ++state->links_it)
586         {
587             nsCOMPtr<nsIDOMNode> node(*state->links_it);
588
589             // Find the link URI and separate any fragment from it.
590             nsCOMPtr<nsILink> link(do_QueryInterface(node));
591             assert(link);
592             nsCOMPtr<nsIURI> uri_iface;
593             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
594             std::string uri_and_fragment, uri, fragment;
595             {
596                 nsCString uri_and_fragment_ns;
597                 check(uri_iface->GetSpec(uri_and_fragment_ns));
598                 uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
599                                         uri_and_fragment_ns.EndReading());
600
601                 std::size_t hash_pos = uri_and_fragment.find('#');
602                 uri.assign(uri_and_fragment, 0, hash_pos);
603                 if (hash_pos != std::string::npos)
604                     fragment.assign(uri_and_fragment,
605                                     hash_pos + 1, std::string::npos);
606             }
607
608             // Is this a new link?
609             if (!state->link_changing)
610             {
611                 // Find a rectangle enclosing the link and clip it to the
612                 // window.
613                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
614                 assert(elem);
615                 state->link_rect = get_elem_rect(ns_doc, elem);
616                 state->link_rect &= window_rect;
617
618                 if (state->link_rect.empty())
619                 {
620                     std::cerr << "WARN: Ignoring invisible link to "
621                               << uri_and_fragment << "\n";
622                     continue;
623                 }
624
625                 // Check whether this is a link to a video or a page then
626                 // add it to the known resources if not already seen; then
627                 // add it to the menu entries.
628                 dvd_generator::pgc_ref target;
629                 video_format format = video_format_from_uri(uri);
630                 if (format != video_format_none)
631                 {
632                     PRBool is_file;
633                     check(uri_iface->SchemeIs("file", &is_file));
634                     if (!is_file)
635                     {
636                         std::cerr << "WARN: Ignoring non-file link to "
637                                   << uri_and_fragment << "\n";
638                         continue;
639                     }
640                     target = add_title(uri, format);
641                     target.sub_index =
642                         std::strtoul(fragment.c_str(), NULL, 10);
643                 }
644                 else // video_format == video_format_none
645                 {
646                     target = add_menu(uri);
647                     // TODO: If there's a fragment, work out which button
648                     // is closest and set target.sub_index.
649                 }
650
651                 generator_.add_menu_entry(menu_index,
652                                           state->link_rect, target);
653
654                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
655                 assert(content);
656                 nsCOMPtr<nsIDOMEventTarget> event_target(
657                     do_QueryInterface(node));
658                 assert(event_target);
659
660                 nsCOMPtr<nsIDOMEvent> event;
661                 check(event_factory->CreateEvent(
662                           NS_ConvertASCIItoUTF16("MouseEvents"),
663                           getter_AddRefs(event)));
664                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
665                     do_QueryInterface(event));
666                 assert(mouse_event);
667                 check(mouse_event->InitMouseEvent(
668                           NS_ConvertASCIItoUTF16("mouseover"),
669                           true,  // can bubble
670                           true,  // cancelable
671                           view,
672                           0,     // detail: mouse click count
673                           state->link_rect.left, // screenX
674                           state->link_rect.top,  // screenY
675                           state->link_rect.left, // clientX
676                           state->link_rect.top,  // clientY
677                           false, false, false, false, // qualifiers
678                           0,     // button: left (or primary)
679                           0));   // related target
680                 PRBool dummy;
681                 check(event_target->DispatchEvent(mouse_event,
682                                                   &dummy));
683                 check(event_state_man->SetContentState(content,
684                                                        NS_EVENT_STATE_HOVER));
685
686                 pres_shell->FlushPendingNotifications(Flush_Display);
687
688                 // We may have to exit and wait for image loading
689                 // to complete, at which point we will be called
690                 // again.
691                 if (browser_is_busy())
692                 {
693                     state->link_changing = true;
694                     return true;
695                 }
696             }
697
698             window->process_updates(true);
699
700             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
701                 Gdk::Pixbuf::create(
702                     Glib::RefPtr<Gdk::Drawable>(window),
703                     window->get_colormap(),
704                     state->link_rect.left,
705                     state->link_rect.top,
706                     0,
707                     0,
708                     state->link_rect.right - state->link_rect.left,
709                     state->link_rect.bottom - state->link_rect.top));
710             diff_rgb_pixbufs(
711                 state->norm_pixbuf,
712                 changed_pixbuf,
713                 state->diff_pixbuf,
714                 state->link_rect.left,
715                 state->link_rect.top,
716                 state->link_rect.right - state->link_rect.left,
717                 state->link_rect.bottom - state->link_rect.top);
718         }
719
720         return false;
721     }
722
723     const video::frame_params & lookup_frame_params(const char * str)
724     {
725         assert(str);
726         static const char * const known_strings[] = {
727             "525",    "625",
728             "525/60", "625/50",
729             "NTSC",   "PAL",
730             "ntsc",   "pal"
731         };
732         for (std::size_t i = 0;
733              i != sizeof(known_strings)/sizeof(known_strings[0]);
734              ++i)
735             if (std::strcmp(str, known_strings[i]) == 0)
736                 return (i & 1)
737                     ? video::frame_params_625
738                     : video::frame_params_525;
739         throw std::runtime_error(
740             std::string("Invalid video standard: ").append(str));
741     }
742
743     void print_usage(std::ostream & stream, const char * command_name)
744     {
745         stream <<
746             "Usage: " << command_name << " [gtk-options] [--preview]\n"
747             "           [--video-std {525|525/60|NTSC|ntsc"
748             " | 625|625/50|PAL|pal}]\n"
749             "           [--encoder {mjpegtools|mjpegtools-old}]\n"
750             "           menu-url [output-dir]\n";
751     }
752     
753     void set_browser_preferences()
754     {
755         nsCOMPtr<nsIPrefService> pref_service;
756         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
757         check(CallGetService<nsIPrefService>(pref_service_cid,
758                                              getter_AddRefs(pref_service)));
759         nsCOMPtr<nsIPrefBranch> pref_branch;
760         check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
761
762         // Disable IE-compatibility kluge that causes backgrounds to
763         // sometimes/usually be missing from snapshots.  This is only
764         // effective from Mozilla 1.8 onward.
765         check(pref_branch->SetBoolPref(
766                   "layout.fire_onload_after_image_background_loads",
767                   true));
768
769         // Set display resolution.  With standard-definition video we
770         // will be fitting ~600 pixels across a screen typically
771         // ranging from 10 to 25 inches wide, for a resolution of
772         // 24-60 dpi.  I therefore declare the average horizontal
773         // resolution to be 40 dpi.  The vertical resolution will be
774         // slightly different but unfortunately Mozilla doesn't
775         // support non-square pixels (and neither do fontconfig or Xft
776         // anyway).
777
778         // The browser.display.screen_resolution preference sets the
779         // the nominal resolution for dimensions expressed in pixels.
780         // (They may be scaled!)  In Mozilla 1.7 it also sets the
781         // assumed resolution of the display - hence pixel sizes are
782         // respected on-screen - but this is no longer the case in
783         // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
784         // In 1.8 we need to set the assumed screen resolution
785         // separately, but don't know how yet.  Setting one to 40
786         // but not the other is *bad*, so currently we set neither.
787
788 #       if 0
789             check(pref_branch->SetIntPref("browser.display.screen_resolution",
790                                           40));
791 #       endif
792     }
793
794 } // namespace
795
796 void fatal_error(const std::string & message)
797 {
798     std::cerr << "ERROR: " << message << "\n";
799     Gtk::Main::quit();
800 }
801
802 int main(int argc, char ** argv)
803 {
804     try
805     {
806         video::frame_params frame_params = video::frame_params_625;
807         bool preview_mode = false;
808         std::string menu_url;
809         std::string output_dir;
810         dvd_generator::mpeg_encoder encoder =
811             dvd_generator::mpeg_encoder_ffmpeg;
812
813         // Do initial option parsing.  We have to do this before
814         // letting Gtk parse the arguments since we may need to spawn
815         // Xvfb first.
816         int argi = 1;
817         while (argi != argc)
818         {
819             if (std::strcmp(argv[argi], "--") == 0)
820             {
821                 break;
822             }
823             else if (std::strcmp(argv[argi], "--help") == 0)
824             {
825                 print_usage(std::cout, argv[0]);
826                 return EXIT_SUCCESS;
827             }
828             else if (std::strcmp(argv[argi], "--preview") == 0)
829             {
830                 preview_mode = true;
831                 argi += 1;
832             }
833             else if (std::strcmp(argv[argi], "--video-std") == 0)
834             {
835                 if (argi + 1 == argc)
836                 {
837                     std::cerr << "Missing argument to --video-std\n";
838                     print_usage(std::cerr, argv[0]);
839                     return EXIT_FAILURE;
840                 }
841                 frame_params = lookup_frame_params(argv[argi + 1]);
842                 argi += 2;
843             }
844             else
845             {
846                 argi += 1;
847             }
848         }
849
850         std::auto_ptr<x_frame_buffer> fb;
851         if (!preview_mode)
852         {
853             // Spawn Xvfb and set env variables so that Xlib will use it
854             // Use 8 bits each for RGB components, which should translate into
855             // "enough" bits for YUV components.
856             fb.reset(new x_frame_buffer(frame_params.width,
857                                         frame_params.height,
858                                         3 * 8));
859             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
860             setenv("DISPLAY", fb->get_display().c_str(), true);
861         }
862
863         // Initialise Gtk
864         Gtk::Main kit(argc, argv);
865
866         // Complete option parsing with Gtk's options out of the way.
867         argi = 1;
868         while (argi != argc)
869         {
870             if (std::strcmp(argv[argi], "--") == 0)
871             {
872                 argi += 1;
873                 break;
874             }
875             else if (std::strcmp(argv[argi], "--preview") == 0)
876             {
877                 argi += 1;
878             }
879             else if (std::strcmp(argv[argi], "--video-std") == 0)
880             {
881                 argi += 2;
882             }
883             else if (std::strcmp(argv[argi], "--save-temps") == 0)
884             {
885                 temp_file::keep_all(true);
886                 argi += 1;
887             }
888             else if (std::strcmp(argv[argi], "--encoder") == 0)
889             {
890                 if (argi + 1 == argc)
891                 {
892                     std::cerr << "Missing argument to --encoder\n";
893                     print_usage(std::cerr, argv[0]);
894                     return EXIT_FAILURE;
895                 }
896                 if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
897                 {
898                     encoder = dvd_generator::mpeg_encoder_ffmpeg;
899                 }
900                 else if (std::strcmp(argv[argi + 1], "mjpegtools-old") == 0)
901                 {
902                     encoder = dvd_generator::mpeg_encoder_mjpegtools_old;
903                 }
904                 else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0
905                          || std::strcmp(argv[argi + 1], "mjpegtools-new") == 0)
906                 {
907                     encoder = dvd_generator::mpeg_encoder_mjpegtools_new;
908                 }
909                 else
910                 {
911                     std::cerr << "Invalid argument to --encoder\n";
912                     print_usage(std::cerr, argv[0]);
913                     return EXIT_FAILURE;
914                 }
915                 argi += 2;
916             }
917             else if (argv[argi][0] == '-')
918             {
919                 std::cerr << "Invalid option: " << argv[argi] << "\n";
920                 print_usage(std::cerr, argv[0]);
921                 return EXIT_FAILURE;
922             }
923             else
924             {
925                 break;
926             }
927         }
928
929         // Look for a starting URL or filename and (except in preview
930         // mode) an output directory after the options.
931         if (argc - argi != (preview_mode ? 1 : 2))
932         {
933             print_usage(std::cerr, argv[0]);
934             return EXIT_FAILURE;
935         }
936         if (std::strstr(argv[argi], "://"))
937         {
938             // It appears to be an absolute URL, so use it as-is.
939             menu_url = argv[argi];
940         }
941         else
942         {
943             // Assume it's a filename.  Resolve it to an absolute URL.
944             std::string path(argv[argi]);
945             if (!Glib::path_is_absolute(path))
946                 path = Glib::build_filename(Glib::get_current_dir(), path);
947             menu_url = Glib::filename_to_uri(path);             
948         }
949         if (!preview_mode)
950             output_dir = argv[argi + 1];
951
952         // Initialise Mozilla
953         browser_widget::initialiser browser_init;
954         set_browser_preferences();
955         init_agent_style_sheet("file://" VIDEOLINK_SHARE_DIR "/videolink.css");
956         init_agent_style_sheet(std::string("file://" VIDEOLINK_SHARE_DIR "/")
957                                .append(frame_params.common_name).append(".css")
958                                .c_str());
959         if (!preview_mode)
960             null_prompt_service::install();
961
962         // Run the browser/converter
963         if (preview_mode)
964         {
965             preview_window window(frame_params, menu_url);
966             window.show();
967             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
968             Gtk::Main::run();
969             return EXIT_SUCCESS;
970         }
971         else
972         {
973             conversion_window window(frame_params, menu_url, output_dir, encoder);
974             window.show();
975             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
976             Gtk::Main::run();
977             return window.is_finished() ? EXIT_SUCCESS  : EXIT_FAILURE;
978         }
979     }
980     catch (std::exception & e)
981     {
982         std::cerr << "ERROR: " << e.what() << "\n";
983         return EXIT_FAILURE;
984     }
985 }