encode.pl 18 KB

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