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