]> git.decadent.org.uk Git - videolink.git/blob - generate_dvd.cpp
Added more standard headers that are strictly required.
[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
96 dvd_generator::dvd_generator(const video::frame_params & frame_params,
97                              mpeg_encoder encoder)
98         : temp_dir_("videolink-"),
99           frame_params_(frame_params),
100           encoder_(encoder)
101 {}
102
103 dvd_generator::pgc_ref dvd_generator::add_menu()
104 {
105     pgc_ref next_menu(menu_pgc, menus_.size());
106
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");
114
115     menus_.resize(next_menu.index + 1);
116     return next_menu;
117 }
118
119 void dvd_generator::add_menu_entry(unsigned index,
120                                    const rectangle & area,
121                                    const pgc_ref & target)
122 {
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);
128 }
129
130 void dvd_generator::generate_menu_vob(unsigned index,
131                                       Glib::RefPtr<Gdk::Pixbuf> background,
132                                       Glib::RefPtr<Gdk::Pixbuf> highlights)
133     const
134 {
135     assert(index < menus_.size());
136     const menu & this_menu = menus_[index];
137
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");
142
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");
147
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());
151     spumux_file <<
152         "<subpictures>\n"
153         "  <stream>\n"
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)
159     {
160         const menu_entry & this_entry = this_menu.entries[i];
161
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)
170         {
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)
175             {
176                 up_button = j;
177                 up_closeness = closeness;
178             }
179             else
180             {
181                 closeness = directed_closeness(
182                     this_entry.area, other_entry.area, 1);
183                 if (closeness > down_closeness)
184                 {
185                     down_button = j;
186                     down_closeness = closeness;
187                 }
188             }
189         }
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 << "'"
199             "/>\n";
200     }
201     spumux_file <<
202         "    </spu>\n"
203         "  </stream>\n"
204         "</subpictures>\n";
205     spumux_file.close();
206     if (!spumux_file)
207         throw std::runtime_error("Failed to write control file for spumux");
208
209     std::ostringstream command_stream;
210     unsigned frame_count(menu_duration_frames(frame_params_));
211     if (encoder_ == mpeg_encoder_ffmpeg)
212     {
213         for (unsigned i = 0; i != frame_count; ++i)
214         {
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)));
222         }
223         command_stream <<
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";
230     }
231     else
232     {
233         assert(encoder_ == mpeg_encoder_mjpegtools_old
234                || encoder_ == mpeg_encoder_mjpegtools_new);
235         command_stream
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
241             << " -Ip ";
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";
247         else
248             command_stream << "-S420mpeg2";
249         command_stream <<
250             " | mpeg2enc -v0 -f8 -a2 -o/dev/stdout"
251             " | mplex -v0 -f8 -o/dev/stdout /dev/stdin";
252     }
253     command_stream
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
259     };
260     std::cout << "running " << command << std::endl;
261     int command_result;
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,
267                      SigC::Slot0<void>(),
268                      0, 0,
269                      &command_result);
270     if (command_result != 0)
271         throw std::runtime_error("spumux pipeline failed");
272 }
273
274 dvd_generator::pgc_ref dvd_generator::add_title(vob_list & content)
275 {
276     pgc_ref next_title(title_pgc, titles_.size());
277
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");
281
282     titles_.resize(next_title.index + 1);
283     titles_[next_title.index].swap(content);
284     return next_title;
285 }
286
287 void dvd_generator::generate(const std::string & output_dir) const
288 {
289     std::string name(temp_file_name(temp_dir_, "videolink.dvdauthor"));
290     std::ofstream file(name.c_str());
291
292     // We generate code that uses registers in the following way:
293     //
294     // g0:     scratch
295     // g1:     target menu location
296     // g2:     source/return menu location for title
297     // g3:     target chapter number
298     //
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.
304     //
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;
308
309     file <<
310         "<dvdauthor>\n"
311         "  <vmgm>\n"
312         "    <menus>\n";
313             
314     for (unsigned menu_index = 0; menu_index != menus_.size(); ++menu_index)
315     {
316         const menu & this_menu = menus_[menu_index];
317
318         if (menu_index == 0)
319         {
320             // This is the first (title) menu, displayed when the
321             // disc is first played.
322             file <<
323                 "      <pgc entry='title'>\n"
324                 "        <pre>\n"
325                 // Set a default target location if none is set.
326                 // This covers first play and use of the "top menu"
327                 // button.
328                 "          if (g1 eq 0)\n"
329                 "            g1 = " << 1 + button_mult << ";\n";
330         }
331         else
332         {
333             file <<
334                 "      <pgc>\n"
335                 "        <pre>\n";
336         }
337
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.
345
346         file << "          g0 = g1 &amp; " << menu_mask << ";\n";
347
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.
358             
359         for (std::size_t menu_incr = (menu_mask + 1) / 2;
360              menu_incr != 0;
361              menu_incr /= 2)
362         {
363             if (menu_index + menu_incr < menus_.size()
364                 && (menu_index & (menu_incr * 2 - 1)) == 0)
365             {
366                 file <<
367                     "          if (g0 ge " << 1 + menu_index + menu_incr
368                                            << ")\n"
369                     "            jump menu " << 1 + menu_index + menu_incr
370                                            << ";\n";
371             }
372         }
373
374         file <<
375             // Highlight the appropriate button.
376             "          s8 = g1 &amp; " << 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
379             // this same menu!
380             "          g1 = 0;\n"
381             "        </pre>\n"
382             "        <vob file='"
383              << temp_file_name(temp_dir_, "menu-%3d.mpeg", 1 + menu_index)
384              << "'>\n"
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"
392             "        </vob>\n";
393
394         for (unsigned button_index = 0;
395              button_index != this_menu.entries.size();
396              ++button_index)
397         {
398             const pgc_ref & target = this_menu.entries[button_index].target;
399
400             file << "        <button> ";
401
402             if (target.type == menu_pgc)
403             {
404                 unsigned target_button_num;
405
406                 if (target.sub_index)
407                 {
408                     target_button_num = target.sub_index;
409                 }
410                 else
411                 {
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
415                     // first button.
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
422                                != this_pgc))
423                         --target_button_num;
424                 }
425                          
426                 file <<
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 << "; ";
432             }
433             else
434             {
435                 assert(target.type == title_pgc);
436
437                 file <<
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 << "; ";
445             }
446
447             file <<  "</button>\n";
448         }
449
450         file <<
451             "      </pgc>\n";
452     }
453
454     file <<
455         "    </menus>\n"
456         "  </vmgm>\n";
457  
458     // Generate a titleset for each title.  This appears to make
459     // jumping to titles a whole lot simpler (but limits us to 99
460     // titles).
461     for (unsigned title_index = 0;
462          title_index != titles_.size();
463          ++title_index)
464     {
465         file <<
466             "  <titleset>\n"
467             // Generate a dummy menu so that the "menu" button will
468             // work.  This returns to the source menu via the title
469             // menu.
470             "    <menus>\n"
471             "      <pgc entry='root'>\n"
472             "        <pre> g1 = g2; jump vmgm menu; </pre>\n"
473             "      </pgc>\n"
474             "    </menus>\n"
475             "    <titles>\n"
476             "      <pgc>\n"
477             "        <pre>\n";
478
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();
484              it != end;
485              ++it)
486         {
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.
492             ++n_chapters;
493             std::size_t pos = 0;
494             while ((pos = it->chapters.find(',', pos)) != std::string::npos)
495             {
496                 ++n_chapters;
497                 ++pos;
498             }
499         }
500
501         // Generate jump "table" for chapters.
502         for (unsigned chapter_num = 1;
503              chapter_num <= n_chapters;
504              ++chapter_num)
505             file <<
506                 "          if (g3 == " << chapter_num << ")\n"
507                 "            jump chapter " << chapter_num << ";\n";
508
509         file <<
510             "        </pre>\n";
511
512         for (vob_list::const_iterator
513                  it = titles_[title_index].begin(),
514                  end = titles_[title_index].end();
515              it != end;
516              ++it)
517         {
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) << "'";
523             file << "/>\n";
524         }
525
526         file <<
527             "        <post>\n"
528             // Return to the source menu, but highlight the next button.
529             "          g2 = g2 + " << button_mult << ";\n"
530             "          call menu;\n"
531             "        </post>\n"
532             "      </pgc>\n"
533             "    </titles>\n"
534             "  </titleset>\n";
535     }
536
537     file <<
538         "</dvdauthor>\n";
539
540     file.close();
541
542     {
543         const char * argv[] = {
544             "dvdauthor",
545             "-o", output_dir.c_str(),
546             "-x", name.c_str(),
547             0
548         };
549         int command_result;
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,
556                          SigC::Slot0<void>(),
557                          0, 0,
558                          &command_result);
559         if (command_result != 0)
560             throw std::runtime_error("dvdauthor failed");
561     }
562 }