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