encode.pl 20 KB

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