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