]> git.decadent.org.uk Git - videolink.git/blob - generate_dvd.cpp
Placed DVD limit values consistently in dvd.hpp.
[videolink.git] / generate_dvd.cpp
1 // Copyright 2005-6 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include <cerrno>
5 #include <cstring>
6 #include <fstream>
7 #include <iomanip>
8 #include <iostream>
9 #include <ostream>
10 #include <sstream>
11 #include <stdexcept>
12
13 #include <gdkmm/pixbuf.h>
14 #include <glibmm/miscutils.h>
15 #include <glibmm/spawn.h>
16
17 #include "dvd.hpp"
18 #include "generate_dvd.hpp"
19 #include "xml_utils.hpp"
20
21 namespace
22 {
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,
29                               int y_dir)
30     {
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
40         // "start" rectangle.
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;
44         int end_x;
45         if (end.right < start_x)
46             end_x = end.right;
47         else if (end.left > start_x)
48             end_x = end.left;
49         else
50             end_x = start_x;
51
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)
57             return 0.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;
62     }
63
64     std::string temp_file_name(const temp_dir & dir,
65                                std::string base_name,
66                                unsigned index=0)
67     {
68         if (index != 0)
69         {
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;
75         }
76
77         return Glib::build_filename(dir.get_name(), base_name);
78     }
79
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)
85     {
86         return 12;
87     }
88     double menu_duration_seconds(const video::frame_params & params)
89     {
90         return double(menu_duration_frames(params))
91             * double(params.rate_numer)
92             / double(params.rate_denom);
93     }
94
95     void throw_length_error(const char * limit_type, std::size_t limit)
96     {
97         std::ostringstream oss;
98         oss << "exceeded DVD limit: " << limit_type << " > " << limit;
99         throw std::length_error(oss.str());
100     }
101 }
102
103 dvd_generator::dvd_generator(const video::frame_params & frame_params,
104                              mpeg_encoder encoder)
105         : temp_dir_("videolink-"),
106           frame_params_(frame_params),
107           encoder_(encoder)
108 {}
109
110 dvd_generator::pgc_ref dvd_generator::add_menu()
111 {
112     pgc_ref next_menu(menu_pgc, menus_.size());
113
114     if (next_menu.index == dvd::domain_pgcs_max)
115         throw_length_error("number of menus", dvd::domain_pgcs_max);
116
117     menus_.resize(next_menu.index + 1);
118     return next_menu;
119 }
120
121 void dvd_generator::add_menu_entry(unsigned index,
122                                    const rectangle & area,
123                                    const pgc_ref & target)
124 {
125     assert(index < menus_.size());
126     assert(target.type == menu_pgc && target.index < menus_.size()
127            || target.type == title_pgc && target.index < titles_.size());
128
129     if (menus_[index].entries.size() == dvd::menu_buttons_max)
130         throw_length_error("number of buttons", dvd::menu_buttons_max);
131
132     menu_entry new_entry = { area, target };
133     menus_[index].entries.push_back(new_entry);
134 }
135
136 void dvd_generator::generate_menu_vob(unsigned index,
137                                       Glib::RefPtr<Gdk::Pixbuf> background,
138                                       Glib::RefPtr<Gdk::Pixbuf> highlights)
139     const
140 {
141     assert(index < menus_.size());
142     const menu & this_menu = menus_[index];
143
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");
148
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");
153
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());
157     spumux_file <<
158         "<subpictures>\n"
159         "  <stream>\n"
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)
165     {
166         const menu_entry & this_entry = this_menu.entries[i];
167
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)
176         {
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)
181             {
182                 up_button = j;
183                 up_closeness = closeness;
184             }
185             else
186             {
187                 closeness = directed_closeness(
188                     this_entry.area, other_entry.area, 1);
189                 if (closeness > down_closeness)
190                 {
191                     down_button = j;
192                     down_closeness = closeness;
193                 }
194             }
195         }
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 << "'"
205             "/>\n";
206     }
207     spumux_file <<
208         "    </spu>\n"
209         "  </stream>\n"
210         "</subpictures>\n";
211     spumux_file.close();
212     if (!spumux_file)
213         throw std::runtime_error("Failed to write control file for spumux");
214
215     std::ostringstream command_stream;
216     unsigned frame_count(menu_duration_frames(frame_params_));
217     if (encoder_ == mpeg_encoder_ffmpeg)
218     {
219         for (unsigned i = 0; i != frame_count; ++i)
220         {
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)));
228         }
229         command_stream <<
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";
236     }
237     else
238     {
239         assert(encoder_ == mpeg_encoder_mjpegtools_old
240                || encoder_ == mpeg_encoder_mjpegtools_new);
241         command_stream
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
247             << " -Ip ";
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";
253         else
254             command_stream << "-S420mpeg2";
255         command_stream <<
256             " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
257             " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
258     }
259     command_stream
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
265     };
266     std::cout << "running " << command << std::endl;
267     int command_result;
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,
273                      SigC::Slot0<void>(),
274                      0, 0,
275                      &command_result);
276     if (command_result != 0)
277         throw std::runtime_error("spumux pipeline failed");
278 }
279
280 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
281 {
282     pgc_ref next_title(title_pgc, titles_.size());
283
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);
287
288     titles_.resize(next_title.index + 1);
289     titles_[next_title.index].swap(content);
290     return next_title;
291 }
292
293 void dvd_generator::generate(const std::string & output_dir) const
294 {
295     std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
296     std::ofstream file(name.c_str());
297
298     // We generate code that uses registers in the following way:
299     //
300     // g0:     scratch
301     // g1:     target menu location
302     // g2:     source/return menu location for title
303     // g3:     target chapter number
304     //
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.
310     //
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;
314
315     file <<
316         "<dvdauthor>\n"
317         "  <vmgm>\n"
318         "    <menus>\n";
319             
320     for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
321     {
322         const menu & this_menu = menus_[menu_index];
323
324         if (menu_index == 0)
325         {
326             // This is the first (title) menu, displayed when the
327             // disc is first played.
328             file <<
329                 "      <pgc entry='title'>\n"
330                 "        <pre>\n"
331                 // Set a default target location if none is set.
332                 // This covers first play and use of the "top menu"
333                 // button.
334                 "          if (g1 eq 0)\n"
335                 "            g1 = " << 1 + button_mult << ";\n";
336         }
337         else
338         {
339             file <<
340                 "      <pgc>\n"
341                 "        <pre>\n";
342         }
343
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.
351
352         file << "          g0 = g1 &amp; " << menu_mask << ";\n";
353
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.
364             
365         for (std::size_t menu_incr = (menu_mask + 1) / 2;
366              menu_incr != 0;
367              menu_incr /= 2)
368         {
369             if (menu_index + menu_incr < menus_.size()
370                 && (menu_index & (menu_incr * 2 - 1)) == 0)
371             {
372                 file <<
373                     "          if (g0 ge " << 1 + menu_index + menu_incr
374                                            << ")\n"
375                     "            jump menu " << 1 + menu_index + menu_incr
376                                            << ";\n";
377             }
378         }
379
380         file <<
381             // Highlight the appropriate button.
382             "          s8 = g1 &amp; " << 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
385             // this same menu!
386             "          g1 = 0;\n"
387             "        </pre>\n"
388             "        <vob file='"
389              << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
390              << "'>\n"
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"
398             "        </vob>\n";
399
400         for (unsigned button_index = 0;
401              button_index != this_menu.entries.size();
402              ++button_index)
403         {
404             const pgc_ref & target = this_menu.entries[button_index].target;
405
406             file << "        <button> ";
407
408             if (target.type == menu_pgc)
409             {
410                 unsigned target_button_num;
411
412                 if (target.sub_index)
413                 {
414                     target_button_num = target.sub_index;
415                 }
416                 else
417                 {
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
421                     // first button.
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
428                                != this_pgc))
429                         --target_button_num;
430                 }
431                          
432                 file <<
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 << "; ";
438             }
439             else
440             {
441                 assert(target.type == title_pgc);
442
443                 file <<
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 << "; ";
451             }
452
453             file <<  "</button>\n";
454         }
455
456         file <<
457             "      </pgc>\n";
458     }
459
460     file <<
461         "    </menus>\n"
462         "  </vmgm>\n";
463  
464     // Generate a titleset for each title.  This appears to make
465     // jumping to titles a whole lot simpler (but limits us to 99
466     // titles).
467     for (unsigned title_index = 0;
468          title_index != titles_.size();
469          ++title_index)
470     {
471         file <<
472             "  <titleset>\n"
473             // Generate a dummy menu so that the "menu" button will
474             // work.  This returns to the source menu via the title
475             // menu.
476             "    <menus>\n"
477             "      <pgc entry='root'>\n"
478             "        <pre> g1 = g2; jump vmgm menu; </pre>\n"
479             "      </pgc>\n"
480             "    </menus>\n"
481             "    <titles>\n"
482             "      <pgc>\n"
483             "        <pre>\n";
484
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();
490              it != end;
491              ++it)
492         {
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.
498             ++n_chapters;
499             std::size_t pos = 0;
500             while ((pos = it->chapters.find(',', pos)) != std::string::npos)
501             {
502                 ++n_chapters;
503                 ++pos;
504             }
505         }
506
507         // Generate jump "table" for chapters.
508         for (unsigned chapter_num = 1;
509              chapter_num <= n_chapters;
510              ++chapter_num)
511             file <<
512                 "          if (g3 == " << chapter_num << ")\n"
513                 "            jump chapter " << chapter_num << ";\n";
514
515         file <<
516             "        </pre>\n";
517
518         for (vob_list::const_iterator
519                  it = titles_[title_index].begin(),
520                  end = titles_[title_index].end();
521              it != end;
522              ++it)
523         {
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) << "'";
529             file << "/>\n";
530         }
531
532         file <<
533             "        <post>\n"
534             // Return to the source menu, but highlight the next button.
535             "          g2 = g2 + " << button_mult << ";\n"
536             "          call menu;\n"
537             "        </post>\n"
538             "      </pgc>\n"
539             "    </titles>\n"
540             "  </titleset>\n";
541     }
542
543     file <<
544         "</dvdauthor>\n";
545
546     file.close();
547
548     {
549         const char * argv[] = {
550             "dvdauthor",
551             "-o", output_dir.c_str(),
552             "-x", name.c_str(),
553             0
554         };
555         int command_result;
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,
562                          SigC::Slot0<void>(),
563                          0, 0,
564                          &command_result);
565         if (command_result != 0)
566             throw std::runtime_error("dvdauthor failed");
567     }
568 }