encode.pl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Default configuration
  8. my $FORMAT = 'mp4';
  9. my $AUDIO_BITRATE = 192;
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 22;
  12. my $AUDIO_COPY = 0;
  13. my $STEREO_ONLY = 0;
  14. my $HEIGHT = undef();
  15. my $WIDTH = undef();
  16. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b';
  17. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  18. my $FORCE_MP4 = 0;
  19. # Applicaton configuration
  20. my $HD_WIDTH = 1350;
  21. my $MIN_VIDEO_WIDTH = 100;
  22. my $MAX_CROP_DIFF = .1;
  23. my $MAX_DURA_DIFF = 5;
  24. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', 'AAC', 'OTHER');
  25. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  26. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  27. my $DEBUG = 0;
  28. # General parameters for HandBrake
  29. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  30. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3', '--mixdown', 'dpl2');
  31. # Runtime debug mode
  32. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  33. $DEBUG = 1;
  34. }
  35. # Shortcut config
  36. if ($ENV{'MOBILE'}) {
  37. $ENV{'QUALITY'} = 24;
  38. $ENV{'HEIGHT'} = 720;
  39. $ENV{'WIDTH'} = 1280;
  40. $ENV{'AUDIO_BITRATE'} = 128;
  41. $ENV{'STEREO_ONLY'} = 1;
  42. }
  43. # Allow overrides for audio languages
  44. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  45. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  46. }
  47. # Allow overrides for subtitle languages
  48. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  49. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  50. }
  51. # Allow copy-only audio transfers (for use in re-encoding)
  52. if ($ENV{'AUDIO_COPY'}) {
  53. $AUDIO_COPY = 1;
  54. }
  55. # Allow AAC-only audio transfers (for use in mobile encoding)
  56. if ($ENV{'STEREO_ONLY'}) {
  57. $STEREO_ONLY = 1;
  58. }
  59. # Allow MP4-only output format (for use in mobile encoding)
  60. if ($ENV{'FORCE_MP4'}) {
  61. $FORCE_MP4 = 1;
  62. }
  63. # Allow overrides for video quality
  64. if ($ENV{'QUALITY'}) {
  65. $QUALITY = $ENV{'QUALITY'};
  66. $HD_QUALITY = $ENV{'QUALITY'};
  67. }
  68. # Allow overrides for audio bitrate
  69. if ($ENV{'AUDIO_BITRATE'}) {
  70. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  71. }
  72. # Allow overrides for video height and width. The default is "same as source".
  73. if ($ENV{'HEIGHT'}) {
  74. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  75. }
  76. if ($ENV{'WIDTH'}) {
  77. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  78. }
  79. # Additional arguments for HandBrake, to allow options not supported directly by this script
  80. # Split on spaces; if you need spaces you'll have to work out something else
  81. if ($ENV{'HANDBRAKE_ARGS'}) {
  82. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  83. push(@video_params, @args);
  84. }
  85. # Command-line parameters
  86. my ($in_file, $out_file, $title) = @ARGV;
  87. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  88. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  89. }
  90. # Sanity checks
  91. if ($AUDIO_COPY && $STEREO_ONLY) {
  92. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  93. }
  94. # Scan for title/track info
  95. my %titles = &scan($in_file);
  96. # Allow external subtitles for single-title files
  97. if (scalar(keys(%titles)) == 1) {
  98. my $srt_file = $in_file;
  99. $srt_file =~ s/\.\w{2,4}$/.srt/;
  100. if (!-r $srt_file) {
  101. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  102. }
  103. if (-r $srt_file) {
  104. if ($DEBUG) {
  105. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  106. }
  107. push(@video_params, '--srt-file', $srt_file);
  108. }
  109. }
  110. # Allow encoding of a specific title
  111. if ($title) {
  112. if ($title =~ /^\d+$/ && $title > 0) {
  113. if (!defined($titles{$title})) {
  114. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  115. }
  116. my $selected_title = $titles{$title};
  117. %titles = ();
  118. $titles{$title} = $selected_title;
  119. } elsif ($title =~ /main/i) {
  120. my $max_title = 0;
  121. my $max_duration = 0;
  122. foreach my $title (keys(%titles)) {
  123. if (!$titles{$title}{'duration'}) {
  124. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  125. next;
  126. }
  127. my $new_max = 0;
  128. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  129. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  130. $new_max = 1;
  131. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  132. $new_max = 1;
  133. }
  134. } elsif ($titles{$title}{'duration'} > $max_duration) {
  135. $new_max = 1;
  136. }
  137. if ($new_max) {
  138. $max_duration = $titles{$title}{'duration'};
  139. $max_title = $title;
  140. }
  141. }
  142. my $selected_title = $titles{$max_title};
  143. %titles = ();
  144. $titles{$max_title} = $selected_title;
  145. }
  146. }
  147. # Ensure we have an output file name
  148. # Force MKV output if the output file name is provided and ends in .MKV
  149. if (!defined($out_file) || length($out_file) < 1) {
  150. $out_file = $in_file;
  151. } else {
  152. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  153. if (defined($force_format) && lc($force_format) eq 'mkv') {
  154. $FORMAT = 'mkv';
  155. }
  156. }
  157. # Keep copies of our defaults so we can reset between tracks
  158. my $format_default = $FORMAT;
  159. # Encode each title
  160. foreach my $title (keys(%titles)) {
  161. if ($DEBUG) {
  162. print STDERR 'Setting options for title: ' . $title . "\n";
  163. }
  164. # Reset
  165. $FORMAT = $format_default;
  166. # Parse the title's audio and subtitle tracks
  167. my $scan = $titles{$title};
  168. my @audio = &audioOptions($scan);
  169. my @subs = &subOptions($scan);
  170. # Skip tracks that have no video
  171. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  172. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  173. next;
  174. }
  175. # Skip tracks that have no audio
  176. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  177. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  178. next;
  179. }
  180. # Set the audio quality for re-encoded tracks
  181. push(@audio, '--ab', $AUDIO_BITRATE);
  182. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  183. my $title_quality = $QUALITY;
  184. if ($scan->{'size'}[0] > $HD_WIDTH) {
  185. $title_quality = $HD_QUALITY;
  186. }
  187. # Override unlikely autocrop values
  188. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  189. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  190. {
  191. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  192. my @crop = (0, 0, 0, 0);
  193. $scan->{'crop'} = \@crop;
  194. }
  195. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  196. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  197. if ($track->{'type'} eq 'PGS') {
  198. $FORMAT = 'mkv';
  199. last;
  200. }
  201. }
  202. # Force MKV muxing if the output contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  203. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  204. if ($track->{'codec'} =~ /DTS/i) {
  205. $FORMAT = 'mkv';
  206. last;
  207. }
  208. }
  209. # Select a file name extension that matches the format
  210. my $title_out_file = $out_file;
  211. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  212. if ($FORMAT eq 'mkv') {
  213. $title_out_file .= '.mkv';
  214. } else {
  215. $title_out_file .= '.m4v';
  216. }
  217. # Force the title number into the output file name if there are multiple titles to be encoded
  218. if (scalar(keys(%titles)) > 1) {
  219. my $title_text = sprintf('%02d', $title);
  220. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  221. }
  222. # Output file
  223. if (uc($title_out_file) eq uc($in_file)) {
  224. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  225. }
  226. # Build the arugment list
  227. my @args = ($HB_EXEC);
  228. push(@args, '--title', $title);
  229. push(@args, '--input', $in_file);
  230. push(@args, '--output', $title_out_file);
  231. push(@args, '--format', $FORMAT);
  232. push(@args, '--quality', $title_quality);
  233. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  234. push(@args, @video_params);
  235. push(@args, @audio_params);
  236. push(@args, @audio);
  237. push(@args, @subs);
  238. if ($DEBUG) {
  239. print STDERR "\n" . join(' ', @args) . "\n\n";
  240. }
  241. # Sanity check
  242. if (-e $title_out_file) {
  243. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  244. next;
  245. }
  246. # Run it
  247. my $child_out = '';
  248. my $child_in = '';
  249. my $pid = open3($child_in, $child_out, $child_out, @args);
  250. close($child_in);
  251. while (<$child_out>) {
  252. if ($DEBUG) {
  253. print STDERR $_;
  254. }
  255. }
  256. waitpid($pid, 0);
  257. close($child_out);
  258. # Provide the new file name if requested
  259. if ($ENV{'RECODE_OUTFILE'}) {
  260. print $title_out_file;
  261. }
  262. }
  263. # Cleanup
  264. exit(0);
  265. sub subOptions($) {
  266. my ($scan) = @_;
  267. my %tracks = ();
  268. foreach my $track (@{ $scan->{'subtitle'} }) {
  269. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  270. if (!defined($iso)) {
  271. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  272. next;
  273. }
  274. # Map text/bitmap into a boolean
  275. if ($text =~ /TEXT/i) {
  276. $text = 1;
  277. } else {
  278. $text = 0;
  279. }
  280. # Standardize the codes
  281. $iso = uc($iso);
  282. $type = uc($type);
  283. # Push all parsed data into an array
  284. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  285. $tracks{ $track->{'index'} } = \%data;
  286. # Print what we found
  287. if ($DEBUG) {
  288. print STDERR 'Found subtitle track: ';
  289. printHash(\%data);
  290. }
  291. }
  292. # Push the parsed data back up the chain
  293. $scan->{'subtitle_parsed'} = \%tracks;
  294. # Select the subtitle tracks we want to keep
  295. my @keep = ();
  296. foreach my $index (keys(%tracks)) {
  297. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  298. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  299. next;
  300. }
  301. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  302. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  303. push(@keep, $index);
  304. } elsif ($tracks{$index}->{'text'}) {
  305. push(@keep, $index);
  306. } else {
  307. if ($DEBUG) {
  308. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  309. }
  310. }
  311. }
  312. # Push the selected tracks back up the chain
  313. my %tmp = ();
  314. foreach my $num (@keep) {
  315. $tmp{$num} = $tracks{$num};
  316. }
  317. $scan->{'subtitle_selected'} = \%tmp;
  318. # Send back the argument string (if any)
  319. if (scalar(@keep) < 1) {
  320. return '';
  321. }
  322. return ('--subtitle', join(',', @keep));
  323. }
  324. sub audioOptions($) {
  325. my ($scan) = @_;
  326. my @retval = ();
  327. # Type the audio tracks
  328. my %tracks = ();
  329. foreach my $track (@{ $scan->{'audio'} }) {
  330. my ($language, $codec, $note, $channels, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?/;
  331. if (!defined($channels)) {
  332. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  333. next;
  334. }
  335. # Decode the channels string to a number
  336. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  337. $channels = $1;
  338. } elsif ($channels =~ /Dolby\s+Surround/i) {
  339. $channels = 3.1;
  340. }
  341. # Standardize the codec
  342. foreach my $code (@CODEC_ORDER) {
  343. my $metacode = quotemeta($code);
  344. if ($codec =~ /${metacode}/i) {
  345. $codec = $code;
  346. last;
  347. } elsif ($code eq 'OTHER') {
  348. if ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  349. $codec = $code;
  350. } elsif ($codec eq 'truehd' || $codec eq 'dca') {
  351. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  352. $codec = undef();
  353. } else {
  354. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  355. $codec = $code;
  356. }
  357. }
  358. }
  359. # Push all parsed data into the array
  360. my %data = ('language' => $language, 'codec' => $codec, 'channels' => $channels, 'iso' => $iso, 'note' => $note);
  361. $tracks{ $track->{'index'} } = \%data;
  362. # Print what we found
  363. if ($DEBUG) {
  364. print STDERR 'Found audio track: ';
  365. printHash(\%data);
  366. }
  367. }
  368. # Push the parsed data back up the chain
  369. $scan->{'audio_parsed'} = \%tracks;
  370. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  371. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  372. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  373. my $mixdown = undef();
  374. my %bestByCodec = ();
  375. my $bestCodec = undef();
  376. my $mostChannels = 0;
  377. # Loop point, in case we need to run the selector more than once
  378. SELECT_AUDIO:
  379. foreach my $codec (@CODEC_ORDER) {
  380. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  381. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  382. $bestCodec = $codec;
  383. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  384. }
  385. }
  386. foreach my $codec (@CODEC_ORDER) {
  387. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  388. $mixdown = $bestByCodec{$codec};
  389. last;
  390. }
  391. }
  392. # Sanity check
  393. if (!defined($mixdown) || $mixdown < 1) {
  394. # If we applied an exclude filter, remove it and try again
  395. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  396. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  397. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  398. goto SELECT_AUDIO;
  399. }
  400. # If we got no audio, give up -- this file is not valid
  401. print STDERR basename($0) . ": No usable audio tracks in title\n";
  402. return;
  403. }
  404. # Clear the mixdown selection if we're copying audio
  405. if ($AUDIO_COPY) {
  406. $mixdown = undef();
  407. }
  408. # Mixdown track first
  409. my @audio_tracks = ();
  410. if (defined($mixdown) && $mixdown > 0) {
  411. if ($DEBUG) {
  412. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  413. if ($tracks{$mixdown}->{'channels'} > 2) {
  414. push(@retval, '--mixdown', 'dpl2');
  415. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  416. }
  417. }
  418. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  419. push(@audio_tracks, \%track);
  420. }
  421. # Keep all other audio tracks, unless STEREO_ONLY is set
  422. if (!$STEREO_ONLY) {
  423. # Passthru DTS-MA, DTS, AC3, and AAC
  424. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  425. foreach my $index (keys(%tracks)) {
  426. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'codec'} eq 'OTHER' && $tracks{$index}->{'channels'} <= 2) {
  427. if ($DEBUG) {
  428. print STDERR 'Skipping recode of track ' . $index . ' since it is already used as the default track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  429. }
  430. next;
  431. } elsif (!$tracks{$index}->{'codec'}) {
  432. if ($DEBUG) {
  433. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  434. }
  435. next;
  436. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  437. if ($DEBUG) {
  438. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  439. }
  440. next;
  441. } else {
  442. my %track = ('index' => $index, 'encoder' => 'copy');
  443. push(@audio_tracks, \%track);
  444. }
  445. }
  446. }
  447. # Push the selected tracks back up the chain
  448. my %sel = ();
  449. foreach my $track (@audio_tracks) {
  450. # Copy the data, rather than just point to it -- we sometimes need modifications
  451. my $index = $track->{'index'};
  452. my %tmp = %{ $tracks{$index} };
  453. # The mixdown track needs special handling -- it appears twice, and with different settings
  454. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  455. $index .= '_mixdown';
  456. $tmp{'codec'} = 'AAC';
  457. $tmp{'channels'} = '2.0';
  458. }
  459. # Collect our (possibly modified) hash
  460. $sel{$index} = \%tmp;
  461. }
  462. $scan->{'audio_selected'} = \%sel;
  463. # Consolidate from the hashes
  464. my @output_tracks = ();
  465. my @output_encoders = ();
  466. foreach my $track (@audio_tracks) {
  467. push(@output_tracks, $track->{'index'});
  468. push(@output_encoders, $track->{'encoder'});
  469. }
  470. # Send back the argument strings
  471. push(@retval, '--audio', join(',', @output_tracks));
  472. push(@retval, '--aencoder', join(',', @output_encoders));
  473. return (@retval);
  474. }
  475. sub scan($) {
  476. my ($in_file) = @_;
  477. # Fork to scan the file
  478. my $child_out = '';
  479. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  480. # Loop through the output
  481. my $scan;
  482. my %titles = ();
  483. my $inTitle = 0;
  484. my $zone = '';
  485. while (<$child_out>) {
  486. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  487. if ($DEBUG) {
  488. print STDERR 'Found ' . $1 . " titles in source\n";
  489. }
  490. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  491. my $stream = $1;
  492. my $desc = $2;
  493. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  494. # Save the current title (if any)
  495. if ($inTitle) {
  496. $titles{$inTitle} = $scan;
  497. }
  498. # Grab the new title number
  499. $inTitle = $1;
  500. # Init the data collectors
  501. my @audio = ();
  502. my @crop = ();
  503. my @subtitle = ();
  504. my @size = ();
  505. my %tmp = (
  506. 'audio' => \@audio,
  507. 'crop' => \@crop,
  508. 'subtitle' => \@subtitle,
  509. 'size' => \@size,
  510. 'duration' => 0,
  511. 'aspect' => 0
  512. );
  513. $scan = \%tmp;
  514. if ($DEBUG) {
  515. print STDERR 'Found data for title ' . $1 . "\n";
  516. }
  517. } elsif ($inTitle) {
  518. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  519. push(@{ $scan->{'size'} }, $1, $2);
  520. if ($DEBUG) {
  521. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  522. }
  523. if (/\s+display aspect\: (\d*\.\d+)/) {
  524. $scan->{'aspect'} = $1;
  525. if ($DEBUG) {
  526. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  527. }
  528. }
  529. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  530. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  531. if ($DEBUG) {
  532. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  533. }
  534. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  535. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  536. if ($DEBUG) {
  537. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  538. }
  539. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  540. $zone = 'audio';
  541. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  542. my %track = ('index' => $1, 'description' => $2);
  543. push(@{ $scan->{'audio'} }, \%track);
  544. if ($DEBUG) {
  545. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  546. }
  547. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  548. $zone = 'subtitle';
  549. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  550. my %track = ('index' => $1, 'description' => $2);
  551. push(@{ $scan->{'subtitle'} }, \%track);
  552. if ($DEBUG) {
  553. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  554. }
  555. }
  556. }
  557. }
  558. # Save the last title (if any)
  559. if ($inTitle) {
  560. $titles{$inTitle} = $scan;
  561. }
  562. # Cleanup the scan process
  563. waitpid($pid, 0);
  564. close($child_out);
  565. # Sanity check
  566. if (scalar(keys(%titles)) < 1) {
  567. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  568. }
  569. # Return
  570. return %titles;
  571. }
  572. sub findBestAudioTrack($$) {
  573. my ($tracks, $codec) = @_;
  574. my $best = undef();
  575. my $channels = 0;
  576. for my $index (keys(%{$tracks})) {
  577. my $track = $tracks->{$index};
  578. # Skip tracks not in the specified codec
  579. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  580. next;
  581. }
  582. # Skip foreign language tracks
  583. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  584. next;
  585. }
  586. # Find the track with the most channels (Ófirst wins)
  587. if (!defined($best) || $track->{'channels'} > $channels) {
  588. $best = $index;
  589. $channels = $track->{'channels'};
  590. }
  591. }
  592. return $best;
  593. }
  594. sub isValidSubLanguage($) {
  595. my ($lang, $iso) = @_;
  596. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  597. return 1;
  598. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  599. return 1;
  600. }
  601. return 0;
  602. }
  603. sub isValidAudioLanguage($) {
  604. my ($lang, $iso) = @_;
  605. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  606. return 1;
  607. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  608. return 0;
  609. }
  610. return 1;
  611. }
  612. sub printHash($) {
  613. my ($data) = @_;
  614. my $first = 1;
  615. foreach my $key (keys(%{$data})) {
  616. if (defined($data->{$key})) {
  617. if ($first) {
  618. $first = 0;
  619. } else {
  620. print STDERR ', ';
  621. }
  622. print STDERR $key . ' => ' . $data->{$key};
  623. }
  624. }
  625. print STDERR "\n";
  626. }