Coverage for pyguymer3/media/optimise_FLAC.py: 4%

25 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-08 18:47 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def optimise_FLAC( 

5 fname1, 

6 /, 

7 *, 

8 chunksize = 1048576, 

9 debug = __debug__, 

10 metaflacPath = None, 

11 timeout = 60.0, 

12): 

13 """ 

14 "metaflac" does not modify, but it does touch, the FLAC even if it cannot 

15 make it smaller, therefore it is NOT safe to keep on running "metaflac" on 

16 the same FLAC over and over again. 

17 

18 chunksize : int, optional 

19 the size of the chunks of any files which are read in (in bytes) 

20 """ 

21 

22 # Import standard modules ... 

23 import os 

24 import shutil 

25 import subprocess 

26 import tempfile 

27 

28 # Import sub-functions ... 

29 from .does_FLAC_have_padding import does_FLAC_have_padding 

30 from ..sha512 import sha512 

31 

32 # ************************************************************************** 

33 

34 # Try to find the paths if the user did not provide them ... 

35 if metaflacPath is None: 

36 metaflacPath = shutil.which("metaflac") 

37 assert metaflacPath is not None, "\"metaflac\" is not installed" 

38 

39 # Check that the FLAC exists ... 

40 if not os.path.exists(fname1): 

41 raise Exception(f"\"{fname1}\" does not exist") from None 

42 

43 # Skip this FLAC if it does not have any padding ... 

44 if not does_FLAC_have_padding(fname1): 

45 if debug: 

46 print(f"INFO: Skipping because \"{fname1}\" does not have any padding") 

47 return 

48 

49 # Create temporary directory ... 

50 with tempfile.TemporaryDirectory(prefix = "optimise_FLAC.") as tname: 

51 # Copy the FLAC into the temporary directory ... 

52 shutil.copy(fname1, tname) 

53 

54 # Deduce the FLAC name in the temporary directory ... 

55 fname2 = f"{tname}/{os.path.basename(fname1)}" 

56 

57 # Optimise FLAC ... 

58 subprocess.run( 

59 [ 

60 metaflacPath, 

61 "--dont-use-padding", 

62 "--remove", 

63 "--block-type=PADDING", 

64 fname2, 

65 ], 

66 check = True, 

67 encoding = "utf-8", 

68 stderr = subprocess.DEVNULL, 

69 stdout = subprocess.DEVNULL, 

70 timeout = timeout, 

71 ) 

72 

73 # Find the two hashes and don't replace the original if the new one is 

74 # the same ... 

75 if sha512(fname1, chunksize = chunksize) == sha512(fname2, chunksize = chunksize): 

76 if debug: 

77 print(f"INFO: Skipping because \"{fname2}\" is the same as \"{fname1}\"") 

78 return 

79 

80 # Replace the original ... 

81 shutil.move(fname2, fname1)