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