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