1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
13 #include <gdkmm/pixbuf.h>
14 #include <glibmm/miscutils.h>
15 #include <glibmm/spawn.h>
18 #include "generate_dvd.hpp"
19 #include "xml_utils.hpp"
23 // Return a closeness metric of an "end" rectangle to a "start"
24 // rectangle in the upward (-1) or downward (+1) direction. Given
25 // several possible "end" rectangles, the one that seems visually
26 // closest in the given direction should have the highest value of
27 // this metric. This is necessarily a heuristic function!
28 double directed_closeness(const rectangle & start, const rectangle & end,
31 // The obvious approach is to use the centres of the
32 // rectangles. However, for the "end" rectangle, using the
33 // horizontal position nearest the centre of the "start"
34 // rectangle seems to produce more reasonable results. For
35 // example, if there are two "end" rectangles equally near to
36 // the "start" rectangle in terms of vertical distance and one
37 // of them horizontally overlaps the centre of the "start"
38 // rectangle, we want to pick that one even if the centre of
39 // that rectangle is further away from the centre of the
41 int start_x = (start.left + start.right) / 2;
42 int start_y = (start.top + start.bottom) / 2;
43 int end_y = (end.top + end.bottom) / 2;
45 if (end.right < start_x)
47 else if (end.left > start_x)
52 // Return cosine of angle between the line between these points
53 // and the vertical, divided by the distance between the points
54 // if that is defined and positive; otherwise return 0.
55 int vertical_distance = (end_y - start_y) * y_dir;
56 if (vertical_distance <= 0)
58 double distance_squared =
59 (end_x - start_x) * (end_x - start_x)
60 + (end_y - start_y) * (end_y - start_y);
61 return vertical_distance / distance_squared;
64 std::string temp_file_name(const temp_dir & dir,
65 std::string base_name,
70 std::size_t index_pos = base_name.find("%3d");
71 assert(index_pos != std::string::npos);
72 base_name[index_pos] = '0' + index / 100;
73 base_name[index_pos + 1] = '0' + (index / 10) % 10;
74 base_name[index_pos + 2] = '0' + index % 10;
77 return Glib::build_filename(dir.get_name(), base_name);
80 // We would like to use just a single frame for the menu but this
81 // seems not to be legal or compatible. The minimum length of a
82 // cell is 0.4 seconds but I've seen a static menu using 12 frames
83 // on a commercial "PAL" disc so let's use 12 frames regardless.
84 unsigned menu_duration_frames(const video::frame_params & params)
88 double menu_duration_seconds(const video::frame_params & params)
90 return double(menu_duration_frames(params))
91 * double(params.rate_numer)
92 / double(params.rate_denom);
95 void throw_length_error(const char * limit_type, std::size_t limit)
97 std::ostringstream oss;
98 oss << "exceeded DVD limit: " << limit_type << " > " << limit;
99 throw std::length_error(oss.str());
103 dvd_generator::dvd_generator(const video::frame_params & frame_params,
104 mpeg_encoder encoder)
105 : temp_dir_("videolink-"),
106 frame_params_(frame_params),
110 dvd_generator::pgc_ref dvd_generator::add_menu()
112 pgc_ref next_menu(menu_pgc, menus_.size());
114 if (next_menu.index == dvd::domain_pgcs_max)
115 throw_length_error("number of menus", dvd::domain_pgcs_max);
117 menus_.resize(next_menu.index + 1);
121 void dvd_generator::add_menu_entry(unsigned index,
122 const rectangle & area,
123 const pgc_ref & target)
125 assert(index < menus_.size());
126 assert(target.type == menu_pgc && target.index < menus_.size()
127 || target.type == title_pgc && target.index < titles_.size());
129 if (menus_[index].entries.size() == dvd::menu_buttons_max)
130 throw_length_error("number of buttons", dvd::menu_buttons_max);
132 menu_entry new_entry = { area, target };
133 menus_[index].entries.push_back(new_entry);
136 void dvd_generator::generate_menu_vob(unsigned index,
137 Glib::RefPtr<Gdk::Pixbuf> background,
138 Glib::RefPtr<Gdk::Pixbuf> highlights)
141 assert(index < menus_.size());
142 const menu & this_menu = menus_[index];
144 std::string background_name(
145 temp_file_name(temp_dir_, "menu-%3d-back.png", 1 + index));
146 std::cout << "saving " << background_name << std::endl;
147 background->save(background_name, "png");
149 std::string highlights_name(
150 temp_file_name(temp_dir_, "menu-%3d-links.png", 1 + index));
151 std::cout << "saving " << highlights_name << std::endl;
152 highlights->save(highlights_name, "png");
154 std::string spumux_name(
155 temp_file_name(temp_dir_, "menu-%3d.subpictures", 1 + index));
156 std::ofstream spumux_file(spumux_name.c_str());
160 " <spu force='yes' start='00:00:00.00'\n"
161 " highlight='" << highlights_name << "'\n"
162 " select='" << highlights_name << "'>\n";
163 int button_count = this_menu.entries.size();
164 for (int i = 0; i != button_count; ++i)
166 const menu_entry & this_entry = this_menu.entries[i];
168 // We program left and right to cycle through the buttons in
169 // the order the entries were added. This should result in
170 // left and right behaving like the tab and shift-tab keys
171 // would in the browser. Hopefully that's a sensible order.
172 // We program up and down to behave geometrically.
173 int up_button = i, down_button = i;
174 double up_closeness = 0.0, down_closeness = 0.0;
175 for (int j = 0; j != button_count; ++j)
177 const menu_entry & other_entry = this_menu.entries[j];
178 double closeness = directed_closeness(
179 this_entry.area, other_entry.area, -1);
180 if (closeness > up_closeness)
183 up_closeness = closeness;
187 closeness = directed_closeness(
188 this_entry.area, other_entry.area, 1);
189 if (closeness > down_closeness)
192 down_closeness = closeness;
196 spumux_file << " <button"
197 " x0='" << this_entry.area.left << "'"
198 " y0='" << this_entry.area.top << "'"
199 " x1='" << this_entry.area.right << "'"
200 " y1='" << this_entry.area.bottom << "'"
201 " left='" << (i == 0 ? button_count : i) << "'"
202 " right='" << 1 + (i + 1) % button_count << "'"
203 " up='" << 1 + up_button << "'"
204 " down='" << 1 + down_button << "'"
213 throw std::runtime_error("Failed to write control file for spumux");
215 std::ostringstream command_stream;
216 unsigned frame_count(menu_duration_frames(frame_params_));
217 if (encoder_ == mpeg_encoder_ffmpeg)
219 for (unsigned i = 0; i != frame_count; ++i)
221 std::string frame_name(background_name);
222 frame_name.push_back('-');
223 frame_name.push_back('0' + i / 10);
224 frame_name.push_back('0' + i % 10);
225 if (symlink(background_name.c_str(), frame_name.c_str()) != 0)
226 throw std::runtime_error(
227 std::string("symlink: ").append(std::strerror(errno)));
230 "ffmpeg -f image2 -vcodec png"
231 " -r " << frame_params_.rate_numer <<
232 "/" << frame_params_.rate_denom <<
233 " -i " << background_name << "-%02d"
234 " -target " << frame_params_.common_name << "-dvd"
235 " -vcodec mpeg2video -aspect 4:3 -an -y /dev/stdout";
239 assert(encoder_ == mpeg_encoder_mjpegtools_old
240 || encoder_ == mpeg_encoder_mjpegtools_new);
242 << "pngtopnm " << background_name
243 << " | ppmtoy4m -v0 -n" << frame_count << " -F"
244 << frame_params_.rate_numer << ":" << frame_params_.rate_denom
245 << " -A" << frame_params_.pixel_ratio_width
246 << ":" << frame_params_.pixel_ratio_height
248 // The chroma subsampling keywords changed between
249 // versions 1.6.2 and 1.8 of mjpegtools. There is no
250 // keyword that works with both.
251 if (encoder_ == mpeg_encoder_mjpegtools_old)
252 command_stream << "-S420_mpeg2";
254 command_stream << "-S420mpeg2";
256 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
257 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
260 << " | spumux -v0 -mdvd " << spumux_name
261 << " > " << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + index);
262 std::string command(command_stream.str());
263 const char * argv[] = {
264 "/bin/sh", "-c", command.c_str(), 0
266 std::cout << "running " << command << std::endl;
268 Glib::spawn_sync(".",
269 Glib::ArrayHandle<std::string>(
270 argv, sizeof(argv)/sizeof(argv[0]),
271 Glib::OWNERSHIP_NONE),
272 Glib::SPAWN_STDOUT_TO_DEV_NULL,
276 if (command_result != 0)
277 throw std::runtime_error("spumux pipeline failed");
280 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
282 pgc_ref next_title(title_pgc, titles_.size());
284 // Check against maximum number of titles.
285 if (next_title.index == dvd::titles_max)
286 throw_length_error("number of titles", dvd::titles_max);
288 titles_.resize(next_title.index + 1);
289 titles_[next_title.index].swap(content);
293 void dvd_generator::generate(const std::string & output_dir) const
295 std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
296 std::ofstream file(name.c_str());
298 // We generate code that uses registers in the following way:
301 // g1: target menu location
302 // g2: source/return menu location for title
303 // g3: target chapter number
305 // All locations are divided into two bitfields: the least
306 // significant 10 bits are a page/menu number and the most
307 // significant 6 bits are a link/button number, and numbering
308 // starts at 1, not 0. This is done for compatibility with
309 // the encoding of the s8 (button) register.
311 static const int button_mult = dvd::reg_s8_button_mult;
312 static const int menu_mask = button_mult - 1;
313 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
320 for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
322 const menu & this_menu = menus_[menu_index];
326 // This is the first (title) menu, displayed when the
327 // disc is first played.
329 " <pgc entry='title'>\n"
331 // Set a default target location if none is set.
332 // This covers first play and use of the "top menu"
335 " g1 = " << 1 + button_mult << ";\n";
344 // When a title finishes or the user presses the "menu"
345 // button, this always jumps to the titleset's root menu.
346 // We want to return the user to the last menu they used.
347 // So we arrange for each titleset's root menu to return
348 // to the vmgm title menu and then dispatch from there to
349 // whatever the correct menu is. We determine the correct
350 // menu by looking at the menu part of g1.
352 file << " g0 = g1 & " << menu_mask << ";\n";
354 // There is a limit of 128 VM instructions in each PGC.
355 // Therefore in each menu's <pre> section we generate
356 // jumps to menus with numbers greater by 512, 256, 128,
357 // ..., 1 where (a) such a menu exists, (b) this menu
358 // number is divisible by twice that increment and (c) the
359 // correct menu is that or a later menu. Thus each menu
360 // has at most 10 such conditional jumps and is reachable
361 // by at most 10 jumps from the title menu. This chain of
362 // jumps might take too long on some players; this has yet
363 // to be investigated.
365 for (std::size_t menu_incr = (menu_mask + 1) / 2;
369 if (menu_index + menu_incr < menus_.size()
370 && (menu_index & (menu_incr * 2 - 1)) == 0)
373 " if (g0 ge " << 1 + menu_index + menu_incr
375 " jump menu " << 1 + menu_index + menu_incr
381 // Highlight the appropriate button.
382 " s8 = g1 & " << button_mask << ";\n"
383 // Forget the link target. If we don't do this, pressing
384 // the "top menu" button will result in jumping back to
389 << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
391 // Define a cell covering the whole menu and set a still
392 // time at the end of that, since it seems all players
393 // support that but some ignore a still time set on a PGC.
394 " <cell start='0' end='"
395 << std::fixed << std::setprecision(4)
396 << menu_duration_seconds(frame_params_) << "'"
397 " chapter='yes' pause='inf'/>\n"
400 for (unsigned button_index = 0;
401 button_index != this_menu.entries.size();
404 const pgc_ref & target = this_menu.entries[button_index].target;
406 file << " <button> ";
408 if (target.type == menu_pgc)
410 unsigned target_button_num;
412 if (target.sub_index)
414 target_button_num = target.sub_index;
418 // Look for a button on the new menu that links
419 // back to this one. If there is one, set that to
420 // be the highlighted button; otherwise, use the
422 const std::vector<menu_entry> & target_menu_entries =
423 menus_[target.index].entries;
424 pgc_ref this_pgc(menu_pgc, menu_index);
425 target_button_num = target_menu_entries.size();
426 while (target_button_num != 1
427 && (target_menu_entries[target_button_num - 1].target
433 // Set new menu location.
434 "g1 = " << (1 + target.index
435 + target_button_num * button_mult) << "; "
436 // Jump to the target menu.
437 "jump menu " << 1 + target.index << "; ";
441 assert(target.type == title_pgc);
444 // Record current menu location.
445 "g2 = " << (1 + menu_index
446 + (1 + button_index) * button_mult) << "; "
447 // Set target chapter number.
448 "g3 = " << target.sub_index << "; "
449 // Jump to the target title.
450 "jump title " << 1 + target.index << "; ";
453 file << "</button>\n";
464 // Generate a titleset for each title. This appears to make
465 // jumping to titles a whole lot simpler (but limits us to 99
467 for (unsigned title_index = 0;
468 title_index != titles_.size();
473 // Generate a dummy menu so that the "menu" button will
474 // work. This returns to the source menu via the title
477 " <pgc entry='root'>\n"
478 " <pre> g1 = g2; jump vmgm menu; </pre>\n"
485 // Count chapters in the title.
486 unsigned n_chapters = 0;
487 for (vob_list::const_iterator
488 it = titles_[title_index].begin(),
489 end = titles_[title_index].end();
493 // Chapter start times may be specified in the "chapters"
494 // attribute as a comma-separated list. If this is not
495 // specified then the beginning of each file starts a new
496 // chapter. Thus the number of chapters in each file is
497 // the number of commas in the chapter attribute, plus 1.
500 while ((pos = it->chapters.find(',', pos)) != std::string::npos)
507 // Generate jump "table" for chapters.
508 for (unsigned chapter_num = 1;
509 chapter_num <= n_chapters;
512 " if (g3 == " << chapter_num << ")\n"
513 " jump chapter " << chapter_num << ";\n";
518 for (vob_list::const_iterator
519 it = titles_[title_index].begin(),
520 end = titles_[title_index].end();
524 file << " <vob file='" << xml_escape(it->file) << "'";
525 if (!it->chapters.empty())
526 file << " chapters='" << xml_escape(it->chapters) << "'";
527 if (!it->pause.empty())
528 file << " pause='" << xml_escape(it->pause) << "'";
534 // Return to the source menu, but highlight the next button.
535 " g2 = g2 + " << button_mult << ";\n"
549 const char * argv[] = {
551 "-o", output_dir.c_str(),
556 Glib::spawn_sync(".",
557 Glib::ArrayHandle<std::string>(
558 argv, sizeof(argv)/sizeof(argv[0]),
559 Glib::OWNERSHIP_NONE),
560 Glib::SPAWN_SEARCH_PATH
561 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
565 if (command_result != 0)
566 throw std::runtime_error("dvdauthor failed");