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