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);
96 dvd_generator::dvd_generator(const video::frame_params & frame_params,
98 : temp_dir_("videolink-"),
99 frame_params_(frame_params),
103 dvd_generator::pgc_ref dvd_generator::add_menu()
105 pgc_ref next_menu(menu_pgc, menus_.size());
107 // Check against maximum number of menus. It appears that no more
108 // than 128 menus are reachable through LinkPGCN instructions, and
109 // dvdauthor uses some menu numbers for special purposes, resulting
110 // in a practical limit of 119 per domain. We can work around this
111 // later by spreading some menus across titlesets.
112 if (next_menu.index == 119)
113 throw std::runtime_error("No more than 119 menus can be used");
115 menus_.resize(next_menu.index + 1);
119 void dvd_generator::add_menu_entry(unsigned index,
120 const rectangle & area,
121 const pgc_ref & target)
123 assert(index < menus_.size());
124 assert(target.type == menu_pgc && target.index < menus_.size()
125 || target.type == title_pgc && target.index < titles_.size());
126 menu_entry new_entry = { area, target };
127 menus_[index].entries.push_back(new_entry);
130 void dvd_generator::generate_menu_vob(unsigned index,
131 Glib::RefPtr<Gdk::Pixbuf> background,
132 Glib::RefPtr<Gdk::Pixbuf> highlights)
135 assert(index < menus_.size());
136 const menu & this_menu = menus_[index];
138 std::string background_name(
139 temp_file_name(temp_dir_, "menu-%3d-back.png", 1 + index));
140 std::cout << "saving " << background_name << std::endl;
141 background->save(background_name, "png");
143 std::string highlights_name(
144 temp_file_name(temp_dir_, "menu-%3d-links.png", 1 + index));
145 std::cout << "saving " << highlights_name << std::endl;
146 highlights->save(highlights_name, "png");
148 std::string spumux_name(
149 temp_file_name(temp_dir_, "menu-%3d.subpictures", 1 + index));
150 std::ofstream spumux_file(spumux_name.c_str());
154 " <spu force='yes' start='00:00:00.00'\n"
155 " highlight='" << highlights_name << "'\n"
156 " select='" << highlights_name << "'>\n";
157 int button_count = this_menu.entries.size();
158 for (int i = 0; i != button_count; ++i)
160 const menu_entry & this_entry = this_menu.entries[i];
162 // We program left and right to cycle through the buttons in
163 // the order the entries were added. This should result in
164 // left and right behaving like the tab and shift-tab keys
165 // would in the browser. Hopefully that's a sensible order.
166 // We program up and down to behave geometrically.
167 int up_button = i, down_button = i;
168 double up_closeness = 0.0, down_closeness = 0.0;
169 for (int j = 0; j != button_count; ++j)
171 const menu_entry & other_entry = this_menu.entries[j];
172 double closeness = directed_closeness(
173 this_entry.area, other_entry.area, -1);
174 if (closeness > up_closeness)
177 up_closeness = closeness;
181 closeness = directed_closeness(
182 this_entry.area, other_entry.area, 1);
183 if (closeness > down_closeness)
186 down_closeness = closeness;
190 spumux_file << " <button"
191 " x0='" << this_entry.area.left << "'"
192 " y0='" << this_entry.area.top << "'"
193 " x1='" << this_entry.area.right << "'"
194 " y1='" << this_entry.area.bottom << "'"
195 " left='" << (i == 0 ? button_count : i) << "'"
196 " right='" << 1 + (i + 1) % button_count << "'"
197 " up='" << 1 + up_button << "'"
198 " down='" << 1 + down_button << "'"
207 throw std::runtime_error("Failed to write control file for spumux");
209 std::ostringstream command_stream;
210 unsigned frame_count(menu_duration_frames(frame_params_));
211 if (encoder_ == mpeg_encoder_ffmpeg)
213 for (unsigned i = 0; i != frame_count; ++i)
215 std::string frame_name(background_name);
216 frame_name.push_back('-');
217 frame_name.push_back('0' + i / 10);
218 frame_name.push_back('0' + i % 10);
219 if (symlink(background_name.c_str(), frame_name.c_str()) != 0)
220 throw std::runtime_error(
221 std::string("symlink: ").append(std::strerror(errno)));
224 "ffmpeg -f image2 -vcodec png"
225 " -r " << frame_params_.rate_numer <<
226 "/" << frame_params_.rate_denom <<
227 " -i " << background_name << "-%02d"
228 " -target " << frame_params_.common_name << "-dvd"
229 " -vcodec mpeg2video -aspect 4:3 -an -y /dev/stdout";
233 assert(encoder_ == mpeg_encoder_mjpegtools_old
234 || encoder_ == mpeg_encoder_mjpegtools_new);
236 << "pngtopnm " << background_name
237 << " | ppmtoy4m -v0 -n" << frame_count << " -F"
238 << frame_params_.rate_numer << ":" << frame_params_.rate_denom
239 << " -A" << frame_params_.pixel_ratio_width
240 << ":" << frame_params_.pixel_ratio_height
242 // The chroma subsampling keywords changed between
243 // versions 1.6.2 and 1.8 of mjpegtools. There is no
244 // keyword that works with both.
245 if (encoder_ == mpeg_encoder_mjpegtools_old)
246 command_stream << "-S420_mpeg2";
248 command_stream << "-S420mpeg2";
250 " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
251 " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
254 << " | spumux -v0 -mdvd " << spumux_name
255 << " > " << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + index);
256 std::string command(command_stream.str());
257 const char * argv[] = {
258 "/bin/sh", "-c", command.c_str(), 0
260 std::cout << "running " << command << std::endl;
262 Glib::spawn_sync(".",
263 Glib::ArrayHandle<std::string>(
264 argv, sizeof(argv)/sizeof(argv[0]),
265 Glib::OWNERSHIP_NONE),
266 Glib::SPAWN_STDOUT_TO_DEV_NULL,
270 if (command_result != 0)
271 throw std::runtime_error("spumux pipeline failed");
274 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
276 pgc_ref next_title(title_pgc, titles_.size());
278 // Check against maximum number of titles.
279 if (next_title.index == 99)
280 throw std::runtime_error("No more than 99 titles can be used");
282 titles_.resize(next_title.index + 1);
283 titles_[next_title.index].swap(content);
287 void dvd_generator::generate(const std::string & output_dir) const
289 std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
290 std::ofstream file(name.c_str());
292 // We generate code that uses registers in the following way:
295 // g1: target menu location
296 // g2: source/return menu location for title
297 // g3: target chapter number
299 // All locations are divided into two bitfields: the least
300 // significant 10 bits are a page/menu number and the most
301 // significant 6 bits are a link/button number, and numbering
302 // starts at 1, not 0. This is done for compatibility with
303 // the encoding of the s8 (button) register.
305 static const int button_mult = dvd::reg_s8_button_mult;
306 static const int menu_mask = button_mult - 1;
307 static const int button_mask = (1 << dvd::reg_bits) - button_mult;
314 for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
316 const menu & this_menu = menus_[menu_index];
320 // This is the first (title) menu, displayed when the
321 // disc is first played.
323 " <pgc entry='title'>\n"
325 // Set a default target location if none is set.
326 // This covers first play and use of the "top menu"
329 " g1 = " << 1 + button_mult << ";\n";
338 // When a title finishes or the user presses the "menu"
339 // button, this always jumps to the titleset's root menu.
340 // We want to return the user to the last menu they used.
341 // So we arrange for each titleset's root menu to return
342 // to the vmgm title menu and then dispatch from there to
343 // whatever the correct menu is. We determine the correct
344 // menu by looking at the menu part of g1.
346 file << " g0 = g1 & " << menu_mask << ";\n";
348 // There is a limit of 128 VM instructions in each PGC.
349 // Therefore in each menu's <pre> section we generate
350 // jumps to menus with numbers greater by 512, 256, 128,
351 // ..., 1 where (a) such a menu exists, (b) this menu
352 // number is divisible by twice that increment and (c) the
353 // correct menu is that or a later menu. Thus each menu
354 // has at most 10 such conditional jumps and is reachable
355 // by at most 10 jumps from the title menu. This chain of
356 // jumps might take too long on some players; this has yet
357 // to be investigated.
359 for (std::size_t menu_incr = (menu_mask + 1) / 2;
363 if (menu_index + menu_incr < menus_.size()
364 && (menu_index & (menu_incr * 2 - 1)) == 0)
367 " if (g0 ge " << 1 + menu_index + menu_incr
369 " jump menu " << 1 + menu_index + menu_incr
375 // Highlight the appropriate button.
376 " s8 = g1 & " << button_mask << ";\n"
377 // Forget the link target. If we don't do this, pressing
378 // the "top menu" button will result in jumping back to
383 << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
385 // Define a cell covering the whole menu and set a still
386 // time at the end of that, since it seems all players
387 // support that but some ignore a still time set on a PGC.
388 " <cell start='0' end='"
389 << std::fixed << std::setprecision(4)
390 << menu_duration_seconds(frame_params_) << "'"
391 " chapter='yes' pause='inf'/>\n"
394 for (unsigned button_index = 0;
395 button_index != this_menu.entries.size();
398 const pgc_ref & target = this_menu.entries[button_index].target;
400 file << " <button> ";
402 if (target.type == menu_pgc)
404 unsigned target_button_num;
406 if (target.sub_index)
408 target_button_num = target.sub_index;
412 // Look for a button on the new menu that links
413 // back to this one. If there is one, set that to
414 // be the highlighted button; otherwise, use the
416 const std::vector<menu_entry> & target_menu_entries =
417 menus_[target.index].entries;
418 pgc_ref this_pgc(menu_pgc, menu_index);
419 target_button_num = target_menu_entries.size();
420 while (target_button_num != 1
421 && (target_menu_entries[target_button_num - 1].target
427 // Set new menu location.
428 "g1 = " << (1 + target.index
429 + target_button_num * button_mult) << "; "
430 // Jump to the target menu.
431 "jump menu " << 1 + target.index << "; ";
435 assert(target.type == title_pgc);
438 // Record current menu location.
439 "g2 = " << (1 + menu_index
440 + (1 + button_index) * button_mult) << "; "
441 // Set target chapter number.
442 "g3 = " << target.sub_index << "; "
443 // Jump to the target title.
444 "jump title " << 1 + target.index << "; ";
447 file << "</button>\n";
458 // Generate a titleset for each title. This appears to make
459 // jumping to titles a whole lot simpler (but limits us to 99
461 for (unsigned title_index = 0;
462 title_index != titles_.size();
467 // Generate a dummy menu so that the "menu" button will
468 // work. This returns to the source menu via the title
471 " <pgc entry='root'>\n"
472 " <pre> g1 = g2; jump vmgm menu; </pre>\n"
479 // Count chapters in the title.
480 unsigned n_chapters = 0;
481 for (vob_list::const_iterator
482 it = titles_[title_index].begin(),
483 end = titles_[title_index].end();
487 // Chapter start times may be specified in the "chapters"
488 // attribute as a comma-separated list. If this is not
489 // specified then the beginning of each file starts a new
490 // chapter. Thus the number of chapters in each file is
491 // the number of commas in the chapter attribute, plus 1.
494 while ((pos = it->chapters.find(',', pos)) != std::string::npos)
501 // Generate jump "table" for chapters.
502 for (unsigned chapter_num = 1;
503 chapter_num <= n_chapters;
506 " if (g3 == " << chapter_num << ")\n"
507 " jump chapter " << chapter_num << ";\n";
512 for (vob_list::const_iterator
513 it = titles_[title_index].begin(),
514 end = titles_[title_index].end();
518 file << " <vob file='" << xml_escape(it->file) << "'";
519 if (!it->chapters.empty())
520 file << " chapters='" << xml_escape(it->chapters) << "'";
521 if (!it->pause.empty())
522 file << " pause='" << xml_escape(it->pause) << "'";
528 // Return to the source menu, but highlight the next button.
529 " g2 = g2 + " << button_mult << ";\n"
543 const char * argv[] = {
545 "-o", output_dir.c_str(),
550 Glib::spawn_sync(".",
551 Glib::ArrayHandle<std::string>(
552 argv, sizeof(argv)/sizeof(argv[0]),
553 Glib::OWNERSHIP_NONE),
554 Glib::SPAWN_SEARCH_PATH
555 | Glib::SPAWN_STDOUT_TO_DEV_NULL,
559 if (command_result != 0)
560 throw std::runtime_error("dvdauthor failed");