]> git.decadent.org.uk Git - videolink.git/blob - videolink.cpp
Added ".mpg" (ugh) to recognised extensions.
[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 << "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                 std::cerr << "Fatal error";
445                 if (!page_queue_.empty())
446                     std::cerr << " while processing <" << page_queue_.front()
447                               << ">";
448                 std::cerr << ": " << e.what() << "\n";
449                 Gtk::Main::quit();
450             }
451             catch (Glib::Exception & e)
452             {
453                 std::cerr << "Fatal error";
454                 if (!page_queue_.empty())
455                     std::cerr << " while processing <" << page_queue_.front()
456                               << ">";
457                 std::cerr << ": " << e.what() << "\n";
458                 Gtk::Main::quit();
459             }
460         }
461     }
462
463     struct conversion_window::page_state
464     {
465         page_state(Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf,
466                    nsIDOMDocument * doc, int width, int height)
467                 : norm_pixbuf(norm_pixbuf),
468                   diff_pixbuf(Gdk::Pixbuf::create(
469                                   Gdk::COLORSPACE_RGB,
470                                   true, 8, // has_alpha, bits_per_sample
471                                   width, height)),
472                   links_it(doc),
473                   link_changing(false)
474             {
475             }
476
477         Glib::RefPtr<Gdk::Pixbuf> norm_pixbuf;
478         Glib::RefPtr<Gdk::Pixbuf> diff_pixbuf;
479
480         link_iterator links_it, links_end;
481
482         rectangle link_rect;
483         bool link_changing;
484     };
485
486     bool conversion_window::process()
487     {
488         assert(!page_queue_.empty());
489
490         nsCOMPtr<nsIWebBrowser> browser(browser_widget_.get_browser());
491         nsCOMPtr<nsIDocShell> doc_shell(do_GetInterface(browser));
492         assert(doc_shell);
493         nsCOMPtr<nsIPresShell> pres_shell;
494         check(doc_shell->GetPresShell(getter_AddRefs(pres_shell)));
495         nsCOMPtr<nsPresContext> pres_context;
496         check(doc_shell->GetPresContext(getter_AddRefs(pres_context)));
497         nsCOMPtr<nsIDOMWindow> dom_window;
498         check(browser->GetContentDOMWindow(getter_AddRefs(dom_window)));
499
500         nsCOMPtr<nsIDOMDocument> basic_doc;
501         check(dom_window->GetDocument(getter_AddRefs(basic_doc)));
502
503         // Start or continue processing links.
504         std::auto_ptr<page_state> state(page_state_);
505         if (!state.get())
506             state.reset(
507                 new page_state(
508                     get_screenshot(),
509                     basic_doc, frame_params_.width, frame_params_.height));
510         if (process_links(
511                 state.get(),
512                 basic_doc, pres_shell, pres_context, dom_window))
513         {
514             // Save iteration state for later.
515             page_state_ = state;
516         }
517         else
518         {
519             // We've finished work on the links so generate the
520             // menu VOB.
521             quantise_rgba_pixbuf(state->diff_pixbuf,
522                                  dvd::button_n_colours);
523             generator_.generate_menu_vob(
524                 resource_map_[page_queue_.front()].index,
525                 state->norm_pixbuf, state->diff_pixbuf);
526
527             // Move on to the next page, if any, or else generate
528             // the DVD filesystem.
529             page_queue_.pop();
530             if (!page_queue_.empty())
531             {
532                 load_next_page();
533             }
534             else
535             {
536                 generator_.generate(output_dir_);
537                 return false;
538             }
539         }
540
541         return true;
542     }
543
544     Glib::RefPtr<Gdk::Pixbuf> conversion_window::get_screenshot()
545     {
546         Glib::RefPtr<Gdk::Window> window(get_window());
547         assert(window);
548         window->process_updates(true);
549
550         return Gdk::Pixbuf::create(Glib::RefPtr<Gdk::Drawable>(window),
551                                    window->get_colormap(),
552                                    0, 0, 0, 0,
553                                    frame_params_.width, frame_params_.height);
554     }
555
556     bool conversion_window::process_links(
557         page_state * state,
558         nsIDOMDocument * basic_doc,
559         nsIPresShell * pres_shell,
560         nsPresContext * pres_context,
561         nsIDOMWindow * dom_window)
562     {
563         Glib::RefPtr<Gdk::Window> window(get_window());
564         assert(window);
565
566         nsCOMPtr<nsIDOMNSDocument> ns_doc(do_QueryInterface(basic_doc));
567         assert(ns_doc);
568         nsCOMPtr<nsIEventStateManager> event_state_man(
569             pres_context->EventStateManager()); // does not AddRef
570         assert(event_state_man);
571         nsCOMPtr<nsIDOMDocumentEvent> event_factory(
572             do_QueryInterface(basic_doc));
573         assert(event_factory);
574         nsCOMPtr<nsIDOMDocumentView> doc_view(do_QueryInterface(basic_doc));
575         assert(doc_view);
576         nsCOMPtr<nsIDOMAbstractView> view;
577         check(doc_view->GetDefaultView(getter_AddRefs(view)));
578
579         rectangle window_rect = {
580             0, 0, frame_params_.width, frame_params_.height
581         };
582
583         unsigned menu_index = resource_map_[page_queue_.front()].index;
584
585         for (/* no initialisation */;
586              state->links_it != state->links_end;
587              ++state->links_it)
588         {
589             nsCOMPtr<nsIDOMNode> node(*state->links_it);
590
591             // Find the link URI and separate any fragment from it.
592             nsCOMPtr<nsILink> link(do_QueryInterface(node));
593             assert(link);
594             nsCOMPtr<nsIURI> uri_iface;
595             check(link->GetHrefURI(getter_AddRefs(uri_iface)));
596             std::string uri_and_fragment, uri, fragment;
597             {
598                 nsCString uri_and_fragment_ns;
599                 check(uri_iface->GetSpec(uri_and_fragment_ns));
600                 uri_and_fragment.assign(uri_and_fragment_ns.BeginReading(),
601                                         uri_and_fragment_ns.EndReading());
602
603                 std::size_t hash_pos = uri_and_fragment.find('#');
604                 uri.assign(uri_and_fragment, 0, hash_pos);
605                 if (hash_pos != std::string::npos)
606                     fragment.assign(uri_and_fragment,
607                                     hash_pos + 1, std::string::npos);
608             }
609
610             // Is this a new link?
611             if (!state->link_changing)
612             {
613                 // Find a rectangle enclosing the link and clip it to the
614                 // window.
615                 nsCOMPtr<nsIDOMElement> elem(do_QueryInterface(node));
616                 assert(elem);
617                 state->link_rect = get_elem_rect(ns_doc, elem);
618                 state->link_rect &= window_rect;
619
620                 if (state->link_rect.empty())
621                 {
622                     std::cerr << "Ignoring invisible link to "
623                               << uri_and_fragment << "\n";
624                     continue;
625                 }
626
627                 // Check whether this is a link to a video or a page then
628                 // add it to the known resources if not already seen; then
629                 // add it to the menu entries.
630                 dvd_generator::pgc_ref target;
631                 video_format format = video_format_from_uri(uri);
632                 if (format != video_format_none)
633                 {
634                     PRBool is_file;
635                     check(uri_iface->SchemeIs("file", &is_file));
636                     if (!is_file)
637                     {
638                         std::cerr << "Links to video must use the file:"
639                                   << " scheme\n";
640                         continue;
641                     }
642                     target = add_title(uri, format);
643                     target.sub_index =
644                         std::strtoul(fragment.c_str(), NULL, 10);
645                 }
646                 else // video_format == video_format_none
647                 {
648                     target = add_menu(uri);
649                     // TODO: If there's a fragment, work out which button
650                     // is closest and set target.sub_index.
651                 }
652
653                 generator_.add_menu_entry(menu_index,
654                                           state->link_rect, target);
655
656                 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
657                 assert(content);
658                 nsCOMPtr<nsIDOMEventTarget> event_target(
659                     do_QueryInterface(node));
660                 assert(event_target);
661
662                 nsCOMPtr<nsIDOMEvent> event;
663                 check(event_factory->CreateEvent(
664                           NS_ConvertASCIItoUTF16("MouseEvents"),
665                           getter_AddRefs(event)));
666                 nsCOMPtr<nsIDOMMouseEvent> mouse_event(
667                     do_QueryInterface(event));
668                 assert(mouse_event);
669                 check(mouse_event->InitMouseEvent(
670                           NS_ConvertASCIItoUTF16("mouseover"),
671                           true,  // can bubble
672                           true,  // cancelable
673                           view,
674                           0,     // detail: mouse click count
675                           state->link_rect.left, // screenX
676                           state->link_rect.top,  // screenY
677                           state->link_rect.left, // clientX
678                           state->link_rect.top,  // clientY
679                           false, false, false, false, // qualifiers
680                           0,     // button: left (or primary)
681                           0));   // related target
682                 PRBool dummy;
683                 check(event_target->DispatchEvent(mouse_event,
684                                                   &dummy));
685                 check(event_state_man->SetContentState(content,
686                                                        NS_EVENT_STATE_HOVER));
687
688                 pres_shell->FlushPendingNotifications(Flush_Display);
689
690                 // We may have to exit and wait for image loading
691                 // to complete, at which point we will be called
692                 // again.
693                 if (browser_is_busy())
694                 {
695                     state->link_changing = true;
696                     return true;
697                 }
698             }
699
700             window->process_updates(true);
701
702             Glib::RefPtr<Gdk::Pixbuf> changed_pixbuf(
703                 Gdk::Pixbuf::create(
704                     Glib::RefPtr<Gdk::Drawable>(window),
705                     window->get_colormap(),
706                     state->link_rect.left,
707                     state->link_rect.top,
708                     0,
709                     0,
710                     state->link_rect.right - state->link_rect.left,
711                     state->link_rect.bottom - state->link_rect.top));
712             diff_rgb_pixbufs(
713                 state->norm_pixbuf,
714                 changed_pixbuf,
715                 state->diff_pixbuf,
716                 state->link_rect.left,
717                 state->link_rect.top,
718                 state->link_rect.right - state->link_rect.left,
719                 state->link_rect.bottom - state->link_rect.top);
720         }
721
722         return false;
723     }
724
725     const video::frame_params & lookup_frame_params(const char * str)
726     {
727         assert(str);
728         static const char * const known_strings[] = {
729             "525",    "625",
730             "525/60", "625/50",
731             "NTSC",   "PAL",
732             "ntsc",   "pal"
733         };
734         for (std::size_t i = 0;
735              i != sizeof(known_strings)/sizeof(known_strings[0]);
736              ++i)
737             if (std::strcmp(str, known_strings[i]) == 0)
738                 return (i & 1)
739                     ? video::frame_params_625
740                     : video::frame_params_525;
741         throw std::runtime_error(
742             std::string("Invalid video standard: ").append(str));
743     }
744
745     void print_usage(std::ostream & stream, const char * command_name)
746     {
747         stream <<
748             "Usage: " << command_name << " [gtk-options] [--preview]\n"
749             "           [--video-std {525|525/60|NTSC|ntsc"
750             " | 625|625/50|PAL|pal}]\n"
751             "           [--encoder {mjpegtools|mjpegtools-old}]\n"
752             "           menu-url [output-dir]\n";
753     }
754     
755     void set_browser_preferences()
756     {
757         nsCOMPtr<nsIPrefService> pref_service;
758         static const nsCID pref_service_cid = NS_PREFSERVICE_CID;
759         check(CallGetService<nsIPrefService>(pref_service_cid,
760                                              getter_AddRefs(pref_service)));
761         nsCOMPtr<nsIPrefBranch> pref_branch;
762         check(pref_service->GetBranch("", getter_AddRefs(pref_branch)));
763
764         // Disable IE-compatibility kluge that causes backgrounds to
765         // sometimes/usually be missing from snapshots.  This is only
766         // effective from Mozilla 1.8 onward.
767         check(pref_branch->SetBoolPref(
768                   "layout.fire_onload_after_image_background_loads",
769                   true));
770
771         // Set display resolution.  With standard-definition video we
772         // will be fitting ~600 pixels across a screen typically
773         // ranging from 10 to 25 inches wide, for a resolution of
774         // 24-60 dpi.  I therefore declare the average horizontal
775         // resolution to be 40 dpi.  The vertical resolution will be
776         // slightly different but unfortunately Mozilla doesn't
777         // support non-square pixels (and neither do fontconfig or Xft
778         // anyway).
779
780         // The browser.display.screen_resolution preference sets the
781         // the nominal resolution for dimensions expressed in pixels.
782         // (They may be scaled!)  In Mozilla 1.7 it also sets the
783         // assumed resolution of the display - hence pixel sizes are
784         // respected on-screen - but this is no longer the case in
785         // 1.8.  Therefore it was renamed to layout.css.dpi in 1.8.1.
786         // In 1.8 we need to set the assumed screen resolution
787         // separately, but don't know how yet.  Setting one to 40
788         // but not the other is *bad*, so currently we set neither.
789
790 #       if 0
791             check(pref_branch->SetIntPref("browser.display.screen_resolution",
792                                           40));
793 #       endif
794     }
795
796 } // namespace
797
798 void fatal_error(const std::string & message)
799 {
800     std::cerr << "Fatal error: " << message << "\n";
801     Gtk::Main::quit();
802 }
803
804 int main(int argc, char ** argv)
805 {
806     try
807     {
808         video::frame_params frame_params = video::frame_params_625;
809         bool preview_mode = false;
810         std::string menu_url;
811         std::string output_dir;
812         dvd_generator::mpeg_encoder encoder =
813             dvd_generator::mpeg_encoder_ffmpeg;
814
815         // Do initial option parsing.  We have to do this before
816         // letting Gtk parse the arguments since we may need to spawn
817         // Xvfb first.
818         int argi = 1;
819         while (argi != argc)
820         {
821             if (std::strcmp(argv[argi], "--") == 0)
822             {
823                 break;
824             }
825             else if (std::strcmp(argv[argi], "--help") == 0)
826             {
827                 print_usage(std::cout, argv[0]);
828                 return EXIT_SUCCESS;
829             }
830             else if (std::strcmp(argv[argi], "--preview") == 0)
831             {
832                 preview_mode = true;
833                 argi += 1;
834             }
835             else if (std::strcmp(argv[argi], "--video-std") == 0)
836             {
837                 if (argi + 1 == argc)
838                 {
839                     std::cerr << "Missing argument to --video-std\n";
840                     print_usage(std::cerr, argv[0]);
841                     return EXIT_FAILURE;
842                 }
843                 frame_params = lookup_frame_params(argv[argi + 1]);
844                 argi += 2;
845             }
846             else
847             {
848                 argi += 1;
849             }
850         }
851
852         std::auto_ptr<x_frame_buffer> fb;
853         if (!preview_mode)
854         {
855             // Spawn Xvfb and set env variables so that Xlib will use it
856             // Use 8 bits each for RGB components, which should translate into
857             // "enough" bits for YUV components.
858             fb.reset(new x_frame_buffer(frame_params.width,
859                                         frame_params.height,
860                                         3 * 8));
861             setenv("XAUTHORITY", fb->get_authority().c_str(), true);
862             setenv("DISPLAY", fb->get_display().c_str(), true);
863         }
864
865         // Initialise Gtk
866         Gtk::Main kit(argc, argv);
867
868         // Complete option parsing with Gtk's options out of the way.
869         argi = 1;
870         while (argi != argc)
871         {
872             if (std::strcmp(argv[argi], "--") == 0)
873             {
874                 argi += 1;
875                 break;
876             }
877             else if (std::strcmp(argv[argi], "--preview") == 0)
878             {
879                 argi += 1;
880             }
881             else if (std::strcmp(argv[argi], "--video-std") == 0)
882             {
883                 argi += 2;
884             }
885             else if (std::strcmp(argv[argi], "--save-temps") == 0)
886             {
887                 temp_file::keep_all(true);
888                 argi += 1;
889             }
890             else if (std::strcmp(argv[argi], "--encoder") == 0)
891             {
892                 if (argi + 1 == argc)
893                 {
894                     std::cerr << "Missing argument to --encoder\n";
895                     print_usage(std::cerr, argv[0]);
896                     return EXIT_FAILURE;
897                 }
898                 if (std::strcmp(argv[argi + 1], "ffmpeg") == 0)
899                 {
900                     encoder = dvd_generator::mpeg_encoder_ffmpeg;
901                 }
902                 else if (std::strcmp(argv[argi + 1], "mjpegtools-old") == 0)
903                 {
904                     encoder = dvd_generator::mpeg_encoder_mjpegtools_old;
905                 }
906                 else if (std::strcmp(argv[argi + 1], "mjpegtools") == 0
907                          || std::strcmp(argv[argi + 1], "mjpegtools-new") == 0)
908                 {
909                     encoder = dvd_generator::mpeg_encoder_mjpegtools_new;
910                 }
911                 else
912                 {
913                     std::cerr << "Invalid argument to --encoder\n";
914                     print_usage(std::cerr, argv[0]);
915                     return EXIT_FAILURE;
916                 }
917                 argi += 2;
918             }
919             else if (argv[argi][0] == '-')
920             {
921                 std::cerr << "Invalid option: " << argv[argi] << "\n";
922                 print_usage(std::cerr, argv[0]);
923                 return EXIT_FAILURE;
924             }
925             else
926             {
927                 break;
928             }
929         }
930
931         // Look for a starting URL or filename and (except in preview
932         // mode) an output directory after the options.
933         if (argc - argi != (preview_mode ? 1 : 2))
934         {
935             print_usage(std::cerr, argv[0]);
936             return EXIT_FAILURE;
937         }
938         if (std::strstr(argv[argi], "://"))
939         {
940             // It appears to be an absolute URL, so use it as-is.
941             menu_url = argv[argi];
942         }
943         else
944         {
945             // Assume it's a filename.  Resolve it to an absolute URL.
946             std::string path(argv[argi]);
947             if (!Glib::path_is_absolute(path))
948                 path = Glib::build_filename(Glib::get_current_dir(), path);
949             menu_url = Glib::filename_to_uri(path);             
950         }
951         if (!preview_mode)
952             output_dir = argv[argi + 1];
953
954         // Initialise Mozilla
955         browser_widget::initialiser browser_init;
956         set_browser_preferences();
957         init_agent_style_sheet("file://" VIDEOLINK_SHARE_DIR "/videolink.css");
958         init_agent_style_sheet(std::string("file://" VIDEOLINK_SHARE_DIR "/")
959                                .append(frame_params.common_name).append(".css")
960                                .c_str());
961         if (!preview_mode)
962             null_prompt_service::install();
963
964         // Run the browser/converter
965         if (preview_mode)
966         {
967             preview_window window(frame_params, menu_url);
968             window.show();
969             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
970             Gtk::Main::run();
971             return EXIT_SUCCESS;
972         }
973         else
974         {
975             conversion_window window(frame_params, menu_url, output_dir, encoder);
976             window.show();
977             window.signal_hide().connect(sigc::ptr_fun(Gtk::Main::quit));
978             Gtk::Main::run();
979             return window.is_finished() ? EXIT_SUCCESS  : EXIT_FAILURE;
980         }
981     }
982     catch (std::exception & e)
983     {
984         std::cerr << "Fatal error: " << e.what() << "\n";
985         return EXIT_FAILURE;
986     }
987 }