encode.pl 21 KB

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